/
upgrades_legacy.go
1963 lines (1695 loc) · 61 KB
/
upgrades_legacy.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) 2018-2019, The Decred-Next developers
// See LICENSE for details.
package dcrpg
import (
"bytes"
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/Decred-Next/dcrnd/blockchain/stake/version2/v8"
"github.com/Decred-Next/dcrnd/chaincfg/chainhash/v8"
"github.com/Decred-Next/dcrnd/wire/v8"
"github.com/Decred-Next/dcrndata/db/dbtypes/v8"
"github.com/Decred-Next/dcrndata/db/dcrpg/v8/internal"
"github.com/Decred-Next/dcrndata/rpcutils/v8"
"github.com/Decred-Next/dcrndata/semver/v8"
"github.com/Decred-Next/dcrndata/txhelpers/v8"
)
// The tables are versioned as follows. The major version is the same for all
// the tables. A bump of this version is used to signal that all tables should
// be dropped and rebuilt. The minor versions may be different, and they are
// used to indicate a change requiring a table upgrade, which would be handled
// by dcrdata or rebuilddb2. The patch versions may also be different. They
// indicate a change of a table's index or constraint, which may require
// re-indexing and a duplicate scan/purge.
const (
tableMajor = 3
tableMinor = 11
tablePatch = 0
)
// TODO eliminiate this map since we're actually versioning each table the same.
var requiredVersions = map[string]TableVersion{
"blocks": NewTableVersion(tableMajor, tableMinor, tablePatch),
"transactions": NewTableVersion(tableMajor, tableMinor, tablePatch),
"vins": NewTableVersion(tableMajor, tableMinor, tablePatch),
"vouts": NewTableVersion(tableMajor, tableMinor, tablePatch),
"block_chain": NewTableVersion(tableMajor, tableMinor, tablePatch),
"addresses": NewTableVersion(tableMajor, tableMinor, tablePatch),
"tickets": NewTableVersion(tableMajor, tableMinor, tablePatch),
"votes": NewTableVersion(tableMajor, tableMinor, tablePatch),
"misses": NewTableVersion(tableMajor, tableMinor, tablePatch),
"agendas": NewTableVersion(tableMajor, tableMinor, tablePatch),
"agenda_votes": NewTableVersion(tableMajor, tableMinor, tablePatch),
"testing": NewTableVersion(tableMajor, tableMinor, tablePatch),
"proposals": NewTableVersion(tableMajor, tableMinor, tablePatch),
"proposal_votes": NewTableVersion(tableMajor, tableMinor, tablePatch),
}
// TableVersion models a table version by major.minor.patch
type TableVersion struct {
major, minor, patch uint32
}
// CompatibilityAction defines the action to be taken once the current and the
// required pg table versions are compared.
type CompatibilityAction int8
const (
compatRebuild CompatibilityAction = iota
compatUpgrade
compatReindex
compatOK
compatUnknown
)
// TableVersionCompatible indicates if the table versions are compatible
// (equal), and if not, what is the required action (rebuild, upgrade, or
// reindex).
func TableVersionCompatible(required, actual TableVersion) CompatibilityAction {
switch {
case required.major != actual.major:
return compatRebuild
case required.minor != actual.minor:
return compatUpgrade
case required.patch != actual.patch:
return compatReindex
default:
return compatOK
}
}
func (s TableVersion) String() string {
return fmt.Sprintf("%d.%d.%d", s.major, s.minor, s.patch)
}
// String implements Stringer for CompatibilityAction.
func (v CompatibilityAction) String() string {
actions := map[CompatibilityAction]string{
compatRebuild: "rebuild",
compatUpgrade: "upgrade",
compatReindex: "reindex",
compatOK: "ok",
}
if actionStr, ok := actions[v]; ok {
return actionStr
}
return "unknown"
}
// NewTableVersion returns a new TableVersion with the version major.minor.patch
func NewTableVersion(major, minor, patch uint32) TableVersion {
return TableVersion{major, minor, patch}
}
// TableUpgrade is used to define a required upgrade for a table
type TableUpgrade struct {
TableName string
UpgradeType CompatibilityAction
CurrentVer, RequiredVer TableVersion
}
func (s TableUpgrade) String() string {
return fmt.Sprintf("Table %s requires %s (%s -> %s).", s.TableName,
s.UpgradeType, s.CurrentVer, s.RequiredVer)
}
var createLegacyTableStatements = map[string]string{
"blocks": internal.CreateBlockTable,
"transactions": internal.CreateTransactionTable,
"vins": internal.CreateVinTable,
"vouts": internal.CreateVoutTable,
"block_chain": internal.CreateBlockPrevNextTable,
"addresses": internal.CreateAddressTable,
"tickets": internal.CreateTicketsTable,
"votes": internal.CreateVotesTable,
"misses": internal.CreateMissesTable,
"agendas": internal.CreateAgendasTable,
"agenda_votes": internal.CreateAgendaVotesTable,
"testing": internal.CreateTestingTable,
"proposals": internal.CreateProposalsTable,
"proposal_votes": internal.CreateProposalVotesTable,
}
// CreateTablesLegacy creates all tables required by dcrdata if they do not
// already exist.
func CreateTablesLegacy(db *sql.DB) error {
var err error
for tableName, createCommand := range createLegacyTableStatements {
var exists bool
exists, err = TableExists(db, tableName)
if err != nil {
return err
}
tableVersion, ok := requiredVersions[tableName]
if !ok {
return fmt.Errorf("no version assigned to table %s", tableName)
}
if !exists {
log.Infof("Creating the \"%s\" table.", tableName)
_, err = db.Exec(createCommand)
if err != nil {
return err
}
_, err = db.Exec(fmt.Sprintf(`COMMENT ON TABLE %s IS 'v%s';`,
tableName, tableVersion))
if err != nil {
return err
}
} else {
log.Tracef("Table \"%s\" exist.", tableName)
}
}
return ClearTestingTable(db)
}
// CreateTableLegacy creates one of the known tables by name.
func CreateTableLegacy(db *sql.DB, tableName string) error {
var err error
createCommand, tableNameFound := createLegacyTableStatements[tableName]
if !tableNameFound {
return fmt.Errorf("table name %s unknown", tableName)
}
tableVersion, ok := requiredVersions[tableName]
if !ok {
return fmt.Errorf("no version assigned to table %s", tableName)
}
var exists bool
exists, err = TableExists(db, tableName)
if err != nil {
return err
}
if !exists {
log.Infof("Creating the \"%s\" table.", tableName)
_, err = db.Exec(createCommand)
if err != nil {
return err
}
_, err = db.Exec(fmt.Sprintf(`COMMENT ON TABLE %s IS 'v%s';`,
tableName, tableVersion))
if err != nil {
return err
}
} else {
log.Tracef("Table \"%s\" exist.", tableName)
}
return err
}
// TableUpgradesRequired builds a list of table upgrade information for each
// of the supported auxiliary db tables. The upgrade information includes the
// table name, its current & required table versions and the action to be taken
// after comparing the current & required versions.
func TableUpgradesRequired(versions map[string]TableVersion) []TableUpgrade {
var tableUpgrades []TableUpgrade
for t := range createLegacyTableStatements {
var ok bool
var req, act TableVersion
if req, ok = requiredVersions[t]; !ok {
log.Errorf("required version unknown for table %s", t)
tableUpgrades = append(tableUpgrades, TableUpgrade{
TableName: t,
UpgradeType: compatUnknown,
})
continue
}
if act, ok = versions[t]; !ok {
log.Errorf("current version unknown for table %s", t)
tableUpgrades = append(tableUpgrades, TableUpgrade{
TableName: t,
UpgradeType: compatRebuild,
RequiredVer: req,
})
continue
}
versionCompatibility := TableVersionCompatible(req, act)
tableUpgrades = append(tableUpgrades, TableUpgrade{
TableName: t,
UpgradeType: versionCompatibility,
CurrentVer: act,
RequiredVer: req,
})
}
return tableUpgrades
}
// TableVersions retrieve and maps the tables names in the auxiliary db to their
// current table versions.
func TableVersions(db *sql.DB) map[string]TableVersion {
versions := map[string]TableVersion{}
for tableName := range createLegacyTableStatements {
// Retrieve the table description.
var desc string
err := db.QueryRow(`select obj_description($1::regclass);`, tableName).Scan(&desc)
if err != nil {
log.Errorf("Query of table %s description failed: %v", tableName, err)
continue
}
// Attempt to parse a version out of the table description.
sv, err := semver.ParseVersionStr(desc)
if err != nil {
log.Errorf("Failed to parse version from table description %s: %v",
desc, err)
continue
}
versions[tableName] = NewTableVersion(sv.Split())
}
return versions
}
// tableUpgradeType defines the types of upgrades that currently exists and
// happen automatically. This upgrade run on normal start up the first the
// style is run after updating dcrdata past version 3.0.0.
type tableUpgradeType int
const (
vinsTableCoinSupplyUpgrade tableUpgradeType = iota
agendasTableUpgrade
vinsTableMainchainUpgrade
blocksTableMainchainUpgrade
transactionsTableMainchainUpgrade
addressesTableMainchainUpgrade
votesTableMainchainUpgrade
ticketsTableMainchainUpgrade
votesTableBlockHashIndex
vinsTxHistogramUpgrade
addressesTxHistogramUpgrade
agendasVotingMilestonesUpgrade
ticketsTableBlockTimeUpgrade
addressesTableValidMainchainPatch
addressesTableMatchingTxHashPatch
addressesTableBlockTimeSortedIndex
addressesBlockTimeDataTypeUpdate
blocksBlockTimeDataTypeUpdate
agendasBlockTimeDataTypeUpdate
transactionsBlockTimeDataTypeUpdate
vinsBlockTimeDataTypeUpdate
blocksChainWorkUpdate
blocksRemoveRootColumns
timestamptzUpgrade
agendasTablePruningUpdate
agendaVotesTableCreationUpdate
votesTableBlockTimeUpdate
proposalsTableTokensUpdate
proposalVotesTableTicketsIndex
)
type TableUpgradeType struct {
TableName string
upgradeType tableUpgradeType
}
// VinVoutTypeUpdateData defines the fetched details from the transactions table that
// are needed to undertake the histogram upgrade.
type VinVoutTypeUpdateData struct {
VinsDbIDs dbtypes.UInt64Array
VoutsDbIDs dbtypes.UInt64Array
TxType stake.TxType
}
// VersionCheck checks the current version of all known tables and notifies when
// an upgrade is required. If there is no automatic upgrade supported, an error
// is returned when any table is not of the correct version. An RPC client is
// passed to implement the supported upgrades if need be.
func (pgb *ChainDB) VersionCheck(client BlockGetter) error {
vers := TableVersions(pgb.db)
for tab, ver := range vers {
log.Debugf("Table %s: v%s", tab, ver)
}
var needsUpgrade []TableUpgrade
tableUpgrades := TableUpgradesRequired(vers)
for _, val := range tableUpgrades {
switch val.UpgradeType {
case compatUpgrade, compatReindex:
// Select the all tables that need an upgrade or reindex.
needsUpgrade = append(needsUpgrade, val)
case compatUnknown, compatRebuild:
// All the tables require rebuilding.
return fmt.Errorf("rebuild of PostgreSQL tables required (drop with rebuilddb2 -D)")
}
}
if len(needsUpgrade) == 0 {
// All tables have the correct version.
log.Debugf("All tables at correct version (%v)", tableUpgrades[0].RequiredVer)
return nil
}
// UpgradeTables adds the pending db upgrades and reindexes.
_, err := pgb.UpgradeTables(client, needsUpgrade[0].CurrentVer,
needsUpgrade[0].RequiredVer)
if err != nil {
return err
}
// Upgrade was successful.
return nil
}
// votingMilestones defines the various milestones phases have taken place when
// the agendas have been up for voting. Only sdiffalgorithm, lnsupport and
// lnfeatures agenda ids exist since appropriate voting mechanisms on the dcrd
// level are not yet fully implemented.
var votingMilestones = map[string]dbtypes.MileStone{}
// toVersion defines a table version to which the pg tables will commented to.
var toVersion TableVersion
// UpgradeTables upgrades all the tables with the pending updates from the
// current table versions to the most recent table version supported. A boolean
// is returned to indicate if the db upgrade was successfully completed.
func (pgb *ChainDB) UpgradeTables(dcrdClient BlockGetter, version, needVersion TableVersion) (bool, error) {
// If the previous DB is between the 3.1/3.2 and 4.0 releases (dcrpg table
// versions >3.5.5 and <3.9.0), an upgrade is likely not possible IF PostgreSQL
// was running in a TimeZone other than UTC. Deny upgrade.
if version.major == 3 && ((version.minor > 5 && version.minor < 9) ||
(version.minor == 5 && version.patch > 5)) {
dataType, err := CheckColumnDataType(pgb.db, "blocks", "time")
if err != nil {
return false, fmt.Errorf("failed to retrieve data_type for blocks.time: %v", err)
}
if dataType == "timestamp without time zone" {
// Timestamp columns are timestamp without time zone.
defaultTZ, _, err := CheckDefaultTimeZone(pgb.db)
if err != nil {
return false, fmt.Errorf("failed in CheckDefaultTimeZone: %v", err)
}
if defaultTZ != "UTC" {
// Postgresql time zone is not UTC, which is bad when the data
// type throws away time zone offset info, as is the case with
// TIMESTAMP. If the default time zone were UTC, there is likely
// no time stamp issue.
return false, fmt.Errorf(
"your dcrpg schema (v%v) has time columns without time zone, "+
"AND the PostgreSQL default/local time zone is %s. "+
"You must rebuild the databases from scratch!!!",
version, defaultTZ)
}
}
}
// Apply each upgrade in succession
switch {
// Upgrade from 3.1.0 --> 3.2.0
case version.major == 3 && version.minor == 1 && version.patch == 0:
toVersion = TableVersion{3, 2, 0}
theseUpgrades := []TableUpgradeType{
{"agendas", agendasTableUpgrade},
{"vins", vinsTableCoinSupplyUpgrade},
}
isSuccess, er := pgb.initiatePgUpgrade(dcrdClient, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.2.0 --> 3.3.0
case version.major == 3 && version.minor == 2 && version.patch == 0:
toVersion = TableVersion{3, 3, 0}
// The order of these upgrades is critical
theseUpgrades := []TableUpgradeType{
{"blocks", blocksTableMainchainUpgrade}, // also patches block_chain
{"transactions", transactionsTableMainchainUpgrade},
{"vins", vinsTableMainchainUpgrade},
{"addresses", addressesTableMainchainUpgrade},
{"votes", votesTableMainchainUpgrade},
}
isSuccess, er := pgb.initiatePgUpgrade(dcrdClient, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.3.0 --> 3.4.0
case version.major == 3 && version.minor == 3 && version.patch == 0:
toVersion = TableVersion{3, 4, 0}
// The order of these upgrades is critical
theseUpgrades := []TableUpgradeType{
{"tickets", ticketsTableMainchainUpgrade},
}
isSuccess, er := pgb.initiatePgUpgrade(dcrdClient, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.4.0 --> 3.4.1
case version.major == 3 && version.minor == 4 && version.patch == 0:
// This is a "reindex" upgrade. Bump patch.
toVersion = TableVersion{3, 4, 1}
// The order of these upgrades is critical
theseUpgrades := []TableUpgradeType{
{"votes", votesTableBlockHashIndex},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.4.1 --> 3.5.0
case version.major == 3 && version.minor == 4 && version.patch == 1:
toVersion = TableVersion{3, 5, 0}
theseUpgrades := []TableUpgradeType{
{"vins", vinsTxHistogramUpgrade},
{"addresses", addressesTxHistogramUpgrade},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.5.0 --> 3.5.1
case version.major == 3 && version.minor == 5 && version.patch == 0:
toVersion = TableVersion{3, 5, 1}
theseUpgrades := []TableUpgradeType{
{"agendas", agendasVotingMilestonesUpgrade},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.5.1 --> 3.5.2
case version.major == 3 && version.minor == 5 && version.patch == 1:
toVersion = TableVersion{3, 5, 2}
theseUpgrades := []TableUpgradeType{
{"tickets", ticketsTableBlockTimeUpgrade},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.5.2 --> 3.5.3
case version.major == 3 && version.minor == 5 && version.patch == 2:
toVersion = TableVersion{3, 5, 3}
theseUpgrades := []TableUpgradeType{
{"addresses", addressesTableValidMainchainPatch},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.5.3 --> 3.5.4
case version.major == 3 && version.minor == 5 && version.patch == 3:
toVersion = TableVersion{3, 5, 4}
theseUpgrades := []TableUpgradeType{
{"addresses", addressesTableMatchingTxHashPatch},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.5.4 --> 3.5.5
case version.major == 3 && version.minor == 5 && version.patch == 4:
toVersion = TableVersion{3, 5, 5} // dcrdata 3.1 release
theseUpgrades := []TableUpgradeType{
{"addresses", addressesTableBlockTimeSortedIndex},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.5.5 --> 3.6.0
case version.major == 3 && version.minor == 5 && version.patch == 5:
toVersion = TableVersion{3, 6, 0}
theseUpgrades := []TableUpgradeType{
{"addresses", addressesBlockTimeDataTypeUpdate},
{"blocks", blocksBlockTimeDataTypeUpdate},
{"agendas", agendasBlockTimeDataTypeUpdate},
{"transactions", transactionsBlockTimeDataTypeUpdate},
{"vins", vinsBlockTimeDataTypeUpdate},
}
pgb.dropBlockTimeIndexes()
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
pgb.createBlockTimeIndexes()
// Go on to next upgrade
fallthrough
// Upgrade from 3.6.0 --> 3.7.0
case version.major == 3 && version.minor == 6 && version.patch == 0:
toVersion = TableVersion{3, 7, 0}
theseUpgrades := []TableUpgradeType{
{"blocks", blocksChainWorkUpdate},
}
isSuccess, er := pgb.initiatePgUpgrade(dcrdClient, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.7.0 --> 3.8.0
case version.major == 3 && version.minor == 7 && version.patch == 0:
toVersion = TableVersion{3, 8, 0}
theseUpgrades := []TableUpgradeType{
{"blocks", blocksRemoveRootColumns},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.8.0 --> 3.9.0
case version.major == 3 && version.minor == 8 && version.patch == 0:
toVersion = TableVersion{3, 9, 0}
theseUpgrades := []TableUpgradeType{
{"all", timestamptzUpgrade},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.9.0 --> 3.10.0
case version.major == 3 && version.minor == 9 && version.patch == 0:
toVersion = TableVersion{3, 10, 0}
theseUpgrades := []TableUpgradeType{
{"agenda_votes", agendaVotesTableCreationUpdate},
{"votes", votesTableBlockTimeUpdate},
// Should be the last to run.
{"agendas", agendasTablePruningUpdate},
}
// chainInfo is needed for this upgrade.
rawChainInfo, err := dcrdClient.GetBlockChainInfo()
if err != nil {
return false, err
}
pgb.UpdateChainState(rawChainInfo)
isSuccess, er := pgb.initiatePgUpgrade(dcrdClient, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
fallthrough
// Upgrade from 3.10.0 --> 3.11.0
case version.major == 3 && version.minor == 10 && version.patch == 0:
toVersion = TableVersion{3, 11, 0}
theseUpgrades := []TableUpgradeType{
{"proposals", proposalsTableTokensUpdate},
{"proposal_votes", proposalVotesTableTicketsIndex},
}
isSuccess, er := pgb.initiatePgUpgrade(nil, theseUpgrades)
if !isSuccess {
return isSuccess, er
}
// Go on to next upgrade
// fallthrough
// or be done
default:
// UpgradeType == "upgrade" or "reindex", but no supported case.
return false, fmt.Errorf("no upgrade path available for version %v --> %v",
version, needVersion)
}
upgradeFailed := fmt.Errorf("failed to upgrade tables to required version %v",
needVersion)
upgradeInfo := TableUpgradesRequired(TableVersions(pgb.db))
// If no upgrade information exists, return an error.
if len(upgradeInfo) == 0 {
return false, upgradeFailed
}
// Ensure that the required version was reached for all the table upgrades
// otherwise return an error.
for _, info := range upgradeInfo {
if info.UpgradeType != compatOK {
return false, upgradeFailed
}
}
// Unsupported upgrades are caught by the default case, so we've succeeded.
log.Infof("Table upgrades completed.")
return true, nil
}
// initiatePgUpgrade starts the specific auxiliary database.
func (pgb *ChainDB) initiatePgUpgrade(client BlockGetter, theseUpgrades []TableUpgradeType) (bool, error) {
for it := range theseUpgrades {
upgradeSuccess, err := pgb.handleUpgrades(client, theseUpgrades[it].upgradeType)
if err != nil || !upgradeSuccess {
return false, fmt.Errorf("failed to upgrade %s table to version %v. Error: %v",
theseUpgrades[it].TableName, toVersion, err)
}
}
// A Table upgrade must have happened therefore Bump version
if err := versionAllTables(pgb.db, toVersion); err != nil {
return false, fmt.Errorf("failed to bump version to %v: %v", toVersion, err)
}
return true, nil
}
// handleUpgrades the individual upgrade and returns a bool and an error
// indicating if the upgrade was successful or not.
func (pgb *ChainDB) handleUpgrades(client BlockGetter, tableUpgrade tableUpgradeType) (bool, error) {
var err error
var startHeight int64
var tableReady bool
var tableName, upgradeTypeStr string
switch tableUpgrade {
case vinsTableCoinSupplyUpgrade:
tableReady, err = addVinsColumnsForCoinSupply(pgb.db)
tableName, upgradeTypeStr = "vins", "vin validity/coin supply"
case vinsTableMainchainUpgrade:
tableReady, err = addVinsColumnsForMainchain(pgb.db)
tableName, upgradeTypeStr = "vins", "sidechain/reorg"
case blocksTableMainchainUpgrade:
tableReady, err = addBlocksColumnsForMainchain(pgb.db)
tableName, upgradeTypeStr = "blocks", "sidechain/reorg"
case addressesTableMainchainUpgrade:
tableReady, err = addAddressesColumnsForMainchain(pgb.db)
tableName, upgradeTypeStr = "addresses", "sidechain/reorg"
case votesTableMainchainUpgrade:
tableReady, err = addVotesColumnsForMainchain(pgb.db)
tableName, upgradeTypeStr = "votes", "sidechain/reorg"
case ticketsTableMainchainUpgrade:
tableReady, err = addTicketsColumnsForMainchain(pgb.db)
tableName, upgradeTypeStr = "tickets", "sidechain/reorg"
case transactionsTableMainchainUpgrade:
tableReady, err = addTransactionsColumnsForMainchain(pgb.db)
tableName, upgradeTypeStr = "transactions", "sidechain/reorg"
case agendasTableUpgrade:
tableReady, err = haveEmptyAgendasTable(pgb.db)
tableName, upgradeTypeStr = "agendas", "new table"
// startHeight is set to a block height of 128000 since that is when
// the first vote for a mainnet agenda was cast. For vins upgrades
// (coin supply and mainchain), startHeight is not set since all the
// blocks are considered.
startHeight = 128000
case votesTableBlockHashIndex:
tableReady = true
tableName, upgradeTypeStr = "votes", "new index"
case vinsTxHistogramUpgrade:
tableReady, err = addVinsColumnsForHistogramUpgrade(pgb.db)
tableName, upgradeTypeStr = "vins", "tx-type addition/histogram"
case addressesTxHistogramUpgrade:
tableReady, err = addAddressesColumnsForHistogramUpgrade(pgb.db)
tableName, upgradeTypeStr = "addresses", "tx-type addition/histogram"
case agendasVotingMilestonesUpgrade:
// upgrade only important to all who have already done a fresh data
// migration between pg version 3.2.0 and 3.5.0.
tableReady = true
tableName, upgradeTypeStr = "agendas", "voting milestones"
case ticketsTableBlockTimeUpgrade:
tableReady = true
tableName, upgradeTypeStr = "tickets", "new index"
case addressesTableValidMainchainPatch:
tableReady = true
tableName, upgradeTypeStr = "addresses", "patch valid_mainchain value"
case addressesTableMatchingTxHashPatch:
tableReady = true
tableName, upgradeTypeStr = "addresses", "patch matching_tx_hash value"
case addressesTableBlockTimeSortedIndex:
tableReady = true
tableName, upgradeTypeStr = "addresses", "reindex"
case addressesBlockTimeDataTypeUpdate:
tableReady = true
tableName, upgradeTypeStr = "addresses", "block time data type update"
case blocksBlockTimeDataTypeUpdate:
tableReady = true
tableName, upgradeTypeStr = "blocks", "block time data type update"
case agendasBlockTimeDataTypeUpdate:
tableReady = true
tableName, upgradeTypeStr = "agendas", "block time data type update"
case transactionsBlockTimeDataTypeUpdate:
tableReady = true
tableName, upgradeTypeStr = "transactions", "block time data type update"
case vinsBlockTimeDataTypeUpdate:
tableReady = true
tableName, upgradeTypeStr = "vins", "block time data type update"
case blocksChainWorkUpdate:
tableReady, err = addChainWorkColumn(pgb.db)
tableName, upgradeTypeStr = "blocks", "new chainwork column"
case blocksRemoveRootColumns:
tableReady, err = deleteRootsColumns(pgb.db)
tableName, upgradeTypeStr = "blocks", "remove columns: extra_data, merkle_root, stake_root, final_state"
case timestamptzUpgrade:
tableReady = true
tableName, upgradeTypeStr = "every", "convert timestamp columns to timestamptz type"
case agendasTablePruningUpdate:
// StakeValidationHeight defines the height from where votes transactions
// exists as from. They only exist after block 4090 on mainnet.
startHeight = pgb.chainParams.StakeValidationHeight
tableReady, err = pruneAgendasTable(pgb.db)
tableName, upgradeTypeStr = "agendas", "prune agendas table"
case agendaVotesTableCreationUpdate:
tableReady, err = createNewAgendaVotesTable(pgb.db)
tableName, upgradeTypeStr = "agendas", "create agenda votes table"
case votesTableBlockTimeUpdate:
tableReady, err = addVotesBlockTimeColumn(pgb.db)
tableName, upgradeTypeStr = "votes", "new block_time column"
case proposalsTableTokensUpdate:
// All missing auxiliary db tables are created by SetupTables() before
// any upgrades are run. New db creation code will not be added since
// it will be unnecessary.
tableReady = true
tableName, upgradeTypeStr = "proposal and proposal_votes", "new tables"
case proposalVotesTableTicketsIndex:
tableReady = true
tableName, upgradeTypeStr = "tickets", "new index"
default:
return false, fmt.Errorf(`upgrade "%v" is unknown`, tableUpgrade)
}
// Ensure new columns were added successfully.
if err != nil || !tableReady {
return false, fmt.Errorf("failed to prepare table(s) %s for %s upgrade: %v",
tableName, upgradeTypeStr, err)
}
// Update table data
var rowsUpdated int64
timeStart := time.Now()
switch tableUpgrade {
case vinsTableCoinSupplyUpgrade, agendasTableUpgrade, agendasTablePruningUpdate:
// height is the best block where this table upgrade should stop at.
height, err := pgb.HeightDBLegacy()
if err != nil {
return false, err
}
log.Infof("found the best block at height: %v", height)
// For each block on the main chain, perform upgrade operations.
for i := startHeight; i <= height; i++ {
block, _, err := rpcutils.GetBlock(i, client)
if err != nil {
return false, err
}
if i%5000 == 0 {
var limit = i + 5000
if height < limit {
limit = height
}
log.Infof("Upgrading the %s table (%s upgrade) from height %v to %v ",
tableName, upgradeTypeStr, i, limit-1)
}
var rows int64
var msgBlock = block.MsgBlock()
switch tableUpgrade {
case vinsTableCoinSupplyUpgrade:
rows, err = pgb.handlevinsTableCoinSupplyUpgrade(msgBlock)
case agendasTableUpgrade:
rows, err = pgb.handleAgendasTableUpgrade(msgBlock)
case agendasTablePruningUpdate:
rows, err = pgb.handleAgendaAndAgendaVotesTablesUpgrade(msgBlock)
}
if err != nil {
return false, err
}
rowsUpdated += rows
}
case blocksTableMainchainUpgrade:
var blockHash string
// blocks table upgrade proceeds from best block back to genesis
_, blockHash, _, err = RetrieveBestBlockHeightAny(context.Background(), pgb.db)
if err != nil {
return false, fmt.Errorf("failed to retrieve best block from DB: %v", err)
}
log.Infof("Starting blocks table mainchain upgrade at block %s (working back to genesis)", blockHash)
rowsUpdated, err = pgb.handleBlocksTableMainchainUpgrade(blockHash)
case transactionsTableMainchainUpgrade:
// transactions table upgrade handled entirely by the DB backend
log.Infof("Starting transactions table mainchain upgrade...")
rowsUpdated, err = pgb.handleTransactionsTableMainchainUpgrade()
case vinsTableMainchainUpgrade:
// vins table upgrade handled entirely by the DB backend
log.Infof("Starting vins table mainchain upgrade...")
rowsUpdated, err = pgb.handleVinsTableMainchainupgrade()
case votesTableMainchainUpgrade:
// votes table upgrade handled entirely by the DB backend
log.Infof("Starting votes table mainchain upgrade...")
rowsUpdated, err = updateAllVotesMainchain(pgb.db)
case ticketsTableMainchainUpgrade:
// tickets table upgrade handled entirely by the DB backend
log.Infof("Starting tickets table mainchain upgrade...")
rowsUpdated, err = updateAllTicketsMainchain(pgb.db)
case addressesTableMainchainUpgrade:
// addresses table upgrade handled entirely by the DB backend
log.Infof("Starting addresses table mainchain upgrade...")
log.Infof("This an extremely I/O intensive operation on the database machine. It can take from 30-90 minutes.")
rowsUpdated, err = updateAllAddressesValidMainchain(pgb.db)
case votesTableBlockHashIndex, ticketsTableBlockTimeUpgrade, addressesTableBlockTimeSortedIndex,
proposalVotesTableTicketsIndex:
// no upgrade, just "reindex"
case vinsTxHistogramUpgrade, addressesTxHistogramUpgrade:
var height int64
// height is the best block where this table upgrade should stop at.
height, err = pgb.HeightDBLegacy()
if err != nil {
return false, err
}
log.Infof("found the best block at height: %v", height)
rowsUpdated, err = pgb.handleTxTypeHistogramUpgrade(uint64(height), tableUpgrade)
case agendasVotingMilestonesUpgrade:
log.Infof("Setting the agendas voting milestones...")
rowsUpdated, err = pgb.handleAgendasVotingMilestonesUpgrade()
case addressesTableValidMainchainPatch:
log.Infof("Patching valid_mainchain in the addresses table...")
rowsUpdated, err = updateAddressesValidMainchainPatch(pgb.db)
case addressesTableMatchingTxHashPatch:
log.Infof("Patching matching_tx_hash in the addresses table...")
rowsUpdated, err = updateAddressesMatchingTxHashPatch(pgb.db)
case blocksChainWorkUpdate:
log.Infof("Syncing chainwork. This might take a while...")
rowsUpdated, err = verifyChainWork(client, pgb.db)
case timestamptzUpgrade:
log.Infof("Converting all TIMESTAMP columns to TIMESTAMPTZ...")
err = handleConvertTimeStampTZ(pgb.db)
case addressesBlockTimeDataTypeUpdate, blocksBlockTimeDataTypeUpdate,
agendasBlockTimeDataTypeUpdate, transactionsBlockTimeDataTypeUpdate,
vinsBlockTimeDataTypeUpdate, blocksRemoveRootColumns,
agendaVotesTableCreationUpdate, votesTableBlockTimeUpdate:
// agendaVotesTableCreationUpdate and votesTableBlockTimeUpdate dbs
// population is fully handled by agendasTablePruningUpdate
case proposalsTableTokensUpdate:
// Handles update for proposals and proposal_votes table.
log.Info("Syncing Politeia's proposals votes data. This might take a while...")
rowsUpdated, err = pgb.PiProposalsHistory()
default:
return false, fmt.Errorf(`upgrade "%v" unknown`, tableUpgrade)
}
if err != nil && err != sql.ErrNoRows {
return false, fmt.Errorf(`%s upgrade of %s table ended prematurely after %d rows.`+
`Error: %v`, upgradeTypeStr, tableName, rowsUpdated, err)
}
if rowsUpdated > 0 {
log.Infof(" - %v rows in %s table (%s upgrade) were successfully upgraded in %.2f sec",
rowsUpdated, tableName, upgradeTypeStr, time.Since(timeStart).Seconds())
}