File
Blob: config/sqlite.go
| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | |
| 13 | "go.miragespace.co/specter/util/sqlite" |
| 14 | |
| 15 | "github.com/ncruces/go-sqlite3" |
| 16 | ) |
| 17 | |
| 18 | const ( |
| 19 | FileName = "db" |
| 20 | applicationID = 0x53504346 // SPCF |
| 21 | databaseVersion = 1 |
| 22 | ) |
| 23 | |
| 24 | const schema = ` |
| 25 | CREATE TABLE documents ( |
| 26 | name TEXT PRIMARY KEY NOT NULL, |
| 27 | value BLOB NOT NULL, |
| 28 | version BLOB NOT NULL CHECK(length(version) = 48) |
| 29 | ) STRICT; |
| 30 | PRAGMA application_id = 1397769030; |
| 31 | PRAGMA user_version = 1; |
| 32 | ` |
| 33 | |
| 34 | func openDatabase(dir string) (*sql.DB, error) { |
| 35 | path := filepath.Join(dir, FileName) |
| 36 | // SQLite's default file mode follows the process umask. Create privately, |
| 37 | // accepting another opener's creation before SQLite serializes schema setup. |
| 38 | f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) |
| 39 | if err == nil { |
| 40 | if err := f.Close(); err != nil { |
| 41 | return nil, err |
| 42 | } |
| 43 | } else if !errors.Is(err, os.ErrExist) { |
| 44 | return nil, err |
| 45 | } |
| 46 | info, err := os.Stat(path) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | if !info.Mode().IsRegular() { |
| 51 | return nil, errors.New("configuration database must be a regular file") |
| 52 | } |
| 53 | // Replacement connections must not recreate a missing file with default |
| 54 | // permissions. The store owns creation; SQLite opens the existing database. |
| 55 | uri := url.URL{Scheme: "file", OmitHost: true, Path: filepath.ToSlash(path)} |
| 56 | uri.RawQuery = url.Values{ |
| 57 | "mode": {"rw"}, |
| 58 | "_txlock": {"immediate"}, |
| 59 | "_pragma": {"busy_timeout(5000)"}, |
| 60 | }.Encode() |
| 61 | db, err := sqlite.Open(uri.String(), setupDatabase) |
| 62 | if err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | db.SetMaxOpenConns(1) |
| 66 | return db, nil |
| 67 | } |
| 68 | |
| 69 | // Connection setup runs for initial and replacement connections. The small |
| 70 | // SQLite-specific bootstrap precedes ordinary database/sql queries. |
| 71 | func setupDatabase(conn *sqlite3.Conn) error { |
| 72 | // SQLite rejects an oversized stored row before copying it into Go memory. |
| 73 | conn.Limit(sqlite3.LIMIT_LENGTH, MaxValueBytes+MaxNameBytes+versionBytes+4096) |
| 74 | // The URI installs the busy handler before any database inspection. |
| 75 | if err := conn.Exec("PRAGMA synchronous=EXTRA; BEGIN IMMEDIATE"); err != nil { |
| 76 | return err |
| 77 | } |
| 78 | id, err := queryInt(conn, "PRAGMA application_id") |
| 79 | if err != nil { |
| 80 | return err |
| 81 | } |
| 82 | version, err := queryInt(conn, "PRAGMA user_version") |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | // An interrupted first transaction can leave an empty SQLite database. |
| 87 | // Only its pristine state may acquire our schema; foreign files stay intact. |
| 88 | pristine := id == 0 && version == 0 |
| 89 | if pristine { |
| 90 | objects, err := queryInt(conn, "SELECT COUNT(*) FROM sqlite_schema") |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | pristine = objects == 0 |
| 95 | } |
| 96 | if !pristine && (id != applicationID || version != databaseVersion) { |
| 97 | return fmt.Errorf("unsupported configuration database (application %d, version %d)", id, version) |
| 98 | } |
| 99 | if pristine { |
| 100 | if err := conn.Exec(schema); err != nil { |
| 101 | return err |
| 102 | } |
| 103 | } |
| 104 | return conn.Exec("COMMIT; PRAGMA journal_mode=DELETE") |
| 105 | } |
| 106 | |
| 107 | func queryInt(conn *sqlite3.Conn, query string) (int64, error) { |
| 108 | stmt, _, err := conn.Prepare(query) |
| 109 | if err != nil { |
| 110 | return 0, err |
| 111 | } |
| 112 | defer stmt.Close() |
| 113 | if !stmt.Step() { |
| 114 | return 0, errors.Join(errors.New("missing configuration database metadata"), stmt.Err()) |
| 115 | } |
| 116 | if stmt.ColumnType(0) != sqlite3.INTEGER { |
| 117 | return 0, errors.New("invalid configuration database metadata") |
| 118 | } |
| 119 | return stmt.ColumnInt64(0), nil |
| 120 | } |
| 121 | |
| 122 | func readRecord(query queryer, name string) (Record, bool, error) { |
| 123 | row := query.QueryRowContext(context.Background(), "SELECT name, value, version FROM documents WHERE name=?", name) |
| 124 | record, err := scanRecord(row) |
| 125 | if errors.Is(err, sql.ErrNoRows) { |
| 126 | return Record{}, false, nil |
| 127 | } |
| 128 | return record, err == nil, err |
| 129 | } |
| 130 | |
| 131 | type queryer interface { |
| 132 | QueryContext(context.Context, string, ...any) (*sql.Rows, error) |
| 133 | QueryRowContext(context.Context, string, ...any) *sql.Row |
| 134 | } |
| 135 | |
| 136 | func readRecords(query queryer) ([]Record, error) { |
| 137 | rows, err := query.QueryContext(context.Background(), "SELECT name, value, version FROM documents ORDER BY name") |
| 138 | if err != nil { |
| 139 | return nil, err |
| 140 | } |
| 141 | defer rows.Close() |
| 142 | records := make([]Record, 0) |
| 143 | size := len(`{"format":1,"records":[]}`) |
| 144 | for rows.Next() { |
| 145 | if len(records) == MaxDocuments { |
| 146 | return nil, ErrTooLarge |
| 147 | } |
| 148 | record, err := scanRecord(rows) |
| 149 | if err != nil { |
| 150 | return nil, err |
| 151 | } |
| 152 | encoded, err := json.Marshal(record) |
| 153 | if err != nil { |
| 154 | return nil, err |
| 155 | } |
| 156 | size += len(encoded) |
| 157 | if len(records) != 0 { |
| 158 | size++ |
| 159 | } |
| 160 | if size > MaxSnapshotBytes { |
| 161 | return nil, ErrTooLarge |
| 162 | } |
| 163 | records = append(records, record) |
| 164 | } |
| 165 | return records, rows.Err() |
| 166 | } |
| 167 | |
| 168 | func scanRecord(row interface{ Scan(...any) error }) (Record, error) { |
| 169 | var nameValue, valueValue, versionValue any |
| 170 | if err := row.Scan(&nameValue, &valueValue, &versionValue); err != nil { |
| 171 | return Record{}, err |
| 172 | } |
| 173 | name, nameOK := nameValue.(string) |
| 174 | value, valueOK := valueValue.([]byte) |
| 175 | encodedVersion, versionOK := versionValue.([]byte) |
| 176 | if !nameOK || !valueOK || !versionOK { |
| 177 | return Record{}, ErrInvalidRecord |
| 178 | } |
| 179 | version, err := decodeVersion(encodedVersion) |
| 180 | if err != nil { |
| 181 | return Record{}, err |
| 182 | } |
| 183 | record := Record{Name: name, Version: version, Value: value} |
| 184 | return record, record.Validate() |
| 185 | } |
| 186 | |
| 187 | func writeRecords(tx *sql.Tx, records []Record) (bool, error) { |
| 188 | // Fixed-width big-endian version bytes preserve schema/revision/digest order. |
| 189 | stmt, err := tx.Prepare(`INSERT INTO documents(name, value, version) VALUES(?, ?, ?) |
| 190 | ON CONFLICT(name) DO UPDATE SET value=excluded.value, version=excluded.version |
| 191 | WHERE excluded.version > documents.version`) |
| 192 | if err != nil { |
| 193 | return false, err |
| 194 | } |
| 195 | defer stmt.Close() |
| 196 | var changed bool |
| 197 | for _, record := range records { |
| 198 | value := record.Value |
| 199 | if value == nil { |
| 200 | value = []byte{} |
| 201 | } |
| 202 | result, err := stmt.Exec(record.Name, value, record.Version.bytes()) |
| 203 | if err != nil { |
| 204 | return false, err |
| 205 | } |
| 206 | count, err := result.RowsAffected() |
| 207 | if err != nil { |
| 208 | return false, err |
| 209 | } |
| 210 | changed = changed || count != 0 |
| 211 | } |
| 212 | return changed, nil |
| 213 | } |