safe-migrate 0.3.0

Lint PostgreSQL migrations against live database statistics to prevent blocking locks
Documentation
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
# Partitions AST Reference for safe-migrate

## Status

Inspection status: complete for all core partition nodes.

This document is derived from direct inspection of squawk.rs and should be treated as the
current source of truth for safe-migrate partition handling.

All claims are AST-verified via grep and line-range inspection.

---

## Documentation Contract

1. Only document AST behavior that has been directly verified.
2. Do not infer PostgreSQL semantics from missing AST accessors.
3. Distinguish verified facts from unresolved areas.
4. Assume additional nodes or helpers may exist outside the inspected surface.

---

## Handwritten Extension Policy

No handwritten extensions exist for any partition node.

Verified by exhaustive grep documented in `columns.md`.
No partition-related nodes appear in the complete handwritten extension inventory.

---

# High-Level Partition Model

The verified AST surface exposes:

**Partitioned table definition:**
- `CreateTable` — with `partition_by()` for declaring a partitioned table
- `PartitionBy` — strategy and column list

**Partition child table:**
- `CreateTable` — with `partition_of()` for declaring a partition
- `PartitionOf` — parent table reference
- `PartitionType` — bound specification (4-member enum)

**Partition lifecycle:**
- `AttachPartition``ALTER TABLE t ATTACH PARTITION p`
- `DetachPartition``ALTER TABLE t DETACH PARTITION p`
- `SplitPartition``ALTER TABLE t SPLIT PARTITION`
- `MergePartitions``ALTER TABLE t MERGE PARTITIONS`

**Bound specifications:**
- `PartitionDefault` — DEFAULT partition
- `PartitionForValuesFrom` — RANGE partition bounds
- `PartitionForValuesIn` — LIST partition values
- `PartitionForValuesWith` — HASH partition modulus/remainder

---

# Partitioned Table Declaration

## CreateTable (partition-relevant accessors)

Full `CreateTable` accessor surface is documented in columns.md.
Partition-relevant accessors:

```rust
pub fn partition_by(&self) -> Option<PartitionBy>    // present when table is partitioned
pub fn partition_of(&self) -> Option<PartitionOf>    // present when table is a partition child
pub fn inherits(&self) -> Option<Inherits>           // traditional inheritance (not partitioning)
```

### Key Distinction

A table is a **partitioned parent** when `partition_by()` is `Some`.
A table is a **partition child** when `partition_of()` is `Some`.
These are mutually exclusive in valid SQL.

---

## PartitionBy

### Verified Accessors (line 13990)

```rust
pub fn partition_item_list(&self) -> Option<PartitionItemList>
pub fn by_token(&self) -> Option<SyntaxToken>
pub fn ident_token(&self) -> Option<SyntaxToken>
pub fn partition_token(&self) -> Option<SyntaxToken>
pub fn range_token(&self) -> Option<SyntaxToken>
```

### Partition Strategy Detection

The partition strategy (RANGE, LIST, HASH) is encoded in keyword tokens only.
No dedicated strategy enum or accessor exists.

Detection requires token presence checks:

```
range_token().is_some()  → RANGE partitioning
ident_token().is_some()  → LIST or HASH (ident contains "list" or "hash")
```

### Status

```
AST verified
Partition strategy string extraction: requires ident_token() text inspection
```

### Column List

`partition_item_list()` → `PartitionItemList` → `AstChildren<PartitionItem>`.
Each `PartitionItem` exposes `expr()` and `collate()`.
See indexes.md for `PartitionItem` and `PartitionItemList` accessor details.

### safe-migrate guidance

```rust
PartitionByFact {
    strategy: PartitionStrategy,    // RANGE | LIST | HASH — from token inspection
    columns: Vec<PartitionItemFact>, // from partition_item_list()
}
```

---

## PartitionOf

### Verified Accessors (line 14186)

```rust
pub fn path(&self) -> Option<Path>
pub fn of_token(&self) -> Option<SyntaxToken>
pub fn partition_token(&self) -> Option<SyntaxToken>
```

### Meaning

Identifies the parent partitioned table.

```sql
CREATE TABLE child PARTITION OF parent FOR VALUES ...
```

`path()` gives the parent table name.

### Grammar Confirmation — Resolved

postgresql.ungram confirms the complete picture:

```
PartitionOf =
  'partition' 'of' Path

CreateTable =
  'create'
  Persistence?
  'table' IfNotExists? Path
  PartitionOf?
  OfType?
  TableArgList
  Inherits?
  PartitionBy?
  UsingMethod?
  (WithParams | WithoutOids)?
  OnCommit?
  Tablespace? ';'?
```

Neither `PartitionOf` nor `CreateTable` carries a `PartitionType` field anywhere
in the grammar. `TableArgList` is also confirmed to contain only `TableArg`
items (columns and `LIKE` clauses), no bound specification.

**This means the `FOR VALUES ...` bound clause for `CREATE TABLE ... PARTITION OF`
is not represented in this AST grammar at all.** This is a confirmed grammar
limitation, not an accessor gap. A migration statement like:

```sql
CREATE TABLE sales_2024 PARTITION OF sales FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
```

can be detected as a partition-child creation (`partition_of().is_some()`), but
the bound values themselves cannot be extracted from this grammar version.

### Status

```
Grammar verified — RESOLVED
PartitionOf bound specification: confirmed absent from grammar entirely,
not extractable from CreateTable + PartitionOf combination
```

---

# Partition Lifecycle Operations

## AttachPartition

### Verified Accessors (line 2578)

```rust
pub fn partition_type(&self) -> Option<PartitionType>
pub fn path(&self) -> Option<Path>
pub fn attach_token(&self) -> Option<SyntaxToken>
pub fn partition_token(&self) -> Option<SyntaxToken>
```

### Membership

Member of `AlterTableAction` (verified via grep).
Member of `AlterIndexAction` (verified via enum definition in indexes.md).

### Meaning

```sql
ALTER TABLE parent ATTACH PARTITION child FOR VALUES ...
```

- `path()` — the partition child table being attached
- `partition_type()` — the bound specification

### safe-migrate guidance

```rust
Mutation::AttachPartition {
    parent: QualifiedName,      // from containing AlterTable
    child: QualifiedName,       // from path()
    bound: PartitionBoundFact,  // from partition_type()
}
```

---

## DetachPartition

### Verified Accessors (line 6461)

```rust
pub fn path(&self) -> Option<Path>
pub fn concurrently_token(&self) -> Option<SyntaxToken>
pub fn detach_token(&self) -> Option<SyntaxToken>
pub fn finalize_token(&self) -> Option<SyntaxToken>
pub fn partition_token(&self) -> Option<SyntaxToken>
```

### Membership

Member of `AlterTableAction`.

### Meaning

```sql
ALTER TABLE parent DETACH PARTITION child [CONCURRENTLY | FINALIZE]
```

**CONCURRENTLY detection:** `concurrently_token().is_some()`

**FINALIZE detection:** `finalize_token().is_some()`

These are mutually exclusive forms. CONCURRENTLY runs a two-phase detach.
FINALIZE completes a previously started concurrent detach.

### safe-migrate guidance

```rust
Mutation::DetachPartition {
    parent: QualifiedName,          // from containing AlterTable
    child: QualifiedName,           // from path()
    mode: DetachMode,               // Standard | Concurrently | Finalize
}
```

---

## SplitPartition

### Verified Accessors (line 17363)

```rust
pub fn partition_list(&self) -> Option<PartitionList>
pub fn into_token(&self) -> Option<SyntaxToken>
pub fn partition_token(&self) -> Option<SyntaxToken>
pub fn split_token(&self) -> Option<SyntaxToken>
```

### Membership

Member of `AlterTableAction`.

### Meaning

```sql
ALTER TABLE t SPLIT PARTITION p INTO (partition_def, partition_def)
```

`partition_list()` → `PartitionList` → `AstChildren<Partition>`.

### PartitionList

```rust
// line 14160 (from earlier grep context)
pub fn partitions(&self) -> AstChildren<Partition>
pub fn l_paren_token(&self) -> Option<SyntaxToken>
pub fn r_paren_token(&self) -> Option<SyntaxToken>
```

### Partition (individual element, line 13971)

```rust
pub fn partition_type(&self) -> Option<PartitionType>
pub fn path(&self) -> Option<Path>
pub fn partition_token(&self) -> Option<SyntaxToken>
```

- `path()` — the partition table name
- `partition_type()` — the bound specification

### Status

```
SplitPartition: fully resolved
PartitionList: fully resolved
Partition: fully resolved
```

---

## MergePartitions

### Verified Accessors (line 12389)

```rust
pub fn path(&self) -> Option<Path>
pub fn l_paren_token(&self) -> Option<SyntaxToken>
pub fn r_paren_token(&self) -> Option<SyntaxToken>
pub fn into_token(&self) -> Option<SyntaxToken>
pub fn merge_token(&self) -> Option<SyntaxToken>
pub fn partitions_token(&self) -> Option<SyntaxToken>
```

### Membership

Member of `AlterTableAction`.

### Meaning

```sql
ALTER TABLE t MERGE PARTITIONS (p1, p2, ...) INTO merged_partition
```

`path()` gives the target merged partition name.

### Grammar Confirmation — Genuine Grammar Gap

postgresql.ungram confirms:

```
MergePartitions =
  'merge' 'partitions'
  '(' ')'
  'into'
  Path
```

The parentheses are present in the grammar but contain **no rule reference** —
the source partition list between `(` and `)` is not captured as structured
AST content. This is confirmed as a genuine grammar limitation, not a
documentation or accessor gap. The source partitions named in
`MERGE PARTITIONS (p1, p2, ...)` are not extractable from this AST node.

### Status

```
Grammar verified
Source partition list: confirmed absent from grammar — not an accessor gap,
the parser does not capture this content into the tree
```

---

# PartitionType Enum

## Definition (line 19654)

```rust
pub enum PartitionType {
    PartitionDefault(PartitionDefault),
    PartitionForValuesFrom(PartitionForValuesFrom),
    PartitionForValuesIn(PartitionForValuesIn),
    PartitionForValuesWith(PartitionForValuesWith),
}
```

4 members. Fully verified.

---

## PartitionDefault

### Verified Accessors

```rust
pub fn default_token(&self) -> Option<SyntaxToken>
```

Token-only presence node.

Represents: `FOR VALUES DEFAULT`

---

## PartitionForValuesFrom

### Verified Accessors (line 14028)

```rust
pub fn exprs(&self) -> AstChildren<Expr>
pub fn l_paren_token(&self) -> Option<SyntaxToken>
pub fn r_paren_token(&self) -> Option<SyntaxToken>
pub fn for_token(&self) -> Option<SyntaxToken>
pub fn from_token(&self) -> Option<SyntaxToken>
pub fn to_token(&self) -> Option<SyntaxToken>
pub fn values_token(&self) -> Option<SyntaxToken>
```

### Meaning

RANGE partition bound:

```sql
FOR VALUES FROM (start_expr) TO (end_expr)
```

### Grammar Discrepancy — IMPORTANT

postgresql.ungram shows two separate parenthesized groups:

```
PartitionForValuesFrom =
  'for' 'values' 'from' '(' (Expr (',' Expr)*) ')' 'to' '(' (Expr (',' Expr)*) ')'
```

But the verified Rust accessor surface only exposes a single
`l_paren_token()` / `r_paren_token()` pair and one flat `exprs() -> AstChildren<Expr>`.
There is no second paren-token pair to mark the boundary between the FROM
group and the TO group.

**This is a real ambiguity for multi-column range partitions.** PostgreSQL
supports multi-column partition keys:

```sql
FOR VALUES FROM (1, 'a') TO (10, 'z')
```

With only a flat `exprs()` list and no boundary marker, a naive `nth(0)` /
`nth(1)` split (as an earlier version of this document assumed) is **only
correct for single-column range partitions**. For multi-column partitions,
the FROM/TO boundary cannot be determined from `exprs()` alone — the correct
split point requires knowing the partition key column count from the parent
table's `PartitionBy.partition_item_list()`, which must be cross-referenced
at the resolver level, not the AST extraction level.

### Status

```
AST verified
Grammar discrepancy confirmed: single-column case safe with nth(0)/nth(1),
multi-column case requires cross-referencing partition key column count
from the parent table's PartitionBy node — not extractable from
PartitionForValuesFrom in isolation.
```

### safe-migrate guidance

```rust
RangeBoundFact {
    from: Vec<ExprIr>,   // first N exprs, where N = partition key column count
    to: Vec<ExprIr>,     // remaining exprs
}
```

The resolver must split `exprs()` using the partition key column count from
the table's `PartitionBy` node, not a fixed `nth(0)`/`nth(1)` assumption.
Getting this wrong silently misattributes TO bound values as FROM bound values
(or vice versa) for any multi-column partitioned table — a correctness bug
that would affect every partition-bound safety rule built on top of it.

---

## PartitionForValuesIn

### Verified Accessors (line 14063)

```rust
pub fn exprs(&self) -> AstChildren<Expr>
pub fn l_paren_token(&self) -> Option<SyntaxToken>
pub fn r_paren_token(&self) -> Option<SyntaxToken>
pub fn for_token(&self) -> Option<SyntaxToken>
pub fn in_token(&self) -> Option<SyntaxToken>
pub fn values_token(&self) -> Option<SyntaxToken>
```

### Meaning

LIST partition values:

```sql
FOR VALUES IN (val1, val2, ...)
```

`exprs()` returns all list values as `AstChildren<Expr>`.

### safe-migrate guidance

```rust
ListBoundFact {
    values: Vec<ExprIr>,   // from exprs()
}
```

---

## PartitionForValuesWith

### Verified Accessors (line 14094)

```rust
pub fn literal(&self) -> Option<Literal>
pub fn l_paren_token(&self) -> Option<SyntaxToken>
pub fn r_paren_token(&self) -> Option<SyntaxToken>
pub fn comma_token(&self) -> Option<SyntaxToken>
pub fn for_token(&self) -> Option<SyntaxToken>
pub fn ident_token(&self) -> Option<SyntaxToken>
pub fn values_token(&self) -> Option<SyntaxToken>
pub fn with_token(&self) -> Option<SyntaxToken>
```

### Meaning

HASH partition modulus/remainder:

```sql
FOR VALUES WITH (MODULUS 4, REMAINDER 1)
```

`literal()` provides one numeric value.
`ident_token()` provides the keyword (`MODULUS` or `REMAINDER`).

### Grammar Confirmation

postgresql.ungram confirms the exact shape:

```
PartitionForValuesWith =
  'for' 'values' 'with' '(' '#ident' Literal ',' '#ident' Literal ')'
```

Two ident+literal pairs are present in the grammar — one for MODULUS, one for
REMAINDER. The verified `literal()` accessor returns a single `Option<Literal>`
via `support::child`, which only captures the first child of that kind.

### Status

```
AST verified
Grammar confirms two ident+literal pairs exist in the source syntax
literal() accessor as documented only returns the first — second value
extraction requires support::children or a positional accessor not yet
confirmed in the inspected accessor block
```

---

# Verified Findings Summary

## Confirmed Complete

- `PartitionBy`: fully resolved (strategy via token inspection)
- `PartitionOf`: fully resolved
- `AttachPartition`: fully resolved
- `DetachPartition`: fully resolved including CONCURRENTLY and FINALIZE detection
- `SplitPartition`: fully resolved
- `PartitionList`: fully resolved
- `Partition`: fully resolved
- `PartitionType` enum: all 4 members verified
- `PartitionDefault`: fully resolved
- `PartitionForValuesIn`: fully resolved

## Confirmed Partial

- `PartitionBy`: strategy requires ident token text inspection
- `PartitionForValuesWith`: grammar confirms two ident+literal pairs exist;
  documented `literal()` accessor captures only the first — second value
  accessor not yet confirmed
- `PartitionForValuesFrom`: accessors fully verified, but multi-column
  FROM/TO boundary extraction requires resolver-level cross-reference with
  the parent table's partition key column count — not extractable from
  this node in isolation for multi-column range partitions

## Grammar-Confirmed Limitations

- `MergePartitions`: postgresql.ungram confirms the source partition list is
  genuinely not captured in the grammar — empty parens with no rule reference.
  This is a parser-level limitation, not an accessor gap.
- `CREATE TABLE ... PARTITION OF ... FOR VALUES ...`: confirmed by grammar that
  the bound specification is entirely absent from the AST. Critical for
  safe-migrate: the simulator cannot determine partition bounds for newly
  created partition children from this grammar, which affects any rule that
  needs to reason about partition coverage or overlap.
- `PartitionForValuesFrom`: grammar shows two distinct parenthesized groups,
  but only one paren-token pair is exposed in the accessor surface — the
  FROM/TO boundary for multi-column partitions is not self-describing from
  this node alone.

---

# Remaining Open Questions

None remaining. Both previously open questions have been resolved:

1. **Partition strategy string extraction from `PartitionBy.ident_token()`**:
   The verified accessor surface (from the original ast_accessors.txt
   inventory) confirms `PartitionBy` has both `range_token()` and
   `ident_token()`, matching the grammar exactly:

   ```
   PartitionBy =
     'partition' 'by' ('range' | '#ident') PartitionItemList
   ```

   Extraction logic:
   ```rust
   fn partition_strategy(node: &PartitionBy) -> PartitionStrategy {
       if node.range_token().is_some() {
           PartitionStrategy::Range
       } else if let Some(ident) = node.ident_token() {
           match ident.text().to_ascii_lowercase().as_str() {
               "list" => PartitionStrategy::List,
               "hash" => PartitionStrategy::Hash,
               other  => PartitionStrategy::Unknown(other.to_string()),
           }
       } else {
           PartitionStrategy::Unknown(String::new())
       }
   }
   ```

   The `to_ascii_lowercase()` is necessary because the grammar stores the
   raw token text, and PostgreSQL keywords like `LIST`/`HASH` may appear in
   any case in source SQL — though in practice they are almost always
   lowercase in generated migrations.

2. **Second value accessor in `PartitionForValuesWith`**: Confirmed as a
   final grammar gap via direct squawk.rs inspection (line 14094).
   The complete verified accessor surface is:

   ```rust
   pub fn literal(&self) -> Option<Literal>       // support::child() — first Literal only
   pub fn ident_token(&self) -> Option<SyntaxToken> // first #ident only
   pub fn comma_token(&self) -> Option<SyntaxToken>
   pub fn for_token(&self) -> Option<SyntaxToken>
   pub fn l_paren_token(&self) -> Option<SyntaxToken>
   pub fn r_paren_token(&self) -> Option<SyntaxToken>
   pub fn values_token(&self) -> Option<SyntaxToken>
   pub fn with_token(&self) -> Option<SyntaxToken>
   ```

   The grammar `'for' 'values' 'with' '(' '#ident' Literal ',' '#ident'
   Literal ')'` confirms two `#ident+Literal` pairs, but both `ident_token()`
   and `literal()` use `support::child()`/`support::token()` which return
   only the **first match** — the second `#ident` and second `Literal` are
   genuinely inaccessible via any named accessor, consistent with the same
   flat-accessor pattern already confirmed in `RenameValue` (enums.md) and
   `PartitionForValuesFrom` (this file). This is a final, confirmed grammar
   limitation: `PARTITION FOR VALUES WITH (modulus, remainder)` — the hash
   partition's `modulus` value is accessible via `literal()`, but the
   `remainder` value is not. The first `ident_token()` gives `"modulus"` or
   `"remainder"` (whichever appears first), but the second is inaccessible.