-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
101 lines (85 loc) · 2.09 KB
/
schema.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
// Copyright (c) 2021, David Url
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ttt
import (
"database/sql"
)
type schemaPatch []string
func initSchema(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for _, stmt := range baseSchema() {
_, err := tx.Exec(stmt)
if err != nil {
return err
}
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func applySchema(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
revRow := tx.QueryRow(selectRevisionStmt)
var dbRev int
err = revRow.Scan(&dbRev)
if err != nil {
return err
}
for rev, patch := range schemaPatches() {
if rev > dbRev {
for _, stmt := range patch {
_, err := tx.Exec(stmt)
if err != nil {
return err
}
}
_, err = tx.Exec(updateRevisionStmt, rev)
if err != nil {
return err
}
}
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
const (
selectRevisionStmt = "SELECT revision FROM schema_version;"
updateRevisionStmt = "UPDATE schema_version SET revision=?, dts=datetime('now');"
)
func baseSchema() schemaPatch {
return schemaPatch{
"CREATE TABLE schema_version (revision int, dts datetime);",
"INSERT INTO schema_version VALUES(-1, datetime('now'));",
}
}
func schemaPatches() []schemaPatch {
return []schemaPatch{
{
"CREATE TABLE config (property text, value text);",
"INSERT INTO config VALUES('break_threshold', '6h'), ('break_deduction', '30m');",
"INSERT INTO config VALUES('monday_hours', '7h 42m');",
"INSERT INTO config VALUES('tuesday_hours', '7h 42m');",
"INSERT INTO config VALUES('wednesday_hours', '7h 42m');",
"INSERT INTO config VALUES('thursday_hours', '7h 42m');",
"INSERT INTO config VALUES('friday_hours', '7h 42m');",
"INSERT INTO config VALUES('saturday_hours', '0h');",
"INSERT INTO config VALUES('sunday_hours', '0h');",
"INSERT INTO config VALUES('holidays', 'AT');",
"CREATE TABLE records (start datetime, end datetime, absence text);",
},
}
}