no-mistakes-postgres-sql 0.109.129

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
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
use super::{temporary_schema, Event};

#[test]
fn temporary_schema_matches_only_postgres_temp_schemas() {
    assert!(temporary_schema("pg_temp"));
    assert!(temporary_schema("pg_temp_1"));
    assert!(temporary_schema("pg_temp_42"));
    assert!(!temporary_schema("pg_temp_"));
    assert!(!temporary_schema("pg_temp_tenant"));
    assert!(!temporary_schema("public"));
}

#[test]
fn temporary_schema_functions_and_drops_are_ignored() {
    for sql in [
        include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0038-temp-function-first.sql"
        )),
        include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0039-temp-function-second.sql"
        )),
    ] {
        let facts = crate::migration::extract_migration_facts(sql);
        assert!(facts.unanalyzable_statements.is_empty(), "{sql}");
        assert!(facts.definition_events.is_empty(), "{:?}", facts.definition_events);
    }
}

#[test]
fn only_cascading_domain_and_operator_drops_reset_tracking() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/cascading-definition-drops.sql"
    ));
    let facts = crate::migration::extract_migration_facts(sql);
    assert_eq!(
        facts
            .definition_events
            .iter()
            .filter(|event| matches!(event, Event::Reset))
            .count(),
        4
    );
}

#[test]
fn cascading_view_and_extension_drops_reset_definition_tracking() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0003.sql"
    ));
    let facts = crate::migration::extract_migration_facts(sql);
    assert_eq!(
        facts
            .definition_events
            .iter()
            .filter(|event| matches!(event, Event::Reset))
            .count(),
        2
    );
}

#[test]
fn alter_function_is_positioned_after_a_procedural_barrier() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0017-domain-drop.sql"
    ));
    let facts = crate::migration::extract_migration_facts(sql);
    assert!(matches!(
        facts.definition_events.as_slice(),
        [.., Event::Create { line: 5, .. }, Event::ResetFunctions]
    ));
}

#[test]
fn identity_changes_in_saved_migrations_are_explicit_barriers() {
    let fixtures = [
        (include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0014-view-schema-move.sql"
        )), 2),
        (include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0015-drop-partition-parent.sql"
        )), 0),
        (include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0016-type-rename.sql"
        )), 1),
    ];
    for (sql, expected_definition_resets) in fixtures {
        let facts = crate::migration::extract_migration_facts(sql);
        assert!(facts.unanalyzable_statements.is_empty(), "{sql}");
        assert!(
            !facts
                .definition_events
                .iter()
                .any(|event| matches!(event, Event::Reset)),
            "{sql}"
        );
        let definition_resets = facts
            .definition_events
            .iter()
            .filter(|event| matches!(event, Event::ResetDefinitions))
            .count();
        assert_eq!(definition_resets, expected_definition_resets, "{sql}");
        if expected_definition_resets == 0 {
            assert!(matches!(
                facts.definition_events.first(),
                Some(Event::DropTable { table, qualified: false }) if table == &["public", "review_parent"]
            ));
        }
    }
    let non_cascading = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-transactional-inheritance/migrations/0001.sql"
    )));
    assert!(non_cascading.unanalyzable_statements.is_empty());
    assert!(!non_cascading
        .definition_events
        .iter()
        .any(|event| matches!(event, Event::Reset)));
    assert_eq!(
        non_cascading
            .definition_events
            .iter()
            .filter(|event| matches!(event, Event::ResetDefinitions))
            .count(),
        4
    );
}

#[test]
fn call_barrier_and_temporary_table_lifetime_are_parsed() {
    let setup = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0023-call-setup.sql"
    )));
    let call = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0024-call-barrier.sql"
    )));
    let temporary = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0025-on-commit-drop.sql"
    )));
    assert!(setup.unanalyzable_statements.is_empty());
    assert!(call.unanalyzable_statements.is_empty());
    assert!(temporary.unanalyzable_statements.is_empty());
    assert!(matches!(
        setup.definition_events.as_slice(),
        [Event::Create { line: 1, .. }]
    ));
    assert!(matches!(
        call.definition_events.as_slice(),
        [Event::Reset, Event::Create { line: 2, .. }]
    ));
    assert!(matches!(
        temporary.definition_events.as_slice(),
        [Event::TableCreated { .. }, Event::Create { .. }, Event::TransactionStart, Event::TemporaryTable { name, on_commit_drop: true }, Event::Create { unqualified_index_table: Some(table), .. }, Event::TransactionEnd { rolled_back: false, .. }]
            if name == "scratch" && table == name
    ));
}

#[test]
fn regular_temporary_tables_and_qualified_index_are_recognized() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/repeated-definitions/migrations/0035-regular-temporary-tables.sql"
    )));
    assert!(facts.unanalyzable_statements.is_empty());
    assert!(matches!(
        facts.definition_events.as_slice(),
        [
            Event::TransactionStart,
            Event::TemporaryTable { name: short, on_commit_drop: false },
            Event::TemporaryTable { name: long, on_commit_drop: false },
            Event::TransactionEnd { rolled_back: false, .. },
            Event::Create { unqualified_index_table: Some(short_index_table), .. },
            Event::Create { unqualified_index_table: Some(long_index_table), .. },
        ] if short == "scratch_short" && long == "Scratch Long"
            && short_index_table == short && long_index_table == long
    ));
}

#[test]
fn catalog_argument_spellings_resolve_to_the_same_signature() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/signature-catalog-types.sql"
    )));
    assert!(facts.unanalyzable_statements.is_empty());
    let [Event::Create {
        definition: spelled,
        ..
    }, Event::Create {
        definition: catalog,
        ..
    }] = facts.definition_events.as_slice()
    else {
        panic!(
            "expected two function definitions: {:?}",
            facts.definition_events
        );
    };
    assert_eq!(spelled, catalog);
    assert_eq!(spelled.argument_types.as_ref().map(Vec::len), Some(17));
}

#[test]
fn search_path_resets_and_chained_transaction_boundaries_are_distinct() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/search-path-statements.sql"
    )));
    assert!(facts.unanalyzable_statements.is_empty());
    assert!(
        matches!(
            facts.definition_events.as_slice(),
            [
                Event::SearchPath {
                    default: false,
                    assignment: true,
                    local: false
                },
                Event::SearchPath {
                    default: false,
                    assignment: true,
                    local: true
                },
                Event::SearchPath {
                    default: true,
                    assignment: true,
                    local: false
                },
                Event::SearchPath {
                    default: true,
                    assignment: false,
                    local: false
                },
                Event::SearchPath {
                    default: true,
                    assignment: false,
                    local: false
                },
                Event::TransactionStart,
                Event::TransactionEnd {
                    chain: true,
                    rolled_back: false
                },
                Event::Reset,
                Event::TransactionEnd {
                    chain: true,
                    rolled_back: true
                },
                Event::TransactionEnd {
                    chain: false,
                    rolled_back: true
                },
            ]
        ),
        "{:?}",
        facts.definition_events
    );
}

#[test]
fn index_schemas_and_function_drop_signatures_keep_object_identity() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/definition-identity-controls.sql"
    )));
    assert!(facts.unanalyzable_statements.is_empty());
    assert!(
        matches!(
            facts.definition_events.as_slice(),
            [
                Event::Create { definition: index, unqualified_index_table: None, index_owner: Some(owner), line: 2 },
                Event::DropIndex(dropped_index),
                Event::Create { definition: function, line: 4, .. },
                Event::Drop(dropped_function),
                Event::DropFunction(dropped_name),
                Event::Reset,
            ] if index.name == ["pg_temp_tenant", "named_idx"] && dropped_index == &index.name
                && owner.table == ["pg_temp_tenant", "items"] && owner.columns.contains("id")
                && function.name == ["app", "lookup"]
                && function.argument_types.as_deref().is_some_and(|types| types == ["pg_catalog.int2"])
                && dropped_function == function && dropped_name == &function.name
        ),
        "{:?}",
        facts.definition_events
    );
}

#[test]
fn full_text_arguments_match_native_definitions_and_drop_signatures() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/full-text-definition-signatures.sql"
    )));
    assert!(facts.unanalyzable_statements.is_empty());
    assert!(
        matches!(
            facts.definition_events.as_slice(),
            [Event::Create { definition: native, .. }, Event::Create { definition: qualified, .. }, Event::Drop(dropped)]
                if native == qualified && dropped == native
                    && native.argument_types.as_deref().is_some_and(|types| types == ["pg_catalog.tsvector", "pg_catalog.tsquery[]"])
        ),
        "{:?}",
        facts.definition_events
    );
}

#[test]
fn unsupported_catalog_qualification_is_conservative_and_do_keeps_clause_lines() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/definition-projection-boundaries/definition-projection-boundaries.sql"
    )));
    assert!(matches!(
        facts.unanalyzable_statements.as_slice(),
        [failure] if failure.procedural_body && failure.line == 10
    ));
    assert!(
        matches!(
            facts.definition_events.as_slice(),
            [
                Event::TableCreated { table, qualified: true },
                Event::Create { line: 2, .. },
                Event::Reset,
                Event::Create { definition: function, line: 6, .. },
                Event::Drop(dropped),
                Event::Reset,
            ] if table == &["public", "items"] && function == dropped
                && function.argument_types.as_deref().is_some_and(|types|
                    types == ["pg_catalog.line", "pg_catalog.line[]"])
        ),
        "{:?}",
        facts.definition_events
    );
    assert!(facts.clause_uses.iter().any(|clause| {
        clause.clause == crate::types::SqlPolicyClause::CreateExtensionVersion
            && clause.line == 10
            && clause.column == 1
    }));
}

#[test]
fn native_aliases_and_user_types_resolve_without_merging_distinct_signatures() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/signature-alias-boundaries.sql"
    )));
    assert!(facts.unanalyzable_statements.is_empty());
    assert!(
        matches!(
            facts.definition_events.as_slice(),
            [Event::Create { definition, .. }, Event::Drop(dropped)]
                if definition == dropped
                    && definition.argument_types.as_deref().is_some_and(|types| types == [
                        "pg_catalog.int4",
                        "pg_catalog.float4",
                        "pg_catalog.bpchar",
                        "pg_catalog.timestamptz",
                        "pg_catalog.bit",
                        "pg_catalog.int4[]",
                        "\"public\".\"_any\"",
                    ])
        ),
        "{:?}",
        facts.definition_events
    );
}

#[test]
fn unrepresentable_type_identity_skips_creates_and_treats_drops_as_barriers() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/definition-projection-boundaries/unsupported-definition-types.sql"
    )));
    assert!(facts.unanalyzable_statements.is_empty());
    assert!(
        matches!(
            facts.definition_events.as_slice(),
            [Event::Reset, Event::Create { definition, line: 5, .. }, Event::Drop(dropped)]
                if definition == dropped
        ),
        "{:?}",
        facts.definition_events
    );
}

#[test]
fn alter_identity_guards_preserve_same_named_indexes_and_reject_ambiguous_moves() {
    let facts = crate::migration::extract_migration_facts(include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-redundant-index/fixture/definition-projection-boundaries/alter-definition-identity-boundaries.sql"
    )));
    assert!(
        matches!(
            facts.definition_events.as_slice(),
            [
                Event::TableCreated { table, qualified: true },
                Event::Create { definition, line: 2, .. },
                Event::Reset,
                Event::TableCreated { table: other, qualified: false },
                Event::Reset,
            ] if table == &["public", "items"]
                && other == &["public", "other"]
                && definition.name == ["public", "items_key"]
        ),
        "{:?}",
        facts.definition_events
    );
}