Debian Codegraph @

dbutil/upgradetable.go

raw
1 // Copyright (c) 2023 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package dbutil
8
9 import (
10 "bytes"
11 "context"
12 "errors"
13 "fmt"
14 "io/fs"
15 "path/filepath"
16 "regexp"
17 "strconv"
18 "strings"
19 )
20
21 type TxnMode string
22
23 const (
24 TxnModeOn TxnMode = "on"
25 TxnModeOff TxnMode = "off"
26 TxnModeSQLiteForeignKeysOff TxnMode = "sqlite-fkey-off"
27 )
28
29 type UpgradeTable []upgrade
30
31 func (ut *UpgradeTable) extend(toSize int) {
32 if cap(*ut) >= toSize {
33 *ut = (*ut)[:toSize]
34 } else {
35 resized := make([]upgrade, toSize)
36 copy(resized, *ut)
37 *ut = resized
38 }
39 }
40
41 func (ut *UpgradeTable) Register(from, to, compat int, message string, txn TxnMode, fn upgradeFunc) {
42 if from < 0 {
43 from += to
44 }
45 if from < 0 {
46 panic("invalid from value in UpgradeTable.Register() call")
47 }
48 if compat <= 0 {
49 compat = to
50 }
51 upg := upgrade{message: message, fn: fn, upgradesTo: to, compatVersion: compat, transaction: txn}
52 if len(*ut) == from {
53 *ut = append(*ut, upg)
54 return
55 } else if len(*ut) < from {
56 ut.extend(from + 1)
57 } else if (*ut)[from].fn != nil {
58 panic(fmt.Errorf("tried to override upgrade at %d ('%s') with '%s'", from, (*ut)[from].message, upg.message))
59 }
60 (*ut)[from] = upg
61 }
62
63 var upgradeHeaderRegex = regexp.MustCompile(`^-- (?:v(\d+) -> )?v(\d+)(?: \(compatible with v(\d+)\+\))?: (.+)$`)
64
65 var transactionDisableRegex = regexp.MustCompile(`^-- transaction: ([a-z-]*)`)
66
67 func parseFileHeader(file []byte) (from, to, compat int, message string, txn TxnMode, lines [][]byte, err error) {
68 lines = bytes.Split(file, []byte("\n"))
69 if len(lines) < 2 {
70 err = errors.New("upgrade file too short")
71 return
72 }
73 var maybeFrom int
74 match := upgradeHeaderRegex.FindSubmatch(lines[0])
75 lines = lines[1:]
76 if match == nil {
77 err = errors.New("header not found")
78 } else if len(match) != 5 {
79 err = errors.New("unexpected number of items in regex match")
80 } else if maybeFrom, err = strconv.Atoi(string(match[1])); len(match[1]) > 0 && err != nil {
81 err = fmt.Errorf("invalid source version: %w", err)
82 } else if to, err = strconv.Atoi(string(match[2])); err != nil {
83 err = fmt.Errorf("invalid target version: %w", err)
84 } else if compat, err = strconv.Atoi(string(match[3])); len(match[3]) > 0 && err != nil {
85 err = fmt.Errorf("invalid compatible version: %w", err)
86 } else {
87 err = nil
88 if len(match[1]) > 0 {
89 from = maybeFrom
90 } else {
91 from = -1
92 }
93 message = string(match[4])
94 txn = "on"
95 match = transactionDisableRegex.FindSubmatch(lines[0])
96 if match != nil {
97 lines = lines[1:]
98 txn = TxnMode(match[1])
99 switch txn {
100 case TxnModeOff, TxnModeOn, TxnModeSQLiteForeignKeysOff:
101 // ok
102 default:
103 err = fmt.Errorf("invalid value %q for transaction flag", match[1])
104 }
105 }
106 }
107 return
108 }
109
110 var dialectLineFilter = regexp.MustCompile(`^\s*-- only: (postgres|sqlite)(?: for next (\d+) lines| until "(end) only")?(?: \(lines? (commented)\))?`)
111
112 // Constants used to make parseDialectFilter clearer
113 const (
114 skipUntilEndTag = -1
115 skipNothing = 0
116 skipNextLine = 1
117 )
118
119 func (db *Database) parseDialectFilter(line []byte) (dialect Dialect, lineCount int, uncomment bool, err error) {
120 match := dialectLineFilter.FindSubmatch(line)
121 if match == nil {
122 return
123 }
124 dialect, err = ParseDialect(string(match[1]))
125 if err != nil {
126 return
127 }
128 uncomment = bytes.Equal(match[4], []byte("commented"))
129 if bytes.Equal(match[3], []byte("end")) {
130 lineCount = skipUntilEndTag
131 } else if len(match[2]) == 0 {
132 lineCount = skipNextLine
133 } else {
134 lineCount, err = strconv.Atoi(string(match[2]))
135 if err != nil {
136 err = fmt.Errorf("invalid line count %q: %w", match[2], err)
137 }
138 }
139 return
140 }
141
142 var endLineFilter = regexp.MustCompile(`^\s*-- end only (postgres|sqlite)$`)
143
144 func (db *Database) Internals() *publishDatabaseInternals {
145 return (*publishDatabaseInternals)(db)
146 }
147
148 type publishDatabaseInternals Database
149
150 func (di *publishDatabaseInternals) FilterSQLUpgrade(lines [][]byte) (string, error) {
151 return (*Database)(di).filterSQLUpgrade(lines)
152 }
153
154 func (db *Database) filterSQLUpgrade(lines [][]byte) (string, error) {
155 output := make([][]byte, 0, len(lines))
156 for i := 0; i < len(lines); i++ {
157 dialect, lineCount, uncomment, err := db.parseDialectFilter(lines[i])
158 if err != nil {
159 return "", err
160 } else if lineCount == skipNothing {
161 output = append(output, lines[i])
162 } else if lineCount == skipUntilEndTag {
163 startedAt := i
164 startedAtMatch := dialectLineFilter.FindSubmatch(lines[startedAt])
165 // Skip filter start line
166 i++
167 for ; i < len(lines); i++ {
168 if match := endLineFilter.FindSubmatch(lines[i]); match != nil {
169 if !bytes.Equal(match[1], startedAtMatch[1]) {
170 return "", fmt.Errorf(`unexpected end tag %q for %q start at line %d`, string(match[0]), string(startedAtMatch[1]), startedAt)
171 }
172 break
173 }
174 if dialect == db.Dialect {
175 if uncomment {
176 if !bytes.HasPrefix(lines[i], []byte("--")) {
177 return "", fmt.Errorf("line %d isn't commented even though the dialect filter claimed it is (-- must be at beginning of line)", i+1)
178 }
179 output = append(output, bytes.TrimPrefix(lines[i], []byte("--")))
180 } else {
181 output = append(output, lines[i])
182 }
183 }
184 }
185 if i == len(lines) {
186 return "", fmt.Errorf(`didn't get end tag matching start %q at line %d`, string(startedAtMatch[1]), startedAt)
187 }
188 } else if dialect != db.Dialect {
189 i += lineCount
190 } else {
191 // Skip current line, uncomment the specified number of lines
192 i++
193 targetI := i + lineCount
194 for ; i < targetI; i++ {
195 if uncomment {
196 output = append(output, bytes.TrimPrefix(lines[i], []byte("--")))
197 } else {
198 output = append(output, lines[i])
199 }
200 }
201 // Decrement counter to avoid skipping the next line
202 i--
203 }
204 }
205 return string(bytes.Join(output, []byte("\n"))), nil
206 }
207
208 func sqlUpgradeFunc(fileName string, lines [][]byte) upgradeFunc {
209 return func(ctx context.Context, db *Database) error {
210 if dialect, skip, _, err := db.parseDialectFilter(lines[0]); err == nil && skip == skipNextLine && dialect != db.Dialect {
211 return nil
212 } else if upgradeSQL, err := db.filterSQLUpgrade(lines); err != nil {
213 panic(fmt.Errorf("failed to parse upgrade %s: %w", fileName, err))
214 } else {
215 _, err = db.Exec(ctx, upgradeSQL)
216 return err
217 }
218 }
219 }
220
221 func splitSQLUpgradeFunc(sqliteData, postgresData string) upgradeFunc {
222 return func(ctx context.Context, db *Database) (err error) {
223 switch db.Dialect {
224 case SQLite:
225 _, err = db.Exec(ctx, sqliteData)
226 case Postgres:
227 _, err = db.Exec(ctx, postgresData)
228 default:
229 err = fmt.Errorf("unknown dialect %s", db.Dialect)
230 }
231 return
232 }
233 }
234
235 func parseSplitSQLUpgrade(name string, fs fullFS, skipNames map[string]struct{}) (from, to, compat int, message string, txn TxnMode, fn upgradeFunc) {
236 postgresName := fmt.Sprintf("%s.postgres.sql", name)
237 sqliteName := fmt.Sprintf("%s.sqlite.sql", name)
238 skipNames[postgresName] = struct{}{}
239 skipNames[sqliteName] = struct{}{}
240 postgresData, err := fs.ReadFile(postgresName)
241 if err != nil {
242 panic(err)
243 }
244 sqliteData, err := fs.ReadFile(sqliteName)
245 if err != nil {
246 panic(err)
247 }
248 from, to, compat, message, txn, _, err = parseFileHeader(postgresData)
249 if err != nil {
250 panic(fmt.Errorf("failed to parse header in %s: %w", postgresName, err))
251 }
252 sqliteFrom, sqliteTo, sqliteCompat, sqliteMessage, sqliteTxn, _, err := parseFileHeader(sqliteData)
253 if err != nil {
254 panic(fmt.Errorf("failed to parse header in %s: %w", sqliteName, err))
255 }
256 if from != sqliteFrom || to != sqliteTo || compat != sqliteCompat {
257 panic(fmt.Errorf("mismatching versions in postgres and sqlite versions of %s: %d/%d -> %d/%d", name, from, sqliteFrom, to, sqliteTo))
258 } else if message != sqliteMessage {
259 panic(fmt.Errorf("mismatching message in postgres and sqlite versions of %s: %q != %q", name, message, sqliteMessage))
260 } else if txn != sqliteTxn {
261 panic(fmt.Errorf("mismatching transaction flag in postgres and sqlite versions of %s: %s != %s", name, txn, sqliteTxn))
262 }
263 fn = splitSQLUpgradeFunc(string(sqliteData), string(postgresData))
264 return
265 }
266
267 type fullFS interface {
268 fs.ReadFileFS
269 fs.ReadDirFS
270 }
271
272 var splitFileNameRegex = regexp.MustCompile(`^(.+)\.(postgres|sqlite)\.sql$`)
273
274 func (ut *UpgradeTable) RegisterFS(fs fullFS) {
275 ut.RegisterFSPath(fs, ".")
276 }
277
278 func (ut *UpgradeTable) RegisterFSPath(fs fullFS, dir string) {
279 files, err := fs.ReadDir(dir)
280 if err != nil {
281 panic(err)
282 }
283 skipNames := map[string]struct{}{}
284 for _, file := range files {
285 if file.IsDir() || !strings.HasSuffix(file.Name(), ".sql") {
286 // do nothing
287 } else if _, skip := skipNames[file.Name()]; skip {
288 // also do nothing
289 } else if splitName := splitFileNameRegex.FindStringSubmatch(file.Name()); splitName != nil {
290 from, to, compat, message, txn, fn := parseSplitSQLUpgrade(splitName[1], fs, skipNames)
291 ut.Register(from, to, compat, message, txn, fn)
292 } else if data, err := fs.ReadFile(filepath.Join(dir, file.Name())); err != nil {
293 panic(err)
294 } else if from, to, compat, message, txn, lines, err := parseFileHeader(data); err != nil {
295 panic(fmt.Errorf("failed to parse header in %s: %w", file.Name(), err))
296 } else {
297 ut.Register(from, to, compat, message, txn, sqlUpgradeFunc(file.Name(), lines))
298 }
299 }
300 }