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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
package db
import (
"context"
"database/sql"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"time"
_ "modernc.org/sqlite"
)
var (
ErrForeignKeysDisabled = errors.New("foreign keys are disabled")
ErrIntegrityCheckFailed = errors.New("integrity check failed")
ErrJournalModeInvalid = errors.New("journal mode is not WAL")
ErrSchemaMismatch = errors.New("database schema does not match expected definition")
ErrTableMissing = errors.New("table is missing")
ErrTableStructure = errors.New("table structure does not match expected schema")
)
type Store struct {
DB *sql.DB
Common []*sql.Stmt
}
func new(db *sql.DB) (*Store, error) {
lst := make([]*sql.Stmt, len(commonTransactions))
for _, common := range commonTransactions {
stmt, err := db.Prepare(common.Cmd)
if err != nil {
return nil, err
}
lst[common.Name] = stmt
}
return &Store{
DB: db,
Common: lst,
}, nil
}
func (s *Store) Close() error {
errs := make([]error, len(s.Common)+1)
for i, s := range s.Common {
if s != nil {
errs[i] = s.Close()
}
}
errs[len(s.Common)] = s.DB.Close()
return errors.Join(errs...)
}
// opts returns connection options that enforce our desired pragmas.
func opts() string {
return "?_foreign_keys=on&_journal_mode=WAL"
}
// Setup opens the SQLite DB at path, verifies its integrity and schema,
// and returns the valid DB handle. If any check fails, it backs up the old file
// and reinitializes the DB using the schema definitions.
func Setup(ctx context.Context, path string) (*Store, error) {
slog.DebugContext(ctx, "Setting up database connection")
// If file does not exist, generate a new DB.
if _, err := os.Stat(path); err != nil {
db, err := genDB(ctx, path)
if err != nil {
return nil, err
}
return new(db)
}
db, err := sql.Open("sqlite", path+opts())
if err != nil {
slog.ErrorContext(ctx, "failed to open DB", "error", err)
backupFile(ctx, path)
db, err := genDB(ctx, path)
if err != nil {
return nil, err
}
return new(db)
}
_, err = db.Exec("PRAGMA foreign_keys = ON")
if err != nil {
return nil, err
}
_, err = db.Exec("PRAGMA journal_mode=WAL")
if err != nil {
return nil, err
}
// Run integrity check.
var integrity string
if err = db.QueryRow("PRAGMA integrity_check;").Scan(&integrity); err != nil || integrity != "ok" {
if err != nil {
slog.ErrorContext(ctx, "integrity check query failed", "error", err)
} else {
slog.ErrorContext(ctx, "integrity check failed", "integrity", integrity)
}
db.Close()
backupFile(ctx, path)
db, err := genDB(ctx, path)
if err != nil {
return nil, err
}
return new(db)
}
// Validate the PRAGMA settings and each table's schema.
if err = validateSchema(ctx, db); err != nil {
slog.ErrorContext(ctx, "schema validation failed", "error", err)
db.Close()
backupFile(ctx, path)
db, err := genDB(ctx, path)
if err != nil {
return nil, err
}
return new(db)
}
return new(db)
}
// validateSchema checks that the PRAGMAs and every table definition match the expected schema.
func validateSchema(ctx context.Context, db *sql.DB) error {
if err := validatePragmas(db); err != nil {
return err
}
for _, table := range schemaDefinitions {
if err := validateTable(ctx, db, table.Name, table.Cmd); err != nil {
return err
}
}
return nil
}
// validatePragmas ensures that the required PRAGMAs are set.
func validatePragmas(db *sql.DB) error {
var fk int
if err := db.QueryRow("PRAGMA foreign_keys;").Scan(&fk); err != nil {
return err
}
if fk != 1 {
return ErrForeignKeysDisabled
}
var jm string
if err := db.QueryRow("PRAGMA journal_mode;").Scan(&jm); err != nil {
return err
}
if strings.ToLower(jm) != "wal" {
return ErrJournalModeInvalid
}
return nil
}
// validateTable fetches the stored SQL for the table and compares it
// (after normalization) with the expected definition.
func validateTable(ctx context.Context, db *sql.DB, tableName, expectedSQL string) error {
actualSQL, err := fetchTableSQL(db, tableName)
if err != nil {
slog.ErrorContext(ctx, "failed to fetch table definition", "table", tableName, "error", err)
return ErrSchemaMismatch
}
if actualSQL == "" {
slog.ErrorContext(ctx, "table is missing", "table", tableName)
return ErrTableMissing
}
normalizedExpected := normalizeSQL(expectedSQL)
normalizedActual := normalizeSQL(actualSQL)
if normalizedExpected != normalizedActual {
slog.ErrorContext(ctx, "table structure does not match expected schema",
"table", tableName,
"expected", normalizedExpected,
"actual", normalizedActual,
)
return ErrTableStructure
}
return nil
}
// normalizeSQL removes SQL comments, converts to lowercase,
// collapses whitespace, and removes a trailing semicolon.
func normalizeSQL(sqlStr string) string {
sqlStr = removeSQLComments(sqlStr)
sqlStr = strings.ToLower(sqlStr)
sqlStr = strings.ReplaceAll(sqlStr, "\n", " ")
sqlStr = strings.Join(strings.Fields(sqlStr), " ")
sqlStr = strings.TrimSuffix(sqlStr, ";")
return sqlStr
}
// removeSQLComments strips out any '--' style comments.
func removeSQLComments(sqlStr string) string {
lines := strings.Split(sqlStr, "\n")
for i, line := range lines {
if idx := strings.Index(line, "--"); idx != -1 {
lines[i] = line[:idx]
}
}
return strings.Join(lines, " ")
}
// fetchTableSQL retrieves the SQL definition of a table from sqlite_master.
func fetchTableSQL(db *sql.DB, table string) (string, error) {
var sqlDef sql.NullString
err := db.QueryRow(
"SELECT sql FROM sqlite_master WHERE type='table' AND name=?",
table,
).Scan(&sqlDef)
if err != nil {
return "", err
}
if !sqlDef.Valid {
return "", fmt.Errorf("no SQL definition found for table %s", table)
}
return sqlDef.String, nil
}
// backupFile renames the existing file by appending a ".bak" (or timestamped) suffix.
func backupFile(ctx context.Context, path string) {
backupPath := path + ".bak"
if _, err := os.Stat(backupPath); err == nil {
backupPath = fmt.Sprintf("%s-%s.bak", path, time.Now().Format(time.RFC3339))
}
if err := os.Rename(path, backupPath); err != nil {
slog.ErrorContext(ctx, "failed to backup file",
"error", err,
"original", path,
"backup", backupPath,
)
} else {
slog.InfoContext(ctx, "backed up corrupt DB",
"original", path,
"backup", backupPath,
)
}
}
|