-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsqlite3.go
133 lines (116 loc) · 3.06 KB
/
sqlite3.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package mtg
import (
"context"
"database/sql"
_ "embed"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/MixinNetwork/mixin/logger"
_ "github.com/mattn/go-sqlite3"
)
//go:embed schema.sql
var SCHEMA string
type SQLite3Store struct {
db *sql.DB
mutex *sync.Mutex
}
func ExpandTilde(path string) string {
if !strings.HasPrefix(path, "~/") {
return path
}
home, err := os.UserHomeDir()
if err != nil {
panic(err)
}
path = strings.Replace(path, "~", home, 1)
return path
}
func OpenSQLite3Store(path string) (*SQLite3Store, error) {
path = ExpandTilde(path)
dsn := fmt.Sprintf("file:%s?mode=rwc&_journal_mode=WAL&cache=private", path)
db, err := sql.Open("sqlite3", dsn)
if err != nil {
return nil, err
}
_, err = db.Exec(SCHEMA)
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
return nil, err
}
return &SQLite3Store{
db: db,
mutex: new(sync.Mutex),
}, nil
}
func (s *SQLite3Store) Close() error {
return s.db.Close()
}
func (s *SQLite3Store) execOne(ctx context.Context, tx *sql.Tx, sql string, params ...any) error {
return s.execMultiple(ctx, tx, 1, sql, params...)
}
func (s *SQLite3Store) execMultiple(ctx context.Context, tx *sql.Tx, num int64, sql string, params ...any) error {
res, err := tx.ExecContext(ctx, sql, params...)
logger.Verbosef("SQLite3Store.ExecContext(%s, %v) => %v", sql, params, err)
if err != nil {
return err
}
rows, err := res.RowsAffected()
if err != nil || rows != num {
return fmt.Errorf("exec(%d, %s) => %d %v", num, sql, rows, err)
}
return nil
}
func buildInsertionSQL(table string, cols []string) string {
vals := strings.Repeat("?, ", len(cols))
return fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", table, strings.Join(cols, ","), vals[:len(vals)-2])
}
func (s *SQLite3Store) checkExistence(ctx context.Context, tx *sql.Tx, sql string, params ...any) (bool, error) {
rows, err := tx.QueryContext(ctx, sql, params...)
if err != nil {
return false, err
}
defer rows.Close()
return rows.Next(), nil
}
func (s *SQLite3Store) ReadProperty(ctx context.Context, k string) (string, error) {
row := s.db.QueryRowContext(ctx, "SELECT value FROM properties WHERE key=?", k)
var value string
err := row.Scan(&value)
if err == sql.ErrNoRows {
return "", nil
}
return value, err
}
func (s *SQLite3Store) WriteProperty(ctx context.Context, k, v string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer rollBack(tx)
existed, err := s.checkExistence(ctx, tx, "SELECT value FROM properties WHERE key=?", k)
if err != nil {
return err
}
createdAt := time.Now().UTC()
if existed {
err = s.execOne(ctx, tx, "UPDATE properties SET value=?, updated_at=? WHERE key=?", v, createdAt, k)
if err != nil {
return fmt.Errorf("UPDATE properties %v", err)
}
} else {
cols := []string{"key", "value", "created_at", "updated_at"}
err = s.execOne(ctx, tx, buildInsertionSQL("properties", cols), k, v, createdAt, createdAt)
if err != nil {
return fmt.Errorf("INSERT properties %v", err)
}
}
return tx.Commit()
}