-
Notifications
You must be signed in to change notification settings - Fork 75
/
cockroachdb.go
1080 lines (966 loc) · 26.8 KB
/
cockroachdb.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
// Copyright (c) 2017-2020 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package cockroachdb
import (
"errors"
"fmt"
"net/url"
"path/filepath"
"sync"
"time"
v1 "github.com/decred/politeia/politeiawww/api/cms/v1"
database "github.com/decred/politeia/politeiawww/legacy/cmsdatabase"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
const (
cacheID = "cms"
cmsVersion = "2"
// Database table names
tableNameVersions = "versions"
tableNameInvoice = "invoices"
tableNameLineItem = "line_items"
tableNameInvoiceChange = "invoice_changes"
tableNameExchangeRate = "exchange_rates"
tableNamePayments = "payments"
tableNameDCC = "dcc"
userPoliteiawww = "politeiawww" // cmsdb user (read/write access)
)
// cockroachdb implements the cache interface.
type cockroachdb struct {
sync.RWMutex
shutdown bool // Backend is shutdown
recordsdb *gorm.DB // Database context
}
// Create new invoice.
//
// CreateInvoice satisfies the database interface.
func (c *cockroachdb) NewInvoice(dbInvoice *database.Invoice) error {
invoice := EncodeInvoice(dbInvoice)
log.Debugf("CreateInvoice: %v", invoice.Token)
return c.recordsdb.Create(invoice).Error
}
// Update existing invoice.
//
// UpdateInvoice satisfies the database interface.
func (c *cockroachdb) UpdateInvoice(dbInvoice *database.Invoice) error {
invoice := EncodeInvoice(dbInvoice)
log.Debugf("UpdateInvoice: %v", invoice.Token)
return c.recordsdb.Save(invoice).Error
}
// RemoveLineItem deletes an existing invoice line items from the database.
func (c *cockroachdb) RemoveInvoiceLineItems(invoiceToken string) error {
log.Debugf("RemoveInvoiceLineItems: %v", invoiceToken)
return c.recordsdb.Where("invoice_token = ?", invoiceToken).Delete(&LineItem{}).Error
}
// Return all invoices by userid
func (c *cockroachdb) InvoicesByUserID(userid string) ([]database.Invoice, error) {
log.Tracef("InvoicesByUserID")
// Lookup the latest version of each invoice
query := `SELECT *
FROM invoices a
LEFT OUTER JOIN invoices b
ON a.token = b.token
AND a.version < b.version
WHERE b.token IS NULL
AND a.user_id = ?`
rows, err := c.recordsdb.Raw(query, userid).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
invoices := make([]Invoice, 0, 1024) // PNOOMA
for rows.Next() {
var i Invoice
err := c.recordsdb.ScanRows(rows, &i)
if err != nil {
return nil, err
}
invoices = append(invoices, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
keys := make([]string, 0, len(invoices))
for _, r := range invoices {
keys = append(keys, r.Key)
}
err = c.recordsdb.
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Where(keys).
Find(&invoices).
Error
if err != nil {
return nil, err
}
dbInvoices := make([]database.Invoice, 0, len(invoices))
for _, v := range invoices {
dbInvoice, err := DecodeInvoice(&v)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *dbInvoice)
}
return dbInvoices, nil
}
// InvoiceByToken Return invoice by its token.
func (c *cockroachdb) InvoiceByToken(token string) (*database.Invoice, error) {
log.Debugf("InvoiceByToken: %v", token)
invoice := Invoice{}
err := c.recordsdb.
Where("token = ?", token).
Order("version desc").
Limit(1).
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Find(&invoice).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = database.ErrInvoiceNotFound
}
return nil, err
}
return DecodeInvoice(&invoice)
}
// InvoiceByKey Return invoice by its key.
func (c *cockroachdb) InvoiceByKey(key string) (*database.Invoice, error) {
log.Debugf("InvoiceByKey: %v", key)
invoice := Invoice{}
err := c.recordsdb.
Where("key = ?", key).
Order("version desc").
Limit(1).
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Find(&invoice).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = database.ErrInvoiceNotFound
}
return nil, err
}
return DecodeInvoice(&invoice)
}
// InvoiceByTokenVersion Return invoice by its token and version
func (c *cockroachdb) InvoiceByTokenVersion(token string, version string) (*database.Invoice, error) {
log.Debugf("InvoiceByTokenVersion: %v", token)
invoice := Invoice{}
err := c.recordsdb.
Where("key = ?", token+version).
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Find(&invoice).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = database.ErrInvoiceNotFound
}
return nil, err
}
return DecodeInvoice(&invoice)
}
// InvoicesByMonthYearStatus returns all invoices by month year and status
func (c *cockroachdb) InvoicesByMonthYearStatus(month, year uint16, status int) ([]database.Invoice, error) {
log.Tracef("InvoicesByMonthYearStatus")
// Lookup the latest version of each invoice
query := `SELECT *
FROM invoices a
LEFT OUTER JOIN invoices b
ON a.token = b.token
AND a.version < b.version
WHERE b.token IS NULL
AND month = ? AND year = ? AND status = ?`
rows, err := c.recordsdb.Raw(query, month, year, status).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
invoices := make([]Invoice, 0, 1024) // PNOOMA
for rows.Next() {
var i Invoice
err := c.recordsdb.ScanRows(rows, &i)
if err != nil {
return nil, err
}
invoices = append(invoices, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
keys := make([]string, 0, len(invoices))
for _, r := range invoices {
keys = append(keys, r.Key)
}
err = c.recordsdb.
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Where(keys).
Find(&invoices).
Error
if err != nil {
return nil, err
}
dbInvoices := make([]database.Invoice, 0, len(invoices))
for _, v := range invoices {
dbInvoice, err := DecodeInvoice(&v)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *dbInvoice)
}
return dbInvoices, nil
}
// InvoicesByMonthYear returns all invoices by month/year
func (c *cockroachdb) InvoicesByMonthYear(month, year uint16) ([]database.Invoice, error) {
log.Tracef("InvoicesByMonthYear")
// Lookup the latest version of each invoice
query := `SELECT *
FROM invoices a
LEFT OUTER JOIN invoices b
ON a.token = b.token
AND a.version < b.version
WHERE b.token IS NULL
AND a.month = ? AND a.year = ?`
rows, err := c.recordsdb.Raw(query, month, year).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
invoices := make([]Invoice, 0, 1024) // PNOOMA
for rows.Next() {
var i Invoice
err := c.recordsdb.ScanRows(rows, &i)
if err != nil {
return nil, err
}
invoices = append(invoices, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
keys := make([]string, 0, len(invoices))
for _, r := range invoices {
keys = append(keys, r.Key)
}
err = c.recordsdb.
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Where(keys).
Find(&invoices).
Error
if err != nil {
return nil, err
}
dbInvoices := make([]database.Invoice, 0, len(invoices))
for _, v := range invoices {
dbInvoice, err := DecodeInvoice(&v)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *dbInvoice)
}
return dbInvoices, nil
}
// InvoicesByStatus returns all invoices by status
func (c *cockroachdb) InvoicesByStatus(status int) ([]database.Invoice, error) {
log.Tracef("InvoicesByStatus")
// Lookup the latest version of each invoice
query := `SELECT *
FROM invoices a
LEFT OUTER JOIN invoices b
ON a.token = b.token
AND a.version < b.version
WHERE a.status = ?`
rows, err := c.recordsdb.Raw(query, status).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
invoices := make([]Invoice, 0, 1024) // PNOOMA
for rows.Next() {
var i Invoice
err := c.recordsdb.ScanRows(rows, &i)
if err != nil {
return nil, err
}
invoices = append(invoices, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
// Compile a list of record primary keys
keys := make([]string, 0, len(invoices))
for _, v := range invoices {
keys = append(keys, v.Key)
}
// Lookup files and metadata streams for each of the
// previously queried records.
err = c.recordsdb.
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Where(keys).
Find(&invoices).
Error
if err != nil {
return nil, err
}
dbInvoices := make([]database.Invoice, 0, len(invoices))
for _, v := range invoices {
dbInvoice, err := DecodeInvoice(&v)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *dbInvoice)
}
return dbInvoices, nil
}
// InvoicesAll returns all invoices
func (c *cockroachdb) InvoicesAll() ([]database.Invoice, error) {
// Lookup the latest version of each invoice
query := `SELECT *
FROM invoices a
LEFT OUTER JOIN invoices b
ON a.token = b.token
AND a.version < b.version`
rows, err := c.recordsdb.Raw(query).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
invoices := make([]Invoice, 0, 1024) // PNOOMA
for rows.Next() {
var i Invoice
err := c.recordsdb.ScanRows(rows, &i)
if err != nil {
return nil, err
}
invoices = append(invoices, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
// Compile a list of record primary keys
keys := make([]string, 0, len(invoices))
for _, v := range invoices {
keys = append(keys, v.Key)
}
// Lookup files and metadata streams for each of the
// previously queried records.
err = c.recordsdb.
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Where(keys).
Find(&invoices).
Error
if err != nil {
return nil, err
}
dbInvoices := make([]database.Invoice, 0, len(invoices))
for _, v := range invoices {
dbInvoice, err := DecodeInvoice(&v)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *dbInvoice)
}
return dbInvoices, nil
}
// InvoicesByAddress return invoices by its payment address.
func (c *cockroachdb) InvoicesByAddress(address string) ([]database.Invoice, error) {
log.Debugf("InvoiceByAddress: %v", address)
// Lookup the latest version of each invoice
query := `SELECT *
FROM invoices a
LEFT OUTER JOIN invoices b
ON a.token = b.token
AND a.version < b.version
WHERE b.token IS NULL
AND a.payment_address = ?`
rows, err := c.recordsdb.Raw(query, address).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
invoices := make([]Invoice, 0, 1024) // PNOOMA
for rows.Next() {
var i Invoice
err := c.recordsdb.ScanRows(rows, &i)
if err != nil {
return nil, err
}
invoices = append(invoices, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
// Compile a list of record primary keys
keys := make([]string, 0, len(invoices))
for _, v := range invoices {
keys = append(keys, v.Key)
}
// Lookup files and metadata streams for each of the
// previously queried records.
err = c.recordsdb.
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Where(keys).
Find(&invoices).
Error
if err != nil {
return nil, err
}
dbInvoices := make([]database.Invoice, 0, len(invoices))
for _, v := range invoices {
dbInvoice, err := DecodeInvoice(&v)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *dbInvoice)
}
return dbInvoices, nil
}
// Create new exchange rate.
//
// NewExchangeRate satisfies the database interface.
func (c *cockroachdb) NewExchangeRate(dbExchangeRate *database.ExchangeRate) error {
exchRate := encodeExchangeRate(dbExchangeRate)
log.Debugf("NewExchangeRate: %v %v", exchRate.Month, exchRate.Year)
return c.recordsdb.Create(exchRate).Error
}
// ExchangeRate returns exchange rate by month/year
func (c *cockroachdb) ExchangeRate(month, year int) (*database.ExchangeRate, error) {
log.Tracef("ExchangeRate")
exchangeRate := ExchangeRate{}
err := c.recordsdb.
Where("month = ? AND year = ?", month, year).
Find(&exchangeRate).
Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = database.ErrExchangeRateNotFound
}
return nil, err
}
return decodeExchangeRate(exchangeRate), nil
}
// InvoicesByDateRangeStatus takes a start and end time (in Unix seconds) and returns
// all invoices with the included status. This uses the
// invoice_changes table to discover the token to look up the correct line items.
func (c *cockroachdb) InvoicesByDateRangeStatus(start, end int64, status int) ([]database.Invoice, error) {
log.Debugf("InvoicesByDateRangeStatus: %v %v", time.Unix(start, 0),
time.Unix(end, 0))
// Get all invoice changes of given status within date range.
invoiceChanges := make([]InvoiceChange, 0, 1024) // PNOOMA
err := c.recordsdb.
Where("new_status = ? AND "+
"timestamp BETWEEN ? AND ?",
status,
time.Unix(start, 0),
time.Unix(end, 0)).
Find(&invoiceChanges).
Error
if err != nil {
return nil, err
}
tokens := make([]string, 0, len(invoiceChanges))
for _, r := range invoiceChanges {
tokens = append(tokens, r.InvoiceToken)
}
invoices := make([]Invoice, 0, len(tokens))
// Using all invoice tokens from the results of the query above, ask for all
// invoices that match those tokens.
dbInvoices := make([]database.Invoice, 0, len(tokens))
err = c.recordsdb.
Preload("LineItems").
Preload("Payments").
Preload("Changes").
Where(tokens).
Find(&invoices).
Error
if err != nil {
return nil, err
}
for _, vv := range invoices {
inv, err := DecodeInvoice(&vv)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *inv)
}
return dbInvoices, nil
}
// InvoicesByDateRange takes a start and end time (in Unix seconds) and returns
// all invoices. This uses the
// invoice_changes table to discover the token to look up the correct line items.
func (c *cockroachdb) InvoicesByDateRange(start, end int64) ([]database.Invoice, error) {
log.Debugf("InvoicesByDateRange: %v %v", time.Unix(start, 0),
time.Unix(end, 0))
// Get all invoice changes of NEW status within date range.
invoiceChanges := make([]InvoiceChange, 0, 1024) // PNOOMA
err := c.recordsdb.
Where("new_status = ? AND"+
"timestamp BETWEEN ? AND ?",
v1.InvoiceStatusNew,
time.Unix(start, 0),
time.Unix(end, 0)).
Find(&invoiceChanges).
Error
if err != nil {
return nil, err
}
tokens := make([]string, 0, len(invoiceChanges))
for _, r := range invoiceChanges {
tokens = append(tokens, r.InvoiceToken)
}
invoices := make([]Invoice, 0, len(tokens))
// Using all invoice tokens from the results of the query above, ask for all
// invoices that match those tokens.
dbInvoices := make([]database.Invoice, 0, len(tokens))
err = c.recordsdb.
Preload("LineItems").
Preload("Changes").
Preload("Payments").
Where(tokens).
Find(&invoices).
Error
if err != nil {
return nil, err
}
for _, vv := range invoices {
inv, err := DecodeInvoice(&vv)
if err != nil {
return nil, err
}
dbInvoices = append(dbInvoices, *inv)
}
return dbInvoices, nil
}
// InvoicesByLineItemsProposalToken takes a proposal token as an argument and
// returns all invoices that have line items corresponding with that token.
// All line items that are not considered relevant to the proposal token will
// be omitted.
func (c *cockroachdb) InvoicesByLineItemsProposalToken(token string) ([]database.Invoice, error) {
log.Debugf("InvoicesByLineItemsProposalToken: %v", token)
// Get all line items from approved, new, updated or paid invoices based
// on the provided proposal token
query := `SELECT
invoices.month,
invoices.year,
invoices.user_id,
invoices.public_key,
invoices.contractor_rate,
invoices.exchange_rate,
line_items.invoice_token,
line_items.type,
line_items.domain,
line_items.subdomain,
line_items.description,
line_items.proposal_url,
line_items.labor,
line_items.expenses,
line_items.contractor_rate AS sub_rate,
line_items.sub_user_id as sub_user
FROM invoices
LEFT OUTER JOIN invoices b
ON invoices.token = b.token
AND invoices.version < b.version
INNER JOIN line_items
ON invoices.key = line_items.invoice_key
WHERE line_items.proposal_url = ? AND (
invoices.status = ? OR
invoices.status = ? OR
invoices.status = ? OR
invoices.status = ?)`
rows, err := c.recordsdb.Raw(query, token,
int(v1.InvoiceStatusNew),
int(v1.InvoiceStatusUpdated),
int(v1.InvoiceStatusApproved),
int(v1.InvoiceStatusPaid),
).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
matching := make([]MatchingLineItems, 0, 1024)
for rows.Next() {
var i MatchingLineItems
err := c.recordsdb.ScanRows(rows, &i)
if err != nil {
return nil, err
}
matching = append(matching, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
return convertMatchingLineItemToInvoices(matching), nil
}
// MatchingLineItems is a type used for finding matched line items based on
// proposal ownership.
type MatchingLineItems struct {
InvoiceToken string
UserID string
Month uint
Year uint
Type uint
Domain string
Subdomain string
Description string
ProposalURL string
Labor uint
Expenses uint
ContractorRate uint
PublicKey string
ExchangeRate uint
SubRate uint
SubUser string
}
// Close satisfies the database interface.
func (c *cockroachdb) Close() error {
return c.recordsdb.Close()
}
// This function must be called within a transaction.
func createCmsTables(tx *gorm.DB) error {
log.Tracef("createCmsTables")
// Create cms tables
if !tx.HasTable(tableNameInvoice) {
err := tx.CreateTable(&Invoice{}).Error
if err != nil {
return err
}
}
if !tx.HasTable(tableNameLineItem) {
err := tx.CreateTable(&LineItem{}).Error
if err != nil {
return err
}
}
if !tx.HasTable(tableNameInvoiceChange) {
err := tx.CreateTable(&InvoiceChange{}).Error
if err != nil {
return err
}
}
if !tx.HasTable(tableNameExchangeRate) {
err := tx.CreateTable(&ExchangeRate{}).Error
if err != nil {
return err
}
}
if !tx.HasTable(tableNamePayments) {
err := tx.CreateTable(&Payments{}).Error
if err != nil {
return err
}
}
if !tx.HasTable(tableNameDCC) {
err := tx.CreateTable(&DCC{}).Error
if err != nil {
return err
}
}
if !tx.HasTable(tableNameVersions) {
err := tx.CreateTable(&Version{}).Error
if err != nil {
return err
}
}
var v Version
err := tx.Where("id = ?", cacheID).
Find(&v).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
err = tx.Create(
&Version{
ID: cacheID,
Version: cmsVersion,
Timestamp: time.Now().Unix(),
}).Error
return err
}
return nil
}
// Setup calls the tables creation function to ensure the database is prepared for use.
func (c *cockroachdb) Setup() error {
tx := c.recordsdb.Begin()
err := createCmsTables(tx)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func (c *cockroachdb) dropTables(tx *gorm.DB) error {
// Drop record tables
err := tx.DropTableIfExists(tableNameInvoice, tableNameInvoiceChange,
tableNameLineItem, tableNamePayments, tableNameDCC).Error
if err != nil {
return err
}
// Remove cms version record
return tx.Delete(&Version{
ID: cacheID,
}).Error
}
// build the records cache using the passed in records.
//
// This function cannot be called using a transaction because it could
// potentially exceed cockroachdb's transaction size limit.
func (c *cockroachdb) build(invoices []Invoice, dccs []DCC) error {
log.Tracef("build")
// Drop record tables
tx := c.recordsdb.Begin()
err := c.dropTables(tx)
if err != nil {
tx.Rollback()
return fmt.Errorf("drop tables: %v", err)
}
err = tx.Commit().Error
if err != nil {
return err
}
// Create record tables
tx = c.recordsdb.Begin()
err = createCmsTables(tx)
if err != nil {
tx.Rollback()
return fmt.Errorf("create tables: %v", err)
}
err = tx.Commit().Error
if err != nil {
return err
}
for _, i := range invoices {
err := c.recordsdb.Create(&i).Error
if err != nil {
return fmt.Errorf("create invoice: %v", err)
}
}
for _, d := range dccs {
err := c.recordsdb.Create(&d).Error
if err != nil {
return fmt.Errorf("create dcc: %v", err)
}
}
return nil
}
// Build drops all existing tables from the records cache, recreates them, then
// builds the records cache using the passed in records.
func (c *cockroachdb) Build(dbInvs []database.Invoice, dbDCCs []database.DCC) error {
log.Tracef("Build")
c.Lock()
defer c.Unlock()
if c.shutdown {
return database.ErrShutdown
}
log.Infof("Building records cache")
invoices := make([]Invoice, 0, len(dbInvs))
for _, dbInv := range dbInvs {
inv := EncodeInvoice(&dbInv)
invoices = append(invoices, *inv)
}
dccs := make([]DCC, 0, len(dbDCCs))
for _, dbDCC := range dbDCCs {
dcc := encodeDCC(&dbDCC)
dccs = append(dccs, *dcc)
}
// Build the records cache. This is not run using a
// transaction because it could potentially exceed
// cockroachdb's transaction size limit.
err := c.build(invoices, dccs)
if err != nil {
// Remove the version record. This will
// force a rebuild on the next start up.
err1 := c.recordsdb.Delete(&Version{
ID: cacheID,
}).Error
if err1 != nil {
panic("the cache is out of sync and will not rebuild" +
"automatically; a rebuild must be forced")
}
}
return err
}
func buildQueryString(user, rootCert, cert, key string) string {
v := url.Values{}
v.Set("sslmode", "require")
v.Set("sslrootcert", filepath.Clean(rootCert))
v.Set("sslcert", filepath.Join(cert))
v.Set("sslkey", filepath.Join(key))
return v.Encode()
}
// New returns a new cockroachdb context that contains a connection to the
// specified database that was made using the politeiawww user and the passed
// in certificates.
func New(host, net, rootCert, cert, key string) (*cockroachdb, error) {
log.Tracef("New: %v %v %v %v %v", host, net, rootCert, cert, key)
// Connect to database
dbName := cacheID + "_" + net
h := "postgresql://" + userPoliteiawww + "@" + host + "/" + dbName
u, err := url.Parse(h)
if err != nil {
return nil, fmt.Errorf("parse url '%v': %v", h, err)
}
qs := buildQueryString(u.User.String(), rootCert, cert, key)
addr := u.String() + "?" + qs
db, err := gorm.Open("postgres", addr)
if err != nil {
return nil, fmt.Errorf("connect to database '%v': %v", addr, err)
}
// Create context
c := &cockroachdb{
recordsdb: db,
}
// Disable gorm logging. This prevents duplicate errors from
// being printed since we handle errors manually.
c.recordsdb.LogMode(false)
// Disable automatic table name pluralization. We set table
// names manually.
c.recordsdb.SingularTable(true)
// Return an error if the version record is not found or
// if there is a version mismatch, but also return the
// cache context so that the cache can be built/rebuilt.
if !c.recordsdb.HasTable(tableNameVersions) {
log.Debugf("table '%v' does not exist", tableNameVersions)
return c, database.ErrNoVersionRecord
}
var v Version
err = c.recordsdb.
Where("id = ?", cacheID).
Find(&v).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Debugf("version record not found for ID '%v'", cacheID)
err = database.ErrNoVersionRecord
} else if v.Version != cmsVersion {
log.Debugf("version mismatch for ID '%v': got %v, want %v",
cacheID, v.Version, cmsVersion)
err = database.ErrWrongVersion
}
return c, err
}
// Update existing payment.
//
// UpdatePayments satisfies the database interface.
func (c *cockroachdb) UpdatePayments(dbPayments *database.Payments) error {
payments := encodePayments(dbPayments)
log.Debugf("UpdatePayments: %v", payments.InvoiceKey)
return c.recordsdb.Save(&payments).Error
}
// PaymentsByAddress returns payments row that has the matching Address.
func (c *cockroachdb) PaymentsByAddress(address string) (*database.Payments, error) {
log.Debugf("PaymentsByAddress: %v", address)
payments := Payments{}
err := c.recordsdb.
Where("address = ?", address).
Find(&payments).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = database.ErrInvoiceNotFound
}
return nil, err
}
dbPayments := decodePayment(&payments)
return &dbPayments, nil
}
// PaymentsByStatus returns all payments rows that match the given status.
func (c *cockroachdb) PaymentsByStatus(status uint) ([]database.Payments, error) {
log.Debugf("PaymentsByStatus: %v", status)
payments := make([]Payments, 0, 1048)
err := c.recordsdb.
Where("status = ?", status).
Find(&payments).
Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = database.ErrInvoiceNotFound
}
return nil, err
}
dbPayments := make([]database.Payments, 0, 1048)
for _, v := range payments {
dbPayments = append(dbPayments, decodePayment(&v))
}
return dbPayments, nil
}
// Create new dcc.
//
// NewDCC satisfies the database interface.
func (c *cockroachdb) NewDCC(dbDCC *database.DCC) error {