-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.go
More file actions
1659 lines (1437 loc) · 49.5 KB
/
Copy pathschema.go
File metadata and controls
1659 lines (1437 loc) · 49.5 KB
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 schema
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"regexp"
"sort"
"strings"
"github.com/jackc/pgx/v4"
"github.com/mitchellh/hashstructure/v2"
"github.com/stripe/pg-schema-diff/internal/concurrent"
"github.com/stripe/pg-schema-diff/internal/queries"
)
type (
// Object represents a resource in a schema (table, column, index...)
Object interface {
// GetName is used to identify the old and new versions of a schema object between the old and new schemas
// If the name is not present in the old schema objects list, then it is added
// If the name is not present in the new schemas objects list, then it is removed
// Otherwise, it has persisted across two schemas and is possibly altered
//
// GetName should be qualified with the schema name.
GetName() string
}
// SchemaQualifiedName represents a schema object name scoped within a schema
SchemaQualifiedName struct {
SchemaName string
// EscapedName is the name of the object. It should already be escaped
// We take an escaped name because there are weird exceptions, like functions, where we can't just
// surround the name in quotes
EscapedName string
}
)
func (o SchemaQualifiedName) GetName() string {
return o.GetFQEscapedName()
}
// GetFQEscapedName gets the fully-qualified, escaped name of the schema object, including the schema name
func (o SchemaQualifiedName) GetFQEscapedName() string {
return fmt.Sprintf("%s.%s", EscapeIdentifier(o.SchemaName), o.EscapedName)
}
func (o SchemaQualifiedName) IsEmpty() bool {
return len(o.SchemaName) == 0
}
// Schema is the schema of the database, not just a single Postgres schema.
type Schema struct {
NamedSchemas []NamedSchema
Extensions []Extension
Enums []Enum
Tables []Table
Indexes []Index
ForeignKeyConstraints []ForeignKeyConstraint
Sequences []Sequence
Functions []Function
Procedures []Procedure
Triggers []Trigger
Views []View
MaterializedViews []MaterializedView
}
// Normalize normalizes the schema (alphabetically sorts tables and columns in tables).
// Useful for hashing and testing.
func (s Schema) Normalize() Schema {
s.NamedSchemas = sortSchemaObjectsByName(s.NamedSchemas)
s.Extensions = sortSchemaObjectsByName(s.Extensions)
s.Enums = sortSchemaObjectsByName(s.Enums)
var normTables []Table
for _, t := range sortSchemaObjectsByName(s.Tables) {
normTables = append(normTables, normalizeTable(t))
}
s.Tables = normTables
s.Indexes = sortSchemaObjectsByName(s.Indexes)
s.ForeignKeyConstraints = sortSchemaObjectsByName(s.ForeignKeyConstraints)
s.Sequences = sortSchemaObjectsByName(s.Sequences)
var normFunctions []Function
for _, function := range sortSchemaObjectsByName(s.Functions) {
function.DependsOnFunctions = sortSchemaObjectsByName(function.DependsOnFunctions)
normFunctions = append(normFunctions, function)
}
s.Functions = normFunctions
s.Procedures = sortSchemaObjectsByName(s.Procedures)
s.Triggers = sortSchemaObjectsByName(s.Triggers)
var normViews []View
for _, v := range sortSchemaObjectsByName(s.Views) {
normViews = append(normViews, normalizeView(v))
}
s.Views = normViews
var normMaterializedViews []MaterializedView
for _, mv := range sortSchemaObjectsByName(s.MaterializedViews) {
normMaterializedViews = append(normMaterializedViews, normalizeMaterializedView(mv))
}
s.MaterializedViews = normMaterializedViews
return s
}
func normalizeTable(t Table) Table {
// Don't normalize columns order. their order is derived from the postgres catalogs
// (relevant to data packing)
var normCheckConstraints []CheckConstraint
for _, checkConstraint := range sortSchemaObjectsByName(t.CheckConstraints) {
checkConstraint.DependsOnFunctions = sortSchemaObjectsByName(checkConstraint.DependsOnFunctions)
checkConstraint.KeyColumns = sortByKey(checkConstraint.KeyColumns, func(s string) string {
return s
})
normCheckConstraints = append(normCheckConstraints, checkConstraint)
}
t.CheckConstraints = normCheckConstraints
var normPolicies []Policy
for _, p := range sortSchemaObjectsByName(t.Policies) {
p.AppliesTo = sortByKey(p.AppliesTo, func(s string) string {
return s
})
p.Columns = sortByKey(p.Columns, func(s string) string {
return s
})
p.FunctionDependencies = sortSchemaObjectsByName(p.FunctionDependencies)
normPolicies = append(normPolicies, p)
}
t.Policies = normPolicies
t.Privileges = sortSchemaObjectsByName(t.Privileges)
return t
}
func normalizeView(v View) View {
var normTableDeps []TableDependency
for _, d := range sortSchemaObjectsByName(v.TableDependencies) {
d.Columns = sortByKey(d.Columns, func(s string) string { return s })
normTableDeps = append(normTableDeps, d)
}
v.TableDependencies = normTableDeps
return v
}
func normalizeMaterializedView(mv MaterializedView) MaterializedView {
var normTableDeps []TableDependency
for _, d := range sortSchemaObjectsByName(mv.TableDependencies) {
d.Columns = sortByKey(d.Columns, func(s string) string { return s })
normTableDeps = append(normTableDeps, d)
}
mv.TableDependencies = normTableDeps
return mv
}
// sortSchemaObjectsByName returns a (copied) sorted list of schema objects.
func sortSchemaObjectsByName[S Object](vals []S) []S {
return sortByKey(vals, func(v S) string {
return v.GetName()
})
}
func sortByKey[S any](vals []S, getValFn func(S) string) []S {
clonedVals := make([]S, len(vals))
copy(clonedVals, vals)
sort.Slice(clonedVals, func(i, j int) bool {
return getValFn(clonedVals[i]) < getValFn(clonedVals[j])
})
return clonedVals
}
func (s Schema) Hash() (string, error) {
// alternatively, we can print the struct as a string and hash it
hashVal, err := hashstructure.Hash(s.Normalize(), hashstructure.FormatV2, nil)
if err != nil {
return "", fmt.Errorf("hashing schema: %w", err)
}
return fmt.Sprintf("%x", hashVal), nil
}
type ReplicaIdentity string
const (
ReplicaIdentityDefault ReplicaIdentity = "d"
ReplicaIdentityNothing ReplicaIdentity = "n"
ReplicaIdentityFull ReplicaIdentity = "f"
ReplicaIdentityIndex ReplicaIdentity = "i"
)
// NamedSchema represents a schema in the database. We call it NamedSchema to distinguish it from the Postgres Database
// schema
type NamedSchema struct {
Name string
}
func (n NamedSchema) GetName() string {
return n.Name
}
type Extension struct {
SchemaQualifiedName
Version string
}
type Enum struct {
SchemaQualifiedName
Labels []string
}
type Table struct {
SchemaQualifiedName
Columns []Column
CheckConstraints []CheckConstraint
Policies []Policy
Privileges []TablePrivilege
ReplicaIdentity ReplicaIdentity
RLSEnabled bool
RLSForced bool
// PartitionKeyDef is the output of Pg function pg_get_partkeydef:
// PARTITION BY $PartitionKeyDef
// If empty, then the table is not partitioned
PartitionKeyDef string
ParentTable *SchemaQualifiedName
ForValues string
}
func (t Table) IsPartitioned() bool {
return len(t.PartitionKeyDef) > 0
}
// IsPartition returns whether the table is a partition.
// It represents a mismatch in modeling because the ForValues and ParentTable are stored separately.
// Instead, the fields should be stored under the same struct as a nilable pointer, and this function should be deleted.
func (t Table) IsPartition() bool {
return t.ParentTable != nil
}
// TablePrivilege represents a privilege granted on a table
type TablePrivilege struct {
// Grantee is the role that has the privilege. Empty string means PUBLIC.
Grantee string
// Privilege is the type of privilege (SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER)
Privilege string
// IsGrantable indicates if the grantee can grant this privilege to others (WITH GRANT OPTION)
IsGrantable bool
}
func (p TablePrivilege) GetName() string {
grantee := p.Grantee
if grantee == "" {
grantee = "PUBLIC"
}
return fmt.Sprintf("%s:%s", grantee, p.Privilege)
}
type ColumnIdentityType string
const (
ColumnIdentityTypeAlways = "a"
ColumnIdentityTypeByDefault = "d"
)
type (
ColumnIdentity struct {
Type ColumnIdentityType
MinValue int64
MaxValue int64
StartValue int64
Increment int64
CacheSize int64
Cycle bool
}
Column struct {
Name string
Type string
Collation SchemaQualifiedName
// If the column has a default value, this will be a SQL string representing that value.
// Examples:
// ''::text
// CURRENT_TIMESTAMP
// If empty, indicates that there is no default value.
Default string
// If the column is a generated column, this will be true.
IsGenerated bool
// If the column is a generated column, this will be the generation expression.
// Examples:
// to_tsvector('simple', title || ' ' || coalesce(artist, ''))
// (price * 1.1)
// Only populated if IsGenerated is true.
GenerationExpression string
IsNullable bool
// HasMissingValOptimization refers to the 'attmissingval' optimization for adding columns with a default.
HasMissingValOptimization bool
// Size is the number of bytes required to store the value.
// It is used for data-packing purposes
Size int
Identity *ColumnIdentity
}
)
func (c Column) GetName() string {
return c.Name
}
func (c Column) IsCollated() bool {
return !c.Collation.IsEmpty()
}
var (
// The first matching group is the "CREATE [UNIQUE] INDEX ". UNIQUE is an optional match
// because only UNIQUE indices will have the UNIQUE keyword in their pg_get_indexdef statement
//
// The third matching group is the rest of the statement
idxToConcurrentlyRegex = regexp.MustCompile("^(CREATE (UNIQUE )?INDEX )(.*)$")
)
// GetIndexDefStatement is the output of pg_getindexdef. It is a `CREATE INDEX` statement that will re-create
// the index. This statement does not contain `CONCURRENTLY`.
// For unique indexes, it does contain `UNIQUE`
// For partitioned tables, it does contain `ONLY`
type GetIndexDefStatement string
func (i GetIndexDefStatement) ToCreateIndexConcurrently() (string, error) {
if !idxToConcurrentlyRegex.MatchString(string(i)) {
return "", fmt.Errorf("%s follows an unexpected structure", i)
}
return idxToConcurrentlyRegex.ReplaceAllString(string(i), "${1}CONCURRENTLY ${3}"), nil
}
type (
IndexConstraintType string
RelKind string
// IndexConstraint informally represents a constraint that is always 1:1 with an index, i.e.,
// primary and unique constraints. It's easiest to just treat these like a property of the index rather than
// a separate entity
IndexConstraint struct {
Type IndexConstraintType
EscapedConstraintName string
ConstraintDef string
IsLocal bool
}
Index struct {
// Name is the name of the index. We don't store the schema because the schema is just the schema of the table.
// Referencing the name is an anti-pattern because it is not qualified. Use should use GetSchemaQualifiedName instead.
Name string
// OwningRelName refers to the owning table or materialized view.
OwningRelName SchemaQualifiedName
// OwningRelKind is the relkind of the owning relation.
OwningRelKind RelKind
Columns []string
IsInvalid bool
IsUnique bool
Constraint *IndexConstraint
// GetIndexDefStmt is the output of pg_getindexdef
GetIndexDefStmt GetIndexDefStatement
ParentIdx *SchemaQualifiedName
}
)
const (
PkIndexConstraintType IndexConstraintType = "p"
RelKindOrdinaryTable RelKind = "r"
RelKindPartitionedTable RelKind = "p"
RelKindMaterializedView RelKind = "m"
)
func (i Index) GetName() string {
return i.GetSchemaQualifiedName().GetFQEscapedName()
}
func (i Index) GetSchemaQualifiedName() SchemaQualifiedName {
return SchemaQualifiedName{
SchemaName: i.OwningRelName.SchemaName,
EscapedName: EscapeIdentifier(i.Name),
}
}
func (i Index) IsPk() bool {
return i.Constraint != nil && i.Constraint.Type == PkIndexConstraintType
}
type CheckConstraint struct {
Name string
// KeyColumns are the columns that the constraint applies to
KeyColumns []string
Expression string
IsValid bool
IsInheritable bool
DependsOnFunctions []SchemaQualifiedName
}
func (c CheckConstraint) GetName() string {
return c.Name
}
type ForeignKeyConstraint struct {
EscapedName string
OwningTable SchemaQualifiedName
ForeignTable SchemaQualifiedName
ConstraintDef string
IsValid bool
}
func (f ForeignKeyConstraint) GetName() string {
return f.OwningTable.GetFQEscapedName() + "-" + f.EscapedName
}
type (
// SequenceOwner represents the owner of a sequence.
SequenceOwner struct {
TableName SchemaQualifiedName
ColumnName string
}
Sequence struct {
SchemaQualifiedName
Owner *SequenceOwner
Type string
StartValue int64
Increment int64
MaxValue int64
MinValue int64
CacheSize int64
Cycle bool
}
)
type Function struct {
SchemaQualifiedName
// FunctionDef is the statement required to completely (re)create
// the function, as returned by `pg_get_functiondef`. It is a CREATE OR REPLACE
// statement
FunctionDef string
// Language is the language of the function. This is relevant in determining if we
// can track the dependencies of the function (or not)
Language string
DependsOnFunctions []SchemaQualifiedName
}
type Procedure struct {
SchemaQualifiedName
// Def is the statement required to completely (re)create
// the procedure, as returned by `pg_get_functiondef`. It is a CREATE OR REPLACE
// statement.
Def string
}
var (
// The first matching group is the "CREATE ". The second matching group is the rest of the statement
triggerToOrReplaceRegex = regexp.MustCompile("^(CREATE )(.*)$")
)
// GetTriggerDefStatement is the output of pg_get_triggerdef. It is a `CREATE TRIGGER` statement that will create
// the trigger. This statement does not contain `OR REPLACE`
type GetTriggerDefStatement string
func (g GetTriggerDefStatement) ToCreateOrReplace() (string, error) {
if !triggerToOrReplaceRegex.MatchString(string(g)) {
return "", fmt.Errorf("%s follows an unexpected structure", g)
}
return triggerToOrReplaceRegex.ReplaceAllString(string(g), "${1}OR REPLACE ${2}"), nil
}
// PolicyCmd represents the polcmd value in the pg_policy system catalog.
// See docs for possible values: https://www.postgresql.org/docs/current/catalog-pg-policy.html#CATALOG-PG-POLICY
type PolicyCmd string
const (
SelectPolicyCmd PolicyCmd = "r"
InsertPolicyCmd PolicyCmd = "a"
UpdatePolicyCmd PolicyCmd = "w"
DeletePolicyCmd PolicyCmd = "d"
AllPolicyCmd PolicyCmd = "*"
)
type Policy struct {
EscapedName string
IsPermissive bool
AppliesTo []string
Cmd PolicyCmd
CheckExpression string
UsingExpression string
// Columns are the columns that the policy applies to.
Columns []string
// TableDependencies are tables (other than the owning table) that the policy
// references in its USING/CHECK expressions. This is used for correct
// statement ordering when a policy references columns from other tables.
TableDependencies []TableDependency
// FunctionDependencies are functions that the policy references in its
// USING/CHECK expressions. This is used for correct statement ordering
// when a policy calls user-defined functions in its expressions.
FunctionDependencies []SchemaQualifiedName
}
func (p Policy) GetName() string {
return p.EscapedName
}
type Trigger struct {
EscapedName string
OwningTable SchemaQualifiedName
Function SchemaQualifiedName
// GetTriggerDefStmt is the statement required to completely (re)create the trigger, as returned
// by pg_get_triggerdef
GetTriggerDefStmt GetTriggerDefStatement
IsConstraint bool
}
func (t Trigger) GetName() string {
return t.OwningTable.GetFQEscapedName() + "-" + t.EscapedName
}
// TableDependency represents a (view's) dependency on a table.
type TableDependency struct {
SchemaQualifiedName
Columns []string
}
type View struct {
SchemaQualifiedName
// ViewDefinition is the select query that defines the view. It is derived from pg_get_viewdef.
ViewDefinition string
// Options represents key value map of view options, i.e., pg_class.reloptions.
Options map[string]string
// TableDependencies is a list of tables the view depends on.
TableDependencies []TableDependency
}
type MaterializedView struct {
SchemaQualifiedName
// ViewDefinition is the select query that defines the materialized view. It is derived from pg_get_viewdef.
ViewDefinition string
// Options represents key value map of materialized view options, i.e., pg_class.reloptions.
Options map[string]string
// Tablespace is the tablespace where the materialized view is stored. Empty string means default tablespace.
Tablespace string
// TableDependencies is a list of tables the materialized view depends on.
TableDependencies []TableDependency
}
type (
GetSchemaOpt func(*getSchemaOptions)
)
// WithIncludeSchemas filters the schema to only include the given schemas. This unions with any schemas that are already included
// via WithIncludeSchemas. If empty, then all schemas are included.
func WithIncludeSchemas(schemas ...string) GetSchemaOpt {
return func(o *getSchemaOptions) {
o.includeSchemas = append(o.includeSchemas, schemas...)
}
}
// WithExcludeSchemas filters the schema to exclude the given schemas. This unions with any schemas that are already excluded
// via WithExcludeSchemas. If empty, then no schemas are excluded.
func WithExcludeSchemas(schemas ...string) GetSchemaOpt {
return func(o *getSchemaOptions) {
o.excludeSchemas = append(o.excludeSchemas, schemas...)
}
}
type getSchemaOptions struct {
// includeSchemas is a list of schemas to include in the schema. If empty, then all schemas are included.
// We could have built a more complex set of options using the nameFilter system (nested unions and intersections);
// however, I felt it could expose some weird behaviors that we don't want to have to worry about just yet,
includeSchemas []string
// excludeSchemas is the exclude analog of includeSchemas.
excludeSchemas []string
}
// GetSchema fetches the database schema. It is a non-atomic operation.
func GetSchema(ctx context.Context, db queries.DBTX, opts ...GetSchemaOpt) (Schema, error) {
// To allow backwards compatibility with connections, we will not use concurrency if passed in a db that is not a
// *sql.DB. This is because not all implementations are thread safe, e.g., pgx.Connection.
//
// In the future, we should maybe create options where users can pass in a DB pool (WithPool(db) or WithConnection(db))
// and we can set concurrency to 1 if the passed in db is not a *sql.DB.
goroutineRunnerFactory := concurrent.NewSynchronousGoroutineRunner
if _, ok := db.(*sql.DB); ok {
goroutineRunnerFactory = func() concurrent.GoroutineRunner {
return concurrent.NewGoroutineLimiter(50)
}
}
options := getSchemaOptions{}
for _, opt := range opts {
opt(&options)
}
nameFilter, err := buildNameFilter(options)
if err != nil {
return Schema{}, fmt.Errorf("building name filter: %w", err)
}
return (&schemaFetcher{
q: queries.New(db),
goroutineRunnerFactory: goroutineRunnerFactory,
nameFilter: nameFilter,
}).getSchema(ctx)
}
func buildNameFilter(options getSchemaOptions) (nameFilter, error) {
if intersection := intersect(options.includeSchemas, options.excludeSchemas); len(intersection) > 0 {
return nil, fmt.Errorf("schemas %v are both included and excluded", intersection)
}
includeSchemasFilter := buildIncludeSchemasFilter(options.includeSchemas)
excludeSchemasFilter := buildExcludeSchemasFilter(options.excludeSchemas)
return andNameFilter(includeSchemasFilter, excludeSchemasFilter), nil
}
func intersect(a, b []string) []string {
inAByA := make(map[string]bool)
for _, s := range a {
inAByA[s] = true
}
intersection := make([]string, 0, len(b))
for _, s := range b {
if inAByA[s] {
intersection = append(intersection, s)
}
}
return intersection
}
func buildIncludeSchemasFilter(schemas []string) nameFilter {
if len(schemas) == 0 {
return func(name SchemaQualifiedName) bool {
return true
}
}
var filters []nameFilter
for _, schema := range schemas {
filters = append(filters, schemaNameFilter(schema))
}
return orNameFilter(filters...)
}
func buildExcludeSchemasFilter(schemas []string) nameFilter {
if len(schemas) == 0 {
return func(name SchemaQualifiedName) bool {
return true
}
}
var filters []nameFilter
for _, schema := range schemas {
filters = append(filters, notSchemaNameFilter(schema))
}
return andNameFilter(filters...)
}
type (
schemaFetcher struct {
q *queries.Queries
// goroutineRunnerFactory is a factory function that returns a GoroutineRunner. We need to be able to construct
// multiple GoroutineRunners to avoid deadlock created by circular dependencies of submitted go routines.
goroutineRunnerFactory func() concurrent.GoroutineRunner
// nameFilter is a filter that determines which schema objects to include in the schema via their
// schema name and object name.
//
// Currently, we don't do any sort of validation to ensure that all dependencies are included, so users might
// experience unexpected outcomes if they accidentally filter out a dependency of an object they are trying to
// diff. In the future, we might want to add some sort of validation layer to ensure that all dependencies are included
// and error out otherwise.
//
// Examples of dependencies that could be filtered out include the functions used by triggers and the parent
// tables of partitions.
nameFilter nameFilter
}
)
func (s *schemaFetcher) getSchema(ctx context.Context) (Schema, error) {
goroutineRunner := s.goroutineRunnerFactory()
namedSchemasFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]NamedSchema, error) {
return s.fetchNamedSchemas(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting named schemas future: %w", err)
}
extensionsFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Extension, error) {
return s.fetchExtensions(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting extensions future: %w", err)
}
enumsFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Enum, error) {
return s.fetchEnums(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting enums future: %w", err)
}
tablesFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Table, error) {
return s.fetchTables(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting tables future: %w", err)
}
indexesFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Index, error) {
return s.fetchIndexes(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting indexes future: %w", err)
}
fkConsFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]ForeignKeyConstraint, error) {
return s.fetchForeignKeyCons(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting foreign key constraints future: %w", err)
}
sequencesFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Sequence, error) {
return s.fetchSequences(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting sequences future: %w", err)
}
functionsFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Function, error) {
return s.fetchFunctions(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting functions future: %w", err)
}
proceduresFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Procedure, error) {
return s.fetchProcedures(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting functions future: %w", err)
}
triggersFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]Trigger, error) {
return s.fetchTriggers(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting triggers future: %w", err)
}
viewsFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]View, error) {
return s.fetchViews(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting views future: %w", err)
}
materializedViewsFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() ([]MaterializedView, error) {
return s.fetchMaterializedViews(ctx)
})
if err != nil {
return Schema{}, fmt.Errorf("starting materialized views future: %w", err)
}
schemas, err := namedSchemasFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting named schemas: %w", err)
}
extensions, err := extensionsFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting extensions: %w", err)
}
enums, err := enumsFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting enums: %w", err)
}
tables, err := tablesFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting tables: %w", err)
}
indexes, err := indexesFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting indexes: %w", err)
}
fkCons, err := fkConsFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting foreign key constraints: %w", err)
}
sequences, err := sequencesFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting sequences: %w", err)
}
functions, err := functionsFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting functions: %w", err)
}
procedures, err := proceduresFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting procedures: %w", err)
}
triggers, err := triggersFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting triggers: %w", err)
}
views, err := viewsFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting views: %w", err)
}
materializedViews, err := materializedViewsFuture.Get(ctx)
if err != nil {
return Schema{}, fmt.Errorf("getting materialized views: %w", err)
}
return Schema{
NamedSchemas: schemas,
Extensions: extensions,
Enums: enums,
Tables: tables,
Indexes: indexes,
ForeignKeyConstraints: fkCons,
Sequences: sequences,
Functions: functions,
Procedures: procedures,
Triggers: triggers,
Views: views,
MaterializedViews: materializedViews,
}, nil
}
func (s *schemaFetcher) fetchNamedSchemas(ctx context.Context) ([]NamedSchema, error) {
schemaNames, err := s.q.GetSchemas(ctx)
if err != nil {
return nil, fmt.Errorf("GetSchemas(): %w", err)
}
var schemas []NamedSchema
for _, schemaName := range schemaNames {
schemas = append(schemas, NamedSchema{
Name: schemaName,
})
}
schemas = filterSliceByName(
schemas,
func(s NamedSchema) SchemaQualifiedName {
return SchemaQualifiedName{
SchemaName: s.Name,
EscapedName: EscapeIdentifier(s.Name),
}
},
s.nameFilter,
)
return schemas, nil
}
func (s *schemaFetcher) fetchExtensions(ctx context.Context) ([]Extension, error) {
rawExtensions, err := s.q.GetExtensions(ctx)
if err != nil {
return nil, fmt.Errorf("GetExtensions(): %w", err)
}
var extensions []Extension
for _, e := range rawExtensions {
extensions = append(extensions, Extension{
SchemaQualifiedName: SchemaQualifiedName{
EscapedName: EscapeIdentifier(e.ExtensionName),
SchemaName: e.SchemaName,
},
Version: e.ExtensionVersion,
})
}
extensions = filterSliceByName(
extensions,
func(e Extension) SchemaQualifiedName {
return e.SchemaQualifiedName
},
s.nameFilter,
)
return extensions, nil
}
func (s *schemaFetcher) fetchEnums(ctx context.Context) ([]Enum, error) {
rawEnums, err := s.q.GetEnums(ctx)
if err != nil {
return nil, fmt.Errorf("GetEnums: %w", err)
}
var enums []Enum
for _, rawEnum := range rawEnums {
enums = append(enums, Enum{
SchemaQualifiedName: SchemaQualifiedName{
SchemaName: rawEnum.EnumSchemaName,
EscapedName: EscapeIdentifier(rawEnum.EnumName),
},
Labels: rawEnum.EnumLabels,
})
}
enums = filterSliceByName(
enums,
func(enum Enum) SchemaQualifiedName {
return enum.SchemaQualifiedName
},
s.nameFilter,
)
return enums, nil
}
func (s *schemaFetcher) fetchTables(ctx context.Context) ([]Table, error) {
rawTables, err := s.q.GetTables(ctx)
if err != nil {
return nil, fmt.Errorf("GetTables(): %w", err)
}
checkCons, err := s.fetchCheckCons(ctx)
if err != nil {
return nil, fmt.Errorf("fetchCheckCons(): %w", err)
}
checkConsByTable := make(map[string][]CheckConstraint)
for _, cc := range checkCons {
checkConsByTable[cc.table.GetFQEscapedName()] = append(checkConsByTable[cc.table.GetFQEscapedName()], cc.checkConstraint)
}
policies, err := s.fetchPolicies(ctx)
if err != nil {
return nil, fmt.Errorf("fetchPolicies(): %w", err)
}
policiesByTable := make(map[string][]Policy)
for _, p := range policies {
policiesByTable[p.table.GetFQEscapedName()] = append(policiesByTable[p.table.GetFQEscapedName()], p.policy)
}
privileges, err := s.fetchPrivileges(ctx)
if err != nil {
return nil, fmt.Errorf("fetchPrivileges(): %w", err)
}
privilegesByTable := make(map[string][]TablePrivilege)
for _, p := range privileges {
privilegesByTable[p.table.GetFQEscapedName()] = append(privilegesByTable[p.table.GetFQEscapedName()], p.privilege)
}
goroutineRunner := s.goroutineRunnerFactory()
var tableFutures []concurrent.Future[Table]
for _, _rawTable := range rawTables {
rawTable := _rawTable // Capture loop variables for go routine
tableFuture, err := concurrent.SubmitFuture(ctx, goroutineRunner, func() (Table, error) {
return s.buildTable(ctx, rawTable, checkConsByTable, policiesByTable, privilegesByTable)
})
if err != nil {
return nil, fmt.Errorf("starting table future: %w", err)
}
tableFutures = append(tableFutures, tableFuture)
}
tables, err := concurrent.GetAll(ctx, tableFutures...)
if err != nil {
return nil, fmt.Errorf("getting tables: %w", err)
}
tables = filterSliceByName(
tables,
func(t Table) SchemaQualifiedName {
return t.SchemaQualifiedName
},
s.nameFilter,
)
return tables, nil
}
func (s *schemaFetcher) buildTable(
ctx context.Context,
table queries.GetTablesRow,
checkConsByTable map[string][]CheckConstraint,