-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.go
1202 lines (1041 loc) · 32.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
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 duckdbreplicator
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log/slog"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/XSAM/otelsql"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/marcboeker/go-duckdb"
"github.com/mitchellh/mapstructure"
"go.opentelemetry.io/otel/attribute"
"gocloud.dev/blob"
)
type DB interface {
// Close closes the database.
Close() error
// AcquireReadConnection returns a connection to the database for reading.
// Once done the connection should be released by calling the release function.
// This connection must only be used for select queries or for creating and working with temporary tables.
AcquireReadConnection(ctx context.Context) (conn Conn, release func() error, err error)
// AcquireWriteConnection returns a connection to the database for writing.
// Once done the connection should be released by calling the release function.
// Any persistent changes to the database should be done by calling CRUD APIs on this connection.
AcquireWriteConnection(ctx context.Context) (conn Conn, release func() error, err error)
// Size returns the size of the database in bytes.
// It is currently implemented as sum of the size of all serving `.db` files.
Size() int64
// CRUD APIs
// CreateTableAsSelect creates a new table by name from the results of the given SQL query.
CreateTableAsSelect(ctx context.Context, name string, sql string, opts *CreateTableOptions) error
// InsertTableAsSelect inserts the results of the given SQL query into the table.
InsertTableAsSelect(ctx context.Context, name string, sql string, opts *InsertTableOptions) error
// DropTable removes a table from the database.
DropTable(ctx context.Context, name string) error
// RenameTable renames a table in the database.
RenameTable(ctx context.Context, oldName, newName string) error
// AddTableColumn adds a column to the table.
AddTableColumn(ctx context.Context, tableName, columnName, typ string) error
// AlterTableColumn alters the type of a column in the table.
AlterTableColumn(ctx context.Context, tableName, columnName, newType string) error
}
type DBOptions struct {
// Clean specifies whether to start with a clean database or download data from cloud storage and start with backed up data.
Clean bool
// LocalPath is the path where local db files will be stored. Should be unique for each database.
LocalPath string
BackupProvider *BackupProvider
// ReadSettings are settings applied the read duckDB handle.
ReadSettings map[string]string
// WriteSettings are settings applied the write duckDB handle.
WriteSettings map[string]string
// InitQueries are the queries to run when the database is first created.
InitQueries []string
Logger *slog.Logger
}
// TODO :: revisit this logic
func (d *DBOptions) ValidateSettings() error {
read := &settings{}
err := mapstructure.Decode(d.ReadSettings, read)
if err != nil {
return fmt.Errorf("read settings: %w", err)
}
write := &settings{}
err = mapstructure.Decode(d.WriteSettings, write)
if err != nil {
return fmt.Errorf("write settings: %w", err)
}
// no memory limits defined
// divide memory equally between read and write
if read.MaxMemory == "" && write.MaxMemory == "" {
connector, err := duckdb.NewConnector("", nil)
if err != nil {
return fmt.Errorf("unable to create duckdb connector: %w", err)
}
defer connector.Close()
db := sql.OpenDB(connector)
defer db.Close()
row := db.QueryRow("SELECT value FROM duckdb_settings() WHERE name = 'max_memory'")
var maxMemory string
err = row.Scan(&maxMemory)
if err != nil {
return fmt.Errorf("unable to get max_memory: %w", err)
}
bytes, err := humanReadableSizeToBytes(maxMemory)
if err != nil {
return fmt.Errorf("unable to parse max_memory: %w", err)
}
read.MaxMemory = fmt.Sprintf("%d bytes", int64(bytes)/2)
write.MaxMemory = fmt.Sprintf("%d bytes", int64(bytes)/2)
}
if read.MaxMemory == "" != (write.MaxMemory == "") {
// only one is defined
var mem string
if read.MaxMemory != "" {
mem = read.MaxMemory
} else {
mem = write.MaxMemory
}
bytes, err := humanReadableSizeToBytes(mem)
if err != nil {
return fmt.Errorf("unable to parse max_memory: %w", err)
}
read.MaxMemory = fmt.Sprintf("%d bytes", int64(bytes)/2)
write.MaxMemory = fmt.Sprintf("%d bytes", int64(bytes)/2)
}
var readThread, writeThread int
if read.Threads != "" {
readThread, err = strconv.Atoi(read.Threads)
if err != nil {
return fmt.Errorf("unable to parse read threads: %w", err)
}
}
if write.Threads != "" {
writeThread, err = strconv.Atoi(write.Threads)
if err != nil {
return fmt.Errorf("unable to parse write threads: %w", err)
}
}
if readThread == 0 && writeThread == 0 {
connector, err := duckdb.NewConnector("", nil)
if err != nil {
return fmt.Errorf("unable to create duckdb connector: %w", err)
}
defer connector.Close()
db := sql.OpenDB(connector)
defer db.Close()
row := db.QueryRow("SELECT value FROM duckdb_settings() WHERE name = 'threads'")
var threads int
err = row.Scan(&threads)
if err != nil {
return fmt.Errorf("unable to get threads: %w", err)
}
read.Threads = strconv.Itoa((threads + 1) / 2)
write.Threads = strconv.Itoa(threads / 2)
}
if readThread == 0 != (writeThread == 0) {
// only one is defined
var threads int
if readThread != 0 {
threads = readThread
} else {
threads = writeThread
}
read.Threads = strconv.Itoa((threads + 1) / 2)
write.Threads = strconv.Itoa(threads / 2)
}
err = mapstructure.WeakDecode(read, &d.ReadSettings)
if err != nil {
return fmt.Errorf("failed to update read settings: %w", err)
}
err = mapstructure.WeakDecode(write, &d.WriteSettings)
if err != nil {
return fmt.Errorf("failed to update write settings: %w", err)
}
return nil
}
type CreateTableOptions struct {
// View specifies whether the created table is a view.
View bool
}
type IncrementalStrategy string
const (
IncrementalStrategyUnspecified IncrementalStrategy = ""
IncrementalStrategyAppend IncrementalStrategy = "append"
IncrementalStrategyMerge IncrementalStrategy = "merge"
)
type InsertTableOptions struct {
ByName bool
Strategy IncrementalStrategy
UniqueKey []string
}
// NewDB creates a new DB instance.
// This can be a slow operation if the backup is large.
// dbIdentifier is a unique identifier for the database reported in metrics.
func NewDB(ctx context.Context, dbIdentifier string, opts *DBOptions) (DB, error) {
if dbIdentifier == "" {
return nil, fmt.Errorf("db identifier cannot be empty")
}
err := opts.ValidateSettings()
if err != nil {
return nil, err
}
db := &db{
dbIdentifier: dbIdentifier,
opts: opts,
readPath: filepath.Join(opts.LocalPath, "read"),
writePath: filepath.Join(opts.LocalPath, "write"),
writeDirty: true,
logger: opts.Logger,
}
if opts.BackupProvider != nil {
db.backup = opts.BackupProvider.bucket
}
// if clean is true, remove the backup
if opts.Clean {
err = db.deleteBackup(ctx, "", "")
if err != nil {
return nil, fmt.Errorf("unable to clean backup: %w", err)
}
}
// create read and write paths
err = os.MkdirAll(db.readPath, fs.ModePerm)
if err != nil {
return nil, fmt.Errorf("unable to create read path: %w", err)
}
err = os.MkdirAll(db.writePath, fs.ModePerm)
if err != nil {
return nil, fmt.Errorf("unable to create write path: %w", err)
}
// sync write path
err = db.syncWrite(ctx)
if err != nil {
return nil, err
}
// sync read path
err = db.syncRead(ctx)
if err != nil {
return nil, err
}
// create read handle
db.readHandle, err = db.openDBAndAttach(ctx, true)
if err != nil {
if strings.Contains(err.Error(), "Symbol not found") {
fmt.Printf("Your version of macOS is not supported. Please upgrade to the latest major release of macOS. See this link for details: https://support.apple.com/en-in/macos/upgrade")
os.Exit(1)
}
return nil, err
}
return db, nil
}
type db struct {
dbIdentifier string
opts *DBOptions
readHandle *sqlx.DB
readPath string
writePath string
readMu sync.RWMutex
writeMu sync.Mutex
writeDirty bool
backup *blob.Bucket
logger *slog.Logger
}
var _ DB = &db{}
func (d *db) Close() error {
d.writeMu.Lock()
defer d.writeMu.Unlock()
d.readMu.Lock()
defer d.readMu.Unlock()
return d.readHandle.Close()
}
func (d *db) AcquireReadConnection(ctx context.Context) (Conn, func() error, error) {
d.readMu.RLock()
c, err := d.readHandle.Connx(ctx)
if err != nil {
d.readMu.RUnlock()
return nil, nil, err
}
return &conn{
Conn: c,
db: d,
}, func() error {
err = c.Close()
d.readMu.RUnlock()
return err
}, nil
}
func (d *db) AcquireWriteConnection(ctx context.Context) (Conn, func() error, error) {
d.writeMu.Lock()
defer d.writeMu.Unlock()
c, release, err := d.acquireWriteConn(ctx)
if err != nil {
return nil, nil, err
}
return &conn{
Conn: c,
db: d,
}, release, nil
}
func (d *db) CreateTableAsSelect(ctx context.Context, name, query string, opts *CreateTableOptions) error {
if opts == nil {
opts = &CreateTableOptions{}
}
d.logger.Debug("create table", slog.String("name", name), slog.Bool("view", opts.View))
d.writeMu.Lock()
defer d.writeMu.Unlock()
conn, release, err := d.acquireWriteConn(ctx)
if err != nil {
return err
}
defer func() {
_ = release()
}()
return d.createTableAsSelect(ctx, conn, release, name, query, opts)
}
func (d *db) createTableAsSelect(ctx context.Context, conn *sqlx.Conn, releaseConn func() error, name, query string, opts *CreateTableOptions) error {
// check if some older version exists
oldVersion, oldVersionExists, _ := tableVersion(d.writePath, name)
d.logger.Debug("old version", slog.String("version", oldVersion), slog.Bool("exists", oldVersionExists))
// create new version directory
newVersion := newVersion()
newVersionDir := filepath.Join(d.writePath, name, newVersion)
err := os.MkdirAll(newVersionDir, fs.ModePerm)
if err != nil {
return fmt.Errorf("create: unable to create dir %q: %w", name, err)
}
var m meta
if opts.View {
// create view - validates that SQL is correct
_, err = conn.ExecContext(ctx, fmt.Sprintf("CREATE OR REPLACE VIEW %s AS (%s\n)", safeSQLName(name), query))
if err != nil {
return err
}
m = meta{ViewSQL: query}
} else {
// create db file
dbFile := filepath.Join(newVersionDir, "data.db")
safeDBName := safeSQLName(dbName(name))
// detach existing db
_, err = conn.ExecContext(ctx, fmt.Sprintf("DETACH DATABASE IF EXISTS %s", safeDBName), nil)
if err != nil {
_ = os.RemoveAll(newVersionDir)
return fmt.Errorf("create: detach %q db failed: %w", safeDBName, err)
}
// attach new db
_, err = conn.ExecContext(ctx, fmt.Sprintf("ATTACH %s AS %s", safeSQLString(dbFile), safeDBName), nil)
if err != nil {
_ = os.RemoveAll(newVersionDir)
return fmt.Errorf("create: attach %q db failed: %w", dbFile, err)
}
// ingest data
_, err = conn.ExecContext(ctx, fmt.Sprintf("CREATE OR REPLACE TABLE %s.default AS (%s\n)", safeDBName, query), nil)
if err != nil {
_ = os.RemoveAll(newVersionDir)
return fmt.Errorf("create: create %q.default table failed: %w", safeDBName, err)
}
m = meta{Format: BackupFormatDB}
}
d.writeDirty = true
// write meta
err = writeMeta(newVersionDir, m)
if err != nil {
_ = os.RemoveAll(newVersionDir)
return err
}
// update version.txt
err = os.WriteFile(filepath.Join(d.writePath, name, "version.txt"), []byte(newVersion), fs.ModePerm)
if err != nil {
_ = os.RemoveAll(newVersionDir)
return fmt.Errorf("create: write version file failed: %w", err)
}
// close write handle before syncing read so that temp files or wal files if any are removed
err = releaseConn()
if err != nil {
return err
}
if err := d.syncBackup(ctx, name); err != nil {
return fmt.Errorf("create: replicate failed: %w", err)
}
d.logger.Debug("table created", slog.String("name", name))
// both backups and write are now in sync
d.writeDirty = false
if oldVersionExists {
_ = os.RemoveAll(filepath.Join(d.writePath, name, oldVersion))
_ = d.deleteBackup(ctx, name, oldVersion)
}
return d.syncRead(ctx)
}
func (d *db) InsertTableAsSelect(ctx context.Context, name, query string, opts *InsertTableOptions) error {
if opts == nil {
opts = &InsertTableOptions{
Strategy: IncrementalStrategyAppend,
}
}
d.logger.Debug("insert table", slog.String("name", name), slog.Group("option", "by_name", opts.ByName, "strategy", string(opts.Strategy), "unique_key", opts.UniqueKey))
d.writeMu.Lock()
defer d.writeMu.Unlock()
conn, release, err := d.acquireWriteConn(ctx)
if err != nil {
return err
}
defer func() {
_ = release()
}()
return d.insertTableAsSelect(ctx, conn, release, name, query, opts)
}
func (d *db) insertTableAsSelect(ctx context.Context, conn *sqlx.Conn, releaseConn func() error, name, query string, opts *InsertTableOptions) error {
// Get current table version
oldVersion, oldVersionExists, err := tableVersion(d.writePath, name)
if err != nil || !oldVersionExists {
return fmt.Errorf("table %q does not exist", name)
}
d.writeDirty = true
// Execute the insert
err = execIncrementalInsert(ctx, conn, fmt.Sprintf("%s.default", safeSQLName(dbName(name))), query, opts)
if err != nil {
return fmt.Errorf("insert: insert into table %q failed: %w", name, err)
}
// rename db directory
newVersion := newVersion()
oldVersionDir := filepath.Join(d.writePath, name, oldVersion)
err = os.Rename(oldVersionDir, filepath.Join(d.writePath, name, newVersion))
if err != nil {
return fmt.Errorf("insert: update version %q failed: %w", newVersion, err)
}
// update version.txt
err = os.WriteFile(filepath.Join(d.writePath, name, "version.txt"), []byte(newVersion), fs.ModePerm)
if err != nil {
return fmt.Errorf("insert: write version file failed: %w", err)
}
err = releaseConn()
if err != nil {
return err
}
// replicate
err = d.syncBackup(ctx, name)
if err != nil {
return fmt.Errorf("insert: replicate failed: %w", err)
}
// both backups and write are now in sync
d.writeDirty = false
// Delete the old version (ignoring errors since source the new data has already been correctly inserted)
_ = os.RemoveAll(oldVersionDir)
_ = d.deleteBackup(ctx, name, oldVersion)
return d.syncRead(ctx)
}
// DropTable implements DB.
func (d *db) DropTable(ctx context.Context, name string) error {
d.logger.Debug("drop table", slog.String("name", name))
d.writeMu.Lock()
defer d.writeMu.Unlock()
_, release, err := d.acquireWriteConn(ctx) // we don't need the handle but need to sync the write
if err != nil {
return err
}
defer func() {
_ = release()
}()
return d.dropTable(ctx, name)
}
func (d *db) dropTable(ctx context.Context, name string) error {
_, exist, _ := tableVersion(d.writePath, name)
if !exist {
return fmt.Errorf("drop: table %q not found", name)
}
d.writeDirty = true
// drop the table from backup location
err := d.deleteBackup(ctx, name, "")
if err != nil {
return fmt.Errorf("drop: unable to drop table %q from backup: %w", name, err)
}
// delete the table directory
err = os.RemoveAll(filepath.Join(d.writePath, name))
if err != nil {
return fmt.Errorf("drop: unable to drop table %q: %w", name, err)
}
// both backups and write are now in sync
d.writeDirty = false
return d.syncRead(ctx)
}
func (d *db) RenameTable(ctx context.Context, oldName, newName string) error {
d.logger.Debug("rename table", slog.String("from", oldName), slog.String("to", newName))
if strings.EqualFold(oldName, newName) {
return fmt.Errorf("rename: Table with name %q already exists", newName)
}
d.writeMu.Lock()
defer d.writeMu.Unlock()
_, release, err := d.acquireWriteConn(ctx) // we don't need the handle but need to sync the write
if err != nil {
return err
}
defer func() {
_ = release()
}()
return d.renameTable(ctx, oldName, newName)
}
func (d *db) renameTable(ctx context.Context, oldName, newName string) error {
oldVersion, exist, err := d.writeTableVersion(oldName)
if err != nil {
return err
}
if !exist {
return fmt.Errorf("rename: Table %q not found", oldName)
}
newTableVersion, replaceInNewTable, _ := d.writeTableVersion(newName)
d.writeDirty = true
err = os.RemoveAll(filepath.Join(d.writePath, newName))
if err != nil {
return fmt.Errorf("rename: unable to delete existing new table: %w", err)
}
err = os.Rename(filepath.Join(d.writePath, oldName), filepath.Join(d.writePath, newName))
if err != nil {
return fmt.Errorf("rename: rename file failed: %w", err)
}
// rename to a new version
version := newVersion()
err = os.Rename(filepath.Join(d.writePath, newName, oldVersion), filepath.Join(d.writePath, newName, version))
if err != nil {
return fmt.Errorf("rename: rename version failed: %w", err)
}
// update version.txt
writeErr := os.WriteFile(filepath.Join(d.writePath, newName, "version.txt"), []byte(newVersion()), fs.ModePerm)
if writeErr != nil {
return fmt.Errorf("rename: write version file failed: %w", writeErr)
}
if d.syncBackup(ctx, newName) != nil {
return fmt.Errorf("rename: unable to replicate new table")
}
err = d.deleteBackup(ctx, oldName, "")
if err != nil {
return fmt.Errorf("rename: unable to delete old table %q from backup: %w", oldName, err)
}
d.writeDirty = false
if replaceInNewTable {
_ = d.deleteBackup(ctx, newName, newTableVersion)
}
return d.syncRead(ctx)
}
func (d *db) AddTableColumn(ctx context.Context, tableName, columnName, typ string) error {
d.logger.Debug("AddTableColumn", slog.String("table", tableName), slog.String("column", columnName), slog.String("typ", typ))
d.writeMu.Lock()
defer d.writeMu.Unlock()
conn, release, err := d.acquireWriteConn(ctx)
if err != nil {
return err
}
defer func() {
_ = release()
}()
return d.addTableColumn(ctx, conn, release, tableName, columnName, typ)
}
func (d *db) addTableColumn(ctx context.Context, conn *sqlx.Conn, releaseConn func() error, tableName, columnName, typ string) error {
version, exist, err := tableVersion(d.writePath, tableName)
if err != nil {
return err
}
if !exist {
return fmt.Errorf("table %q does not exist", tableName)
}
d.writeDirty = true
_, err = conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s.default ADD COLUMN %s %s", safeSQLName(dbName(tableName)), safeSQLName(columnName), typ))
if err != nil {
return err
}
// rename to new version
newVersion := newVersion()
err = os.Rename(filepath.Join(d.writePath, tableName, version), filepath.Join(d.writePath, tableName, newVersion))
if err != nil {
return err
}
// update version.txt
err = os.WriteFile(filepath.Join(d.writePath, tableName, "version.txt"), []byte(newVersion), fs.ModePerm)
if err != nil {
return err
}
err = releaseConn()
if err != nil {
return err
}
// replicate
err = d.syncBackup(ctx, tableName)
if err != nil {
return err
}
d.writeDirty = false
// remove old version
_ = d.deleteBackup(ctx, tableName, version)
return d.syncRead(ctx)
}
// AlterTableColumn implements drivers.OLAPStore.
func (d *db) AlterTableColumn(ctx context.Context, tableName, columnName, newType string) error {
d.logger.Debug("AlterTableColumn", slog.String("table", tableName), slog.String("column", columnName), slog.String("typ", newType))
d.writeMu.Lock()
defer d.writeMu.Unlock()
conn, release, err := d.acquireWriteConn(ctx)
if err != nil {
return err
}
defer func() {
_ = release()
}()
return d.alterTableColumn(ctx, conn, release, tableName, columnName, newType)
}
func (d *db) alterTableColumn(ctx context.Context, conn *sqlx.Conn, releaseConn func() error, tableName, columnName, newType string) error {
version, exist, err := tableVersion(d.writePath, tableName)
if err != nil {
return err
}
if !exist {
return fmt.Errorf("table %q does not exist", tableName)
}
d.writeDirty = true
_, err = conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s.default ALTER %s TYPE %s", safeSQLName(dbName(tableName)), safeSQLName(columnName), newType))
if err != nil {
return err
}
// rename to new version
newVersion := fmt.Sprint(time.Now().UnixMilli())
err = os.Rename(filepath.Join(d.writePath, tableName, version), filepath.Join(d.writePath, tableName, newVersion))
if err != nil {
return err
}
// update version.txt
err = os.WriteFile(filepath.Join(d.writePath, tableName, "version.txt"), []byte(newVersion), fs.ModePerm)
if err != nil {
return err
}
err = releaseConn()
if err != nil {
return err
}
// replicate
err = d.syncBackup(ctx, tableName)
if err != nil {
return err
}
d.writeDirty = false
// remove old version
_ = d.deleteBackup(ctx, tableName, version)
return d.syncRead(ctx)
}
func (d *db) syncRead(ctx context.Context) error {
entries, err := os.ReadDir(d.writePath)
if err != nil {
return err
}
tableVersion := make(map[string]string)
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// Check if there is already a table with the same version
writeVersion, exist, _ := d.writeTableVersion(entry.Name())
if !exist {
continue
}
tableVersion[entry.Name()] = writeVersion
readVersion, _, _ := d.readTableVersion(entry.Name())
if writeVersion == readVersion {
continue
}
d.logger.Debug("Sync: copying table", slog.String("table", entry.Name()))
err = copyDir(filepath.Join(d.readPath, entry.Name()), filepath.Join(d.writePath, entry.Name()))
if err != nil {
return err
}
}
handle, err := d.openDBAndAttach(ctx, true)
if err != nil {
return err
}
var oldDBHandle *sqlx.DB
d.readMu.Lock()
// swap read handle
oldDBHandle = d.readHandle
d.readHandle = handle
d.readMu.Unlock()
// close old read handle
if oldDBHandle != nil {
err = oldDBHandle.Close()
if err != nil {
d.logger.Warn("error in closing old read handle", slog.String("error", err.Error()))
}
}
// delete data for tables/versions that have been removed from write
entries, err = os.ReadDir(d.readPath)
if err != nil {
return err
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
readVersion, ok, _ := d.readTableVersion(entry.Name())
if !ok {
// invalid table
_ = os.RemoveAll(filepath.Join(d.readPath, entry.Name()))
continue
}
writeVersion, ok := tableVersion[entry.Name()]
if !ok {
// table not in write
d.logger.Debug("Sync: removing table", slog.String("table", entry.Name()))
err = os.RemoveAll(filepath.Join(d.readPath, entry.Name()))
if err != nil {
return err
}
continue
}
if readVersion == writeVersion {
continue
}
d.logger.Debug("Sync: removing old version", slog.String("table", entry.Name()), slog.String("version", readVersion))
err = os.RemoveAll(filepath.Join(d.readPath, entry.Name(), readVersion))
if err != nil {
return err
}
}
return nil
}
func (d *db) Size() int64 {
var paths []string
entries, err := os.ReadDir(d.readPath)
if err != nil { // ignore error
return 0
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// this is to avoid counting temp tables during source ingestion
// in certain cases we only want to compute the size of the serving db files
// TODO :: remove this when removing staged table concepts
if strings.HasPrefix(entry.Name(), "__rill_tmp_") {
continue
}
path := filepath.Join(d.readPath, entry.Name())
version, exist, _ := d.readTableVersion(entry.Name())
if !exist {
continue
}
paths = append(paths, filepath.Join(path, fmt.Sprintf("%s.db", version)))
}
return fileSize(paths)
}
// acquireWriteConn syncs the write database, initializes the write handle and returns a write connection.
// The release function should be called to release the connection.
// It should be called with the writeMu locked.
func (d *db) acquireWriteConn(ctx context.Context) (*sqlx.Conn, func() error, error) {
err := d.syncWrite(ctx)
if err != nil {
return nil, nil, err
}
db, err := d.openDBAndAttach(ctx, false)
if err != nil {
return nil, nil, err
}
conn, err := db.Connx(ctx)
if err != nil {
_ = db.Close()
return nil, nil, err
}
return conn, func() error {
_ = conn.Close()
err = db.Close()
return err
}, nil
}
func (d *db) openDBAndAttach(ctx context.Context, read bool) (*sqlx.DB, error) {
// open the db
var (
dsn *url.URL
err error
settings map[string]string
path string
)
if read {
dsn, err = url.Parse("") // in-memory
settings = d.opts.ReadSettings
path = d.readPath
} else {
path = d.writePath
dsn, err = url.Parse(filepath.Join(path, "stage.db"))
settings = d.opts.WriteSettings
}
if err != nil {
return nil, err
}
query := dsn.Query()
for k, v := range settings {
query.Set(k, v)
}
dsn.RawQuery = query.Encode()
connector, err := duckdb.NewConnector(dsn.String(), func(execer driver.ExecerContext) error {
for _, qry := range d.opts.InitQueries {
_, err := execer.ExecContext(context.Background(), qry, nil)
if err != nil && strings.Contains(err.Error(), "Failed to download extension") {
// Retry using another mirror. Based on: https://github.com/duckdb/duckdb/issues/9378
_, err = execer.ExecContext(context.Background(), qry+" FROM 'http://nightly-extensions.duckdb.org'", nil)
}
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
db := sqlx.NewDb(otelsql.OpenDB(connector), "duckdb")
err = otelsql.RegisterDBStatsMetrics(db.DB, otelsql.WithAttributes(attribute.String("db.system", "duckdb"), attribute.String("db_identifier", d.dbIdentifier)))
if err != nil {
return nil, fmt.Errorf("registering db stats metrics: %w", err)
}
err = db.PingContext(ctx)
if err != nil {
db.Close()
return nil, err
}
err = d.attachDBs(ctx, db, path, read)
if err != nil {
db.Close()
return nil, err
}
// 2023-12-11: Hail mary for solving this issue: https://github.com/duckdblabs/rilldata/issues/6.
// Forces DuckDB to create catalog entries for the information schema up front (they are normally created lazily).
// Can be removed if the issue persists.
_, err = db.ExecContext(context.Background(), `
select
coalesce(t.table_catalog, current_database()) as "database",
t.table_schema as "schema",
t.table_name as "name",
t.table_type as "type",
array_agg(c.column_name order by c.ordinal_position) as "column_names",
array_agg(c.data_type order by c.ordinal_position) as "column_types",
array_agg(c.is_nullable = 'YES' order by c.ordinal_position) as "column_nullable"
from information_schema.tables t
join information_schema.columns c on t.table_schema = c.table_schema and t.table_name = c.table_name
group by 1, 2, 3, 4
order by 1, 2, 3, 4
`)
if err != nil {
return nil, err
}
return db, nil
}
func (d *db) attachDBs(ctx context.Context, db *sqlx.DB, path string, read bool) error {
entries, err := os.ReadDir(path)
if err != nil {
return err
}
var views []string
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// NOTE :: we always look at the write version
// Tables in read path are removed after getting a new handle
// So we need to always look at the write version to ensure we do not reattach dropped tables
version, exist, _ := d.writeTableVersion(entry.Name())
if !exist {
continue
}
versionPath := filepath.Join(path, entry.Name(), version)
// read meta file
f, err := os.ReadFile(filepath.Join(versionPath, "meta.json"))
if err != nil {
_ = os.RemoveAll(versionPath)
d.logger.Warn("error in reading meta file", slog.String("table", entry.Name()), slog.Any("error", err))
return err
}
var meta meta