Repository navigation
Expand file tree
/
Copy pathpostgres.go
More file actions
1717 lines (1628 loc) · 81.9 KB
/
Copy pathpostgres.go
File metadata and controls
1717 lines (1628 loc) · 81.9 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 postgres implements the Engine interface for PostgreSQL databases.
package postgres
import (
"context"
"errors"
"fmt"
"log/slog"
"maps"
"math"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/block/pg-sprite/pkg/dbconn"
"github.com/block/pg-sprite/pkg/executor"
pgplan "github.com/block/pg-sprite/pkg/plan"
"github.com/block/pg-sprite/pkg/planner"
"github.com/block/pg-sprite/pkg/preflight"
"github.com/block/pg-sprite/pkg/progress"
"github.com/block/pg-sprite/pkg/router"
"github.com/block/pg-sprite/pkg/schemadiff"
pgstatement "github.com/block/pg-sprite/pkg/statement"
"github.com/block/pg-sprite/pkg/verdict"
spirittable "github.com/block/spirit/pkg/table"
"github.com/block/spirit/pkg/utils"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/block/schemabot/pkg/ddl"
"github.com/block/schemabot/pkg/engine"
"github.com/block/schemabot/pkg/postgresconn"
"github.com/block/schemabot/pkg/schema"
"github.com/block/schemabot/pkg/targetauth"
)
// Engine implements engine.Engine for PostgreSQL databases.
type Engine struct {
mu sync.Mutex
wg sync.WaitGroup
pullDatabase string
pullCredentials *engine.Credentials
tableOwner string
// progress holds the latest state of every schema change this engine is
// tracking, keyed by the apply's identity (its
// ResumeState.MigrationContext). One engine is shared for the lifetime of a
// target, so Progress must answer for the apply the caller identifies — and
// accepting a second apply on the same target must not evict the first
// one's state while it is still running, or the running apply's driver
// would be told its work no longer exists.
progress map[string]*trackedApply
tableSizeLimit int64
// optimisticApplyCeiling is the fixed client-side ceiling on one ordinary
// apply, seeded from the package constant of the same name. It is not an
// operator option: production never varies it, and only in-package tests
// assign it, to observe the ceiling ending an apply without waiting out
// the production value.
optimisticApplyCeiling time.Duration
concurrentIndexMaxDuration time.Duration
// execute is a test seam standing in for executeOptimistic, so the apply
// drive — accept, claim, execute, terminal publish — can be exercised
// against an executor the test scripts instead of a target to dial. Nil
// selects the real executor.
execute func(ctx context.Context, conn targetConn, change nativeApply, tableSizeLimit int64, tracker *progress.Tracker, logger *slog.Logger) error
}
// trackedApply pairs the progress the engine has published for one apply
// with the pg-sprite tracker its executor feeds. The published result changes
// only at accept and at the terminal outcome; the tracker is what moves in
// between, so Progress reads the step position and statement from it. The
// logger is the apply's own, so a poll that cannot read the tracker logs
// under the identifiers the apply was accepted with.
//
// Every field but done is read and written under Engine.mu. done is closed
// by the drive goroutine once its terminal result is published, so a cancel
// can wait for the outcome the drive settles on instead of guessing it.
type trackedApply struct {
result *engine.ProgressResult
tracker buildTracker
logger *slog.Logger
// concurrentIndex records the shape the apply was admitted as: a
// concurrent index build is the one PostgreSQL change an operator can
// cancel, so the shape decides the answer before any server is asked.
concurrentIndex bool
// cancelApply ends the drive's own context. It is the cancel of last
// resort: the build backend is signalled through the tracker first, and
// the context is cancelled only when that signal cannot reach a running
// statement — the build has not started, has already returned, or its
// backend cannot be observed or signalled by this role.
cancelApply context.CancelFunc
// cancelRequested records that a Cancel may have reached this apply — its
// signal may have landed on the build backend, or it cancelled the drive's
// context — so the drive can tell the operator's cancellation from a
// backend cancellation it did not ask for. Once set it is never reset.
cancelRequested bool
// cancelsInFlight counts the Cancel calls that have committed to acting
// on this apply but have not yet learned whether their signal was sent.
// The drive reads the apply as cancelled by the operator while any is in
// flight, because a signal can land before the call that sent it hears
// back. The cost runs the other way too: while a call is in flight, a
// backend cancellation SchemaBot did not send is also read as the
// operator's.
cancelsInFlight int
done chan struct{}
// owner is the drive the apply was started for (engine.WithWorkOwner).
owner string
}
type buildTracker interface {
Progress(context.Context) (progress.Snapshot, error)
CancelBuild(context.Context) error
}
// DefaultNativeSafeTableSizeLimitBytes preserves the native-safe execution
// ceiling when the server does not configure one.
const DefaultNativeSafeTableSizeLimitBytes = int64(1 << 30)
// DefaultConcurrentIndexMaxDuration bounds one concurrent index build.
const DefaultConcurrentIndexMaxDuration = 24 * time.Hour
// MaxConcurrentIndexMaxDuration is the largest bound the engine accepts for
// one concurrent index build: the largest statement_timeout PostgreSQL
// accepts, in milliseconds. The build runs under that server-side timer set
// to the bound, so a larger value could not be handed to the server; the
// recovery's engine-owned deadline honors the same ceiling. A bound above it
// is not a build anyone waits for; it is the absence of a bound.
const MaxConcurrentIndexMaxDuration = time.Duration(math.MaxInt32) * time.Millisecond
// MinConcurrentIndexMaxDuration is the smallest bound the engine accepts for
// one concurrent index build: statement_timeout is an integer millisecond
// count, so anything shorter rounds to zero on the server, which disables
// the timer instead of tightening it. The executor refuses such a budget as
// unbounded; the engine never hands it one.
const MinConcurrentIndexMaxDuration = time.Millisecond
// New creates a new PostgreSQL engine.
func New() *Engine {
return NewWithTableSizeLimit(DefaultNativeSafeTableSizeLimitBytes)
}
// NewWithTableSizeLimit creates a PostgreSQL engine with the native-safe
// table size ceiling expressed in bytes. Zero means unset and adopts
// DefaultNativeSafeTableSizeLimitBytes. A negative value is kept as-is
// rather than silently replaced with a ceiling the caller did not choose:
// the plan-time preflight check rejects a non-positive limit before apply,
// and server config validation rejects it at startup.
func NewWithTableSizeLimit(tableSizeLimit int64) *Engine {
return NewWithOptions(tableSizeLimit, DefaultConcurrentIndexMaxDuration)
}
// NewWithOptions creates a PostgreSQL engine with its process-wide apply
// bounds. A concurrentIndexMaxDuration that is not positive adopts
// DefaultConcurrentIndexMaxDuration: unlike the table size limit, no later
// check refuses a negative bound, and a deadline already in the past would
// end every concurrent build the instant it started. One above
// MaxConcurrentIndexMaxDuration is clamped to it, and a positive one below
// MinConcurrentIndexMaxDuration is raised to it, so the bound the engine
// serves is always one the server's timer can hold. Server config validation
// refuses all three before they reach this constructor; the normalization
// here covers embedders that build the engine directly.
func NewWithOptions(tableSizeLimit int64, concurrentIndexMaxDuration time.Duration) *Engine {
if tableSizeLimit == 0 {
tableSizeLimit = DefaultNativeSafeTableSizeLimitBytes
}
if concurrentIndexMaxDuration <= 0 {
concurrentIndexMaxDuration = DefaultConcurrentIndexMaxDuration
}
if concurrentIndexMaxDuration < MinConcurrentIndexMaxDuration {
concurrentIndexMaxDuration = MinConcurrentIndexMaxDuration
}
if concurrentIndexMaxDuration > MaxConcurrentIndexMaxDuration {
concurrentIndexMaxDuration = MaxConcurrentIndexMaxDuration
}
return &Engine{
tableSizeLimit: tableSizeLimit,
optimisticApplyCeiling: optimisticApplyCeiling,
concurrentIndexMaxDuration: concurrentIndexMaxDuration,
}
}
// NewForTarget creates a PostgreSQL engine with the target information needed
// by capabilities whose request does not carry resolved credentials.
func NewForTarget(tableSizeLimit int64, concurrentIndexMaxDuration time.Duration, database string, credentials *engine.Credentials) *Engine {
e := NewWithOptions(tableSizeLimit, concurrentIndexMaxDuration)
e.pullDatabase = database
e.pullCredentials = credentials
return e
}
// WithTableOwner configures the PostgreSQL role used for greenfield table
// creation. Empty preserves creation as the connected role.
func (e *Engine) WithTableOwner(owner string) *Engine {
e.tableOwner = owner
return e
}
// TableSizeLimit exposes the native-safe ceiling for wiring verification and observability.
func (e *Engine) TableSizeLimit() int64 {
return e.tableSizeLimit
}
// ConcurrentIndexMaxDuration exposes the bound one concurrent index build
// runs under, for wiring verification and observability.
func (e *Engine) ConcurrentIndexMaxDuration() time.Duration {
return e.concurrentIndexMaxDuration
}
// Name returns the engine identifier.
func (e *Engine) Name() string {
return "postgres"
}
// Plan computes the changes needed to reach the desired schema.
func (e *Engine) Plan(ctx context.Context, req *engine.PlanRequest) (*engine.PlanResult, error) {
if req == nil {
return nil, fmt.Errorf("plan PostgreSQL schema: request is required")
}
if req.Credentials == nil || req.Credentials.DSN == "" {
return nil, fmt.Errorf("plan PostgreSQL database %q: DSN credentials are required", req.Database)
}
pool, closePool, err := openTargetPool(ctx, req.Credentials)
if err != nil {
return nil, fmt.Errorf("plan PostgreSQL database %q: %w", req.Database, err)
}
defer closePool()
return planSchemas(ctx, pool, req, e.tableSizeLimit, e.tableOwner)
}
// openTargetPool opens the pg-sprite pool one engine operation runs on.
// Before it, it verifies the target through the SchemaBot-managed connection
// path, including its transport policy, and adapts the same normalized DSN to
// pg-sprite's pool API. Errors do not name the database or the operation;
// the caller wraps them with both. The returned close releases the pool and
// the validation connection.
func openTargetPool(ctx context.Context, creds *engine.Credentials) (*pgxpool.Pool, func(), error) {
caPath, err := caCertPath(creds)
if err != nil {
return nil, nil, fmt.Errorf("resolve PostgreSQL CA certificate: %w", err)
}
validationOpts, err := validationRootCAs(caPath)
if err != nil {
return nil, nil, fmt.Errorf("load PostgreSQL validation root CAs: %w", err)
}
db, err := postgresconn.Open(creds.DSN, validationOpts...)
if err != nil {
return nil, nil, fmt.Errorf("open PostgreSQL connection: %w", err)
}
// Open only parsed the DSN; this ping is the first dial, so it is where the
// target can refuse the session and the only error worth classifying.
if err := db.PingContext(ctx); err != nil {
utils.CloseAndLog(db)
return nil, nil, fmt.Errorf("ping PostgreSQL target: %w", targetauth.Wrap(err))
}
poolCfg, err := spritePoolConfig(creds.DSN, caPath)
if err != nil {
utils.CloseAndLog(db)
return nil, nil, fmt.Errorf("build pg-sprite pool config: %w", err)
}
pool, err := dbconn.NewPool(ctx, poolCfg)
if err != nil {
utils.CloseAndLog(db)
return nil, nil, fmt.Errorf("open pg-sprite pool: %w", err)
}
return pool, func() {
pool.Close()
utils.CloseAndLog(db)
}, nil
}
func planSchemas(ctx context.Context, pool *pgxpool.Pool, req *engine.PlanRequest, tableSizeLimit int64, tableOwner string) (*engine.PlanResult, error) {
parser, err := ddl.ParserForDialect(schema.DialectPostgres)
if err != nil {
return nil, fmt.Errorf("select PostgreSQL statement parser: %w", err)
}
namespaces := sortedKeys(req.SchemaFiles)
ignored, err := engine.NewIgnoredTables(req.IgnoreTables)
if err != nil {
return nil, fmt.Errorf("plan PostgreSQL database %q: %w", req.Database, err)
}
result := &engine.PlanResult{}
for _, namespace := range namespaces {
ns := req.SchemaFiles[namespace]
if ns == nil {
return nil, fmt.Errorf("plan PostgreSQL namespace %q: schema files are required", namespace)
}
parsed, err := parseDesiredFiles(namespace, ns.Files)
if err != nil {
return nil, err
}
if err := refuseTableDeclaredTwice(namespace, parsed); err != nil {
return nil, err
}
schemaChange := engine.SchemaChange{Namespace: namespace}
files := sortedKeys(ns.Files)
desiredTables := make(map[string]bool, len(files))
for _, filename := range files {
file := parsed[filename]
if rowSecurity, ok := file.RowSecurity(); ok {
rlsChanges, err := planRowSecurityOperation(ctx, pool, namespace, rowSecurity)
if err != nil {
return nil, fmt.Errorf("plan PostgreSQL schema in %q/%q: %w", namespace, filename, err)
}
desiredTables[file.Table()] = true
schemaChange.TableChanges = append(schemaChange.TableChanges, rlsChanges...)
continue
}
desired, ok := file.Schema()
if !ok {
return nil, fmt.Errorf("plan PostgreSQL schema in %q/%q: the parse admitted no planner input", namespace, filename)
}
report, table, err := planPostgresDefinition(ctx, pool, namespace, desired)
if err != nil {
return nil, fmt.Errorf("plan PostgreSQL schema in %q/%q: %w", namespace, filename, err)
}
desiredTables[table] = true
crossNamespace, err := crossNamespaceForeignKeysForDrops(ctx, pool, namespace, report)
if err != nil {
return nil, err
}
changes, tiers, unrecognized, err := tableChanges(report, crossNamespace, parser)
if err != nil {
return nil, fmt.Errorf("render PostgreSQL plan for table %q in namespace %q: %w", table, namespace, err)
}
for _, vocabulary := range unrecognized {
// The plan renders a blocked placeholder for the statement,
// so the operator is safe but uninformed; the log is where
// triage learns the planner's vocabulary grew, for whose
// schema file, and which value to map next.
slog.Warn("PostgreSQL planner returned vocabulary SchemaBot does not recognize; the plan blocks the statement with a placeholder verdict",
"database", req.Database,
"namespace", namespace,
"table", table,
"vocabulary", vocabulary.kind,
"value", vocabulary.value)
}
changes, err = blockMissingPrivileges(ctx, pool, req.Database, report, changes, tiers, tableOwner)
if err != nil {
return nil, fmt.Errorf("verify privileges for table %q in namespace %q: %w", table, namespace, err)
}
changes, err = blockOversizedTable(ctx, pool, req.Database, report, changes, tableSizeLimit)
if err != nil {
return nil, fmt.Errorf("verify size for table %q in namespace %q: %w", table, namespace, err)
}
schemaChange.TableChanges = append(schemaChange.TableChanges, changes...)
}
// A table the config withholds that a schema file also declares is a
// contradiction: the declaring file would keep managing the table while
// the config says to leave it alone.
if err := ignored.RefuseDeclared(namespace, sortedKeys(desiredTables)); err != nil {
return nil, err
}
drops, exempt, withheld, err := undeclaredTableDrops(ctx, pool, req.Database, namespace, desiredTables, ignored, parser)
if err != nil {
return nil, fmt.Errorf("compare live tables against schema files in namespace %q: %w", namespace, err)
}
schemaChange.TableChanges = append(schemaChange.TableChanges, drops...)
if len(exempt) > 0 {
slices.Sort(exempt)
result.ExemptTables = append(result.ExemptTables, &engine.ExemptTables{
Namespace: namespace,
Tables: exempt,
Reason: exemptReasonArchiveNaming,
})
}
if exemption := ignored.Exemption(namespace, withheld); exemption != nil {
result.ExemptTables = append(result.ExemptTables, exemption)
}
if len(schemaChange.TableChanges) > 0 {
// Only a namespace with changes needs a rollback baseline, so
// the render is paid once per changed namespace rather than for
// every namespace the schema files declare.
schemaChange.OriginalFiles, schemaChange.OriginalFilesCaptured, err = captureOriginalFiles(ctx, pool, req.Database, namespace, desiredTables, ignored)
if err != nil {
return nil, err
}
result.Changes = append(result.Changes, schemaChange)
}
}
result.NoChanges = len(result.Changes) == 0
result.PlanID = engine.NewPlanID()
return result, nil
}
// refuseTableDeclaredTwice fails the plan when two schema files in one
// namespace declare the same table. Each file is diffed against the live table
// on its own, so a table declared twice would get two contradictory diffs,
// each dropping what only the other file declares; there is no single desired
// definition to review. The error names the table and both files so the
// operator knows which one to remove. It runs before any file is planned, on
// the same admitted files the plan uses, and applies the same rule every
// planner does (ddl.TableDeclarations), so a duplicate declaration reads the
// same whichever engine refuses it.
func refuseTableDeclaredTwice(namespace string, files map[string]pgstatement.DesiredFile) error {
var declared ddl.TableDeclarations
for _, filename := range sortedKeys(files) {
if err := declared.Declare(filename, files[filename].Table()); err != nil {
return fmt.Errorf("plan PostgreSQL namespace %q: %w", namespace, err)
}
}
return nil
}
// captureOriginalFiles renders the live namespace as the plan's rollback
// baseline, keyed by schema file name. The baseline is every managed table
// in the namespace except ignored tables and undeclared archives. Declared
// archives keep their originals. Exclusions are applied before introspection,
// so only tables the forward plan manages decide capture completeness. It is
// complete or it is nothing, and the two ways it can fall short end
// differently. A table the engine read but pg-sprite's renderer refuses —
// each shape it refuses is named by one of its ErrUnrenderable errors,
// foreign keys on either side and inheritance among them — leaves captured
// false, and RV-7 then refuses rollback for this plan rather than
// reconstructing the originals; the plan itself still proceeds, because
// rollback capability is not a precondition for reviewing or applying the
// change. A table the engine could not read — the listing named it and
// introspection cannot find or resolve it, a catalog query fails, the
// context is cancelled — is an error that ends the plan, whether it is one
// table's read or the namespace's: a catalog that could not be read
// consistently is not one to plan against, and a plan interrupted
// mid-capture is never recorded as rollback-incapable.
//
// The render introspects every managed table in the namespace, changed or
// not, so its cost grows with the namespace rather than with the change; the
// introspections run concurrently within the pool's ceiling, so the wall
// time grows more slowly than the table count does.
func captureOriginalFiles(ctx context.Context, pool *pgxpool.Pool, database, namespace string, declared map[string]bool, ignored engine.IgnoredTables) (files map[string]string, captured bool, err error) {
originalTables, renderErrors, err := renderPostgresTables(ctx, pool, database, namespace, rollbackBaseline(declared, ignored))
if err != nil {
return nil, false, fmt.Errorf("capture original PostgreSQL schema in namespace %q: %w", namespace, err)
}
if len(renderErrors) > 0 {
// One representative cause is enough to start triage; the count says
// how far the namespace is from a complete baseline without the log
// line growing with the number of unrenderable tables.
slog.Warn("PostgreSQL plan could not capture the whole namespace as rollback originals; the plan proceeds rollback-incapable",
"database", database,
"namespace", namespace,
"unrenderable_tables", len(renderErrors),
"first_error", renderErrors[0])
return nil, false, nil
}
files = make(map[string]string, len(originalTables))
for table, content := range originalTables {
files[table+".sql"] = content
}
return files, true, nil
}
// tierUnderived marks a step whose privilege tier could not be derived: its
// statement is a shape the engine does not execute, so the step is blocked
// and there is no access to probe on its behalf. It sits below preflight's
// lowest rung so it can never match a checked tier.
const tierUnderived preflight.Tier = -1
// tableChanges renders the report's statements as planned table changes and
// derives each step's privilege tier alongside them. The returned slices are
// parallel: tiers[i] is the access changes[i] needs from the engine role,
// including when an earlier verdict already blocked that step, so a later
// gate can name the grant a blocked step will also need; a blocked step whose
// shape has no tier carries tierUnderived. unrecognized carries one entry per
// statement whose verdict is a placeholder for planner vocabulary this build
// does not map, for the caller to log with the plan's identifiers.
// crossNamespaceForeignKeysForDrops reads the live table's foreign keys into
// another namespace when the plan drops a foreign key, so the drop's remedy
// can name them; a plan with no dropped foreign key never reads the catalog.
// The live table must exist, since only a live constraint can be dropped, so
// a missing row is an error rather than a table without foreign keys.
func crossNamespaceForeignKeysForDrops(ctx context.Context, pool *pgxpool.Pool, namespace string, report pgplan.Report) ([]string, error) {
if !slices.ContainsFunc(report.Statements, func(s pgplan.Statement) bool { return s.Kind == schemadiff.ChangeDropForeignKey }) {
return nil, nil
}
keys, err := foreignKeysFor(ctx, pool, namespace, []string{report.Table})
if err != nil {
return nil, err
}
if len(keys) != 1 {
return nil, fmt.Errorf("table %q in namespace %q left the catalog while the plan was reading its foreign keys; retry the plan", report.Table, namespace)
}
return keys[0].crossNamespaceForeignKeys, nil
}
// tableChanges maps a table's planned statements to the changes the operator
// reviews. crossNamespaceForeignKeys names the live table's foreign keys into
// another namespace, which a schema file cannot declare, so a dropped foreign
// key's remedy names them only when the table has any.
func tableChanges(report pgplan.Report, crossNamespaceForeignKeys []string, parser ddl.StatementParser) ([]engine.TableChange, []preflight.Tier, []unrecognizedPlannerVocabulary, error) {
// Each statement's verdict is derived once and reused for both the
// greenfield decision and the rendering, so a placeholder verdict is
// reported once per statement.
verdicts := make([]stepVerdict, len(report.Statements))
var unrecognized []unrecognizedPlannerVocabulary
for i, statement := range report.Statements {
verdicts[i] = executionVerdict(report.FormatVersion, statement, report.Table, crossNamespaceForeignKeys)
if verdicts[i].unrecognized != nil {
unrecognized = append(unrecognized, *verdicts[i].unrecognized)
}
}
if isGreenfieldCreateSet(report, verdicts) {
change, tier, err := greenfieldCreateSet(report, parser)
if err != nil {
return nil, nil, nil, err
}
return []engine.TableChange{change}, []preflight.Tier{tier}, unrecognized, nil
}
changes := make([]engine.TableChange, 0, len(report.Statements))
tiers := make([]preflight.Tier, 0, len(report.Statements))
for i, statement := range report.Statements {
mode, reason := verdicts[i].mode, verdicts[i].reason
rendered := statement.ExecSQL
if len(rendered) == 0 {
rendered = []string{statement.SQL}
}
for _, sql := range rendered {
operation, table, err := parser.Classify(sql)
if err != nil {
return nil, nil, nil, fmt.Errorf("classify planned statement for table %q: %w", report.Table, err)
}
if table == "" {
table = report.Table
}
stepMode, stepReason := mode, reason
// The apply path derives a privilege tier for every statement it
// executes, and that derivation refuses shapes outside the
// native-safe set. Run the same authority here, for blocked steps
// too: an executable step whose shape it refuses becomes a blocked
// verdict that matches what the engine will do, instead of an
// executable plan that deterministically fails at apply, and a
// step the planner already blocked keeps the tier the privilege
// gate needs to name the grant the operator will also need.
stepTier := tierUnderived
tier, tierErr := preflight.RequiredTier([]string{sql})
switch {
case tierErr == nil:
stepTier = tier
case stepMode == "":
stepMode = engine.ExecutionModeBlocked
stepReason = fmt.Sprintf("statement for table %q is a shape SchemaBot's PostgreSQL support does not execute yet; rewriting the change cannot make it eligible", table)
}
// Verdict reasons quote the table name, a planner-sourced
// identifier, so the reserved cause separator is neutralized
// before the reason becomes one cause of the verdict.
changes = append(changes, engine.TableChange{
Table: table,
Operation: operation,
DDL: sql,
IsUnsafe: statement.Destructive,
UnsafeReason: destructiveReason(statement.Destructive, table),
ExecutionMode: stepMode,
ModeReason: engine.SanitizeBlockedCause(stepReason),
})
tiers = append(tiers, stepTier)
}
}
return changes, tiers, unrecognized, nil
}
// stepVerdict is the execution mode and operator-facing reason derived for
// one planned statement; an empty mode means the statement is executable.
// unrecognized is set when the verdict is a placeholder for planner
// vocabulary this build does not map, so the caller can log what moved.
type stepVerdict struct {
mode string
reason string
unrecognized *unrecognizedPlannerVocabulary
}
// unrecognizedPlannerVocabulary names a planner value outside the set this
// build renders in its own words: kind says which vocabulary grew (the plan
// contract, a disposition, or a create shape cause) and value is the entry
// the planner returned. The operator sees a blocked placeholder either way;
// this record exists so the server log names the value and the schema file
// behind it.
type unrecognizedPlannerVocabulary struct {
kind string
value string
}
// isGreenfieldCreateSet reports whether the report describes a table that
// does not exist yet and whose every statement is executable, so the table
// and its indexes can ship as one apply unit. A report carrying any verdict
// or destructive step keeps its per-statement rendering so each verdict
// stays visible to the reviewer.
func isGreenfieldCreateSet(report pgplan.Report, verdicts []stepVerdict) bool {
if !isGreenfieldTable(report) {
return false
}
if len(report.Statements) == 0 {
return false
}
for i, statement := range report.Statements {
if verdicts[i].mode != "" || statement.Destructive {
return false
}
}
return true
}
// isGreenfieldTable reports whether the planner proved the table absent.
func isGreenfieldTable(report pgplan.Report) bool {
return report.TableExists != nil && !*report.TableExists
}
// greenfieldCreateSet renders a greenfield report as a single CREATE TABLE
// change whose DDL carries the table and its indexes in execution order, and
// derives the privilege tier the whole set needs. Every statement is
// re-classified against the planner's own table so a report that is not a
// create set fails closed here rather than at apply time.
func greenfieldCreateSet(report pgplan.Report, parser ddl.StatementParser) (engine.TableChange, preflight.Tier, error) {
statements := make([]string, len(report.Statements))
for i, statement := range report.Statements {
// pg-sprite may render ExecSQL with CONCURRENTLY, which ExecuteCreate
// refuses for a table born in the run; canonical SQL is deliberate
// regardless of renderer behavior.
statements[i] = statement.SQL
}
createSet, err := ddl.CreateSetStatements(parser, strings.Join(statements, ";\n"))
if err != nil {
return engine.TableChange{}, 0, fmt.Errorf("validate greenfield create set for table %q: %w", report.Table, err)
}
_, table, err := parser.Classify(createSet[0])
if err != nil {
return engine.TableChange{}, 0, fmt.Errorf("classify greenfield CREATE TABLE for table %q: %w", report.Table, err)
}
if table != report.Table {
return engine.TableChange{}, 0, fmt.Errorf("greenfield create set targets table %q, expected planner table %q", table, report.Table)
}
tier, err := preflight.RequiredTier(createSet)
if err != nil {
return engine.TableChange{}, 0, fmt.Errorf("derive privilege tier for greenfield table %q: %w", report.Table, err)
}
if err := ensureGreenfieldCreateTier(report.Table, tier); err != nil {
return engine.TableChange{}, 0, err
}
return engine.TableChange{
Table: report.Table,
Operation: ddl.StatementCreateTable,
DDL: strings.Join(createSet, ";\n"),
}, tier, nil
}
func ensureGreenfieldCreateTier(table string, tier preflight.Tier) error {
if tier != preflight.TierCreateTable {
return fmt.Errorf("greenfield table %q requires tier %s, expected %s", table, tier, preflight.TierCreateTable)
}
return nil
}
// blockMissingPrivileges verifies the connected role holds the access each
// step needs, at that step's own tier, so a missing grant surfaces
// on the plan the operator reviews — with the exact provisioning statement —
// instead of failing only after apply is requested. Tiers are checked
// per-step rather than aggregated so a refusal's remediation names only the
// access the blocked step actually needs: an index build's missing schema
// CREATE must not mislabel an in-place ALTER the role can already run. The
// apply path re-runs the same per-statement check before executing, so a
// grant revoked between plan and apply still fails closed there. A privilege
// refusal blocks the steps at its tier; a table-scoped refusal blocks every
// executable step; any other failure fails the plan — an executable plan
// must never be produced while the check's answer is unknown. When every step
// is already blocked, a refusal the operator answers by provisioning — a
// grant, a role, a schema — is appended as an independent cause; any other
// answer leaves the safe verdicts intact and is logged. Reasons come
// from classifyRefusal, so the same failure carries the same detail at plan
// and apply time; here it is prefixed with the statement it blocks. The
// returned slice is the input with verdicts marked.
func blockMissingPrivileges(ctx context.Context, pool *pgxpool.Pool, database string, report pgplan.Report, changes []engine.TableChange, tiers []preflight.Tier, tableOwner string) ([]engine.TableChange, error) {
checkTier := func(ctx context.Context, pool *pgxpool.Pool, report pgplan.Report, tier preflight.Tier, tableOwner string) error {
if tier == preflight.TierCreateTable {
// The off-ladder create tier is checked against the schema, not
// the table: CheckPrivileges' ladder walks facts about an
// existing table, and a greenfield target has none.
_, err := preflight.CheckCreatePrivilegesAs(ctx, pool, report.Schema, tableOwner)
return err
}
_, err := preflight.CheckPrivileges(ctx, pool, report.Schema, report.Table, preflight.Requirement{Tier: tier})
return err
}
return blockMissingPrivilegesWithCheck(ctx, pool, database, report, changes, tiers, tableOwner, checkTier)
}
// privilegeTierCheck answers whether the connected role holds one tier's
// access for the report's target; the error is the preflight's own so
// classifyRefusal can render it.
type privilegeTierCheck func(ctx context.Context, pool *pgxpool.Pool, report pgplan.Report, tier preflight.Tier, tableOwner string) error
// blockMissingPrivilegesWithCheck is blockMissingPrivileges with the per-tier
// check injected, so the verdict rewriting can be exercised without a target.
func blockMissingPrivilegesWithCheck(ctx context.Context, pool *pgxpool.Pool, database string, report pgplan.Report, changes []engine.TableChange, tiers []preflight.Tier, tableOwner string, checkTier privilegeTierCheck) ([]engine.TableChange, error) {
if len(changes) != len(tiers) {
return nil, fmt.Errorf("verify privileges for table %q: %d planned changes carry %d privilege tiers", report.Table, len(changes), len(tiers))
}
fullyBlocked := !hasExecutableChanges(changes)
// Checked before any verdict rewriting below: blocking dependent steps
// must never launder a report that carries executable work but names no
// target into a plan that skips the privilege check entirely.
if report.Table == "" {
if fullyBlocked {
return changes, nil
}
return nil, fmt.Errorf("plan report carries executable steps but names no target table")
}
if isGreenfieldTable(report) {
// A privilege probe against a table that provably does not exist can
// only answer "table not found" — a dead end for the operator. Only
// the CREATE TABLE step's off-ladder tier states facts an absent
// target can satisfy; every other executable step depends on the
// table's creation, so that dependency is its accurate reason.
blockAbsentTableDependents(changes, tiers, report.Table)
// Blocking the dependents can leave no executable step: a plan whose
// CREATE TABLE the planner refused and whose index build was the
// only executable work is now blocked throughout, and its create
// step is probed below like any other fully blocked plan's, so the
// schema grant is named beside the shape refusal here too.
fullyBlocked = !hasExecutableChanges(changes)
}
// Executable steps are always checked. On a plan every gate has already
// refused, the blocked steps' tiers are checked too, so a grant the
// operator will also need is named in the same verdict rather than after
// the planner refusal is fixed.
greenfield := isGreenfieldTable(report)
required := make(map[preflight.Tier]bool)
for i, change := range changes {
switch {
case change.ExecutionMode == "":
if tiers[i] == tierUnderived {
return nil, fmt.Errorf("verify privileges for table %q: executable statement %q carries no privilege tier", report.Table, change.DDL)
}
required[tiers[i]] = true
case fullyBlocked && change.ExecutionMode == engine.ExecutionModeBlocked && blockedTierIsProbeable(tiers[i], greenfield):
required[tiers[i]] = true
}
}
if len(required) == 0 {
return changes, nil
}
for _, tier := range slices.Sorted(maps.Keys(required)) {
err := checkTier(ctx, pool, report, tier, tableOwner)
if err == nil {
continue
}
r := classifyRefusal(err, report.Table)
if fullyBlocked {
// The plan is already safe as it stands, so the probe's answer
// can only add to the verdicts, never replace them. A refusal
// that names something to provision — a grant, a role, a
// schema — is work the operator will have to do anyway, so it
// is appended beside the earlier cause. Every other answer goes
// to the log: a refusal about the table itself names nothing to
// provision on a plan nothing will run, and an operational
// failure is not a fact about the target at all.
switch {
case r != nil && r.provisionable:
appendBlockedCauseAtTier(changes, tiers, tier, r.detail)
case r != nil:
slog.Warn("PostgreSQL privilege check refused the table; existing blocked plan verdicts remain unchanged",
"database", database,
"namespace", report.Schema,
"table", report.Table,
"refusal", r.reason,
"detail", r.detail)
default:
slog.Warn("PostgreSQL privilege check failed; existing blocked plan verdicts remain unchanged",
"database", database,
"namespace", report.Schema,
"table", report.Table,
"error", err)
}
continue
}
if r == nil {
return nil, fmt.Errorf("check privileges for table %q: %w", report.Table, err)
}
var privilegeErr *preflight.PrivilegeError
if errors.As(err, &privilegeErr) {
// Missing access is a property of this tier alone: steps at the
// other tiers keep their own verdicts, from their own checks.
blockChangesAtTier(changes, tiers, tier, r.detail)
continue
}
// Any other refusal is a property of the table itself — vanished,
// not an ordinary table, or to be created for an owner the target
// has no role for — so it holds for every executable step.
blockExecutableChanges(changes, r.detail)
return changes, nil
}
return changes, nil
}
// blockedTierIsProbeable reports whether a blocked step's tier can be checked
// against the target on a plan every gate has already refused. A step whose
// shape has no tier has no access to probe. On a table the planner proved
// absent, only the CREATE TABLE tier states facts the target can answer:
// probing an absent table for any other tier can only say "table not found",
// which names nothing the operator can provision.
func blockedTierIsProbeable(tier preflight.Tier, greenfield bool) bool {
if tier == tierUnderived {
return false
}
return !greenfield || tier == preflight.TierCreateTable
}
// blockOversizedTable applies the native-safe table size ceiling to executable
// steps whose native cost scales with the existing table. The preflight
// measures the table and proves it exists and is an ordinary or partitioned
// table; which steps a size refusal blocks is decided in blockRewriteSteps,
// where concurrent index builds keep their verdict because their bound is a
// duration envelope, not the table size. A typed refusal is rendered as a
// blocked verdict; an operational failure fails planning rather than producing
// an executable plan while the table size is unknown. When an earlier gate has
// already blocked every step, an operational failure or a refusal unrelated to
// size leaves those safe verdicts intact and is logged for operator triage.
func blockOversizedTable(ctx context.Context, pool *pgxpool.Pool, database string, report pgplan.Report, changes []engine.TableChange, tableSizeLimit int64) ([]engine.TableChange, error) {
return blockOversizedTableWithCheck(ctx, pool, database, report, changes, tableSizeLimit, preflight.CheckTable)
}
func blockOversizedTableWithCheck(ctx context.Context, pool *pgxpool.Pool, database string, report pgplan.Report, changes []engine.TableChange, tableSizeLimit int64, checkTable func(context.Context, *pgxpool.Pool, string, string, int64) (preflight.PreflightedTable, error)) ([]engine.TableChange, error) {
// A table the plan leaves untouched has no step for a size verdict to
// land on, so it is not charged a catalog round trip.
if len(changes) == 0 {
return changes, nil
}
// When an earlier gate has already blocked every step the plan is safe as
// it stands; the size check then runs only so the operator sees both
// causes at once, and nothing it finds may turn that safe plan into a
// planning failure.
fullyBlocked := !hasExecutableChanges(changes)
if report.Table == "" {
if fullyBlocked {
return changes, nil
}
return nil, fmt.Errorf("plan report carries executable steps but names no target table")
}
if isGreenfieldTable(report) {
return changes, nil
}
_, err := checkTable(ctx, pool, report.Schema, report.Table, tableSizeLimit)
if err == nil {
return changes, nil
}
r := classifyRefusal(err, report.Table)
if r == nil {
if fullyBlocked {
slog.Warn("PostgreSQL table size check failed; existing blocked plan verdicts remain unchanged",
"database", database,
"namespace", report.Schema,
"table", report.Table,
"error", err)
return changes, nil
}
return nil, fmt.Errorf("check size for table %q: %w", report.Table, err)
}
// The table name is a database-sourced identifier. Quoting escapes control
// characters but not whitespace runs, so the composed reason is collapsed
// to one line as a whole; the Markdown surfaces that render it escape
// their own delimiters at the rendering boundary, so the name reaches the
// operator as the relation it is. The blocked-cause separator is the one
// delimiter decoded before rendering, so it is neutralized here.
reason := engine.SanitizeBlockedCause(singleLine(fmt.Sprintf("statement for table %q: %s", report.Table, r.detail)))
var sizeErr *preflight.SizeError
if errors.As(err, &sizeErr) {
if err := blockRewriteSteps(changes, reason); err != nil {
if fullyBlocked {
slog.Warn("PostgreSQL table size check could not classify a blocked step; existing blocked plan verdicts remain unchanged",
"database", database,
"namespace", report.Schema,
"table", report.Table,
"error", err)
return changes, nil
}
return nil, err
}
return changes, nil
}
if fullyBlocked {
// A refusal about the table itself, not its size, has no executable
// step left to land on; the verdicts already carry a cause the
// operator can act on, so the answer goes to the log instead of
// being lost.
slog.Warn("PostgreSQL table size check refused the table; existing blocked plan verdicts remain unchanged",
"database", database,
"namespace", report.Schema,
"table", report.Table,
"refusal", r.reason,
"detail", r.detail)
return changes, nil
}
blockExecutableChanges(changes, reason)
return changes, nil
}
// blockRewriteSteps marks every step whose native cost scales with the existing
// table blocked with the reason. A concurrent index build keeps its verdict: it
// is bounded by its duration envelope rather than the table size ceiling. An
// earlier blocked verdict retains its reason and gains the independent size
// cause so the operator can resolve both without another planning round trip.
// parser.Classify in tableChanges parsed every rendered statement, including
// blocked steps, with the same single-statement requirements used here. A
// statement that now fails to classify is therefore an invariant violation.
// Every step is classified before any verdict is written, so a caller that
// keeps the plan on that error keeps it exactly as it was rather than with
// the size cause on some steps and not others.
func blockRewriteSteps(changes []engine.TableChange, reason string) error {
concurrentIndexes := make([]bool, len(changes))
for i := range changes {
if changes[i].ExecutionMode != "" && changes[i].ExecutionMode != engine.ExecutionModeBlocked {
continue
}
concurrentIndex, err := concurrentIndexStatement(changes[i].DDL)
if err != nil {
return fmt.Errorf("classify planned statement for table %q: %w", changes[i].Table, err)
}
concurrentIndexes[i] = concurrentIndex
}
for i := range changes {
if changes[i].ExecutionMode != "" && changes[i].ExecutionMode != engine.ExecutionModeBlocked {
continue
}
if concurrentIndexes[i] {
continue
}
if changes[i].ExecutionMode == engine.ExecutionModeBlocked {
causes := engine.BlockedCauses(changes[i].ModeReason)
if !slices.Contains(causes, reason) {
changes[i].ModeReason = engine.JoinBlockedCauses(append(causes, reason))
}
continue
}
changes[i].ExecutionMode = engine.ExecutionModeBlocked
changes[i].ModeReason = reason
}
return nil
}
// concurrentIndexStatement reports whether sql is a single CREATE INDEX
// CONCURRENTLY statement — the one shape SchemaBot's PostgreSQL support runs
// under the concurrent index duration envelope instead of the table size
// ceiling. Every other concurrent form the parser recognizes, including a
// concurrent partition detach, stays inside the ceiling. The plan and apply
// paths share this classification so the two can never disagree about which
// bound a statement is admitted under.
func concurrentIndexStatement(sql string) (bool, error) {
statement, err := pgstatement.ParseOne(sql)
if err != nil {
return false, fmt.Errorf("parse PostgreSQL statement: %w", err)
}
return statement.Kind() == pgstatement.KindCreateIndex && statement.Concurrent(), nil
}
// exemptReasonArchiveNaming is the exemption reason a plan carries for an
// undeclared live table whose name marks it as an archive: the table is left
// in place rather than dropped, and left out of the rollback baseline.
const exemptReasonArchiveNaming = "archive naming"
// undeclaredTableDrops surfaces every live table in the namespace that no
// schema file declares, whether its file was deleted or it was never declared
// at all. Desired state is declarative: an undeclared table converges only by
// being dropped, so the plan must show that drop rather than stay silent while
// the table lingers on the target. Each drop is both destructive and blocked —
// SchemaBot's PostgreSQL support never executes DROP TABLE — so the operator
// either brings the table under management by declaring it in a schema file
// or removes it through a separately reviewed process; a plan that hid the
// drop would let a merge pass with the target still diverged from the
// repository.
//
// Archive tables (<name>_archive_YYYY[_MM[_DD]]) are the one naming
// convention exempt from the verdict, as they are in the MySQL engine's view
// of its live schema: an archive is a retired copy kept outside declarative
// schema files. The naming convention is the per-table exemption;
// ignore_namespaces is the per-namespace one. Each exempt table is logged
// and returned on the plan so the PR comment discloses what the verdict
// skipped.
//
// The verdict names only remedies the operator can follow. A table that owns
// or is referenced by foreign key constraints cannot be brought under
// management by a pulled file — the declarative format refuses foreign keys —
// so its reason names the constraints and says what each side of the
// relationship needs instead of pointing at a file the pull cannot write. The
// catalog is read directly because the namespace's schema may not exist yet,
// in which case the answer is an empty set, not an error.
func undeclaredTableDrops(ctx context.Context, pool *pgxpool.Pool, database, namespace string, declared map[string]bool, ignored engine.IgnoredTables, parser ddl.StatementParser) ([]engine.TableChange, []string, []string, error) {
tables, err := liveTables(ctx, pool, namespace)
if err != nil {
return nil, nil, nil, err
}
var drops []engine.TableChange
var exempt []string
var withheld []string
for _, live := range tables {
if declared[live.name] {
continue
}