forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
500 lines (413 loc) · 14.9 KB
/
db.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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package core
import (
"context"
"errors"
"fmt"
"hash/crc32"
"regexp"
"slices"
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/security"
"github.com/spf13/cast"
)
const (
idColumn string = "id"
// DefaultIdLength is the default length of the generated model id.
DefaultIdLength int = 15
// DefaultIdAlphabet is the default characters set used for generating the model id.
DefaultIdAlphabet string = "abcdefghijklmnopqrstuvwxyz0123456789"
)
// DefaultIdRegex specifies the default regex pattern for an id value.
var DefaultIdRegex = regexp.MustCompile(`^\w+$`)
// DBExporter defines an interface for custom DB data export.
// Usually used as part of [App.Save].
type DBExporter interface {
// DBExport returns a key-value map with the data to be used when saving the struct in the database.
DBExport(app App) (map[string]any, error)
}
// PreValidator defines an optional model interface for registering a
// function that will run BEFORE firing the validation hooks (see [App.ValidateWithContext]).
type PreValidator interface {
// PreValidate defines a function that runs BEFORE the validation hooks.
PreValidate(ctx context.Context, app App) error
}
// PostValidator defines an optional model interface for registering a
// function that will run AFTER executing the validation hooks (see [App.ValidateWithContext]).
type PostValidator interface {
// PostValidate defines a function that runs AFTER the successful
// execution of the validation hooks.
PostValidate(ctx context.Context, app App) error
}
// GenerateDefaultRandomId generates a default random id string
// (note: the generated random string is not intended for security purposes).
func GenerateDefaultRandomId() string {
return security.PseudorandomStringWithAlphabet(DefaultIdLength, DefaultIdAlphabet)
}
// crc32Checksum generates a stringified crc32 checksum from the provided plain string.
func crc32Checksum(str string) string {
return strconv.Itoa(int(crc32.ChecksumIEEE([]byte(str))))
}
// ModelQuery creates a new preconfigured select app.DB() query with preset
// SELECT, FROM and other common fields based on the provided model.
func (app *BaseApp) ModelQuery(m Model) *dbx.SelectQuery {
return app.modelQuery(app.DB(), m)
}
// AuxModelQuery creates a new preconfigured select app.AuxDB() query with preset
// SELECT, FROM and other common fields based on the provided model.
func (app *BaseApp) AuxModelQuery(m Model) *dbx.SelectQuery {
return app.modelQuery(app.AuxDB(), m)
}
func (app *BaseApp) modelQuery(db dbx.Builder, m Model) *dbx.SelectQuery {
tableName := m.TableName()
return db.
Select("{{" + tableName + "}}.*").
From(tableName).
WithBuildHook(func(query *dbx.Query) {
query.WithExecHook(execLockRetry(app.config.QueryTimeout, defaultMaxLockRetries))
})
}
// Delete deletes the specified model from the regular app database.
func (app *BaseApp) Delete(model Model) error {
return app.DeleteWithContext(context.Background(), model)
}
// Delete deletes the specified model from the regular app database
// (the context could be used to limit the query execution).
func (app *BaseApp) DeleteWithContext(ctx context.Context, model Model) error {
return app.delete(ctx, model, false)
}
// AuxDelete deletes the specified model from the auxiliary database.
func (app *BaseApp) AuxDelete(model Model) error {
return app.AuxDeleteWithContext(context.Background(), model)
}
// AuxDeleteWithContext deletes the specified model from the auxiliary database
// (the context could be used to limit the query execution).
func (app *BaseApp) AuxDeleteWithContext(ctx context.Context, model Model) error {
return app.delete(ctx, model, true)
}
func (app *BaseApp) delete(ctx context.Context, model Model, isForAuxDB bool) error {
event := new(ModelEvent)
event.App = app
event.Type = ModelEventTypeDelete
event.Context = ctx
event.Model = model
deleteErr := app.OnModelDelete().Trigger(event, func(e *ModelEvent) error {
pk := cast.ToString(e.Model.LastSavedPK())
if cast.ToString(pk) == "" {
return errors.New("the model can be deleted only if it is existing and has a non-empty primary key")
}
// db write
return e.App.OnModelDeleteExecute().Trigger(event, func(e *ModelEvent) error {
var db dbx.Builder
if isForAuxDB {
db = e.App.AuxNonconcurrentDB()
} else {
db = e.App.NonconcurrentDB()
}
return baseLockRetry(func(attempt int) error {
_, err := db.Delete(e.Model.TableName(), dbx.HashExp{
idColumn: pk,
}).WithContext(e.Context).Execute()
return err
}, defaultMaxLockRetries)
})
})
if deleteErr != nil {
errEvent := &ModelErrorEvent{ModelEvent: *event, Error: deleteErr}
errEvent.App = app // replace with the initial app in case it was changed by the hook
hookErr := app.OnModelAfterDeleteError().Trigger(errEvent)
if hookErr != nil {
return errors.Join(deleteErr, hookErr)
}
return deleteErr
}
if app.txInfo != nil {
// execute later after the transaction has completed
app.txInfo.onAfterFunc(func(txErr error) error {
if app.txInfo != nil && app.txInfo.parent != nil {
event.App = app.txInfo.parent
}
if txErr != nil {
return app.OnModelAfterDeleteError().Trigger(&ModelErrorEvent{
ModelEvent: *event,
Error: txErr,
})
}
return app.OnModelAfterDeleteSuccess().Trigger(event)
})
} else if err := event.App.OnModelAfterDeleteSuccess().Trigger(event); err != nil {
return err
}
return nil
}
// Save validates and saves the specified model into the regular app database.
//
// If you don't want to run validations, use [App.SaveNoValidate()].
func (app *BaseApp) Save(model Model) error {
return app.SaveWithContext(context.Background(), model)
}
// SaveWithContext is the same as [App.Save()] but allows specifying a context to limit the db execution.
//
// If you don't want to run validations, use [App.SaveNoValidateWithContext()].
func (app *BaseApp) SaveWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, true, false)
}
// SaveNoValidate saves the specified model into the regular app database without performing validations.
//
// If you want to also run validations before persisting, use [App.Save()].
func (app *BaseApp) SaveNoValidate(model Model) error {
return app.SaveNoValidateWithContext(context.Background(), model)
}
// SaveNoValidateWithContext is the same as [App.SaveNoValidate()]
// but allows specifying a context to limit the db execution.
//
// If you want to also run validations before persisting, use [App.SaveWithContext()].
func (app *BaseApp) SaveNoValidateWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, false, false)
}
// AuxSave validates and saves the specified model into the auxiliary app database.
//
// If you don't want to run validations, use [App.AuxSaveNoValidate()].
func (app *BaseApp) AuxSave(model Model) error {
return app.AuxSaveWithContext(context.Background(), model)
}
// AuxSaveWithContext is the same as [App.AuxSave()] but allows specifying a context to limit the db execution.
//
// If you don't want to run validations, use [App.AuxSaveNoValidateWithContext()].
func (app *BaseApp) AuxSaveWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, true, true)
}
// AuxSaveNoValidate saves the specified model into the auxiliary app database without performing validations.
//
// If you want to also run validations before persisting, use [App.AuxSave()].
func (app *BaseApp) AuxSaveNoValidate(model Model) error {
return app.AuxSaveNoValidateWithContext(context.Background(), model)
}
// AuxSaveNoValidateWithContext is the same as [App.AuxSaveNoValidate()]
// but allows specifying a context to limit the db execution.
//
// If you want to also run validations before persisting, use [App.AuxSaveWithContext()].
func (app *BaseApp) AuxSaveNoValidateWithContext(ctx context.Context, model Model) error {
return app.save(ctx, model, false, true)
}
// Validate triggers the OnModelValidate hook for the specified model.
func (app *BaseApp) Validate(model Model) error {
return app.ValidateWithContext(context.Background(), model)
}
// ValidateWithContext is the same as Validate but allows specifying the ModelEvent context.
func (app *BaseApp) ValidateWithContext(ctx context.Context, model Model) error {
if m, ok := model.(PreValidator); ok {
if err := m.PreValidate(ctx, app); err != nil {
return err
}
}
event := new(ModelEvent)
event.App = app
event.Context = ctx
event.Type = ModelEventTypeValidate
event.Model = model
return event.App.OnModelValidate().Trigger(event, func(e *ModelEvent) error {
if m, ok := e.Model.(PostValidator); ok {
if err := m.PostValidate(ctx, e.App); err != nil {
return err
}
}
return e.Next()
})
}
// -------------------------------------------------------------------
func (app *BaseApp) save(ctx context.Context, model Model, withValidations bool, isForAuxDB bool) error {
if model.IsNew() {
return app.create(ctx, model, withValidations, isForAuxDB)
}
return app.update(ctx, model, withValidations, isForAuxDB)
}
func (app *BaseApp) create(ctx context.Context, model Model, withValidations bool, isForAuxDB bool) error {
event := new(ModelEvent)
event.App = app
event.Context = ctx
event.Type = ModelEventTypeCreate
event.Model = model
saveErr := app.OnModelCreate().Trigger(event, func(e *ModelEvent) error {
// run validations (if any)
if withValidations {
validateErr := e.App.ValidateWithContext(e.Context, e.Model)
if validateErr != nil {
return validateErr
}
}
// db write
return e.App.OnModelCreateExecute().Trigger(event, func(e *ModelEvent) error {
var db dbx.Builder
if isForAuxDB {
db = e.App.AuxNonconcurrentDB()
} else {
db = e.App.NonconcurrentDB()
}
dbErr := baseLockRetry(func(attempt int) error {
if m, ok := e.Model.(DBExporter); ok {
data, err := m.DBExport(e.App)
if err != nil {
return err
}
// manually add the id to the data if missing
if _, ok := data[idColumn]; !ok {
data[idColumn] = e.Model.PK()
}
if cast.ToString(data[idColumn]) == "" {
return errors.New("empty primary key is not allowed when using the DBExporter interface")
}
_, err = db.Insert(e.Model.TableName(), data).WithContext(e.Context).Execute()
return err
}
return db.Model(e.Model).WithContext(e.Context).Insert()
}, defaultMaxLockRetries)
if dbErr != nil {
return dbErr
}
e.Model.MarkAsNotNew()
return nil
})
})
if saveErr != nil {
event.Model.MarkAsNew() // reset "new" state
errEvent := &ModelErrorEvent{ModelEvent: *event, Error: saveErr}
errEvent.App = app // replace with the initial app in case it was changed by the hook
hookErr := app.OnModelAfterCreateError().Trigger(errEvent)
if hookErr != nil {
return errors.Join(saveErr, hookErr)
}
return saveErr
}
if app.txInfo != nil {
// execute later after the transaction has completed
app.txInfo.onAfterFunc(func(txErr error) error {
if app.txInfo != nil && app.txInfo.parent != nil {
event.App = app.txInfo.parent
}
if txErr != nil {
event.Model.MarkAsNew() // reset "new" state
return app.OnModelAfterCreateError().Trigger(&ModelErrorEvent{
ModelEvent: *event,
Error: txErr,
})
}
return app.OnModelAfterCreateSuccess().Trigger(event)
})
} else if err := event.App.OnModelAfterCreateSuccess().Trigger(event); err != nil {
return err
}
return nil
}
func (app *BaseApp) update(ctx context.Context, model Model, withValidations bool, isForAuxDB bool) error {
event := new(ModelEvent)
event.App = app
event.Context = ctx
event.Type = ModelEventTypeUpdate
event.Model = model
saveErr := app.OnModelUpdate().Trigger(event, func(e *ModelEvent) error {
// run validations (if any)
if withValidations {
validateErr := e.App.ValidateWithContext(e.Context, e.Model)
if validateErr != nil {
return validateErr
}
}
// db write
return e.App.OnModelUpdateExecute().Trigger(event, func(e *ModelEvent) error {
var db dbx.Builder
if isForAuxDB {
db = e.App.AuxNonconcurrentDB()
} else {
db = e.App.NonconcurrentDB()
}
return baseLockRetry(func(attempt int) error {
if m, ok := e.Model.(DBExporter); ok {
data, err := m.DBExport(e.App)
if err != nil {
return err
}
// note: for now disallow primary key change for consistency with dbx.ModelQuery.Update()
if data[idColumn] != e.Model.LastSavedPK() {
return errors.New("primary key change is not allowed")
}
_, err = db.Update(e.Model.TableName(), data, dbx.HashExp{
idColumn: e.Model.LastSavedPK(),
}).WithContext(e.Context).Execute()
return err
}
return db.Model(e.Model).WithContext(e.Context).Update()
}, defaultMaxLockRetries)
})
})
if saveErr != nil {
errEvent := &ModelErrorEvent{ModelEvent: *event, Error: saveErr}
errEvent.App = app // replace with the initial app in case it was changed by the hook
hookErr := app.OnModelAfterUpdateError().Trigger(errEvent)
if hookErr != nil {
return errors.Join(saveErr, hookErr)
}
return saveErr
}
if app.txInfo != nil {
// execute later after the transaction has completed
app.txInfo.onAfterFunc(func(txErr error) error {
if app.txInfo != nil && app.txInfo.parent != nil {
event.App = app.txInfo.parent
}
if txErr != nil {
return app.OnModelAfterUpdateError().Trigger(&ModelErrorEvent{
ModelEvent: *event,
Error: txErr,
})
}
return app.OnModelAfterUpdateSuccess().Trigger(event)
})
} else if err := event.App.OnModelAfterUpdateSuccess().Trigger(event); err != nil {
return err
}
return nil
}
func validateCollectionId(app App, optTypes ...string) validation.RuleFunc {
return func(value any) error {
id, _ := value.(string)
if id == "" {
return nil
}
collection := &Collection{}
if err := app.ModelQuery(collection).Model(id, collection); err != nil {
return validation.NewError("validation_invalid_collection_id", "Missing or invalid collection.")
}
if len(optTypes) > 0 && !slices.Contains(optTypes, collection.Type) {
return validation.NewError(
"validation_invalid_collection_type",
fmt.Sprintf("Invalid collection type - must be %s.", strings.Join(optTypes, ", ")),
)
}
return nil
}
}
func validateRecordId(app App, collectionNameOrId string) validation.RuleFunc {
return func(value any) error {
id, _ := value.(string)
if id == "" {
return nil
}
collection, err := app.FindCachedCollectionByNameOrId(collectionNameOrId)
if err != nil {
return validation.NewError("validation_invalid_collection", "Missing or invalid collection.")
}
var exists bool
rowErr := app.DB().Select("(1)").
From(collection.Name).
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
Row(&exists)
if rowErr != nil || !exists {
return validation.NewError("validation_invalid_record", "Missing or invalid record.")
}
return nil
}
}