djogi 0.1.0-alpha.17

Model-first web framework for Rust — web-framework-agnostic core; Axum integration opt-in via the `axum` feature flag
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
//! Postgres 18 built-in default-expression volatility lookup.
//! The online-safety classifier walks `DEFAULT` expressions on
//! [`crate::migrate::SchemaOperation::AddColumn`] / `AlterColumn`
//! operations and asks "would Pg18 catalog-fast-path this default,
//! or does it require a 3-step ExpandContract pattern?". The answer
//! follows Postgres' own `provolatile` category for the function
//! reference inside the expression — `IMMUTABLE` and `STABLE`
//! expressions catalog-fast-path; `VOLATILE` ones force a backfill
//! per Pg18 release notes (catalog-only fast-path is gated on the
//! default being non-volatile).
//! # Why a static table
//! The classifier is required to be **pure** — given the same two
//! descriptor states it must always produce the same classification
//! (per §7 plan and `feedback_completionist_lens.md`). Reading
//! `pg_proc.provolatile` from a live database would push host
//! variability into compose-time output: the same migration source
//! could classify differently depending on which Pg version, which
//! extensions, or which contrib functions happen to be installed on
//! the operator's machine. That is the kind of latent inconsistency
//! that makes `git diff schema_snapshot.json` reviews unreliable.
//! Instead, this module ships a Djogi-owned static slice of every
//! Pg18 built-in identifier the classifier needs to recognise.
//! Lookup is a simple `binary_search` against the sorted slice. The
//! representation is deliberate: a sorted const slice is host-stable
//! (no per-machine variation), zero-allocation (no `HashMap`
//! initialisation), and the sortedness invariant is asserted in a
//! unit test so additions cannot silently break the binary search.
//! # Conservative fallback
//! Identifiers absent from the table — user-defined functions,
//! extension-shipped helpers Djogi cannot enumerate — classify as
//! [`Volatility::Volatile`]. That is the safe direction: an unknown
//! identifier routed through the 3-step ExpandContract path is
//! slower than necessary; the inverse mistake (assuming `IMMUTABLE`
//! when the function is in fact `VOLATILE`) would silently emit a
//! catalog-only `ADD COLUMN ... DEFAULT <volatile>()` that Postgres
//! accepts but the classifier promised would not require backfill,
//! producing the wrong runtime behaviour.
//! Adopters with a known-safe UDF override per-field via
//! `#[field(default_volatility = "stable" | "immutable" | "volatile")]`
//! (parsed by see
//! [`crate::descriptor::DefaultVolatility`]).
//! # §7 routing
//! - `IMMUTABLE` / `STABLE` defaults: `OnlineSafe` (Pg18 catalog-only
//!   fast-path).
//! - `VOLATILE` defaults: `ExpandContract` (3-step pattern — add
//!   nullable column with no default → SET DEFAULT → chunked
//!   backfill).
//!   See `docs/spec/live-migrations.md` for the full routing matrix.

/// Postgres `provolatile` category lifted into Rust.
/// Mirrors the Pg18 `pg_proc.provolatile` axis; the variant order
/// matches Postgres' own ordering of "least to most variable".
/// `#[non_exhaustive]` so future Postgres categories (or refinements
/// like a `Leakproof` axis) can land without breaking downstream
/// matches.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Volatility {
    /// Pure function — no DB reads, no side effects, same input
    /// always produces same output. Catalog-only fast-path.
    Immutable,
    /// Consistent within one query / statement; consults DB state
    /// but does not modify it. Catalog-only fast-path.
    Stable,
    /// Value can change on every call. Forces 3-step ExpandContract.
    Volatile,
}

/// Sorted slice of `(identifier, volatility)` pairs for every Pg18
/// built-in the classifier needs to recognise.
/// **Sort invariant.** Entries are sorted lexicographically by
/// identifier. `binary_search_by_key` depends on this — a unit test
/// asserts the invariant and any future addition must preserve it.
/// **Identifier shape.** Built-ins that take no arguments are stored
/// with their parenthesised call form (`now()`, `clock_timestamp()`)
/// because that is the literal text the classifier sees inside a
/// `DEFAULT` expression. SQL keywords that work without parentheses
/// (`CURRENT_TIMESTAMP`, `current_date`, `current_time`,
/// `current_timestamp`) appear in their bare form. The classifier
/// normalises whitespace before lookup but does NOT transform between
/// the two shapes — Postgres treats `now()` and `now` differently
/// (the first is a function call, the second is an identifier
/// reference) and the classifier preserves that distinction.
/// **Why both `current_timestamp` cases.** Postgres accepts SQL
/// keywords case-insensitively, so the table holds both forms the
/// classifier is likely to see in a descriptor's `default_sql`
/// expression: the uppercase keyword form `CURRENT_TIMESTAMP` and
/// the lowercase form `current_timestamp` actually emitted by
/// adopters who follow the Djogi convention of lowercase SQL. The
/// classifier compares case-sensitively (via `binary_search_by_key`)
/// rather than performing an `eq_ignore_ascii_case` walk because the
/// sorted-slice + `binary_search` shape costs O(log n) per lookup
/// where a case-folding walk is O(n) — and the few SQL keywords that
/// matter here are short enough that listing both casings keeps the
/// table readable. Function-call forms (`now()`, `random()`) are
/// always lowercase per Postgres' identifier rules, so no parallel
/// uppercase entry is required.
const BUILTIN_VOLATILITY: &[(&str, Volatility)] = &[
    ("CURRENT_TIMESTAMP", Volatility::Stable),
    ("clock_timestamp()", Volatility::Volatile),
    ("current_date", Volatility::Stable),
    ("current_time", Volatility::Stable),
    ("current_timestamp", Volatility::Stable),
    ("gen_random_uuid()", Volatility::Volatile),
    ("now()", Volatility::Stable),
    ("random()", Volatility::Volatile),
    ("statement_timestamp()", Volatility::Stable),
    ("transaction_timestamp()", Volatility::Stable),
];

/// Classify a `DEFAULT` expression's volatility.
/// Resolution order:
/// 1. Trim ASCII whitespace.
/// 2. Recognise literal shapes — string literals (`'...'` /
///    `E'...'` / dollar-quoted), numeric literals, boolean
///    literals (`true` / `false`), and `NULL`. Literals are pure
///    constants with no runtime evaluation; classify as
///    [`Volatility::Immutable`].
/// 3. Look up the trimmed expression against [`BUILTIN_VOLATILITY`]
///    via `binary_search_by_key`. A match returns the catalog
///    category.
/// 4. Fall through to [`Volatility::Volatile`] — the conservative
///    default. Per the module-level docs, unknown identifiers must
///    route through the 3-step ExpandContract path because we cannot
///    prove they are safe to catalog-fast-path.
///    The classifier never reads `pg_catalog`. Compose stays pure.
/// # Examples
/// ```ignore
/// use djogi::migrate::pg_volatility::{Volatility, classify_default_expression};
///
/// assert_eq!(classify_default_expression("'hello'"), Volatility::Immutable);
/// assert_eq!(classify_default_expression("42"), Volatility::Immutable);
/// assert_eq!(classify_default_expression("true"), Volatility::Immutable);
/// assert_eq!(classify_default_expression("NULL"), Volatility::Immutable);
/// assert_eq!(classify_default_expression("now()"), Volatility::Stable);
/// assert_eq!(classify_default_expression("clock_timestamp()"), Volatility::Volatile);
/// assert_eq!(classify_default_expression("myapp_helper()"), Volatility::Volatile);
/// ```
pub fn classify_default_expression(expr: &str) -> Volatility {
    let trimmed = expr.trim();

    if is_literal_shape(trimmed) {
        return Volatility::Immutable;
    }

    if let Ok(idx) = BUILTIN_VOLATILITY.binary_search_by_key(&trimmed, |(name, _)| *name) {
        return BUILTIN_VOLATILITY[idx].1;
    }

    Volatility::Volatile
}

/// Recognise the four literal shapes Postgres accepts in a `DEFAULT`
/// expression: string, numeric, boolean, and `NULL`.
/// **The entire trimmed expression must be a single literal token.**
/// Compound expressions like `1 + random()` are NOT literals — the
/// presence of operators, function-call parentheses, or whitespace
/// separators between tokens means the expression evaluates at write
/// time and the volatility of any sub-call dominates. Returning `true`
/// for those would route a volatile compound default through the
/// Immutable fast-path, silently skipping the 3-step ExpandContract
/// pattern Pg18 requires.
/// Plain-English shape rules, implemented with byte-level checks only:
/// - **String literal.** Trimmed expression starts AND ends with a
///   single quote `'`, OR is `E'...'` / `e'...'` (escape-string
///   syntax) starting with the prefix and ending with `'`, OR is
///   dollar-quoted (`$tag$...$tag$`) starting and ending with `$`.
///   The trimmed form must have no characters following the closing
///   quote. Internal escaping is not validated here — Postgres
///   rejects malformed literals at the `ALTER TABLE` site.
/// - **Numeric literal.** Trimmed expression is an optional `+` /
///   `-` sign, followed by one or more ASCII digits, optionally a
///   single `.` and more digits, optionally a single `e` / `E`
///   followed by an optional sign and digits. Anything beyond that
///   (operators, whitespace, parens, additional tokens) disqualifies.
/// - **Boolean literal.** Exactly `true` or `false` (case-insensitive,
///   matching Postgres' own behaviour).
/// - **NULL.** Exactly `NULL` or `null` (case-insensitive).
fn is_literal_shape(expr: &str) -> bool {
    let bytes = expr.as_bytes();
    if bytes.is_empty() {
        return false;
    }

    // Boolean / NULL — exact case-insensitive match against the full
    // expression. `eq_ignore_ascii_case` already enforces "no extra
    // bytes" because the comparison is byte-length-checked.
    if expr.eq_ignore_ascii_case("true")
        || expr.eq_ignore_ascii_case("false")
        || expr.eq_ignore_ascii_case("null")
    {
        return true;
    }

    // String literal — must START and END with the matching quote
    // delimiter and form a SINGLE self-contained quoted run. The
    // classifier rejects compound forms like `'a' || 'b'` because
    // they evaluate at write time; the volatility of the operands
    // dominates, not the string-ness of either token.
    if is_single_quoted_run(bytes, 0) {
        return true;
    }
    // E-strings allow C-style backslash escapes inside the literal
    // `E'it\'s'` is a single literal whose body holds an apostrophe.
    // Plain `'...'` runs do not interpret backslash escapes (only the
    // `''` doubled-quote form), so the two paths use different
    // sub-walkers.
    if bytes.len() >= 3
        && (bytes[0] == b'E' || bytes[0] == b'e')
        && is_single_e_string_run(bytes, 1)
    {
        return true;
    }
    if is_single_dollar_quoted_run(bytes) {
        return true;
    }

    // Numeric literal — single token: optional sign, one or more
    // digits, optional `.<digits>`, optional `[eE][+-]?<digits>`. The
    // walk consumes the whole expression; any byte that is not part
    // of this grammar disqualifies the expression as a pure literal.
    is_numeric_literal(bytes)
}

/// `true` iff `bytes[start..]` is `'...'` — a single self-contained
/// Postgres string literal. Embedded `'` characters are accepted only
/// as Postgres' standard `''` escape (an apostrophe doubled inside
/// the literal); a lone `'` mid-string ends the run and would mean
/// the expression is not a single quoted token.
fn is_single_quoted_run(bytes: &[u8], start: usize) -> bool {
    if start + 2 > bytes.len() {
        return false;
    }
    if bytes[start] != b'\'' {
        return false;
    }
    let mut idx = start + 1;
    while idx < bytes.len() {
        if bytes[idx] == b'\'' {
            // Doubled quote — Postgres's standard escape; consume both
            // bytes and continue the run.
            if idx + 1 < bytes.len() && bytes[idx + 1] == b'\'' {
                idx += 2;
                continue;
            }
            // Single quote: this must be the closing quote, and the
            // run must end here exactly.
            return idx + 1 == bytes.len();
        }
        idx += 1;
    }
    false
}

/// `true` iff `bytes[start..]` is `'...'` for the body of an
/// E-string (`E'...'`). Inside an E-string Postgres interprets
/// C-style backslash escapes: `\'` is an apostrophe, `\\` is a
/// backslash, etc. The walker treats any byte after `\` as escaped
/// and skips it; the run ends only at an unescaped `'`.
fn is_single_e_string_run(bytes: &[u8], start: usize) -> bool {
    if start + 2 > bytes.len() {
        return false;
    }
    if bytes[start] != b'\'' {
        return false;
    }
    let mut idx = start + 1;
    while idx < bytes.len() {
        if bytes[idx] == b'\\' {
            // Backslash-escape: consume the backslash and the next byte
            // verbatim (whatever it is) and continue.
            if idx + 1 >= bytes.len() {
                return false;
            }
            idx += 2;
            continue;
        }
        if bytes[idx] == b'\'' {
            // Postgres's `''` doubled-quote escape works in E-strings
            // too — consume both and continue the run.
            if idx + 1 < bytes.len() && bytes[idx + 1] == b'\'' {
                idx += 2;
                continue;
            }
            // Single unescaped quote: must be the closing quote, and
            // the run must end here exactly.
            return idx + 1 == bytes.len();
        }
        idx += 1;
    }
    false
}

/// `true` iff `bytes` is `$tag$...$tag$` — a single self-contained
/// dollar-quoted Postgres string. The tag is the bytes between the
/// leading and second `$`; the matching closing `$tag$` must end the
/// expression exactly.
fn is_single_dollar_quoted_run(bytes: &[u8]) -> bool {
    if bytes.is_empty() || bytes[0] != b'$' {
        return false;
    }
    // Locate the closing `$` of the opening tag.
    let mut tag_end = 1;
    while tag_end < bytes.len() && bytes[tag_end] != b'$' {
        tag_end += 1;
    }
    if tag_end >= bytes.len() {
        return false;
    }
    let tag = &bytes[..=tag_end];
    if bytes.len() < tag.len() * 2 {
        return false;
    }
    // The closing tag must end exactly at the last byte; require the
    // expression to be `<open-tag><body><close-tag>` with the body
    // containing no occurrence of `<close-tag>`.
    let close_start = bytes.len() - tag.len();
    if &bytes[close_start..] != tag {
        return false;
    }
    let body = &bytes[tag.len()..close_start];
    // Body must not contain the tag as a substring (otherwise the
    // expression contains multiple dollar-quoted runs / partial tags).
    if body.windows(tag.len()).any(|w| w == tag) {
        return false;
    }
    true
}

/// Walk `bytes` as a single Postgres numeric literal token. Returns
/// `true` iff the entire byte slice (after the optional sign) consists
/// of digits with at most one `.` and at most one exponent suffix
/// (`e` / `E` with an optional sign and one or more digits). No
/// embedded whitespace, no operators, no parentheses.
fn is_numeric_literal(bytes: &[u8]) -> bool {
    if bytes.is_empty() {
        return false;
    }
    let mut idx: usize = 0;
    if bytes[0] == b'+' || bytes[0] == b'-' {
        idx += 1;
    }
    // Integer part — at least one digit.
    let int_start = idx;
    while idx < bytes.len() && bytes[idx].is_ascii_digit() {
        idx += 1;
    }
    if idx == int_start {
        // No leading digits after the optional sign — the leading byte
        // could have been `.` (rare but legal), so handle that here.
        if idx >= bytes.len() || bytes[idx] != b'.' {
            return false;
        }
    }
    // Optional fractional part.
    if idx < bytes.len() && bytes[idx] == b'.' {
        idx += 1;
        while idx < bytes.len() && bytes[idx].is_ascii_digit() {
            idx += 1;
        }
    }
    // Optional exponent.
    if idx < bytes.len() && (bytes[idx] == b'e' || bytes[idx] == b'E') {
        idx += 1;
        if idx < bytes.len() && (bytes[idx] == b'+' || bytes[idx] == b'-') {
            idx += 1;
        }
        let exp_start = idx;
        while idx < bytes.len() && bytes[idx].is_ascii_digit() {
            idx += 1;
        }
        if idx == exp_start {
            return false;
        }
    }
    idx == bytes.len()
}

#[cfg(test)]
mod tests {
    use super::{BUILTIN_VOLATILITY, Volatility, classify_default_expression, is_literal_shape};

    /// The binary-search lookup in [`classify_default_expression`]
    /// requires the table to be sorted lexicographically by
    /// identifier. This invariant is load-bearing — a sort-order
    /// regression silently makes `binary_search` return `Err` for
    /// values that are present in the table.
    #[test]
    fn builtin_volatility_table_is_sorted() {
        for window in BUILTIN_VOLATILITY.windows(2) {
            assert!(
                window[0].0 < window[1].0,
                "BUILTIN_VOLATILITY entries out of order: {:?} should sort before {:?}",
                window[0].0,
                window[1].0,
            );
        }
    }

    /// The binary-search lookup also requires no duplicate keys
    /// the strict `<` in the sortedness assertion catches duplicates,
    /// but a second test asserts the property explicitly so a future
    /// refactor of the sort assertion (e.g. relaxing to `<=`) cannot
    /// silently introduce duplicates.
    #[test]
    fn builtin_volatility_table_has_no_duplicate_keys() {
        for window in BUILTIN_VOLATILITY.windows(2) {
            assert_ne!(
                window[0].0, window[1].0,
                "BUILTIN_VOLATILITY contains duplicate key {:?}",
                window[0].0
            );
        }
    }

    #[test]
    fn string_literals_classify_as_immutable() {
        assert_eq!(
            classify_default_expression("'hello'"),
            Volatility::Immutable
        );
        assert_eq!(classify_default_expression("''"), Volatility::Immutable);
        assert_eq!(
            classify_default_expression("E'with\\nescape'"),
            Volatility::Immutable
        );
        assert_eq!(
            classify_default_expression("$tag$dollar quoted$tag$"),
            Volatility::Immutable
        );
    }

    #[test]
    fn e_string_with_escaped_quote_classifies_as_immutable() {
        // `E'it\'s'` is a single literal whose body holds an
        // apostrophe via the C-style backslash escape. The plain
        // `'...'` walker would see the embedded `\'` and either reject
        // (treating the unescaped `'` as the close) or fail to
        // close — only the E-string walker handles the escape.
        assert_eq!(
            classify_default_expression(r"E'it\'s'"),
            Volatility::Immutable
        );
        assert_eq!(
            classify_default_expression(r"E'tab\there'"),
            Volatility::Immutable
        );
        // Doubled-quote escape still works inside E-strings.
        assert_eq!(
            classify_default_expression("E'don''t'"),
            Volatility::Immutable
        );
    }

    #[test]
    fn numeric_literals_classify_as_immutable() {
        assert_eq!(classify_default_expression("0"), Volatility::Immutable);
        assert_eq!(classify_default_expression("42"), Volatility::Immutable);
        assert_eq!(classify_default_expression("-7"), Volatility::Immutable);
        assert_eq!(classify_default_expression("+1"), Volatility::Immutable);
        assert_eq!(classify_default_expression("3.14"), Volatility::Immutable);
        assert_eq!(classify_default_expression("1e10"), Volatility::Immutable);
    }

    #[test]
    fn boolean_literals_classify_as_immutable() {
        assert_eq!(classify_default_expression("true"), Volatility::Immutable);
        assert_eq!(classify_default_expression("TRUE"), Volatility::Immutable);
        assert_eq!(classify_default_expression("false"), Volatility::Immutable);
        assert_eq!(classify_default_expression("False"), Volatility::Immutable);
    }

    #[test]
    fn null_literal_classifies_as_immutable() {
        assert_eq!(classify_default_expression("NULL"), Volatility::Immutable);
        assert_eq!(classify_default_expression("null"), Volatility::Immutable);
        assert_eq!(classify_default_expression("Null"), Volatility::Immutable);
    }

    #[test]
    fn stable_builtins_classify_as_stable() {
        assert_eq!(classify_default_expression("now()"), Volatility::Stable);
        assert_eq!(
            classify_default_expression("CURRENT_TIMESTAMP"),
            Volatility::Stable
        );
        assert_eq!(
            classify_default_expression("current_timestamp"),
            Volatility::Stable
        );
        assert_eq!(
            classify_default_expression("current_date"),
            Volatility::Stable
        );
        assert_eq!(
            classify_default_expression("current_time"),
            Volatility::Stable
        );
        assert_eq!(
            classify_default_expression("statement_timestamp()"),
            Volatility::Stable
        );
        assert_eq!(
            classify_default_expression("transaction_timestamp()"),
            Volatility::Stable
        );
    }

    #[test]
    fn volatile_builtins_classify_as_volatile() {
        assert_eq!(
            classify_default_expression("clock_timestamp()"),
            Volatility::Volatile
        );
        assert_eq!(
            classify_default_expression("random()"),
            Volatility::Volatile
        );
        assert_eq!(
            classify_default_expression("gen_random_uuid()"),
            Volatility::Volatile
        );
    }

    #[test]
    fn unknown_identifiers_default_to_volatile() {
        // User-defined functions, extension calls, anything not in the
        // built-in table — must route through the conservative path.
        assert_eq!(
            classify_default_expression("myapp_helper()"),
            Volatility::Volatile
        );
        assert_eq!(
            classify_default_expression("custom_seq_next()"),
            Volatility::Volatile
        );
        assert_eq!(
            classify_default_expression("extension_func(arg)"),
            Volatility::Volatile
        );
    }

    #[test]
    fn surrounding_whitespace_is_trimmed() {
        assert_eq!(classify_default_expression("  now()  "), Volatility::Stable);
        assert_eq!(
            classify_default_expression("\tnull\n"),
            Volatility::Immutable
        );
        assert_eq!(
            classify_default_expression("  clock_timestamp()  "),
            Volatility::Volatile
        );
    }

    #[test]
    fn empty_expression_classifies_as_volatile() {
        // Empty string is not a literal and not in the table; the
        // conservative fallback applies. (Empty default is a
        // malformed declaration anyway — this test only pins the
        // observable behaviour.)
        assert_eq!(classify_default_expression(""), Volatility::Volatile);
        assert_eq!(classify_default_expression("   "), Volatility::Volatile);
    }

    #[test]
    fn is_literal_shape_recognises_strings() {
        assert!(is_literal_shape("'foo'"));
        assert!(is_literal_shape("E'foo'"));
        assert!(is_literal_shape("e'foo'"));
        assert!(is_literal_shape("$tag$foo$tag$"));
    }

    #[test]
    fn is_literal_shape_recognises_numbers() {
        assert!(is_literal_shape("0"));
        assert!(is_literal_shape("123"));
        assert!(is_literal_shape("-1"));
        assert!(is_literal_shape("+42"));
    }

    #[test]
    fn is_literal_shape_rejects_function_calls() {
        assert!(!is_literal_shape("now()"));
        assert!(!is_literal_shape("clock_timestamp()"));
        assert!(!is_literal_shape("myapp_helper()"));
    }

    #[test]
    fn is_literal_shape_rejects_bare_identifiers() {
        assert!(!is_literal_shape("some_column"));
        assert!(!is_literal_shape("CURRENT_TIMESTAMP"));
    }

    #[test]
    fn is_literal_shape_rejects_compound_numeric_expressions() {
        // `1 + random` starts with a digit but is not a pure literal
        // the operator and function call mean Postgres evaluates the
        // expression at write time and the volatility of any sub-call
        // dominates. The classifier MUST NOT short-circuit to Immutable.
        assert!(!is_literal_shape("1 + random()"));
        assert!(!is_literal_shape("1+random()"));
        assert!(!is_literal_shape("0 + clock_timestamp()"));
        assert!(!is_literal_shape("42 * 2"));
        assert!(!is_literal_shape("-1 + 2"));
    }

    #[test]
    fn is_literal_shape_rejects_string_followed_by_call() {
        // String literal that is part of a larger expression — must
        // not classify as a pure literal.
        assert!(!is_literal_shape("'a' || random()::text"));
        assert!(!is_literal_shape("'foo' || 'bar'"));
    }

    #[test]
    fn is_literal_shape_accepts_decimals_and_exponents() {
        assert!(is_literal_shape("3.14"));
        assert!(is_literal_shape("-0.5"));
        assert!(is_literal_shape("1e10"));
        assert!(is_literal_shape("1.5E-3"));
        assert!(is_literal_shape("+0.0"));
    }

    #[test]
    fn is_literal_shape_rejects_malformed_numbers() {
        // Tokens that LOOK numeric-ish but aren't a valid single
        // numeric literal — must not short-circuit to Immutable.
        assert!(!is_literal_shape("1.2.3"));
        assert!(!is_literal_shape("1e"));
        assert!(!is_literal_shape("1.5e+"));
        assert!(!is_literal_shape("1 2"));
    }

    #[test]
    fn classify_compound_with_volatile_call_returns_volatile() {
        // Spec-correctness: `1 + random()` MUST classify as Volatile so
        // the live-migrate classifier routes it through ExpandContract.
        // Pre-fix the literal-shape check accepted any byte-slice
        // starting with a digit and silently returned Immutable.
        assert_eq!(
            classify_default_expression("1 + random()"),
            Volatility::Volatile
        );
        assert_eq!(
            classify_default_expression("0 + clock_timestamp()"),
            Volatility::Volatile
        );
    }

    /// Smoke test that every `Volatility` variant is exhaustively
    /// matched by the classifier. Adding a new variant trips this on
    /// compile (the match is non-`_`-terminated). `#[non_exhaustive]`
    /// is enforced at the source level — out-of-crate consumers must
    /// add a wildcard arm or fail to compile.
    #[test]
    fn volatility_variants_are_distinct() {
        fn classify(v: Volatility) -> u8 {
            match v {
                Volatility::Immutable => 0,
                Volatility::Stable => 1,
                Volatility::Volatile => 2,
            }
        }
        assert_eq!(classify(Volatility::Immutable), 0);
        assert_eq!(classify(Volatility::Stable), 1);
        assert_eq!(classify(Volatility::Volatile), 2);
        assert_ne!(Volatility::Immutable, Volatility::Stable);
        assert_ne!(Volatility::Stable, Volatility::Volatile);
    }
}