squawk-linter 2.62.0

Linter for Postgres migrations & SQL
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
use std::fmt;

use rowan::TextSize;
use squawk_syntax::{
    Parse, SourceFile, SyntaxKind,
    ast::{self, AstNode},
};

use crate::{Edit, Fix, Linter, Rule, Violation, analyze};

fn find_insert_pos(file: &SourceFile) -> TextSize {
    for child in file.syntax().children_with_tokens() {
        match child.kind() {
            SyntaxKind::COMMENT | SyntaxKind::WHITESPACE => continue,
            _ => return child.text_range().start(),
        }
    }
    TextSize::from(0)
}

fn create_stmt_timeout_fix(file: &SourceFile) -> Fix {
    let at = find_insert_pos(file);
    Fix::new(
        "Add statement timeout",
        vec![Edit::insert(
            format!(
                "set statement_timeout = '5s';{}",
                file.line_ending().as_str()
            ),
            at,
        )],
    )
}

fn create_lock_timeout_fix(file: &SourceFile) -> Fix {
    let at = find_insert_pos(file);
    Fix::new(
        "Add lock timeout",
        vec![Edit::insert(
            format!("set lock_timeout = '1s';{}", file.line_ending().as_str()),
            at,
        )],
    )
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReportOnce {
    Missing,
    Present,
    Reported,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct LockImpact(u8);

impl LockImpact {
    const READS: u8 = 0b001;
    const SCHEMA_CHANGES: u8 = 0b100;
    const WRITES: u8 = 0b010;

    const fn new(blocks: u8) -> Self {
        Self(blocks)
    }

    fn blocked(self) -> Vec<&'static str> {
        let mut items = vec![];
        for (bit, label) in [
            (Self::READS, "reads"),
            (Self::WRITES, "writes"),
            (Self::SCHEMA_CHANGES, "schema changes"),
        ] {
            if self.0 & bit != 0 {
                items.push(label);
            }
        }
        items
    }
}

/// The lock a statement takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LockKind {
    AccessExclusive,
    AccessShare,
    Exclusive,
    RowExclusive,
    RowShare,
    Share,
    ShareRowExclusive,
    ShareUpdateExclusive,
    Unknown,
}

impl fmt::Display for LockKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LockKind::AccessExclusive => f.write_str("ACCESS EXCLUSIVE"),
            LockKind::AccessShare => f.write_str("ACCESS SHARE"),
            LockKind::Exclusive => f.write_str("EXCLUSIVE"),
            LockKind::RowExclusive => f.write_str("ROW EXCLUSIVE"),
            LockKind::RowShare => f.write_str("ROW SHARE"),
            LockKind::Share => f.write_str("SHARE"),
            LockKind::ShareRowExclusive => f.write_str("SHARE ROW EXCLUSIVE"),
            LockKind::ShareUpdateExclusive => f.write_str("SHARE UPDATE EXCLUSIVE"),
            LockKind::Unknown => Ok(()),
        }
    }
}

impl LockKind {
    fn from_lock_mode(lock_mode: ast::LockMode) -> LockKind {
        match lock_mode {
            ast::LockMode::AccessExclusive(_) => LockKind::AccessExclusive,
            ast::LockMode::AccessShare(_) => LockKind::AccessShare,
            ast::LockMode::Exclusive(_) => LockKind::Exclusive,
            ast::LockMode::RowExclusive(_) => LockKind::RowExclusive,
            ast::LockMode::RowShare(_) => LockKind::RowShare,
            ast::LockMode::Share(_) => LockKind::Share,
            ast::LockMode::ShareRowExclusive(_) => LockKind::ShareRowExclusive,
            ast::LockMode::ShareUpdateExclusive(_) => LockKind::ShareUpdateExclusive,
        }
    }

    fn strength(self) -> u8 {
        match self {
            LockKind::Unknown => 0,
            LockKind::AccessShare => 1,
            LockKind::RowShare => 2,
            LockKind::RowExclusive => 3,
            LockKind::ShareUpdateExclusive => 4,
            LockKind::Share => 5,
            LockKind::ShareRowExclusive => 6,
            LockKind::Exclusive => 7,
            LockKind::AccessExclusive => 8,
        }
    }

    fn from_alter_table_action(action: &ast::AlterTableAction) -> LockKind {
        match action {
            ast::AlterTableAction::ClusterOn(_)
            | ast::AlterTableAction::ResetOptions(_)
            | ast::AlterTableAction::SetOptions(_)
            | ast::AlterTableAction::SetWithoutCluster(_)
            | ast::AlterTableAction::ValidateConstraint(_) => LockKind::ShareUpdateExclusive,
            ast::AlterTableAction::DetachPartition(_) => LockKind::AccessExclusive,
            ast::AlterTableAction::AddConstraint(add_constraint) => {
                if let Some(ast::Constraint::ForeignKeyConstraint(_)) = add_constraint.constraint()
                {
                    LockKind::ShareRowExclusive
                } else {
                    LockKind::AccessExclusive
                }
            }
            ast::AlterTableAction::DisableTrigger(_)
            | ast::AlterTableAction::EnableAlwaysTrigger(_)
            | ast::AlterTableAction::EnableReplicaTrigger(_)
            | ast::AlterTableAction::EnableTrigger(_) => LockKind::ShareRowExclusive,
            ast::AlterTableAction::AlterColumn(alter_column) => match alter_column.option() {
                Some(
                    ast::AlterColumnOption::ResetOptions(_)
                    | ast::AlterColumnOption::SetOptions(_)
                    | ast::AlterColumnOption::SetStatistics(_),
                ) => LockKind::ShareUpdateExclusive,
                Some(
                    ast::AlterColumnOption::AddGenerated(_)
                    | ast::AlterColumnOption::DropDefault(_)
                    | ast::AlterColumnOption::DropExpression(_)
                    | ast::AlterColumnOption::DropIdentity(_)
                    | ast::AlterColumnOption::DropNotNull(_)
                    | ast::AlterColumnOption::Inherit(_)
                    | ast::AlterColumnOption::NoInherit(_)
                    | ast::AlterColumnOption::Restart(_)
                    | ast::AlterColumnOption::SetCompression(_)
                    | ast::AlterColumnOption::SetDefault(_)
                    | ast::AlterColumnOption::SetExpression(_)
                    | ast::AlterColumnOption::SetGenerated(_)
                    | ast::AlterColumnOption::SetGeneratedOptions(_)
                    | ast::AlterColumnOption::SetNotNull(_)
                    | ast::AlterColumnOption::SetOptionsList(_)
                    | ast::AlterColumnOption::SetSequenceOption(_)
                    | ast::AlterColumnOption::SetStorage(_)
                    | ast::AlterColumnOption::SetType(_),
                )
                | None => LockKind::AccessExclusive,
            },
            ast::AlterTableAction::AddColumn(_)
            | ast::AlterTableAction::AlterConstraint(_)
            | ast::AlterTableAction::AttachPartition(_)
            | ast::AlterTableAction::DisableRls(_)
            | ast::AlterTableAction::DisableRule(_)
            | ast::AlterTableAction::DropColumn(_)
            | ast::AlterTableAction::DropConstraint(_)
            | ast::AlterTableAction::EnableAlwaysRule(_)
            | ast::AlterTableAction::EnableReplicaRule(_)
            | ast::AlterTableAction::EnableRls(_)
            | ast::AlterTableAction::EnableRule(_)
            | ast::AlterTableAction::ForceRls(_)
            | ast::AlterTableAction::InheritTable(_)
            | ast::AlterTableAction::MergePartitions(_)
            | ast::AlterTableAction::NoForceRls(_)
            | ast::AlterTableAction::NoInheritTable(_)
            | ast::AlterTableAction::NotOf(_)
            | ast::AlterTableAction::OfType(_)
            | ast::AlterTableAction::OptionItemList(_)
            | ast::AlterTableAction::OwnerTo(_)
            | ast::AlterTableAction::RenameColumn(_)
            | ast::AlterTableAction::RenameConstraint(_)
            | ast::AlterTableAction::TableRenameTo(_)
            | ast::AlterTableAction::ReplicaIdentity(_)
            | ast::AlterTableAction::SetAccessMethod(_)
            | ast::AlterTableAction::SetLogged(_)
            | ast::AlterTableAction::SetSchema(_)
            | ast::AlterTableAction::SetTablespace(_)
            | ast::AlterTableAction::SetUnlogged(_)
            | ast::AlterTableAction::SetWithoutOids(_)
            | ast::AlterTableAction::SplitPartition(_) => LockKind::AccessExclusive,
        }
    }

    fn from(stmt: &ast::Stmt) -> LockKind {
        match stmt {
            ast::Stmt::AlterTable(alter_table) => alter_table
                .actions()
                .map(|action| Self::from_alter_table_action(&action))
                .max_by_key(|lock| lock.strength())
                .unwrap_or(LockKind::AccessExclusive),
            ast::Stmt::Cluster(_) => LockKind::AccessExclusive,
            ast::Stmt::CommentOn(_) => LockKind::ShareUpdateExclusive,
            ast::Stmt::CreateIndex(create_index) => {
                if create_index.concurrently_token().is_some() {
                    LockKind::ShareUpdateExclusive
                } else {
                    LockKind::Share
                }
            }
            ast::Stmt::DropIndex(drop_index) => {
                if drop_index.concurrently_token().is_some() {
                    LockKind::ShareUpdateExclusive
                } else {
                    LockKind::AccessExclusive
                }
            }
            ast::Stmt::DropTable(_) | ast::Stmt::DropView(_) => LockKind::AccessExclusive,
            ast::Stmt::Lock(lock) => lock
                .lock_mode()
                .map(Self::from_lock_mode)
                .unwrap_or(LockKind::AccessExclusive),
            ast::Stmt::Refresh(refresh) => {
                if refresh.concurrently_token().is_some() {
                    LockKind::Exclusive
                } else {
                    LockKind::AccessExclusive
                }
            }
            ast::Stmt::Reindex(reindex) => {
                if reindex.is_concurrently() {
                    LockKind::ShareUpdateExclusive
                } else {
                    LockKind::AccessExclusive
                }
            }
            ast::Stmt::Truncate(_) => LockKind::AccessExclusive,
            ast::Stmt::Vacuum(vacuum) => {
                if vacuum.is_full() {
                    LockKind::AccessExclusive
                } else {
                    LockKind::ShareUpdateExclusive
                }
            }
            _ => LockKind::Unknown,
        }
    }

    fn violation_message(self) -> String {
        let name = self.to_string();
        if name.is_empty() {
            "Missing `set lock_timeout` before potentially slow operations".to_string()
        } else {
            format!("Missing `set lock_timeout` before potentially slow {name} lock operations")
        }
    }

    fn impact(self) -> Option<LockImpact> {
        match self {
            LockKind::AccessExclusive => Some(LockImpact::new(
                LockImpact::READS | LockImpact::WRITES | LockImpact::SCHEMA_CHANGES,
            )),
            LockKind::AccessShare => Some(LockImpact::new(LockImpact::SCHEMA_CHANGES)),
            LockKind::Exclusive | LockKind::Share | LockKind::ShareRowExclusive => Some(
                LockImpact::new(LockImpact::WRITES | LockImpact::SCHEMA_CHANGES),
            ),
            LockKind::RowExclusive | LockKind::RowShare | LockKind::ShareUpdateExclusive => {
                Some(LockImpact::new(LockImpact::SCHEMA_CHANGES))
            }
            LockKind::Unknown => None,
        }
    }

    fn help(self) -> String {
        let help = "Configure a `lock_timeout` before this statement.";
        let name = self.to_string();
        let Some(impact) = self.impact() else {
            return help.to_string();
        };

        let blocked = impact.blocked();
        if blocked.is_empty() {
            format!("{help} Statement requires: {name} lock.")
        } else {
            format!(
                "{help} Statement requires: {name} lock; blocking: {}.",
                blocked.join(", ")
            )
        }
    }
}

pub(crate) fn require_timeout_settings(ctx: &mut Linter, parse: &Parse<SourceFile>) {
    let file = parse.tree();

    // treat a disabled rule as already reported so it never reports
    let mut lock_timeout = if ctx.rules.contains(&Rule::RequireLockTimeout) {
        ReportOnce::Missing
    } else {
        ReportOnce::Reported
    };
    let mut stmt_timeout = if ctx.rules.contains(&Rule::RequireStatementTimeout) {
        ReportOnce::Missing
    } else {
        ReportOnce::Reported
    };

    for stmt in file.stmts() {
        // stop early if both are reported
        if lock_timeout == ReportOnce::Reported && stmt_timeout == ReportOnce::Reported {
            break;
        }

        match stmt {
            ast::Stmt::Set(set) => {
                if let Some(ast::SetTarget::SetConfig(set_config)) = set.set_target()
                    && let Some(path) = set_config
                        .config_parameter_ref()
                        .and_then(|config_parameter| config_parameter.path_ref())
                {
                    // only want to check for `set lock_timeout = '1s'`, not `set foo.lock_timeout = '1s'`
                    if path.qualifier().is_some() {
                        continue;
                    }
                    if let Some(segment) = path.segment() {
                        let name = segment.text();
                        if name == "lock_timeout" {
                            lock_timeout = ReportOnce::Present;
                        } else if name == "statement_timeout" {
                            stmt_timeout = ReportOnce::Present;
                        }
                    }
                }
            }
            _ if analyze::possibly_slow_stmt(&stmt) => {
                let lock = LockKind::from(&stmt);
                if lock_timeout == ReportOnce::Missing {
                    ctx.report(
                        Violation::for_node(
                            Rule::RequireLockTimeout,
                            lock.violation_message(),
                            stmt.syntax(),
                        )
                        .help(lock.help())
                        .fix(create_lock_timeout_fix(&file)),
                    );
                    lock_timeout = ReportOnce::Reported;
                }
                if stmt_timeout == ReportOnce::Missing {
                    ctx.report(
                        Violation::for_node(
                            Rule::RequireStatementTimeout,
                            "Missing `set statement_timeout` before potentially slow operations"
                                .to_string(),
                            stmt.syntax(),
                        )
                        .help("Configure a `statement_timeout` before this statement".to_string())
                        .fix(create_stmt_timeout_fix(&file)),
                    );
                    stmt_timeout = ReportOnce::Reported;
                }
            }
            _ => (),
        }
    }
}

#[cfg(test)]
mod test {
    use insta::assert_snapshot;
    use squawk_syntax::SourceFile;
    use tabled::{builder::Builder, settings::Style};

    use crate::{
        Rule,
        test_utils::{fix_sql, lint_errors, lint_ok},
    };

    #[must_use]
    fn fix(sql: &str) -> String {
        fix_sql(sql, Rule::RequireTimeoutSettings)
    }

    fn lock_kinds(cases: &[&str]) -> String {
        let mut builder = Builder::default();
        builder.push_record(["sql", "lock"]);

        for sql in cases {
            let file = SourceFile::parse(sql);
            assert_eq!(file.errors(), vec![]);
            let stmt = file.tree().stmts().next().expect("expected statement");
            let lock = super::LockKind::from(&stmt);
            builder.push_record([sql.to_string(), format!("{lock:?}")]);
        }

        let mut table = builder.build();
        table.with(Style::psql());
        table.to_string()
    }

    #[test]
    fn fixes_preserve_cr_line_endings() {
        assert_snapshot!(
            format!(
                "{:?}",
                fix("ALTER TABLE t ADD COLUMN c BOOLEAN;\rSELECT 1;")
            ),
            @r#""set statement_timeout = '5s';\rset lock_timeout = '1s';\rALTER TABLE t ADD COLUMN c BOOLEAN;\rSELECT 1;""#
        );
    }

    #[test]
    fn lock_kind_for_statement_variants() {
        let cases = [
            "ALTER TABLE t ADD COLUMN c int;",
            "CLUSTER t;",
            "COMMENT ON TABLE t IS 'x';",
            "CREATE INDEX idx ON t (c);",
            "CREATE INDEX CONCURRENTLY idx ON t (c);",
            "DROP INDEX idx;",
            "DROP INDEX CONCURRENTLY idx;",
            "DROP TABLE t;",
            "DROP VIEW v;",
            "REFRESH MATERIALIZED VIEW mv;",
            "REFRESH MATERIALIZED VIEW CONCURRENTLY mv;",
            "REINDEX INDEX idx;",
            "REINDEX INDEX CONCURRENTLY idx;",
            "TRUNCATE t;",
            "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');",
        ];

        assert_snapshot!(lock_kinds(&cases), @"
         sql                                              | lock                 
        --------------------------------------------------+----------------------
         ALTER TABLE t ADD COLUMN c int;                  | AccessExclusive      
         CLUSTER t;                                       | AccessExclusive      
         COMMENT ON TABLE t IS 'x';                       | ShareUpdateExclusive 
         CREATE INDEX idx ON t (c);                       | Share                
         CREATE INDEX CONCURRENTLY idx ON t (c);          | ShareUpdateExclusive 
         DROP INDEX idx;                                  | AccessExclusive      
         DROP INDEX CONCURRENTLY idx;                     | ShareUpdateExclusive 
         DROP TABLE t;                                    | AccessExclusive      
         DROP VIEW v;                                     | AccessExclusive      
         REFRESH MATERIALIZED VIEW mv;                    | AccessExclusive      
         REFRESH MATERIALIZED VIEW CONCURRENTLY mv;       | Exclusive            
         REINDEX INDEX idx;                               | AccessExclusive      
         REINDEX INDEX CONCURRENTLY idx;                  | ShareUpdateExclusive 
         TRUNCATE t;                                      | AccessExclusive      
         CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); | Unknown
        ");
    }

    #[test]
    fn lock_kind_for_alter_table_variants() {
        let cases = [
            "ALTER TABLE t ADD COLUMN c int;",
            "ALTER TABLE t DROP COLUMN c;",
            "ALTER TABLE t ALTER COLUMN c TYPE bigint;",
            "ALTER TABLE t VALIDATE CONSTRAINT c;",
            "ALTER TABLE t ALTER COLUMN c SET STATISTICS 100;",
            "ALTER TABLE t ALTER COLUMN c SET (n_distinct = 5);",
            "ALTER TABLE t SET (fillfactor = 70);",
            "ALTER TABLE t RESET (fillfactor);",
            "ALTER TABLE t CLUSTER ON idx;",
            "ALTER TABLE t SET WITHOUT CLUSTER;",
            "ALTER TABLE t DETACH PARTITION p;",
            "ALTER TABLE t DETACH PARTITION p CONCURRENTLY;",
            "ALTER TABLE t ADD CONSTRAINT fk FOREIGN KEY (a) REFERENCES o (id);",
            "ALTER TABLE t ADD CONSTRAINT ck CHECK (a > 0);",
            "ALTER TABLE t DISABLE TRIGGER trg;",
            "ALTER TABLE t ENABLE TRIGGER trg;",
            "ALTER TABLE t ENABLE REPLICA TRIGGER trg;",
            "ALTER TABLE t ENABLE ALWAYS TRIGGER trg;",
            "ALTER TABLE t VALIDATE CONSTRAINT c, ADD COLUMN d int;",
        ];

        assert_snapshot!(lock_kinds(&cases), @"
         sql                                                                | lock                 
        --------------------------------------------------------------------+----------------------
         ALTER TABLE t ADD COLUMN c int;                                    | AccessExclusive      
         ALTER TABLE t DROP COLUMN c;                                       | AccessExclusive      
         ALTER TABLE t ALTER COLUMN c TYPE bigint;                          | AccessExclusive      
         ALTER TABLE t VALIDATE CONSTRAINT c;                               | ShareUpdateExclusive 
         ALTER TABLE t ALTER COLUMN c SET STATISTICS 100;                   | ShareUpdateExclusive 
         ALTER TABLE t ALTER COLUMN c SET (n_distinct = 5);                 | ShareUpdateExclusive 
         ALTER TABLE t SET (fillfactor = 70);                               | ShareUpdateExclusive 
         ALTER TABLE t RESET (fillfactor);                                  | ShareUpdateExclusive 
         ALTER TABLE t CLUSTER ON idx;                                      | ShareUpdateExclusive 
         ALTER TABLE t SET WITHOUT CLUSTER;                                 | ShareUpdateExclusive 
         ALTER TABLE t DETACH PARTITION p;                                  | AccessExclusive      
         ALTER TABLE t DETACH PARTITION p CONCURRENTLY;                     | AccessExclusive      
         ALTER TABLE t ADD CONSTRAINT fk FOREIGN KEY (a) REFERENCES o (id); | ShareRowExclusive    
         ALTER TABLE t ADD CONSTRAINT ck CHECK (a > 0);                     | AccessExclusive      
         ALTER TABLE t DISABLE TRIGGER trg;                                 | ShareRowExclusive    
         ALTER TABLE t ENABLE TRIGGER trg;                                  | ShareRowExclusive    
         ALTER TABLE t ENABLE REPLICA TRIGGER trg;                          | ShareRowExclusive    
         ALTER TABLE t ENABLE ALWAYS TRIGGER trg;                           | ShareRowExclusive    
         ALTER TABLE t VALIDATE CONSTRAINT c, ADD COLUMN d int;             | AccessExclusive
        ");
    }

    #[test]
    fn lock_kind_for_explicit_lock_modes() {
        let cases = [
            "LOCK TABLE t;",
            "LOCK TABLE t IN ACCESS EXCLUSIVE MODE;",
            "LOCK TABLE t IN ACCESS SHARE MODE;",
            "LOCK TABLE t IN EXCLUSIVE MODE;",
            "LOCK TABLE t IN ROW EXCLUSIVE MODE;",
            "LOCK TABLE t IN ROW SHARE MODE;",
            "LOCK TABLE t IN SHARE MODE;",
            "LOCK TABLE t IN SHARE ROW EXCLUSIVE MODE;",
            "LOCK TABLE t IN SHARE UPDATE EXCLUSIVE MODE;",
        ];

        assert_snapshot!(lock_kinds(&cases), @"
         sql                                          | lock                 
        ----------------------------------------------+----------------------
         LOCK TABLE t;                                | AccessExclusive      
         LOCK TABLE t IN ACCESS EXCLUSIVE MODE;       | AccessExclusive      
         LOCK TABLE t IN ACCESS SHARE MODE;           | AccessShare          
         LOCK TABLE t IN EXCLUSIVE MODE;              | Exclusive            
         LOCK TABLE t IN ROW EXCLUSIVE MODE;          | RowExclusive         
         LOCK TABLE t IN ROW SHARE MODE;              | RowShare             
         LOCK TABLE t IN SHARE MODE;                  | Share                
         LOCK TABLE t IN SHARE ROW EXCLUSIVE MODE;    | ShareRowExclusive    
         LOCK TABLE t IN SHARE UPDATE EXCLUSIVE MODE; | ShareUpdateExclusive
        ");
    }

    #[test]
    fn lock_kind_for_reindex_concurrently_options() {
        let cases = [
            "REINDEX (CONCURRENTLY) INDEX idx;",
            "REINDEX (CONCURRENTLY true) INDEX idx;",
            "REINDEX (CONCURRENTLY false) INDEX idx;",
            "REINDEX (CONCURRENTLY 'false') INDEX idx;",
            "REINDEX (CONCURRENTLY E'false') INDEX idx;",
            "REINDEX (CONCURRENTLY U&'false') INDEX idx;",
            "REINDEX (CONCURRENTLY off) INDEX idx;",
            "REINDEX (CONCURRENTLY 0) INDEX idx;",
        ];

        assert_snapshot!(lock_kinds(&cases), @"
         sql                                         | lock                 
        ---------------------------------------------+----------------------
         REINDEX (CONCURRENTLY) INDEX idx;           | ShareUpdateExclusive 
         REINDEX (CONCURRENTLY true) INDEX idx;      | ShareUpdateExclusive 
         REINDEX (CONCURRENTLY false) INDEX idx;     | AccessExclusive      
         REINDEX (CONCURRENTLY 'false') INDEX idx;   | AccessExclusive      
         REINDEX (CONCURRENTLY E'false') INDEX idx;  | AccessExclusive      
         REINDEX (CONCURRENTLY U&'false') INDEX idx; | AccessExclusive      
         REINDEX (CONCURRENTLY off) INDEX idx;       | AccessExclusive      
         REINDEX (CONCURRENTLY 0) INDEX idx;         | AccessExclusive
        ");
    }

    #[test]
    fn lock_kind_for_vacuum_full_options() {
        let cases = [
            "VACUUM t;",
            "VACUUM FULL t;",
            "VACUUM (FULL) t;",
            "VACUUM (FULL true) t;",
            "VACUUM (FULL false) t;",
            "VACUUM (FULL 'false') t;",
            "VACUUM (FULL E'false') t;",
            "VACUUM (FULL U&'false') t;",
            "VACUUM (FULL off) t;",
            "VACUUM (FULL 0) t;",
        ];

        assert_snapshot!(lock_kinds(&cases), @"
         sql                        | lock                 
        ----------------------------+----------------------
         VACUUM t;                  | ShareUpdateExclusive 
         VACUUM FULL t;             | AccessExclusive      
         VACUUM (FULL) t;           | AccessExclusive      
         VACUUM (FULL true) t;      | AccessExclusive      
         VACUUM (FULL false) t;     | ShareUpdateExclusive 
         VACUUM (FULL 'false') t;   | ShareUpdateExclusive 
         VACUUM (FULL E'false') t;  | ShareUpdateExclusive 
         VACUUM (FULL U&'false') t; | ShareUpdateExclusive 
         VACUUM (FULL off) t;       | ShareUpdateExclusive 
         VACUUM (FULL 0) t;         | ShareUpdateExclusive
        ");
    }

    #[test]
    fn err_missing_both_timeouts() {
        let sql = r#"
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow ACCESS EXCLUSIVE lock operations
          ╭▸ 
        2 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: ACCESS EXCLUSIVE lock; blocking: reads, writes, schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn err_missing_lock_timeout() {
        let sql = r#"
SET statement_timeout = '5s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow ACCESS EXCLUSIVE lock operations
          ╭▸ 
        3 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: ACCESS EXCLUSIVE lock; blocking: reads, writes, schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        ");
    }

    #[test]
    fn err_missing_statement_timeout() {
        let sql = r#"
SET lock_timeout = '1s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        3 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn err_only_lock_timeout_rule_enabled() {
        let sql = r#"
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireLockTimeout), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow ACCESS EXCLUSIVE lock operations
          ╭▸ 
        2 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: ACCESS EXCLUSIVE lock; blocking: reads, writes, schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        ");
    }

    #[test]
    fn err_only_statement_timeout_rule_enabled() {
        let sql = r#"
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireStatementTimeout), @"
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn ok_only_lock_timeout_rule_enabled() {
        let sql = r#"
SET lock_timeout = '1s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        lint_ok(sql, Rule::RequireLockTimeout);
    }

    #[test]
    fn ok_only_statement_timeout_rule_enabled() {
        let sql = r#"
SET statement_timeout = '5s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        lint_ok(sql, Rule::RequireStatementTimeout);
    }

    #[test]
    fn ok_both_timeouts_present() {
        let sql = r#"
SET lock_timeout = '1s';
SET statement_timeout = '5s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        lint_ok(sql, Rule::RequireTimeoutSettings);
    }

    #[test]
    fn ok_both_timeouts_present_casing() {
        let sql = r#"
SET Lock_Timeout = '1s';
SET Statement_Timeout = '5s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        lint_ok(sql, Rule::RequireTimeoutSettings);
    }

    #[test]
    fn ok_no_ddl_operations() {
        let sql = r#"
SELECT * FROM t;
        "#;
        lint_ok(sql, Rule::RequireTimeoutSettings);
    }

    #[test]
    fn err_timeouts_using_schema() {
        let sql = r#"
SET foo.lock_timeout = '1s';
SET foo.statement_timeout = '5s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow ACCESS EXCLUSIVE lock operations
          ╭▸ 
        4 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: ACCESS EXCLUSIVE lock; blocking: reads, writes, schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        4 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }
    #[test]
    fn err_timeouts_after_ddl() {
        let sql = r#"
ALTER TABLE t ADD COLUMN c BOOLEAN;
SET lock_timeout = '1s';
SET statement_timeout = '5s';
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow ACCESS EXCLUSIVE lock operations
          ╭▸ 
        2 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: ACCESS EXCLUSIVE lock; blocking: reads, writes, schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ ALTER TABLE t ADD COLUMN c BOOLEAN;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn err_other_ddl_operations() {
        let sql = r#"
CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow operations
          ╭▸ 
        2 │ CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn err_comment_on_explains_lock_impact() {
        // COMMENT ON takes a SHARE UPDATE EXCLUSIVE lock, so the help should
        // name the lock mode.
        let sql = r#"
COMMENT ON COLUMN t.c IS 'an opaque id';
        "#;
        let out = lint_errors(sql, Rule::RequireTimeoutSettings);
        assert_snapshot!(out, @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow SHARE UPDATE EXCLUSIVE lock operations
          ╭▸ 
        2 │ COMMENT ON COLUMN t.c IS 'an opaque id';
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: SHARE UPDATE EXCLUSIVE lock; blocking: schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ COMMENT ON COLUMN t.c IS 'an opaque id';
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn err_reindex_concurrently_false_uses_non_concurrent_lock() {
        let sql = r#"
REINDEX (CONCURRENTLY false) INDEX idx;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow ACCESS EXCLUSIVE lock operations
          ╭▸ 
        2 │ REINDEX (CONCURRENTLY false) INDEX idx;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: ACCESS EXCLUSIVE lock; blocking: reads, writes, schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ REINDEX (CONCURRENTLY false) INDEX idx;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn err_vacuum_full_false_uses_non_full_lock() {
        let sql = r#"
VACUUM (FULL false) t;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow SHARE UPDATE EXCLUSIVE lock operations
          ╭▸ 
        2 │ VACUUM (FULL false) t;
          │ ━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: SHARE UPDATE EXCLUSIVE lock; blocking: schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ VACUUM (FULL false) t;
          │ ━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn err_lock_access_share_uses_correct_article() {
        let sql = r#"
LOCK TABLE t IN ACCESS SHARE MODE;
        "#;
        assert_snapshot!(lint_errors(sql, Rule::RequireTimeoutSettings), @"
        warning[require-lock-timeout]: Missing `set lock_timeout` before potentially slow ACCESS SHARE lock operations
          ╭▸ 
        2 │ LOCK TABLE t IN ACCESS SHARE MODE;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `lock_timeout` before this statement. Statement requires: ACCESS SHARE lock; blocking: schema changes.
          ╭╴
        2 + set lock_timeout = '1s';
          ╰╴
        warning[require-statement-timeout]: Missing `set statement_timeout` before potentially slow operations
          ╭▸ 
        2 │ LOCK TABLE t IN ACCESS SHARE MODE;
          │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          │
          ├ help: Configure a `statement_timeout` before this statement
          ╭╴
        2 + set statement_timeout = '5s';
          ╰╴
        ");
    }

    #[test]
    fn ok_other_ddl_with_timeouts() {
        let sql = r#"
SET lock_timeout = '1s';
SET statement_timeout = '5s';
CREATE FUNCTION add(integer, integer) RETURNS integer
    AS 'select $1 + $2;'
    LANGUAGE SQL;
        "#;
        lint_ok(sql, Rule::RequireTimeoutSettings);
    }

    #[test]
    fn fix_add_both_timeouts() {
        let sql = "ALTER TABLE t ADD COLUMN c BOOLEAN;";
        let result = fix(sql);
        assert_snapshot!(result, @r"
        set statement_timeout = '5s';
        set lock_timeout = '1s';
        ALTER TABLE t ADD COLUMN c BOOLEAN;
        ");
    }

    #[test]
    fn fix_add_lock_timeout_only() {
        let sql = r#"
SET statement_timeout = '5s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        let result = fix(sql);
        assert_snapshot!(result, @r"
        set lock_timeout = '1s';
        SET statement_timeout = '5s';
        ALTER TABLE t ADD COLUMN c BOOLEAN;
        ");
    }

    #[test]
    fn fix_add_statement_timeout_only() {
        let sql = r#"
SET lock_timeout = '1s';
ALTER TABLE t ADD COLUMN c BOOLEAN;
        "#;
        let result = fix(sql);
        assert_snapshot!(result, @r"
        set statement_timeout = '5s';
        SET lock_timeout = '1s';
        ALTER TABLE t ADD COLUMN c BOOLEAN;
        ");
    }

    #[test]
    fn fix_with_leading_comments() {
        let sql = r#"-- leading comment
-- should be okay

ALTER TABLE users ADD COLUMN email TEXT;"#;
        let result = fix(sql);
        assert_snapshot!(result, @r"
        -- leading comment
        -- should be okay

        set statement_timeout = '5s';
        set lock_timeout = '1s';
        ALTER TABLE users ADD COLUMN email TEXT;
        ");
    }

    #[test]
    fn fix_with_leading_comment_c_style() {
        let sql = r#"/* foo bar */
ALTER TABLE users ADD COLUMN email TEXT;"#;
        let result = fix(sql);
        assert_snapshot!(result, @r"
        /* foo bar */
        set statement_timeout = '5s';
        set lock_timeout = '1s';
        ALTER TABLE users ADD COLUMN email TEXT;
        ");
    }

    #[test]
    fn fix_with_prefix_comment_c_style() {
        let sql = r#"/* boo */ALTER TABLE users ADD COLUMN email TEXT;"#;
        let result = fix(sql);
        assert_snapshot!(result, @r"
        /* boo */set statement_timeout = '5s';
        set lock_timeout = '1s';
        ALTER TABLE users ADD COLUMN email TEXT;
        ");
    }

    #[test]
    fn fix_multiple_ddl_statements() {
        let sql = r#"
CREATE TABLE users (id SERIAL);
ALTER TABLE users ADD COLUMN email TEXT;
        "#;
        let result = fix(sql);
        assert_snapshot!(result, @r"
        set statement_timeout = '5s';
        set lock_timeout = '1s';
        CREATE TABLE users (id SERIAL);
        ALTER TABLE users ADD COLUMN email TEXT;
        ");
    }
}