-
Notifications
You must be signed in to change notification settings - Fork 918
/
open.go
55 lines (46 loc) · 1.31 KB
/
open.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
package node
import (
"context"
"database/sql"
"fmt"
"path/filepath"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/logger"
)
// Open the node-local database object.
func Open(dir string) (*sql.DB, error) {
path := filepath.Join(dir, "local.db")
db, err := sqliteOpen(path)
if err != nil {
return nil, fmt.Errorf("cannot open node database: %w", err)
}
return db, nil
}
// EnsureSchema applies all relevant schema updates to the node-local
// database.
//
// Return the initial schema version found before starting the update, along
// with any error occurred.
func EnsureSchema(db *sql.DB, dir string) (int, error) {
backupDone := false
schema := Schema()
schema.File(filepath.Join(dir, "patch.local.sql")) // Optional custom queries
schema.Hook(func(ctx context.Context, version int, tx *sql.Tx) error {
if !backupDone {
logger.Infof("Updating the LXD database schema. Backup made as \"local.db.bak\"")
path := filepath.Join(dir, "local.db")
err := shared.FileCopy(path, path+".bak")
if err != nil {
return err
}
backupDone = true
}
if version == -1 {
logger.Debugf("Running pre-update queries from file for local DB schema")
} else {
logger.Debugf("Updating DB schema from %d to %d", version, version+1)
}
return nil
})
return schema.Ensure(db)
}