forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1690319366_reset_null_values.go
58 lines (49 loc) · 1.19 KB
/
1690319366_reset_null_values.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
package migrations
import (
"fmt"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/models/schema"
)
// Reset all previously inserted NULL values to the fields zero-default.
func init() {
AppMigrations.Register(func(db dbx.Builder) error {
dao := daos.New(db)
collections := []*models.Collection{}
if err := dao.CollectionQuery().All(&collections); err != nil {
return err
}
for _, collection := range collections {
if collection.IsView() {
continue
}
for _, f := range collection.Schema.Fields() {
defaultVal := "''"
switch f.Type {
case schema.FieldTypeJson:
continue
case schema.FieldTypeBool:
defaultVal = "FALSE"
case schema.FieldTypeNumber:
defaultVal = "0"
default:
if opt, ok := f.Options.(schema.MultiValuer); ok && opt.IsMultiple() {
defaultVal = "'[]'"
}
}
_, err := db.NewQuery(fmt.Sprintf(
"UPDATE {{%s}} SET [[%s]] = %s WHERE [[%s]] IS NULL",
collection.Name,
f.Name,
defaultVal,
f.Name,
)).Execute()
if err != nil {
return err
}
}
}
return nil
}, nil)
}