-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminidb.go
1484 lines (1395 loc) · 43 KB
/
minidb.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package minidb is a minimalist database. It stores items in tables, where each item has a fixed number of fields.
// The package has two APIs. The direct API is centered around MDB structures that represent database connections.
// Functions of MDB call directly the underlying database layer. The second API is slower and may be used
// for cases when commands and results have to be serialized. It uses Command structures that are created
// by functions like OpenCommand, AddTableCommand, etc. These are passed to Exec() which returns a Result
// structure that is populated with result values.
package minidb
import (
"database/sql"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
_ "github.com/mattn/go-sqlite3" // The driver for sqlite3 is pulled in.
)
// MDB is the main database object.
type MDB struct {
base *sql.DB
tx *Tx
driver string
location string
globalLock *sync.Mutex
}
// Tx represents a transaction similar to sql.Tx.
type Tx struct {
tx *sql.Tx
prev *Tx
mdb *MDB
savePoint uint
released bool
}
var savePointCounter uint
// Item is a database item. Fields and tables are identified by strings.
type Item int64
// FieldType is a field in the database, which might be a list type or a base type.
type FieldType int
const (
// DBError represents an error in a field definition.
DBError FieldType = iota + 1
// DBInt is the type of an int64 field.
DBInt
// DBString is the type of a string field.
DBString
// DBBlob is the type of a []byte field.
DBBlob
// DBIntList is the type of a list of int64 field.
DBIntList
// DBStringList is the type of a list of strings field.
DBStringList
// DBBlobList is the type of a list of []byte field, i.e., corresponding to [][]byte.
DBBlobList
// DBDate is the type of an RFC 3339 date field.
DBDate
// DBDateList is the type of a list of RFC 3339 dates field.
DBDateList
)
// ToBaseType converts a list type into the list's base type. A non-list type remains unchanged.
func ToBaseType(t FieldType) FieldType {
switch t {
case DBIntList:
return DBInt
case DBStringList:
return DBString
case DBBlobList:
return DBBlob
case DBDateList:
return DBDate
default:
return t
}
}
// Field represents a database field.
type Field struct {
Name string `json:"name"`
Sort FieldType `json:"sort"`
}
// Fail returns a new error message formatted with fmt.Sprintf.
func Fail(msg string, args ...interface{}) error {
return fmt.Errorf(msg, args...)
}
// Value holds the values that can be put into the database or retrieved from it.
type Value struct {
Str string `json:"str"`
Num int64 `json:"num"`
Sort FieldType `json:"sort"`
}
// Int returns the value as an int64 and panics if conversion is not possible
func (v *Value) Int() int64 {
switch v.Sort {
case DBInt:
return v.Num
default:
panic(fmt.Sprintf("cannot convert %s value to integer",
GetUserTypeString(v.Sort)))
}
}
// String returns the string value. It automatically converts int and blob,
// where binary Blob data is Base64 encoded and the int is converted
// to decimal format.
func (v *Value) String() string {
switch v.Sort {
case DBInt:
return fmt.Sprintf("%d", v.Num)
case DBString, DBDate:
return v.Str
case DBBlob:
return base64.StdEncoding.EncodeToString([]byte(v.Str))
default:
panic(fmt.Sprintf("cannot convert %s value to string",
GetUserTypeString(v.Sort)))
}
}
// Bytes returns the value as a bytes slice. It automatically converts int64 and string.
// An int64 is written in Little Endian format.
func (v *Value) Bytes() []byte {
switch v.Sort {
case DBInt:
bs := make([]byte, 8)
binary.LittleEndian.PutUint64(bs, uint64(v.Num))
return bs
case DBString, DBDate:
bs := []byte(v.Str)
return bs
case DBBlob:
bs := []byte(v.Str)
return bs
default:
panic(fmt.Sprintf("cannot convert %s value to bytes",
GetUserTypeString(v.Sort)))
}
}
// Datetime returns the time value and panics of no valid date is stored.
func (v *Value) Datetime() time.Time {
switch v.Sort {
case DBString, DBBlob, DBDate:
t, err := ParseTime(v.Str)
if err != nil {
panic(fmt.Sprintf("invalid datetime representation '%s'", v.Str))
}
return t
default:
panic(fmt.Sprintf("cannot convert %s value to date", GetUserTypeString(v.Sort)))
}
}
// NewInt creates a value that stores an int64.
func NewInt(n int64) Value {
return Value{Num: n, Sort: DBInt}
}
// NewString creates a value that stores a string.
func NewString(s string) Value {
return Value{Str: s, Sort: DBString}
}
// NewBytes creates a value that holds a []byte slice. This is similar to String() but notice
// that strings and byte slices are handled differently in the database. For example,
// byte slices may contain NULL characters and may be converted to and from Base64.
func NewBytes(b []byte) Value {
return Value{Str: string(b), Sort: DBBlob}
}
// NewDate create a value that holds a datetime.
func NewDate(t time.Time) Value {
return Value{Str: t.UTC().Format(time.RFC3339), Sort: DBDate}
}
// NewDateStr creates a value that holds a datetime given by a RFC3339 representation.
// The correctness of the date string is not validated, so use this function with care.
func NewDateStr(d string) Value {
return Value{Str: d, Sort: DBDate}
}
var validTable *regexp.Regexp
var validFieldName *regexp.Regexp
var validItemName *regexp.Regexp
func init() {
validTable = regexp.MustCompile(`^\p{L}+[_0-9\p{L}]*$`)
validFieldName = regexp.MustCompile(`^\p{L}+[_0-9\p{L}]*$`)
validItemName = regexp.MustCompile(`^\d+$`)
}
func isListFieldType(field FieldType) bool {
switch field {
case DBStringList, DBIntList, DBBlobList, DBDateList:
return true
default:
return false
}
}
func listFieldToTableName(ownerTable string, field string) string {
return "_" + ownerTable + "_" + field
}
func getTypeString(field FieldType) string {
switch field {
case DBString, DBStringList:
return "TEXT"
case DBBlob, DBBlobList:
return "BLOB"
case DBDate, DBDateList:
return "DATE"
default:
return "INTEGER"
}
}
// GetUserTypeString returns a user-readable string for the type of a field.
func GetUserTypeString(field FieldType) string {
switch field {
case DBString:
return "string"
case DBStringList:
return "string-list"
case DBInt:
return "int"
case DBIntList:
return "int-list"
case DBBlob:
return "blob"
case DBBlobList:
return "blob-list"
case DBDate:
return "date"
case DBDateList:
return "date-list"
default:
return "unknown"
}
}
func parseFieldType(ident string) (FieldType, error) {
s := strings.ToLower(ident)
switch s {
case "int", "integer":
return DBInt, nil
case "str", "string", "text", "txt":
return DBString, nil
case "blob":
return DBBlob, nil
case "date":
return DBDate, nil
case "string-list", "str-list", "text-list", "txt-list":
return DBStringList, nil
case "blob-list":
return DBBlobList, nil
case "int-list", "integer-list":
return DBIntList, nil
case "date-list":
return DBDateList, nil
}
return DBError,
Fail("Invalid field type '%s', should be one of int,string,blob,int-list,string-list,blob-list", ident)
}
// ParseFieldDesc parses the given string slice into a []Field slice based on
// the format "type name", or returns an error. This can be used for command line parsing.
func ParseFieldDesc(desc []string) ([]Field, error) {
result := make([]Field, 0)
if len(desc)%2 != 0 {
return nil, Fail("invalid field descriptions, they must be of the form <type> <fieldname>!")
}
if len(desc) == 0 {
return nil, Fail("no fields specified!")
}
for i := 0; i < len(desc)-1; i += 2 {
ftype, err := parseFieldType(desc[i])
if err != nil {
return nil, err
}
if !validFieldName.MatchString(desc[i+1]) {
return nil, Fail("invalid field name '%s'", desc[i+1])
}
if strings.ToLower(desc[i+1]) == "id" {
return nil, Fail("fields may not be called 'id'!")
}
result = append(result, Field{desc[i+1], ftype})
}
return result, nil
}
var errNilDB = Fail("db object is nil")
func (db *MDB) init() error {
if db.base == nil {
return errNilDB
}
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.tx.Exec(`CREATE TABLE IF NOT EXISTS _TABLES (Id INTEGER PRIMARY KEY,
Name TEXT NOT NULL)`)
if err != nil {
return err
}
_, err = tx.tx.Exec(`CREATE INDEX IF NOT EXISTS _TABIDX ON _TABLES (Name)`)
if err != nil {
return err
}
_, err = tx.tx.Exec(`CREATE TABLE IF NOT EXISTS _COLS (Id INTEGER PRIMARY KEY,
Name STRING NOT NULL,
FieldType INTEGER NOT NULL,
Owner INTEGER NOT NULL,
FOREIGN KEY(Owner) REFERENCES _TABLES(Id))`)
if err != nil {
return err
}
_, err = tx.tx.Exec(`CREATE TABLE IF NOT EXISTS _KVINT (Id INTEGER PRIMARY KEY NOT NULL, Value INTEGER NOT NULL)`)
if err != nil {
return err
}
_, err = tx.tx.Exec(`CREATE TABLE IF NOT EXISTS _KVSTR (Id INTEGER PRIMARY KEY NOT NULL, Value TEXT NOT NULL)`)
if err != nil {
return err
}
_, err = tx.tx.Exec(`CREATE TABLE IF NOT EXISTS _KVBLOB (Id INTEGER PRIMARY KEY NOT NULL, Value BLOB NOT NULL)`)
if err != nil {
return err
}
_, err = tx.tx.Exec(`CREATE TABLE IF NOT EXISTS _KVDATE (Id INTEGER PRIMARY KEY NOT NULL, Value TEXT NOT NULL)`)
if err != nil {
return err
}
return tx.Commit()
}
// Open creates or opens a minidb.
func Open(driver string, file string) (*MDB, error) {
db := new(MDB)
base, err := sql.Open(driver, file)
if err != nil {
return nil, err
}
if base == nil {
return nil, errNilDB
}
db.globalLock = &sync.Mutex{}
db.base = base
db.driver = driver
db.location = file
if err := db.init(); err != nil {
return nil, Fail("cannot initialize database: %s", err)
}
return db, nil
}
// Backup a database and return the original opened, not the backed up database.
// The new MDB pointer needs to be used after this method unless an error
// has occurred since the old one might have become invalid.
// This function may result in a corrupt copy if the database is open by another
// process, so you need to make sure that it isn't.
func (db *MDB) Backup(destination string) error {
if db.base == nil {
return Fail("the database must be open to back it up, this one is closed")
}
// use manual copy for now (should use sqlite3 backup API for sqlite3)
src := db.location
driver := db.driver
db.Close()
sourceFileStat, err := os.Stat(src)
if err != nil {
return err
}
if !sourceFileStat.Mode().IsRegular() {
return fmt.Errorf("backup: %s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
dest, err := os.Create(destination)
if err != nil {
return err
}
defer dest.Close()
_, err = io.Copy(dest, source)
if err != nil {
return err
}
newdb, err := Open(driver, src)
if err != nil {
return err
}
db = newdb
return err
}
// Close closes the database, making sure that all remaining transactions are finished.
func (db *MDB) Close() error {
if db.base != nil {
_, _ = db.base.Exec(`PRAGMA optimize;`)
err := db.base.Close()
if err != nil {
return Fail("ERROR Failed to close database - %s.\n", err)
}
db.driver = ""
db.location = ""
db.globalLock = nil
}
return nil
}
// Base returns the base sqlx.DB that minidb uses for its underlying storage.
func (db *MDB) Base() *sql.DB {
return db.base
}
// Begin starts a transaction.
func (db *MDB) Begin() (*Tx, error) {
if db.globalLock == nil {
return nil, errors.New("attempt to open a transaction on a closed DB")
}
db.globalLock.Lock()
defer db.globalLock.Unlock()
if db.tx == nil {
//fmt.Println("*** new real transaction")
sqltx, err := db.base.Begin()
if err != nil {
return nil, err
}
tx := &Tx{
tx: sqltx,
mdb: db,
}
db.tx = tx
return tx, nil
}
savePointCounter++
tx := &Tx{
tx: db.tx.tx,
mdb: db,
prev: db.tx,
savePoint: savePointCounter,
}
db.tx = tx
_, err := db.tx.tx.Exec(fmt.Sprintf("SAVEPOINT SP%d;", tx.savePoint))
//fmt.Printf("*** New savepoint SP%d\n", savePoint)
if err != nil {
return nil, fmt.Errorf("minidb begin transaction failed, %s", err)
}
return tx, nil
}
// Commit the changes to the database.
func (tx *Tx) Commit() error {
if tx.mdb.globalLock == nil {
return errors.New("attempt to commit a transaction of a closed DB")
}
tx.mdb.globalLock.Lock()
defer tx.mdb.globalLock.Unlock()
tx.mdb.tx = tx.prev
if tx.prev == nil {
//fmt.Println("*** real commit")
return tx.tx.Commit()
}
if tx.released {
return errors.New("nested transaction has already been rolled back or commmitted")
}
_, err := tx.tx.Exec(fmt.Sprintf("RELEASE SP%d;", tx.savePoint))
if err != nil {
return fmt.Errorf("minidb commit transaction failed, %s", err)
}
//fmt.Printf("*** release savepoint SP%d\n", savePoint)
tx.released = true
return nil
}
// Rollback the changes in the database.
func (tx *Tx) Rollback() error {
if tx.mdb.globalLock == nil {
return errors.New("attempt to rollback a transaction of a closed DB")
}
tx.mdb.globalLock.Lock()
defer tx.mdb.globalLock.Unlock()
if tx.released {
//fmt.Println("*** rollback after savepoint release (do nothing)")
return nil
}
tx.mdb.tx = tx.prev
tx.released = true
if tx.prev == nil {
//fmt.Println("*** real rollback")
return tx.tx.Rollback()
}
//fmt.Printf("*** rollback to savepoint SP%d\n", savePoint)
_, err := tx.tx.Exec(fmt.Sprintf("ROLLBACK TO SP%d", tx.savePoint))
if err != nil {
return fmt.Errorf("minidb rollback transaction failed, %s", err)
}
return nil
}
// TableExists returns true if the table exists, false otherwise.
func (db *MDB) TableExists(table string) bool {
var result int
err := db.base.QueryRow(`SELECT EXISTS (SELECT 1 FROM _TABLES WHERE Name=? LIMIT 1)`, table).Scan(&result)
switch {
case err == sql.ErrNoRows:
return false
case err != nil:
return false
default:
return result > 0
}
}
// FieldIsNull returns true if the field is null for the item in the table, false otherwise.
func (db *MDB) FieldIsNull(table string, item Item, field string) bool {
var result int
err := db.base.QueryRow(fmt.Sprintf(`SELECT EXISTS (SELECT 1 FROM "%s" WHERE ? IS NULL and Id=?);`, table), field, item).Scan(&result)
if err != nil {
return false
}
return result == 0
}
// FieldIsEmpty returns true if the field is null or empty, false otherwise.
func (db *MDB) FieldIsEmpty(table string, item Item, field string) bool {
if db.FieldIsNull(table, item, field) {
return true
}
var result int
err := db.base.QueryRow(fmt.Sprintf(`SELECT EXISTS (SELECT 1 FROM "%s" WHERE ?='' and Id=?)`, table), field, item).Scan(&result)
if err != nil {
return false
}
return result == 0
}
// ItemExists returns true if the item exists in the table, false otherwise.
func (db *MDB) ItemExists(table string, item Item) bool {
var result int
err := db.base.QueryRow(fmt.Sprintf(`SELECT EXISTS (SELECT 1 FROM "%s" WHERE Id=? LIMIT 1)`, table), item).Scan(&result)
if err != nil {
return false
}
return result > 0
}
// IsListField is true if the field in the table is a list, false otherwise.
// List fields are internally stored as special tables.
func (db *MDB) IsListField(table string, field string) bool {
return db.TableExists(listFieldToTableName(table, field))
}
// IsEmptyListField returns true if the field is a list field and has no element matching item.
// If the item does not exist, the function returns true as well.
func (db *MDB) IsEmptyListField(table string, item Item, field string) bool {
var result int
if !db.IsListField(table, field) {
return false
}
err := db.base.QueryRow(fmt.Sprintf(`SELECT EXISTS (SELECT 1 FROM "%s" WHERE Owner=? AND %s IS NOT NULL LIMIT 1)`, table, field), item).Scan(&result)
if err != nil {
return true
}
return result == 0
}
func (db *MDB) getTableId(table string) (int64, error) {
var result int64
err := db.base.QueryRow(`SELECT Id FROM _TABLES WHERE Name=?`, table).Scan(&result)
if err != nil {
return 0, err
}
return result, nil
}
// FieldExists returns true if the table has the field, false otherwise.
func (db *MDB) FieldExists(table string, field string) bool {
var result int
id, err := db.getTableId(table)
if err != nil {
return false
}
err = db.base.QueryRow(`SELECT EXISTS (SELECT 1 FROM _COLS WHERE Owner=? AND Name=? LIMIT 1)`, id, field).Scan(&result)
if err != nil {
fmt.Println(err)
return false
}
return result > 0
}
// MustGetFieldType returns the type of the field. This method panics if the table or field don't exist.
func (db *MDB) MustGetFieldType(table string, field string) FieldType {
id, _ := db.getTableId(table)
var result int64
db.base.QueryRow(`SELECT FieldType FROM _COLS WHERE Owner=? AND Name=? LIMIT 1;`, id, field).Scan(&result)
return FieldType(result)
}
// ParseFieldValues parses potential value(s) for a field from strings, returns an error if their type is
// incompatible with the field type, the table or field don't exist, or if the input is empty.
// Data for a Blob field must be Base64 encoded, data for an Integer field must be a valid
// digit sequence for a 64 bit integer in base 10 format.
func (db *MDB) ParseFieldValues(table string, field string, data []string) ([]Value, error) {
if !validTable.MatchString(table) {
return nil, Fail("invalid table name '%s'", table)
}
if !db.TableExists(table) {
return nil, Fail("table '%s' does not exist", table)
}
if !db.FieldExists(table, field) {
return nil, Fail("field '%s' does not exist in table '%s'", field, table)
}
if len(data) == 0 {
return nil, Fail("no input values given")
}
if !db.IsListField(table, field) && len(data) > 1 {
return nil, Fail("too many input values: expected 1, given %d", len(data))
}
t := ToBaseType(db.MustGetFieldType(table, field))
result := make([]Value, 0, len(data))
for i := range data {
switch t {
case DBInt:
j, err := strconv.ParseInt(data[i], 10, 64)
if err != nil {
return nil, Fail("type error: expected int, given '%s'", data[i])
}
result = append(result, NewInt(j))
case DBBlob:
b, err := base64.StdEncoding.DecodeString(data[i])
if err != nil {
return nil, Fail("type error: expected binary data in Base64 format but the given data seems invalid")
}
result = append(result, NewBytes(b))
case DBString:
result = append(result, NewString(data[i]))
case DBDate:
var t time.Time
var err error
if t, err = ParseTime(data[i]); err != nil {
return nil, Fail("type error: expected datetime in RFC3339 format - %s", err)
}
result = append(result, NewDate(t))
default:
return nil,
Fail("internal error: %s %s expects type %d, which is unknown to this version of minidb",
table, field, t)
}
}
return result, nil
}
// ParseTime parses a time string in RFC3339 format and returns the time or an error if
// the format is wrong.
func ParseTime(s string) (time.Time, error) {
t, err := time.ParseInLocation(time.RFC3339, s, time.Now().Local().Location())
if err == nil {
return t, nil
}
return t, Fail("invalid date format '%s'", s)
}
// AddTable is used to create a new table. Table and field names are validated. They need to be alphanumeric
// sequences plus underscore "_" as the only allowed special character. None of the names may start with
// an underscore.
func (db *MDB) AddTable(table string, fields []Field) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if !validTable.MatchString(table) {
return Fail("invalid table name '%s'", table)
}
// normal fields are just columns
toExec := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS "%s" (Id INTEGER PRIMARY KEY`, table)
for _, field := range fields {
if !isListFieldType(field.Sort) {
toExec += fmt.Sprintf(",\n\"%s\" %s", field.Name, getTypeString(field.Sort))
}
}
toExec += ");"
_, err = tx.tx.Exec(toExec)
if err != nil {
return Fail("cannot create maintenance table: %s", err)
}
// list fields are composite tables with name _Basetable_Fieldname
for _, field := range fields {
if isListFieldType(field.Sort) {
toExec = fmt.Sprintf(`CREATE TABLE IF NOT EXISTS "%s" (Id INTEGER PRIMARY KEY,
Owner INTEGER NOT NULL,
%s %s,
FOREIGN KEY(Owner) REFERENCES %s(Id))`, listFieldToTableName(table, field.Name),
field.Name,
getTypeString(field.Sort),
table)
_, err = tx.tx.Exec(toExec)
if err != nil {
return Fail("cannot create list field %s in table %s: %s", field.Name, table, err)
}
}
}
// update the internal housekeeping tables
toExec = "INSERT OR IGNORE INTO _TABLES (Name) VALUES (?)"
result, err := tx.tx.Exec(toExec, table)
if err != nil {
return Fail("Failed to update maintenance table: %s", err)
}
tableID, err := result.LastInsertId()
if err != nil {
return Fail("failed to update maintenance table: %s", err)
}
for _, field := range fields {
_, err := tx.tx.Exec(`INSERT INTO _COLS (Name,FieldType,Owner) VALUES (?,?,?)`, field.Name, field.Sort, tableID)
if err != nil {
return Fail("cannot insert maintenance field %s for table %s: %s",
field.Name, table, err)
}
if isListFieldType(field.Sort) {
_, err = tx.tx.Exec(`INSERT INTO _TABLES (Name) VALUES (?)`, listFieldToTableName(table, field.Name))
}
if err != nil {
return Fail("cannot insert maintenance list table %s for table %s: %s",
listFieldToTableName(table, field.Name), table, err)
}
}
return tx.Commit()
}
// Index creates an index for field in table unless the index exists already.
// An index increases the search speed of certain string queries on the field, such as "Person name=joh%".
func (tx *Tx) Index(table, field string) error {
if !validTable.MatchString(table) {
return Fail("invalid table name '%s'", table)
}
if !tx.mdb.FieldExists(table, field) {
return Fail("field '%s' does not exist in table '%s'", field, table)
}
var realtable string
if tx.mdb.IsListField(table, field) {
realtable = listFieldToTableName(table, field)
} else {
realtable = table
}
indexName := field + "_" + realtable + "_IDX"
_, err := tx.tx.Exec(fmt.Sprintf(`CREATE INDEX IF NOT EXISTS %s ON %s(%s);`, indexName, realtable, field))
if err != nil {
return Fail("failed to create index for field '%s' in table '%s': %s", field, table, err)
}
return nil
}
// NewItem creates a new item in the table and returns its numerical ID.
func (db *MDB) NewItem(table string) (Item, error) {
if !validTable.MatchString(table) {
return 0, Fail("invalid table name '%s'", table)
}
if !db.TableExists(table) {
return 0, Fail("table '%s' does not exist", table)
}
toExec := fmt.Sprintf("INSERT INTO %s DEFAULT VALUES;", table)
result, err := db.base.Exec(toExec)
if err != nil {
return 0, err
}
id, err := result.LastInsertId()
if err != nil {
return 0, err
}
return Item(id), nil
}
// UseItem creates a new item with the given ID or returns the item with the given ID
// if it already exists. This may be used when fixed IDs are needed, but should be avoided
// when these are not strictly necessary.
func (db *MDB) UseItem(table string, id uint64) (Item, error) {
if !validTable.MatchString(table) {
return 0, Fail("invalid table name '%s'", table)
}
if !db.TableExists(table) {
return 0, Fail("table '%s' does not exist", table)
}
if db.ItemExists(table, Item(id)) {
return Item(id), nil
}
toExec := fmt.Sprintf("INSERT INTO %s(Id) VALUES (?);", table)
_, err := db.base.Exec(toExec, id)
if err != nil {
return 0, err
}
return Item(id), nil
}
// RemoveItem remove an item from the table.
func (tx *Tx) RemoveItem(table string, item Item) error {
if !validTable.MatchString(table) {
return Fail(`invalid table name "%s"`, table)
}
if !tx.mdb.TableExists(table) {
return Fail("table '%s' does not exist", table)
}
if tx.mdb.ItemExists(table, item) {
_, err := tx.tx.Exec(fmt.Sprintf(`DELETE FROM %s WHERE Id=?;`, table), item)
if err != nil {
return Fail(`error while deleting %s %d`, table, item)
}
}
return nil
}
// Count returns the number of items in the table.
func (db *MDB) Count(table string) (int64, error) {
if !validTable.MatchString(table) {
return 0, Fail("invalid table name '%s'", table)
}
if !db.TableExists(table) {
return 0, Fail("table '%s' does not exist", table)
}
var result int64
err := db.base.QueryRow(fmt.Sprintf(`SELECT COUNT(*) FROM %s;`, table)).Scan(&result)
if err != nil {
return 0, err
}
return result, nil
}
// ListItems returns a list of items in the table.
func (db *MDB) ListItems(table string, limit int64) ([]Item, error) {
empty := make([]Item, 0)
if !validTable.MatchString(table) {
return empty, Fail("invalid table name '%s'", table)
}
if !db.TableExists(table) {
return empty, Fail("table '%s' does not exist", table)
}
rows, err := db.base.Query(fmt.Sprintf(`SELECT (Id) FROM %s;`, table))
if err != nil {
return empty, err
}
defer rows.Close()
results := make([]Item, 0)
var c int64
for rows.Next() {
var datum sql.NullInt64
if err := rows.Scan(&datum); err == nil && datum.Valid {
results = append(results, Item(datum.Int64))
}
c++
if limit > 0 && c >= limit {
break
}
}
return results, nil
}
// Get returns the value(s) of a field of an item in a table.
func (db *MDB) Get(table string, item Item, field string) ([]Value, error) {
if !validTable.MatchString(table) {
return nil, Fail("invalid table name '%s'", table)
}
if !db.TableExists(table) {
return nil, Fail("table '%s' does not exist", table)
}
if !db.ItemExists(table, item) {
return nil, Fail("no %s %d", table, item)
}
if db.IsListField(table, field) {
return db.getListField(table, item, field)
}
return db.getSingleField(table, item, field)
}
func (db *MDB) getSingleField(table string, item Item, field string) ([]Value, error) {
if !db.FieldExists(table, field) {
return nil,
Fail(`no field %s in table %s`, field, table)
}
t := db.MustGetFieldType(table, field)
row := db.base.QueryRow(fmt.Sprintf(`SELECT "%s" FROM "%s" WHERE Id=?;`, field, table), item)
var intResult sql.NullInt64
var strResult sql.NullString
var err error
switch t {
case DBInt:
err = row.Scan(&intResult)
case DBString, DBBlob, DBDate:
err = row.Scan(&strResult)
default:
return nil,
Fail("unsupported field type for %s %d %s: %d (try a newer version?)", table, item, field, int(t))
}
if err == sql.ErrNoRows {
return nil,
Fail("no value for %s %d %s", table, item, field)
}
if err != nil {
return nil,
Fail("cannot find value for %s %d %s: %s", table, item, field, err)
}
vslice := make([]Value, 1)
switch t {
case DBInt:
if !intResult.Valid {
return nil,
Fail("no int value for %s %d %s", table, item, field)
}
vslice[0] = NewInt(intResult.Int64)
case DBString, DBBlob, DBDate:
if !strResult.Valid {
return nil,
Fail("no string, blob, or date value for %s %d %s", table, item, field)
}
vslice[0] = NewString(strResult.String)
vslice[0].Sort = t
}
return vslice, nil
}
func (db *MDB) getListField(table string, item Item, field string) ([]Value, error) {
tableName := listFieldToTableName(table, field)
if !db.TableExists(tableName) {
return nil,
Fail("list field %s does not exist in table %s", field, table)
}
if db.IsEmptyListField(tableName, item, field) {
return nil,
Fail("no values for %s %d %s", table, item, field)
}
t := db.MustGetFieldType(table, field)
rows, err := db.base.Query(fmt.Sprintf(`SELECT "%s" FROM "%s" WHERE Owner=?`, field, tableName), item)
if err != nil {
return nil,
Fail("cannot find values for %s %d %s: %s", table, item, field, err)
}
defer rows.Close()
results := make([]Value, 0)
var intResult sql.NullInt64
var strResult sql.NullString
for rows.Next() {
switch t {
case DBInt, DBIntList:
if err := rows.Scan(&intResult); err != nil {
return nil,
Fail("cannot find int values for %s %d %s: %s", table, item, field, err)
}
if !intResult.Valid {
return nil, Fail("no int value for %s %d %s", table, item, field)
}
results = append(results, NewInt(intResult.Int64))
case DBString, DBStringList:
if err := rows.Scan(&strResult); err != nil {
return nil,
Fail("cannot find string values for %s %d %s: %s", table, item, field, err)
}
if !strResult.Valid {
return nil,
Fail("no string value for %s %d %s", table, item, field)
}
results = append(results, NewString(strResult.String))
case DBBlob, DBBlobList:
if err := rows.Scan(&strResult); err != nil {
return nil,
Fail("cannot find string values for %s %d %s: %s", table, item, field, err)
}
if !strResult.Valid {
return nil,
Fail("no string value for %s %d %s", table, item, field)
}
b := []byte(strResult.String)
results = append(results, NewBytes(b))
case DBDate, DBDateList:
if err := rows.Scan(&strResult); err != nil {
return nil, Fail("cannot find date values for %s %d %s: %s", table, item, field, err)
}
if !strResult.Valid {