-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
1093 lines (994 loc) · 36.1 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 db
import (
"database/sql"
"fmt"
"github.com/jmoiron/sqlx"
rawsql "github.com/upwrd/sift/db/sql"
"github.com/upwrd/sift/lib"
"github.com/upwrd/sift/logging"
"github.com/upwrd/sift/types"
log "gopkg.in/inconshreveable/log15.v2"
logext "gopkg.in/inconshreveable/log15.v2/ext"
"io/ioutil"
"os"
// imports sqlite3 driver
_ "github.com/mattn/go-sqlite3"
)
// Log is used to log messages for the auth package. Logs are disabled by
// default; use sift/logging.SetLevel() to set log levels for all packages, or
// Log.SetHandler() to set a custom handler for this package (see:
// https://godoc.org/gopkg.in/inconshreveable/log15.v2)
var Log = logging.Log.New("pkg", "db/components")
// ExpansionFlags are used when retrieving SIFT Devices and Components to
// specify which parts should be gathered (expanded) from the database
type ExpansionFlags byte
// Expansion flags
const (
ExpandNone = 0
ExpandAll = 1 << iota
ExpandSpecs
ExpandStats
)
// Device contains fields matching those in the 'device' table in the SIFT
// database, which is useful when querying the database using sqlx.
type Device struct {
ID int64
Manufacturer string
ExternalID string `db:"external_id"`
Name sql.NullString
LocationID sql.NullInt64 `db:"location_id"`
IsOnline bool `db:"is_online"`
}
// Component contains fields matching those in the 'component' table in the
// SIFT database, which is useful when querying the database using sqlx.
type Component struct {
ID int64
DeviceID int64 `db:"device_id"`
Name, Make, Model, Type string
}
// Location contains fields matching those in the 'location' table in the SIFT
// database, which is useful when querying the database using sqlx.
type Location struct {
ID int64
Name string
}
// A SiftDB manages interactions with the underlying SIFT database
type SiftDB struct {
//*sqlx.DB
dbpath string
tempFile *os.File
log log.Logger
}
// Open opens the SIFT database at the provided file path. If the file does not
// exist, it is created and initialized with the SIFT schema.
func Open(pathToDBFile string) (*SiftDB, error) {
var tempFile *os.File // will be populated if caller requests a temporary file
switch pathToDBFile {
case "":
file, err := ioutil.TempFile(os.TempDir(), "siftdb_")
if err != nil {
return nil, fmt.Errorf("could not open temporary DB file: %v", err)
}
tempFile = file
pathToDBFile = file.Name()
case ":memory:":
return nil, fmt.Errorf("SiftDB cannot be opened with :memory:")
}
// Open a connection to the file at the specified path
db, err := sqlx.Connect("sqlite3", pathToDBFile)
if err != nil {
Log.Error("could not open database", "err", err, "filename", pathToDBFile)
return nil, fmt.Errorf("could not open database at path %v: %v", pathToDBFile, err)
}
defer db.Close()
// Check that this is a valid SIFT DB. If it isn't, initialize it.
if validErr := isDBValid(db); validErr != nil {
Log.Debug("could not validate database; this may be a new file. Initializing", "filename", pathToDBFile, "validation_error", validErr)
if err := dbInitByGoFile(db); err != nil {
return nil, fmt.Errorf("error initializing sift DB: %v", err)
}
}
return &SiftDB{
dbpath: pathToDBFile,
tempFile: tempFile,
log: Log.New("obj", "components_db", "id", logext.RandId(8)),
}, nil
}
// DB returns a connection to the sift database
func (sdb *SiftDB) DB() (*sqlx.DB, error) {
return sqlx.Connect("sqlite3", sdb.dbpath)
}
// Close closes any temporary files that were used
func (sdb *SiftDB) Close() error {
// Mark all Devices as inactive
if err := sdb.markAllDevicesInactive(); err != nil {
sdb.log.Crit("could not mark devices inactive as SIFT DB is closed")
return err
}
if sdb.tempFile != nil {
return sdb.tempFile.Close()
}
return nil
}
var numColumnsByTable = map[string]int{
"component": 6,
"device": 6,
"light_emitter_spec": 5,
}
// isDBValid checks if the given db is a SIFT DB
func isDBValid(db *sqlx.DB) error {
for table, numColumns := range numColumnsByTable {
q := "PRAGMA table_info(" + table + ")"
//rows, err := db.Queryx("PRAGMA table_info(?)", table)
rows, err := db.Queryx(q)
if err != nil {
return fmt.Errorf("error trying to find number of columns in table %v: %v", table, err)
}
count := 0
for rows.Next() {
count++
}
if count != numColumns {
return fmt.Errorf("number of columns on database (%v) != num expected (%v)", count, numColumns)
}
}
return nil
}
// dbInit initializes the database
func dbInit(db *sqlx.DB) error {
sqlPaths := []string{"sql2/init.sql", "sql2/populate_specs.sql"}
for _, path := range sqlPaths {
// Load the init SQL file
initSQL, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("could not read %v: %v", path, err)
}
// Exec it
_, err = db.Exec(string(initSQL))
if err != nil {
return fmt.Errorf("error while execing %v: %v", path, err)
}
}
return nil
}
// TODO: implement import from .sql files which is portable.
// May require embedding files in the binary; see https://github.com/jteeuwen/go-bindata
func dbInitByGoFile(db *sqlx.DB) error {
sqls := []string{rawsql.InitSql, rawsql.PopulateSpecsSQL}
for i, sql := range sqls {
// Exec it
_, err := db.Exec(string(sql))
if err != nil {
return fmt.Errorf("error while execing sql %v: %v", i, err)
}
}
return nil
}
func getDBDeviceTx(tx *sqlx.Tx, extID types.ExternalDeviceID) (Device, bool) {
var dev Device
err := tx.Get(&dev, "SELECT * FROM device WHERE manufacturer=? AND external_id=? LIMIT 1", extID.Manufacturer, extID.ID)
if err != nil || dev.ID == 0 {
Log.Debug("could not get dbDevice", "err", err, "ext_id", extID, "dbDev_id", dev.ID)
return dev, false
}
return dev, true
}
// A DeviceUpsertResponse describes the result of a call to UpsertDevice
type DeviceUpsertResponse struct {
DeviceID types.DeviceID
UpsertedComponents map[string]types.Component
DeletedComponents map[string]types.Component
HasDeviceChanged bool
}
// UpsertDevice updates or inserts a Device into the SIFT database using the
// provided types.ExternalDeviceID. This also includes Upserting any Components
// which are attached to the Device. UpsertDevice considers the Device to be
// "whole"; if any Components which were previously attached to the Device are
// not present in the Device's Components map, those Components will be deleted
// from the SIFT database.
//
// If successful, the response object contains the new or updated Device's SIFT
// ID, as well as indications of which specific components were upserted or
// deleted.
func (sdb SiftDB) UpsertDevice(extID types.ExternalDeviceID, d types.Device) (resp DeviceUpsertResponse, err error) {
sdb.log.Info("upserting device (incl. components)", "device", d)
// Get a connection to the database
db, err := sdb.DB()
if err != nil {
return DeviceUpsertResponse{}, err
}
defer db.Close()
// begin a database transaction
tx, err := db.Beginx()
if err != nil {
return DeviceUpsertResponse{}, fmt.Errorf("could not begin transaction: %v", err)
}
// If something bad happens, roll back the transaction
defer func() {
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
sdb.log.Error("could not roll back db transaction", "original_err", err, "rollback_err", rbErr)
}
sdb.log.Warn("rolled back db transaction", "original_err", err)
} else {
if cmErr := tx.Commit(); cmErr != nil {
sdb.log.Error("could not commit transaction", "commit_err", cmErr)
err = fmt.Errorf("could not commit transaction: %v", cmErr)
}
sdb.log.Debug("device updated; transaction committed")
}
}()
// Upsert the base Device
id, err := upsertDeviceTx(tx, extID, d)
if err != nil {
err = fmt.Errorf("could not upsert device: %v", err)
return
}
var oldDevicePtr *types.Device
// Compare the new device against the previous device
// (or any empty device, if no previous device existed)
oldDevice := types.Device{}
if oldDevicePtr != nil {
oldDevice = *oldDevicePtr
}
toUpsert, toDelete, hasDeviceChanged := lib.DiffDevice(oldDevice, d)
// Upsert all new or updated components
if err = upsertComponentsForDeviceTx(tx, id, toUpsert); err != nil {
err = fmt.Errorf("could not upsert components for device %v: %v", id, err)
return
}
// Delete any missing components
for name := range toDelete {
if err = deleteComponentTx(tx, id, name); err != nil {
err = fmt.Errorf("could not delete component %v-%v: %v", id, name, err)
return
}
}
resp = DeviceUpsertResponse{
DeviceID: id,
UpsertedComponents: toUpsert,
DeletedComponents: toDelete,
HasDeviceChanged: hasDeviceChanged,
}
return
}
type upsertDeviceResponse struct {
id string
previousDevice *types.Device
hasChanged bool
}
func upsertDeviceTx(tx *sqlx.Tx, extID types.ExternalDeviceID, d types.Device) (types.DeviceID, error) {
// Try updating
q := "UPDATE device SET name=?, is_online=? WHERE manufacturer=? AND external_id=?"
res, err := tx.Exec(q, d.Name, d.IsOnline, extID.Manufacturer, extID.ID)
if err != nil {
return 0, fmt.Errorf("error updating device: %v", err)
}
// Check the number of rows affected by the update; should be 1 if the
// light_emitter_state row existed, and 0 if not
if n, err := res.RowsAffected(); err != nil {
return 0, fmt.Errorf("error getting row count (required for update): %v", err)
} else if n == 0 {
// The update failed, do an insert instead
q = "INSERT INTO device (manufacturer, external_id, name, is_online) VALUES (?, ?, ?, ?)"
res, err := tx.Exec(q, extID.Manufacturer, extID.ID, d.Name, d.IsOnline)
if err != nil {
return 0, fmt.Errorf("error inserting device: %v", err)
}
id, err := res.LastInsertId() // Get ID from insert
if err != nil || id == 0 {
return 0, fmt.Errorf("error or zero-value ID (id: %v, err: %v)", id, err)
}
Log.Debug("inserted new device", "id", id, "external_id", extID, "device", d, "query", q)
return types.DeviceID(id), nil
}
// Do Select to get the ID
var id int64
if err = tx.Get(&id, "SELECT id FROM device WHERE manufacturer=? AND external_id=?", extID.Manufacturer, extID.ID); err != nil {
return 0, fmt.Errorf("could not run select to get ID: %v", err)
}
Log.Debug("updated existing device", "id", id, "external_id", extID, "device", d, "query", q)
return types.DeviceID(id), nil
}
func upsertComponentsForDeviceTx(tx *sqlx.Tx, id types.DeviceID, compsByName map[string]types.Component) error {
Log.Debug("upserting components", "device_id", id, "components", compsByName, "tx", tx)
for name, component := range compsByName {
id, err := upsertComponentTx(tx, id, name, component)
if err != nil || id == 0 {
Log.Debug("could not upsert component", "err", err, "device_id", id, "comp_name", name, "comp", component)
return fmt.Errorf("could not upsert component %v-%v: %v", id, name, err)
}
}
return nil
}
// GetDevices returns a map of all Devices in the SIFT database, indexed by
// their SIFT-internal DeviceIDs, and expanded to the degree indicated by
// exFlags
func (sdb SiftDB) GetDevices(exFlags ExpansionFlags) (devs map[types.DeviceID]types.Device, err error) {
// Get a connection to the database
db, err := sdb.DB()
if err != nil {
return nil, fmt.Errorf("could not establish connection to database: %v", err)
}
defer db.Close()
// begin a database transaction
tx, err := db.Beginx()
if err != nil {
return nil, fmt.Errorf("could not begin transaction: %v", err)
}
// If something bad happens, roll back the transaction
defer func() {
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
sdb.log.Error("could not roll back db transaction", "original_err", err, "rollback_err", rbErr)
}
sdb.log.Warn("rolled back db transaction", "original_err", err)
} else {
if cmErr := tx.Commit(); cmErr != nil {
sdb.log.Error("could not commit transaction", "commit_err", cmErr)
}
sdb.log.Debug("device updated; transaction committed")
}
}()
devs, err = getDevicesTx(tx, exFlags)
return
}
func getDevicesTx(tx *sqlx.Tx, exFlags ExpansionFlags) (map[types.DeviceID]types.Device, error) {
devIDs := []int64{}
if err := tx.Select(&devIDs, "SELECT id FROM device"); err != nil {
return nil, fmt.Errorf("error getting device IDs from database: %v", err)
}
devs := make(map[types.DeviceID]types.Device)
for _, id := range devIDs {
dev := types.Device{}
devID := types.DeviceID(id)
if err := getDeviceTx(tx, &dev, devID, exFlags); err != nil {
return nil, fmt.Errorf("could not get expanded Device with ID %v: %v", id, err)
}
devs[devID] = dev
}
return devs, nil
}
func (sdb SiftDB) getDevice(d *types.Device, id types.DeviceID, exFlags ExpansionFlags) (err error) {
// Get a connection to the database
db, err := sdb.DB()
if err != nil {
return err
}
defer db.Close()
// begin a database transaction
tx, err := db.Beginx()
if err != nil {
return fmt.Errorf("could not begin transaction: %v", err)
}
// If something bad happens, roll back the transaction
defer func() {
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
sdb.log.Error("could not roll back db transaction", "original_err", err, "rollback_err", rbErr)
}
sdb.log.Warn("rolled back db transaction", "original_err", err)
} else {
if cmErr := tx.Commit(); cmErr != nil {
sdb.log.Error("could not commit transaction", "commit_err", cmErr)
}
sdb.log.Debug("device updated; transaction committed")
}
}()
err = getDeviceTx(tx, d, id, exFlags)
return
}
func getDeviceTx(tx *sqlx.Tx, d *types.Device, id types.DeviceID, exFlags ExpansionFlags) error {
var dbDev Device
q := "SELECT * FROM device WHERE id=?"
if err := tx.Get(&dbDev, q, id); err != nil {
return fmt.Errorf("could not get device: %v", err) // device was probably not found
}
// device was found in database, copy in the values
if dbDev.Name.Valid {
d.Name = dbDev.Name.String
}
d.IsOnline = dbDev.IsOnline
// Populate the Components list for the Device
if d.Components == nil {
d.Components = make(map[string]types.Component)
}
if err := getComponentsForDevice(tx, d.Components, id, exFlags); err != nil {
return fmt.Errorf("error getting components for Device: %v", err)
}
Log.Debug("got completed device from DB", "id", id, "device", d)
return nil
}
func getComponentsForDevice(tx *sqlx.Tx, dest map[string]types.Component, deviceID types.DeviceID, exFlags ExpansionFlags) error {
// get base components matching the device ID
componentIDs := []int64{}
err := tx.Select(&componentIDs, "SELECT id FROM component WHERE device_id=?", deviceID)
if err != nil {
return fmt.Errorf("error getting components for device %v: %v", deviceID, err)
}
Log.Debug("queried for components", "device_id", deviceID, "found_component_ids", componentIDs)
// Build a set of components from database
for _, id := range componentIDs {
name, comp, err := getComponentTx(tx, id, exFlags)
if err != nil {
return fmt.Errorf("error getting component with ID %v: %v", id, err)
}
dest[name] = comp // put into the destination map
}
return nil // all components gathered without error
}
// GetComponents returns a map of all Components in the SIFT database, indexed
// by their SIFT-internal ComponentIDs, and expanded to the degree indicated by
// exFlags
func (sdb SiftDB) GetComponents(exFlags ExpansionFlags) (comps map[types.ComponentID]types.Component, err error) {
// Get a connection to the database
db, err := sdb.DB()
if err != nil {
return nil, err
}
defer db.Close()
// begin a database transaction
tx, err := db.Beginx()
if err != nil {
return nil, fmt.Errorf("could not begin transaction: %v", err)
}
// If something bad happens, roll back the transaction
defer func() {
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
sdb.log.Error("could not roll back db transaction", "original_err", err, "rollback_err", rbErr)
}
sdb.log.Warn("rolled back db transaction", "original_err", err)
} else {
if cmErr := tx.Commit(); cmErr != nil {
sdb.log.Error("could not commit transaction", "commit_err", cmErr)
}
sdb.log.Debug("device updated; transaction committed")
}
}()
comps, err = getAllComponents(tx, exFlags)
sdb.log.Debug("got all components", "err", err, "comps", comps, "expand_flags", exFlags)
return
}
func getAllComponents(tx *sqlx.Tx, exFlags ExpansionFlags) (map[types.ComponentID]types.Component, error) {
type result struct {
ID int64
DeviceID int64 `db:"device_id"`
}
// get results for each component in the database
results := []result{}
err := tx.Select(&results, "SELECT id, device_id FROM component")
if err != nil {
return nil, fmt.Errorf("error getting component IDs: %v", err)
}
// Build a set of components from database
componentsByKey := make(map[types.ComponentID]types.Component)
for _, result := range results {
name, comp, err := getComponentTx(tx, result.ID, exFlags)
if err != nil {
return nil, fmt.Errorf("error getting component with ID %v: %v", result.ID, err)
}
key := types.ComponentID{
Name: name,
DeviceID: types.DeviceID(result.DeviceID),
}
componentsByKey[key] = comp // put into the destination map
}
return componentsByKey, nil // all components gathered without error
}
func getComponentTx(tx *sqlx.Tx, id int64, exFlags ExpansionFlags) (string, types.Component, error) {
// Get the db base component
dbBaseComp, err := getBaseComponentByIDTx(tx, id)
if err != nil {
return "", nil, fmt.Errorf("could not get component with id %v: %v", id, err)
}
switch dbBaseComp.Type {
default:
return "", nil, fmt.Errorf("unhandled type: %v", dbBaseComp.Type)
case types.LightEmitter{}.Type():
le, err := getLightEmitterTx(tx, dbBaseComp, exFlags)
return dbBaseComp.Name, le, err
case types.MediaPlayer{}.Type():
mp, err := getMediaPlayerTx(tx, dbBaseComp, exFlags)
return dbBaseComp.Name, mp, err
}
}
func getBaseComponentByIDTx(tx *sqlx.Tx, id int64) (Component, error) {
var dbComp Component
if err := tx.Get(&dbComp, "SELECT * FROM component WHERE id=? LIMIT 1", id); err != nil {
Log.Debug("could not get base component", "id", id, "err", err)
return Component{}, fmt.Errorf("error getting component with id %v: %v", id, err)
}
if dbComp.ID == 0 {
Log.Warn("base component has id 0", "search_id", id)
return Component{}, fmt.Errorf("got unexpected component id: 0")
}
Log.Debug("got base component", "id", id, "comp", dbComp)
return dbComp, nil
}
func getBaseComponentTx(tx *sqlx.Tx, deviceID types.DeviceID, compName string) (Component, bool) {
var dbComp Component
err := tx.Get(&dbComp, "SELECT * FROM component WHERE device_id=? AND name=? LIMIT 1", deviceID, compName)
if err != nil || dbComp.ID == 0 {
return dbComp, false
}
return dbComp, true
}
func upsertBaseComponentTx(tx *sqlx.Tx, deviceID types.DeviceID, name string, c types.Component) (int64, error) {
base := c.GetBaseComponent()
existingBaseComp, found := getBaseComponentTx(tx, deviceID, name)
if !found {
// not found: do insert
q := "INSERT INTO component (device_id, name, make, model, type) VALUES (?, ?, ?, ?, ?)"
res, err := tx.Exec(q, deviceID, name, base.Make, base.Model, c.Type())
if err != nil {
return 0, fmt.Errorf("error inserting component: %v", err)
}
id, err := res.LastInsertId() // Get ID from insert
if err != nil || id == 0 {
return 0, fmt.Errorf("error or zero-value ID (id: %v, err: %v)", id, err)
}
Log.Debug("inserted component", "id", id, "base_component", base, "stmt", q)
return id, nil
}
// found: do update
q := "UPDATE component SET make=?, model=?, type=? WHERE id=?;"
_, err := tx.Exec(q, base.Make, base.Model, c.Type(), existingBaseComp.ID)
if err != nil {
return 0, fmt.Errorf("error updating base component: %v", err)
}
Log.Debug("updated component", "base", base, "query", q, "update_err", err)
return existingBaseComp.ID, err
}
func upsertComponentTx(tx *sqlx.Tx, deviceID types.DeviceID, compName string, comp types.Component) (id int64, err error) {
// Upsert the base component and get comp ID
id, err = upsertBaseComponentTx(tx, deviceID, compName, comp)
if err != nil || id == 0 {
return 0, err
}
// Upsert the specific component
switch typed := comp.(type) {
default:
return 0, fmt.Errorf("unhandled component type: %T", comp)
case types.LightEmitter:
return id, upsertLightEmitterTx(tx, id, typed)
case types.MediaPlayer:
return id, upsertMediaPlayerTx(tx, id, typed)
}
}
func deleteComponentTx(tx *sqlx.Tx, deviceID types.DeviceID, compName string) error {
// Get the base component, if it exists
if comp, found := getBaseComponentTx(tx, deviceID, compName); found {
// delete the specific component info (changes by type)
switch comp.Type {
default:
return fmt.Errorf("unhandled component type: %T", comp)
case types.LightEmitter{}.Type():
if err := deleteLightEmitterTx(tx, comp.ID); err != nil {
return fmt.Errorf("could not delete light emitter: %v", err)
}
case types.MediaPlayer{}.Type():
if err := deleteMediaPlayerTx(tx, comp.ID); err != nil {
return fmt.Errorf("could not delete media player: %v", err)
}
}
// delete the base component
if _, err := tx.Queryx("DELETE FROM component WHERE device_id=? AND name=?", deviceID, compName); err != nil {
return fmt.Errorf("error deleting base component: %v", err)
}
}
return nil
}
type dbLightEmitter struct {
Component
types.LightEmitterState
types.LightEmitterSpecs
types.LightEmitterStats
}
func getLightEmitterTx(tx *sqlx.Tx, dbc Component, exFlags ExpansionFlags) (types.LightEmitter, error) {
dbLE, err := getDBLightEmitterTx(tx, dbc.ID, dbc, exFlags)
if err != nil {
return types.LightEmitter{}, fmt.Errorf("error getting light emitter with id %v: %v", dbc.ID, err)
}
if dbLE.BrightnessInPercent < 0 || dbLE.BrightnessInPercent > 255 {
return types.LightEmitter{}, fmt.Errorf("brightness value from database does not fit in uint8: %v", dbLE.BrightnessInPercent)
}
brightnessAsUint8 := uint8(dbLE.BrightnessInPercent)
le := types.LightEmitter{
BaseComponent: dbToBaseComponent(dbc),
State: types.LightEmitterState{
BrightnessInPercent: brightnessAsUint8,
},
}
if exFlags&(ExpandAll|exFlags&ExpandSpecs) != 0 {
le.Specs = &types.LightEmitterSpecs{
MaxOutputInLumens: dbLE.MaxOutputInLumens,
MinOutputInLumens: dbLE.MinOutputInLumens,
ExpectedLifetimeInHours: dbLE.ExpectedLifetimeInHours,
}
}
return le, nil
}
func getDBLightEmitterTx(tx *sqlx.Tx, id int64, baseComp Component, exFlags ExpansionFlags) (dbLightEmitter, error) {
var dbLE dbLightEmitter
// build a select statement based on the expand keys
stmt := "SELECT * FROM component c JOIN light_emitter_state lstate ON c.id=lstate.id"
if exFlags&(ExpandAll|ExpandSpecs) != 0 {
stmt += " JOIN light_emitter_spec lspec ON lspec.make=c.make AND lspec.model=c.model"
}
// TODO: Add stats
// if exFlags&(ExpandAll|exFlags&ExpandStats) != 0 {
// stmt += " JOIN light_emitter_stats lstats ON c.id=lstats.id"
// }
stmt += " WHERE c.id=? LIMIT 1"
Log.Debug("getting light emitter", "query", stmt, "id", id)
if err := tx.Get(&dbLE, stmt, id); err != nil {
return dbLightEmitter{}, fmt.Errorf("error getting light emitter with id %v: %v", id, err)
}
if dbLE.ID == 0 {
Log.Warn("light emitter has id 0", "search_id", id)
return dbLightEmitter{}, fmt.Errorf("got unexpected component id: 0")
}
return dbLE, nil
}
// upsertLightEmitterTx upserts a light emitter to the database.
func upsertLightEmitterTx(tx *sqlx.Tx, compID int64, le types.LightEmitter) error {
// Try updating
q := "UPDATE light_emitter_state SET brightness_in_percent=? WHERE id=?"
res, err := tx.Exec(q, le.State.BrightnessInPercent, compID)
if err != nil {
return fmt.Errorf("error updating component: %v", err)
}
// Check the number of rows affected by the udpate; should be 1 if the
// light_emitter_state row existed, and 0 if not
if n, err := res.RowsAffected(); err != nil {
return fmt.Errorf("error getting row count (required for update): %v", err)
} else if n == 0 {
// The update failed, do an insert instead
q = "INSERT INTO light_emitter_state (id, brightness_in_percent) VALUES (?, ?)"
res, err := tx.Exec(q, compID, le.State.BrightnessInPercent)
if err != nil {
return fmt.Errorf("error inserting component: %v", err)
}
id, err := res.LastInsertId() // Get ID from insert
if err != nil || id == 0 {
return fmt.Errorf("error or zero-value ID (id: %v, err: %v)", id, err)
}
Log.Debug("inserted new light emitter", "id", compID, "new_values", le, "query", q)
return nil
}
Log.Debug("updated existing light emitter", "id", compID, "new_values", le, "query", q)
return nil
}
func (sdb *SiftDB) expandLightEmitter(le *types.LightEmitter, exFlags ExpansionFlags) error {
if exFlags&(ExpandAll|exFlags&ExpandSpecs) != 0 {
if err := sdb.expandLightEmitterSpecs(le); err != nil {
sdb.log.Debug("could not expand light emitter specs", "err", err, "light_emitter", le)
return fmt.Errorf("could not expand light emitter specs: %v", err)
}
sdb.log.Debug("expanded specs for light emitter", "light_emitter", le)
}
if exFlags&(ExpandAll|exFlags&ExpandStats) != 0 {
sdb.log.Warn("STUB: expandLightEmitter does not yet expand stats!")
}
return nil
}
func (sdb *SiftDB) expandLightEmitterSpecs(le *types.LightEmitter) error {
specs, err := sdb.getLightEmitterSpecs(le.Make, le.Model)
if err != nil {
return err
}
le.Specs = specs
return nil
}
func (sdb *SiftDB) getLightEmitterSpecs(make, model string) (*types.LightEmitterSpecs, error) {
// Get a connection to the database
db, err := sdb.DB()
if err != nil {
return nil, err
}
defer db.Close()
// Run the query to get the appropriate specs
spec := types.LightEmitterSpecs{}
q := `SELECT max_output_in_lumens, min_output_in_lumens, expected_lifetime_in_hours
FROM light_emitter_spec
WHERE make=? AND model=?
LIMIT 1`
err = db.Get(&spec, q, make, model)
if err != nil {
return nil, fmt.Errorf("error querying for light emitter spec: %v", err)
}
sdb.log.Debug("got light emitter specs", "make", make, "model", model, "specs", spec)
return &spec, nil
}
func deleteLightEmitterTx(tx *sqlx.Tx, compID int64) error {
if _, err := tx.Queryx("DELETE FROM light_emitter_state WHERE id=?", compID); err != nil {
return fmt.Errorf("error deleteing from light_emitter_state: %v", err)
}
//TODO: also delete light_emitter_stats
return nil
}
//
// Media players
//
type dbMediaPlayer struct {
Component
types.MediaPlayerState
types.MediaPlayerSpecs
types.MediaPlayerStats
}
func getMediaPlayerTx(tx *sqlx.Tx, dbc Component, exFlags ExpansionFlags) (types.MediaPlayer, error) {
dbMP, err := getDBMediaPlayerTx(tx, dbc.ID, dbc, exFlags)
if err != nil {
return types.MediaPlayer{}, fmt.Errorf("error getting media player with id %v: %v", dbc.ID, err)
}
mp := types.MediaPlayer{
BaseComponent: dbToBaseComponent(dbc),
State: types.MediaPlayerState{
PlayState: dbMP.PlayState,
MediaType: dbMP.MediaType,
Source: dbMP.Source,
},
}
if exFlags&(ExpandAll|exFlags&ExpandSpecs) != 0 {
mp.Specs = &types.MediaPlayerSpecs{
SupportedAudioTypes: dbMP.SupportedAudioTypes,
SupportedVideoTypes: dbMP.SupportedVideoTypes,
}
}
return mp, nil
}
func getDBMediaPlayerTx(tx *sqlx.Tx, id int64, baseComp Component, exFlags ExpansionFlags) (dbMediaPlayer, error) {
var dbMP dbMediaPlayer
// build a select statement based on the expand keys
stmt := "SELECT * FROM component c JOIN media_player_state mpstate ON c.id=mpstate.id"
if exFlags&(ExpandAll|ExpandSpecs) != 0 {
stmt += " JOIN media_player_spec mpspec ON mpspec.make=c.make AND mpspec.model=c.model"
}
// TODO: Add stats
// if exFlags&(ExpandAll|exFlags&ExpandStats) != 0 {
// stmt += " JOIN media_player_stats lstats ON c.id=lstats.id"
// }
stmt += " WHERE c.id=? LIMIT 1"
Log.Debug("getting media player", "query", stmt, "id", id)
if err := tx.Get(&dbMP, stmt, id); err != nil {
return dbMediaPlayer{}, fmt.Errorf("error getting media player with id %v: %v", id, err)
}
if dbMP.ID == 0 {
Log.Warn("media player has id 0", "search_id", id)
return dbMediaPlayer{}, fmt.Errorf("got unexpected component id: 0")
}
return dbMP, nil
}
// upsertMediaPlayerTx upserts a media player to the database.
func upsertMediaPlayerTx(tx *sqlx.Tx, compID int64, mp types.MediaPlayer) error {
// Try updating
q := "UPDATE media_player_state SET play_state=?, media_type=?, source=? WHERE id=?"
res, err := tx.Exec(q, mp.State.PlayState, mp.State.MediaType, mp.State.Source, compID)
if err != nil {
return fmt.Errorf("error updating component: %v", err)
}
// Check the number of rows affected by the udpate; should be 1 if the
// media_player_state row existed, and 0 if not
if n, err := res.RowsAffected(); err != nil {
return fmt.Errorf("error getting row count (required for update): %v", err)
} else if n == 0 {
// The update failed, do an insert instead
q = "INSERT INTO media_player_state (id, play_state, media_type, source) VALUES (?, ?, ?, ?)"
res, err := tx.Exec(q, compID, mp.State.PlayState, mp.State.MediaType, mp.State.Source)
if err != nil {
return fmt.Errorf("error inserting component: %v", err)
}
id, err := res.LastInsertId() // Get ID from insert
if err != nil || id == 0 {
return fmt.Errorf("error or zero-value ID (id: %v, err: %v)", id, err)
}
Log.Debug("inserted new media player", "id", compID, "new_values", mp, "query", q)
return nil
}
Log.Debug("updated existing media player", "id", compID, "new_values", mp, "query", q)
return nil
}
func (sdb *SiftDB) expandMediaPlayer(le *types.MediaPlayer, exFlags ExpansionFlags) error {
if exFlags&(ExpandAll|exFlags&ExpandSpecs) != 0 {
if err := sdb.expandMediaPlayerSpecs(le); err != nil {
sdb.log.Debug("could not expand media player specs", "err", err, "media_player", le)
return fmt.Errorf("could not expand media player specs: %v", err)
}
sdb.log.Debug("expanded specs for media player", "media_player", le)
}
if exFlags&(ExpandAll|exFlags&ExpandStats) != 0 {
sdb.log.Warn("STUB: expandMediaPlayer does not yet expand stats!")
}
return nil
}
func (sdb *SiftDB) expandMediaPlayerSpecs(le *types.MediaPlayer) error {
specs, err := sdb.getMediaPlayerSpecs(le.Make, le.Model)
if err != nil {
return err
}
le.Specs = specs
return nil
}
func (sdb *SiftDB) getMediaPlayerSpecs(make, model string) (*types.MediaPlayerSpecs, error) {
// Get a connection to the database
db, err := sdb.DB()
if err != nil {
return nil, err
}
defer db.Close()
// Run the query to get the appropriate specs
spec := types.MediaPlayerSpecs{}
q := `SELECT supported_audio_types, supported_video_types
FROM media_player_spec
WHERE make=? AND model=?
LIMIT 1`
err = db.Get(&spec, q, make, model)
if err != nil {
return nil, fmt.Errorf("error querying for media player spec: %v", err)
}
sdb.log.Debug("got media player specs", "make", make, "model", model, "specs", spec)
return &spec, nil
}
func deleteMediaPlayerTx(tx *sqlx.Tx, compID int64) error {
if _, err := tx.Queryx("DELETE FROM media_player_state WHERE id=?", compID); err != nil {
return fmt.Errorf("error deleteing from media_player_state: %v", err)
}
//TODO: also delete media_player_stats
return nil
}
//func (sdb *SiftDB) UpsertAdapterCredentials(key, value string) (err error) {
// // Get a connection to the database
// db, err := sdb.DB()
// if err != nil {
// return fmt.Errorf("error getting db connection: %v", err)
// }
// defer db.Close()
// // begin a database transaction
// tx, err := db.Beginx()
// if err != nil {
// return fmt.Errorf("could not begin transaction: %v", err)
// }
// // If something bad happens, roll back the transaction
// defer func() {
// if err != nil {
// if rbErr := tx.Rollback(); rbErr != nil {
// sdb.log.Error("could not roll back db transaction", "original_err", err, "rollback_err", rbErr)
// }
// sdb.log.Warn("rolled back db transaction", "original_err", err)
// } else {
// if cmErr := tx.Commit(); cmErr != nil {
// sdb.log.Error("could not commit transaction", "commit_err", cmErr)
// err = fmt.Errorf("could not commit transaction: %v", cmErr)
// }
// sdb.log.Debug("adapter credentials updated; transaction committed")
// }
// }()
//
// // Try updating the Adapter Credentials
// q := "UPDATE adapter_credentials SET value=? WHERE key=?"
// res, err := tx.Exec(q, value, key)
// if err != nil {
// err = fmt.Errorf("error updating adapter_credentials: %v", err)
// return
// }
//
// // Check the number of rows affected by the update; should be 1 if the
// // row existed, and 0 if not
// var n int64
// if n, err = res.RowsAffected(); err != nil {
// err = fmt.Errorf("error getting row count (required for update): %v", err)
// return
// } else if n == 0 {
// // The update failed, do an insert instead
// q = "INSERT INTO adapter_credentials (key, value) VALUES (?, ?)"
// _, err = tx.Exec(q, key, value)
// if err != nil {
// err = fmt.Errorf("error inserting adapter credentials: %v", err)
// return
// }
// }
// return
//}
//
//func (sdb *SiftDB) GetAdapterCredentials(key string) (string, error) {
// var value string
// // Get a connection to the database
// db, err := sdb.DB()
// if err != nil {
// return "", fmt.Errorf("error getting db connection: %v", err)
// }
// defer db.Close()
// if err := db.Get(&value, "SELECT value FROM adapter_credentials WHERE key=?", key); err != nil {
// return "", fmt.Errorf("could not get credentials from database: %v", err)
// }
// return value, nil
//}