-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
96 lines (85 loc) · 2.09 KB
/
db.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
89
90
91
92
93
94
95
96
package main
import (
"database/sql"
"fmt"
"github.com/cznic/bufs"
_ "github.com/mattn/go-sqlite3"
"path/filepath"
)
var (
minKeywordCode = uint32(1)
sharedBufs = &bufs.CCache{}
)
const (
sqlKeywordTable = ` create table if not exists keywords (
code integer primary key autoincrement,
name text not null unique
)`
sqlNodeTable = ` create table if not exists nodes (
code integer primary key autoincrement,
kind integer not null,
contents blob
)`
sqlInsertKeyword = `insert into keywords (name) values (?)`
sqlKeywordByName = `select code, name from keywords where name = ?`
sqlKeywordByCode = `select code, name form keywords where code = ?`
sqlInsertNode = `insert into nodes (kind, contents) values (?, ?)`
sqlNodeByCode = `select code, kind, contents from nodes where code = ?`
sqlNodeByKind = `select code, kind, contents from nodes where kind = ?`
)
type DB struct {
folder string
metadb *sql.DB
}
func CreateDB(folder string) (*DB, error) {
db := &DB{folder: folder}
err := db.createMetaDB(filepath.Join(folder, "meta.db"))
return db, err
}
func (db *DB) createMetaDB(path string) error {
var err error
db.metadb, err = sql.Open("sqlite3", path)
if err != nil {
return err
}
_, err = db.metadb.Exec(sqlKeywordTable)
if err != nil {
return err
}
return err
}
func (db *DB) Close() error {
if db.metadb != nil {
return db.metadb.Close()
}
return nil
}
func (db *DB) CreateKeyword(key *Keyword) error {
if !key.ValidName() {
return fmt.Errorf("%v is invalid.", key)
}
if exists, err := db.keywordExists(key); exists {
return err
} else {
return db.insertKeyword(key)
}
panic("not reached")
return nil
}
func (db *DB) keywordExists(key *Keyword) (bool, error) {
row := db.metadb.QueryRow(sqlKeywordByName, key.name)
var code uint64
var name string
err := row.Scan(&code, &name)
key.val = uint32(code)
return err == nil && key.Valid(), err
}
func (db *DB) insertKeyword(key *Keyword) error {
result, err := db.metadb.Exec(sqlInsertKeyword, key.name)
if err != nil {
return err
}
val, err := result.LastInsertId()
key.val = uint32(val)
return err
}