1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16
17 package sqlite
18
19 import (
20 "database/sql"
21 "fmt"
22 "log"
23 "strconv"
24
25 "perkeep.org/pkg/sorted"
26 )
27
28 const requiredSchemaVersion = 1
29
30 func SchemaVersion() int {
31 return requiredSchemaVersion
32 }
33
34 func SQLCreateTables() []string {
35
36
37 return []string{
38 `CREATE TABLE rows (
39 k VARCHAR(` + strconv.Itoa(sorted.MaxKeySize) + `) NOT NULL PRIMARY KEY,
40 v VARCHAR(` + strconv.Itoa(sorted.MaxValueSize) + `))`,
41
42 `CREATE TABLE meta (
43 metakey VARCHAR(255) NOT NULL PRIMARY KEY,
44 value VARCHAR(255) NOT NULL)`,
45 }
46 }
47
48
49 func InitDB(path string) error {
50 db, err := sql.Open("sqlite", path)
51 if err != nil {
52 return err
53 }
54 defer db.Close()
55 for _, tableSQL := range SQLCreateTables() {
56 if _, err := db.Exec(tableSQL); err != nil {
57 return err
58 }
59 }
60
61
62
63 if _, err := db.Exec("PRAGMA journal_mode = WAL"); err != nil {
64 return err
65 }
66
67
68 var journalMode string
69 if err = db.QueryRow("PRAGMA journal_mode").Scan(&journalMode); err != nil {
70 log.Fatalf("Unable to determine sqlite3 journal_mode: %v", err)
71 }
72 if journalMode != "wal" {
73 log.Fatal("SQLite Write Ahead Logging (introducted in v3.7.0) is required. See http://perkeep.org/issue/114")
74 }
75
76 _, err = db.Exec(fmt.Sprintf(`REPLACE INTO meta VALUES ('version', '%d')`, SchemaVersion()))
77 return err
78 }