This repository has been archived by the owner on Mar 6, 2019. It is now read-only.
forked from adtac/commento
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database_sqlite.go
88 lines (77 loc) · 1.73 KB
/
database_sqlite.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"database/sql"
"log"
"time"
)
type SqliteDatabase struct {
*sql.DB
}
func sqliteInit(connectionStr string) (*SqliteDatabase, error) {
db, err := sql.Open("sqlite3", connectionStr[8:])
if err != nil {
return nil, err
}
statement := `
CREATE TABLE IF NOT EXISTS comments (
url varchar(2083) not null,
name varchar(200) not null,
comment varchar(3000) not null,
depth int not null,
time timestamp not null,
parent int
);
`
if _, err = db.Exec(statement); err != nil {
return nil, err
} else {
return &SqliteDatabase{db}, nil
}
}
func (db *SqliteDatabase) CreateComment(c *Comment) error {
statement := `
SELECT depth, parent FROM comments WHERE rowid=?;
`
rows, err := db.Query(statement, c.Parent)
if err != nil {
return err
}
defer rows.Close()
depth := 0
for rows.Next() {
var pParent int
if err := rows.Scan(&depth, &pParent); err == nil {
if depth+1 > 5 {
c.Parent = pParent
}
}
}
if err := rows.Err(); err != nil {
log.Println(err)
return err
}
statement = `
INSERT INTO comments(url, name, comment, time, depth, parent) VALUES(?, ?, ?, ?, ?, ?);
`
_, err = db.Exec(statement, c.URL, c.Name, c.Comment, time.Now(), depth+1, c.Parent)
return err
}
func (db *SqliteDatabase) GetComments(url string) ([]Comment, error) {
statement := `
SELECT rowid, url, comment, name, time, parent FROM comments WHERE url=?;
`
rows, err := db.Query(statement, url)
if err != nil {
return nil, err
}
defer rows.Close()
comments := []Comment{}
for rows.Next() {
c := Comment{}
if err = rows.Scan(&c.ID, &c.URL, &c.Comment, &c.Name, &c.Timestamp, &c.Parent); err != nil {
return nil, err
}
comments = append(comments, c)
}
return comments, rows.Err()
}