razeri-plugin-contract 0.17.0

The dialect contract Razeri plugins are written against — rendering traits, data types, platform identity
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
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! Boolean capability flags with conservative defaults.
//!
//! [`DialectCapabilities`] tells the rendering layer what syntax features
//! the platform supports. Defaults are conservative (`false` / ANSI-safe),
//! so unknown platforms produce safe SQL.

use crate::data_type::DataType;
use crate::engine_version::EngineVersion;
use crate::evolution::EvolutionAnswers;
use crate::merge_shape::MergeShape;

/// **What one engine holds in a text column**: the longest `varchar(n)` it
/// takes, how that length is counted, where the number came from, and what an
/// unbounded `text` column cannot be there.
///
/// Answered by [`DialectCapabilities::text_limits`]. A length past the
/// longest is refused by name before anything is rendered, as a decimal wider
/// than the engine holds is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TextLimits {
    /// The longest `varchar(n)` a column takes, where the engine has one.
    pub longest_varchar: Option<u32>,
    /// How [`Self::longest_varchar`] is counted.
    pub counted_in: VarcharUnit,
    /// Where the number came from.
    pub source: LimitSource,
    /// What the engine refuses an unbounded `text` column as, where it
    /// refuses it as a key — `a key or UNIQUE`, `a primary key`.
    pub text_is_not: Option<&'static str>,
}

impl TextLimits {
    /// A longest `varchar`, counted in `counted_in`, from `source`.
    #[must_use]
    pub const fn new(longest_varchar: u32, counted_in: VarcharUnit, source: LimitSource) -> Self {
        Self { longest_varchar: Some(longest_varchar), counted_in, source, text_is_not: None }
    }

    /// The same limits, for an engine that refuses an unbounded `text` as
    /// `what` — `a key or UNIQUE`.
    #[must_use]
    pub const fn and_text_is_not(self, what: &'static str) -> Self {
        Self { text_is_not: Some(what), ..self }
    }

    /// Why `varchar(length)` does not fit, in a few plain words, or `None`
    /// when it does.
    #[must_use]
    pub fn misfit(&self, length: u32) -> Option<String> {
        let longest = self.longest_varchar?;
        (length > longest).then(|| {
            format!(
                "its varchar holds at most {longest} {}, and this asks for {length}",
                self.counted_in.word()
            )
        })
    }
}

/// **How an engine counts a `varchar`'s declared length.**
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum VarcharUnit {
    /// In characters, whatever each takes to store.
    Characters,
    /// In bytes: a character outside ASCII takes more than one.
    Bytes,
}

impl VarcharUnit {
    /// The unit as a sentence says it: `characters`, `bytes`.
    #[must_use]
    pub const fn word(self) -> &'static str {
        match self {
            Self::Characters => "characters",
            Self::Bytes => "bytes",
        }
    }
}

/// **Where a stated limit came from.**
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LimitSource {
    /// Measured on the engine: one length past it refused at `CREATE TABLE`.
    MeasuredOnTheEngine,
    /// Read from the engine's documentation; no engine was run.
    TheEnginesDocumentation,
}

/// **One stated limit**: the most an engine holds, and where the number came
/// from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limit {
    /// The most the engine holds: digits of a second, or a length.
    pub most: u32,
    /// Where the number came from.
    pub source: LimitSource,
}

impl Limit {
    /// The most measured on the engine: that many created, one more refused.
    #[must_use]
    pub const fn measured(most: u32) -> Self {
        Self { most, source: LimitSource::MeasuredOnTheEngine }
    }

    /// The most the engine's documentation states; no engine was run.
    #[must_use]
    pub const fn documented(most: u32) -> Self {
        Self { most, source: LimitSource::TheEnginesDocumentation }
    }
}

/// **What one engine's columns hold, past its decimals and its varchars** —
/// the answer to [`DialectCapabilities::type_limits`].
///
/// `None` in a field means *nothing stated*: the engine stores the type as
/// text that holds any value, or the number has not been recorded. Either way
/// nothing is refused for it. Start from [`TypeLimits::NONE`] and fill in
/// what your engine has.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TypeLimits {
    /// The most digits of a second this dialect's spelling of a `timestamp`,
    /// `timestamptz` or `datetime` keeps.
    pub timestamp_digits: Option<Limit>,
    /// The most digits of a second this dialect's spelling of a `time` keeps.
    pub time_digits: Option<Limit>,
    /// The longest `char(n)`, counted in [`Self::char_counted_in`].
    pub longest_char: Option<Limit>,
    /// How [`Self::longest_char`] is counted.
    pub char_counted_in: VarcharUnit,
    /// The longest `binary(n)`, in bytes.
    pub longest_binary: Option<Limit>,
    /// The longest `varbinary(n)`, in bytes.
    pub longest_varbinary: Option<Limit>,
}

impl TypeLimits {
    /// Nothing stated: every field `None`, a `char` counted in characters.
    pub const NONE: Self = Self {
        timestamp_digits: None,
        time_digits: None,
        longest_char: None,
        char_counted_in: VarcharUnit::Characters,
        longest_binary: None,
        longest_varbinary: None,
    };

    /// **Why the engine cannot hold `data_type`**, or `None` when it can.
    ///
    /// Only the type itself is asked, not a type nested inside it: a caller
    /// walks an array's or a record's members itself.
    #[must_use]
    pub fn misfit(&self, data_type: &DataType) -> Option<Misfit> {
        match data_type {
            DataType::Timestamp(moment) => {
                self.too_many_digits(moment.precision, |most| format!("timestamp({most})"))
            }
            // A design spells a zoned timestamp and a datetime only at six
            // digits, which every engine that states a limit keeps.
            DataType::TimestampTz(moment) => {
                self.too_many_digits(moment.precision, |_| "timestamptz".to_owned())
            }
            DataType::DateTime(moment) => {
                self.too_many_digits(moment.precision, |_| "datetime".to_owned())
            }
            DataType::Time(time) => {
                let limit = self.time_digits?;
                // A bare `time` keeps the engine's own, which it holds.
                let asked = u32::from(time.precision?);
                (asked > limit.most).then(|| Misfit {
                    why: if limit.most == 0 {
                        format!(
                            "its times of day keep whole seconds only, and this asks for {asked} \
                             digits of a second"
                        )
                    } else {
                        format!(
                            "its times of day keep at most {} digits of a second, and this asks \
                             for {asked}",
                            limit.most
                        )
                    },
                    kind: "time",
                    fits: if limit.most == 0 {
                        "time".to_owned()
                    } else {
                        format!("time({})", limit.most)
                    },
                })
            }
            DataType::Char(text) => {
                let limit = self.longest_char?;
                (text.length > limit.most).then(|| Misfit {
                    why: format!(
                        "its char holds at most {} {}, and this asks for {}",
                        limit.most,
                        self.char_counted_in.word(),
                        text.length
                    ),
                    kind: "char",
                    fits: format!("char({})", limit.most),
                })
            }
            DataType::Binary(bytes) => {
                let limit = self.longest_binary?;
                (bytes.length > limit.most).then(|| Misfit {
                    why: format!(
                        "its binary holds at most {} bytes, and this asks for {}",
                        limit.most, bytes.length
                    ),
                    kind: "binary",
                    fits: format!("binary({})", limit.most),
                })
            }
            DataType::VarBinary(bytes) => {
                let limit = self.longest_varbinary?;
                let asked = bytes.max_length?;
                (asked > limit.most).then(|| Misfit {
                    why: format!(
                        "its varbinary holds at most {} bytes, and this asks for {asked}",
                        limit.most
                    ),
                    kind: "varbinary",
                    fits: format!("varbinary({})", limit.most),
                })
            }
            _ => None,
        }
    }

    /// A timestamp's digits of a second against [`Self::timestamp_digits`].
    fn too_many_digits(&self, asked: u8, fits: impl Fn(u32) -> String) -> Option<Misfit> {
        let limit = self.timestamp_digits?;
        (u32::from(asked) > limit.most).then(|| Misfit {
            why: format!(
                "its timestamps keep at most {} digits of a second, and this asks for {asked}",
                limit.most
            ),
            kind: "timestamp",
            fits: fits(limit.most),
        })
    }
}

/// **Why a column type does not fit an engine**, in the words a refusal uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Misfit {
    /// What the engine holds and what was asked, in a few plain words:
    /// `its timestamps keep at most 6 digits of a second, and this asks for 12`.
    pub why: String,
    /// The kind of type, as a refusal names it: `timestamp`, `char`.
    pub kind: &'static str,
    /// The nearest type the engine holds, as a design declares it:
    /// `timestamp(6)`, `char(255)`.
    pub fits: String,
}

/// **The widest exact decimal one engine's column holds.**
///
/// Every engine that records one refuses a precision of zero, so the fewest
/// digits is always one and is not a field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecimalLimits {
    /// The most digits a column may declare.
    pub max_precision: u16,
    /// The most digits after the decimal point.
    pub max_scale: u16,
    /// Whether the digits after the point must be no more than the digits in
    /// all. Some engines let a column hold only a fraction smaller than a
    /// thousandth, with more scale than precision; most refuse it.
    pub scale_within_precision: bool,
    /// The most digits before the decimal point, where the engine bounds
    /// them apart from the digits in all; `None` where the digits in all are
    /// the only bound. `BigQuery` holds 76 digits, but never more than 38 of
    /// them before the point.
    pub max_integer_digits: Option<u16>,
}

impl DecimalLimits {
    /// Why `decimal(precision, scale)` does not fit, in a few plain words, or
    /// `None` when it does.
    ///
    /// Parameters:
    /// - `precision`: the declared digits in all;
    /// - `scale`: the declared digits after the point.
    #[must_use]
    pub fn misfit(&self, precision: u16, scale: u16) -> Option<String> {
        let most = self.max_precision;
        if precision == 0 || precision > most {
            return Some(format!(
                "its decimals hold 1 to {most} digits, and this asks for {precision}"
            ));
        }
        if scale > self.max_scale {
            return Some(format!(
                "its decimals hold at most {} digits after the point, and this asks for {scale}",
                self.max_scale
            ));
        }
        if self.scale_within_precision && scale > precision {
            return Some(format!(
                "its decimals hold no more digits after the point than in all, and this asks for \
                 {scale} of {precision}"
            ));
        }
        let before_point = precision.saturating_sub(scale);
        if let Some(most) = self.max_integer_digits
            && before_point > most
        {
            return Some(format!(
                "its decimals hold at most {most} digits before the point, and this asks for \
                 {before_point}"
            ));
        }
        None
    }

    /// The nearest `decimal(precision, scale)` these limits hold, for a
    /// refusal to suggest in place of the one declared.
    ///
    /// Parameters:
    /// - `precision`: the declared digits in all;
    /// - `scale`: the declared digits after the point.
    #[must_use]
    pub fn nearest(&self, precision: u16, scale: u16) -> (u16, u16) {
        let mut scale = scale.min(self.max_scale);
        let mut precision = precision.clamp(1, self.max_precision);
        if self.scale_within_precision {
            scale = scale.min(precision);
        }
        if let Some(most) = self.max_integer_digits {
            precision = precision.min(scale + most).max(1);
        }
        if self.scale_within_precision {
            scale = scale.min(precision);
        }
        (precision, scale)
    }
}

/// Level 6 — Boolean capability flags with conservative defaults.
///
/// These flags tell the rendering layer what syntax features the platform supports.
/// Defaults are `false` / conservative, so unknown platforms produce safe ANSI SQL.
pub trait DialectCapabilities {
    // ═══════════════════════════════════════════════════════════════
    // DML Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// **How this engine performs the upsert Razeri's generated load is.**
    ///
    /// See [`MergeShape`]. The default is a refusal, because the honest answer
    /// for an engine nobody has measured is that Razeri does not know how to
    /// load it — not that it spells its upsert the way `MySQL` does.
    fn merge_shape(&self) -> MergeShape {
        MergeShape::None
    }

    /// **How much of the deployed schema a reconciliation can compare with
    /// the design here.**
    ///
    /// Razeri's schema check reads the engine's catalogue in one query: the
    /// ANSI `information_schema.columns`, a `FULL OUTER JOIN` against the
    /// design's own columns, and a table value constructor with a derived
    /// column list, `(VALUES ('a'), ('b')) AS designed (column_name)`. See
    /// [`CatalogueReach`]. The default is
    /// [`CatalogueReach::Nothing`] with a sentence saying Razeri has not
    /// written this engine's catalogue query: an engine nobody has measured
    /// gets no check, and a warning that says why, rather than a query that
    /// fails.
    fn catalogue_reach(&self) -> CatalogueReach {
        CatalogueReach::Nothing(
            "razeri has not written this platform's catalog query, and guessing at one would \
             emit SQL that fails rather than a verdict",
        )
    }

    /// **What this engine keeps when a table that already holds rows changes
    /// shape.**
    ///
    /// See [`EvolutionAnswers`]. The default answers nothing, which Razeri
    /// reads as *nobody has measured this engine* — so a change Razeri cannot
    /// otherwise prove keeps every value is reported as one that does not, and
    /// an operator gets a warning they can read instead of a surprise.
    fn evolution_answers(&self) -> EvolutionAnswers {
        EvolutionAnswers::none()
    }

    /// Whether the platform supports INSERT ... ON CONFLICT (PostgreSQL-style upsert).
    fn supports_on_conflict(&self) -> bool {
        false
    }

    /// Whether the platform supports INSERT OVERWRITE.
    fn supports_insert_overwrite(&self) -> bool {
        false
    }

    /// Whether the platform supports UPDATE ... FROM.
    fn supports_update_from(&self) -> bool {
        false
    }

    /// Whether the platform supports RETURNING / OUTPUT clauses.
    fn supports_returning(&self) -> bool {
        false
    }

    // ═══════════════════════════════════════════════════════════════
    // The server's version
    // ═══════════════════════════════════════════════════════════════

    /// **How to ask a running server its version**, or `None` where this
    /// engine has no version a user chooses, or nobody has written the
    /// question.
    ///
    /// The query answers one row whose first word is the version in the
    /// spelling this dialect declares (`17`, `8.4`, `23ai`); anything after it
    /// is the server's own words, which a refusal prints. A generated deploy
    /// script sends it after login and before the schema, and refuses a server
    /// older than the version the bundle was rendered for, naming both. The
    /// default is `None`, and a script that has no question asks none.
    fn server_version_query(&self) -> Option<&str> {
        None
    }

    /// **The version in one answer to [`Self::server_version_query`]**, or
    /// `None` when the answer holds none.
    ///
    /// Parameters:
    /// - `answer`: the one row the query answered, as text.
    ///
    /// The default reads the first word, which is what a deploy script reads
    /// too; override it only to read more of the answer than that.
    fn parse_server_version(&self, answer: &str) -> Option<EngineVersion> {
        answer.split_whitespace().next().and_then(|word| EngineVersion::parse(word).ok())
    }

    // ═══════════════════════════════════════════════════════════════
    // Query Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether the platform supports Common Table Expressions (WITH).
    fn supports_cte(&self) -> bool {
        true
    }

    /// Whether the platform supports recursive CTEs.
    fn supports_recursive_cte(&self) -> bool {
        true
    }

    /// Whether the platform supports window functions.
    fn supports_window_functions(&self) -> bool {
        true
    }

    /// Whether the platform supports named windows (WINDOW clause).
    fn supports_named_windows(&self) -> bool {
        true
    }

    /// Whether the platform supports QUALIFY clause.
    fn supports_qualify(&self) -> bool {
        false
    }

    /// Whether the platform supports GROUPS frame type in window functions.
    fn supports_groups_frame(&self) -> bool {
        false
    }

    /// Whether the platform supports NULLS FIRST/LAST in ORDER BY.
    fn supports_nulls_ordering(&self) -> bool {
        true
    }

    // ═══════════════════════════════════════════════════════════════
    // DDL Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether the platform supports IDENTITY columns.
    fn supports_identity(&self) -> bool {
        false
    }

    /// Whether the platform supports sequences (CREATE SEQUENCE).
    fn supports_sequences(&self) -> bool {
        false
    }

    /// Whether the platform supports schema namespacing.
    fn supports_schemas(&self) -> bool {
        true
    }

    /// **Can a routine created in one schema be called from a routine created
    /// in another, with nothing else done?**
    ///
    /// True nearly everywhere, and true by default: a schema on most engines is
    /// a namespace, and naming an object in another namespace is all that
    /// reaching it takes.
    ///
    /// Answer `false` where a schema is also an owner and reaching across one
    /// costs a privilege granted per object. On Oracle a schema IS a user; a
    /// routine runs with its owner's privileges, so a function created in
    /// `acme_core` calling one created in `acme_raw` compiles with errors —
    /// `ORA-60535: invalid identifier`, measured — however exactly it spells
    /// the name.
    ///
    /// What Razeri does with the answer is put a copy of the key function in
    /// **every namespace that calls it** instead of one per domain, so each
    /// namespace stands on its own and no deploy owes a grant. It is one
    /// derivation either way: the copies are the same builder over the same
    /// vocabulary, not two spellings free to drift. The engine-level hash
    /// beneath them keeps its single home — see
    /// [`ReplicationRenderer::sid_prerequisite_home`](crate::ReplicationRenderer::sid_prerequisite_home)
    /// — because that one is Razeri's own object and installs its own grant.
    fn routine_is_callable_across_schemas(&self) -> bool {
        true
    }

    /// Whether the platform supports bulk load (COPY, BULK INSERT, etc.).
    fn supports_bulk_load(&self) -> bool {
        false
    }

    /// **Whether a generated load is written as a stored procedure** on this
    /// engine.
    ///
    /// Razeri asks this before it writes a load as a procedure, and asks
    /// [`SqlRenderer::procedure_form`](crate::SqlRenderer::procedure_form)
    /// how to spell one. The default is `false`, and a load is then written as
    /// plain statements. A dialect that answers `procedure_form` with
    /// `ProcedureForm::Custom` answers `true` here, or its procedures are
    /// never asked for; one that answers `ProcedureForm::Unsupported` leaves
    /// this `false`. The conformance report holds the two to each other.
    fn supports_stored_procedures(&self) -> bool {
        false
    }

    /// Whether the platform **stores functions at all** — a routine the schema
    /// creates and later calls by name, in any spelling.
    ///
    /// Nearly every engine razeri reaches has one: `CREATE FUNCTION` on
    /// `PostgreSQL`, `MySQL`, `MariaDB`, Snowflake, `SQL Server` and Databricks,
    /// a `MACRO` on `DuckDB`, a lambda `CREATE FUNCTION` on `ClickHouse`.
    ///
    /// **`SQLite` answers `false`, and it is the reason this question is asked
    /// out loud.** `SQLite` has no `CREATE FUNCTION` statement in any spelling
    /// and no `CREATE PROCEDURE` either — a function there is registered by the
    /// program that opens the database, so nothing written into a schema script
    /// can create one. Inheriting the `PostgreSQL` form wrote
    /// `CREATE OR REPLACE FUNCTION … LANGUAGE SQL RETURN …` into `schema.sql`,
    /// which `SQLite` answers with `near "CREATE": syntax error` part way
    /// through the script, so the build refuses in front of the script instead.
    ///
    /// The default is `true`, matching [`Self::supports_table_functions`] and
    /// for the same reason: refusing is the destructive answer, so a refusal
    /// fires only where an engine is KNOWN to have no form, never because a
    /// dialect forgot to answer. That reverses the conservative-`false` default
    /// this trait uses for flags that *add* syntax — here `false` is the
    /// unusual claim, and it is made deliberately, one dialect at a time.
    fn supports_stored_functions(&self) -> bool {
        true
    }

    /// Whether the platform has a **table-valued function** — a routine a query
    /// selects FROM, returning columns rather than one value.
    ///
    /// Most engines have one in some spelling: `RETURNS TABLE(…)` on
    /// `PostgreSQL`, Snowflake and Databricks, an inline TVF on SQL Server, a
    /// table `MACRO` on `DuckDB`, a parameterized view on `ClickHouse`.
    ///
    /// **`MySQL` and `MariaDB` answer `false`, and they are the reason this
    /// question exists.** A stored function there returns exactly one value;
    /// there is no clause that returns a relation, in any spelling. Rendering
    /// `RETURNS TABLE` for them produced `ERROR 1064 … syntax error` in the
    /// middle of a schema script (measured on `MySQL` 8.4 and `MariaDB` 11.4),
    /// so the build refuses in front of the script instead.
    ///
    /// The default is `true`: a refusal fires only where an engine is KNOWN to
    /// have no form, never because a dialect forgot to answer.
    fn supports_table_functions(&self) -> bool {
        true
    }

    /// Whether the platform supports tasks / scheduled jobs.
    fn supports_tasks(&self) -> bool {
        false
    }

    /// Whether the platform supports native table partitioning.
    fn supports_partitioning(&self) -> bool {
        true
    }

    /// Whether the platform supports materialized views.
    fn supports_materialized_views(&self) -> bool {
        true
    }

    /// Whether the platform supports generated/computed columns.
    fn supports_generated_columns(&self) -> bool {
        true
    }

    /// Whether the platform supports JSONB or native JSON type.
    fn supports_json(&self) -> bool {
        true
    }

    // ═══════════════════════════════════════════════════════════════
    // Type Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether the platform supports unsigned integers natively.
    fn supports_unsigned_integers(&self) -> bool {
        false
    }

    /// Whether the platform supports arrays natively.
    fn supports_arrays(&self) -> bool {
        false
    }

    /// **Whether this engine has a type of its own for a nested type, or
    /// stores it as something else.**
    ///
    /// A nested column is an array, a map or a record. Some engines have all
    /// three; some have one; some have none and hold the value as JSON or as
    /// text. Razeri never refuses the column — the design is portable and it is
    /// the storage that degrades — but it does say so once, naming the engine,
    /// the columns and what each became.
    ///
    /// The default is `false`, which is the honest answer for an engine nobody
    /// has answered for: the reader is told what the column became rather than
    /// left to assume the type survived.
    ///
    /// Parameters:
    /// - `data_type`: the nested type in question.
    fn renders_nested_type_natively(&self, data_type: &DataType) -> bool {
        let _ = data_type;
        false
    }

    /// **Whether this engine can tell two values of a nested type apart.**
    ///
    /// Change detection asks whether an arriving value differs from the
    /// standing one. For a scalar every engine answers with `<>`. For a nested
    /// value they do not agree: some compare arrays, maps and records directly,
    /// some refuse the comparison outright, and some hold the value as text and
    /// compare the text. A column this returns `false` for is left out of
    /// change detection and named in a note, rather than compared with an
    /// operator the engine will reject.
    ///
    /// The default is `false` — an unanswered engine leaves the column
    /// unwatched and says so, which is the failure that can be read.
    ///
    /// Parameters:
    /// - `data_type`: the nested type in question.
    fn compares_nested_values(&self, data_type: &DataType) -> bool {
        let _ = data_type;
        false
    }

    /// **Whether this engine can collapse rows on a nested column** — group by
    /// it, or select distinct over it.
    ///
    /// A load reads its staged rows through one collapsed form so that a row
    /// stated twice, identically, is one arriving row rather than a conflict.
    /// The plain spelling of that collapse is `SELECT DISTINCT` over every
    /// column, and grouping is what `DISTINCT` is: an engine that will not
    /// group a value of a nested type will not take the column in a `DISTINCT`
    /// either.
    ///
    /// It is a separate question from [`Self::compares_nested_values`], and the
    /// two engines that answer them differently are the reason it is asked
    /// separately: `BigQuery` compares two records with `=` and refuses to group
    /// on one.
    ///
    /// Where the answer is `false` the collapse is written as a `GROUP BY` over
    /// the other columns with [`crate::SqlRenderer::render_any_value`] around
    /// this one.
    ///
    /// The default is `true`: `SELECT DISTINCT` over every column is the plain
    /// spelling, and an engine says otherwise only where somebody has found
    /// that it refuses.
    ///
    /// Asked only of a nested type — an array, a map or a record. The answer
    /// for anything else is not read.
    ///
    /// Parameters:
    /// - `data_type`: the nested type in question.
    fn groups_nested_values(&self, data_type: &DataType) -> bool {
        let _ = data_type;
        true
    }

    /// Whether the platform supports native BOOLEAN type (vs BIT).
    fn supports_boolean(&self) -> bool {
        true
    }

    // ═══════════════════════════════════════════════════════════════
    // Limits & Defaults
    // ═══════════════════════════════════════════════════════════════

    /// The default schema name for this platform.
    fn default_schema(&self) -> &'static str {
        "public"
    }

    /// Maximum identifier length for this platform.
    fn max_identifier_length(&self) -> usize {
        63
    }

    /// Maximum number of columns in a table (approximate).
    fn max_columns(&self) -> usize {
        10000
    }

    /// Maximum query parameters (approximate, 0 = unlimited).
    fn max_parameters(&self) -> usize {
        0
    }

    /// **The widest exact decimal a column on this platform holds**, where it
    /// has been measured against the engine.
    ///
    /// A type over it is refused by name rather than rendered: the engine
    /// would refuse the `CREATE TABLE` anyway, later and in its own words.
    ///
    /// The default is `None`, which means *not measured here*, not *no
    /// limit*. An engine with no limit at all says so in its own doc comment
    /// and still answers `None`.
    fn decimal_limits(&self) -> Option<DecimalLimits> {
        None
    }

    /// **What a text column on this platform holds**, where it has been
    /// measured against the engine or read from its documentation (see
    /// [`TextLimits`]).
    ///
    /// The default is `None`, which means *not recorded here*, not *no
    /// limit*. Measure the longest `varchar(n)` your engine creates — one
    /// more is refused at `CREATE TABLE` — and say how it counts it.
    fn text_limits(&self) -> Option<TextLimits> {
        None
    }

    /// **What this engine's other columns hold** — the digits of a second a
    /// timestamp and a time of day keep, and the longest `char(n)`,
    /// `binary(n)` and `varbinary(n)` (see [`TypeLimits`]).
    ///
    /// A type over a stated limit is refused by name before anything is
    /// rendered. The default is `None`: nothing is stated, and nothing is
    /// refused for this engine, which then refuses the `CREATE TABLE` later in
    /// its own words. Measure each the way the varchar is measured — the most
    /// your engine creates, one more refused — and leave `None` in a field
    /// your engine stores with no limit.
    fn type_limits(&self) -> Option<TypeLimits> {
        None
    }

    /// **Whether this engine has a type that keeps a time zone**, for a
    /// `timestamptz` column: a moment that keeps its offset, or one read in
    /// the session's zone. The default is `true`. An engine with no such type
    /// answers `false`, and a `timestamptz` column is refused by name rather
    /// than stored as a clock time two hours off the moment the file named.
    fn keeps_a_time_zone(&self) -> bool {
        true
    }

    // ═══════════════════════════════════════════════════════════════
    // Drop Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether DROP supports CASCADE modifier.
    fn supports_cascade_drop(&self) -> bool {
        true
    }

    /// Whether DROP FUNCTION requires parameter types for overloaded functions.
    fn supports_function_overloading(&self) -> bool {
        false
    }

    /// Whether DROP supports SYNC modifier (`ClickHouse`).
    fn supports_sync_drop(&self) -> bool {
        false
    }

    /// Whether DROP supports FORCE modifier (Databricks).
    fn supports_force_drop(&self) -> bool {
        false
    }

    // ═══════════════════════════════════════════════════════════════
    // DML Extended Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether the platform supports compound assignment (e.g., `col += value`).
    fn supports_compound_assignment(&self) -> bool {
        false
    }

    /// Whether the platform supports EXCLUDE clause in window frame specs.
    fn supports_window_frame_exclude(&self) -> bool {
        false
    }

    /// Whether the platform supports MERGE NOT MATCHED BY SOURCE.
    fn supports_merge_not_matched_by_source(&self) -> bool {
        false
    }

    /// Keyword emitted for MERGE NOT MATCHED branch.
    fn merge_not_matched_keyword(&self) -> &'static str {
        "WHEN NOT MATCHED"
    }

    /// Whether the platform supports UPDATE SET * / INSERT * in MERGE.
    fn supports_merge_star_syntax(&self) -> bool {
        false
    }

    /// Whether an UPDATE is spelled `ALTER TABLE … UPDATE` (`ClickHouse`).
    ///
    /// **There is a second declaration of the same fact** on
    /// [`crate::SqlRenderer::uses_alter_table_update`], and that one is the
    /// declaration Razeri's generators consult. A dialect that overrides one
    /// must override both and keep them agreeing; the duplication is named
    /// here so a reader finds it before an ambiguous-method error does.
    fn uses_alter_table_update(&self) -> bool {
        false
    }

    /// Whether the platform supports multi-table INSERT (Snowflake).
    fn supports_multi_table_insert(&self) -> bool {
        false
    }

    // ═══════════════════════════════════════════════════════════════
    // DDL / Namespace Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// The SQL keyword for the schema-level namespace.
    ///
    /// Most platforms use `SCHEMA` (`CREATE SCHEMA IF NOT EXISTS ...`).
    /// `ClickHouse` uses `DATABASE` (`CREATE DATABASE IF NOT EXISTS ...`).
    fn schema_namespace_keyword(&self) -> &'static str {
        "SCHEMA"
    }

    // ═══════════════════════════════════════════════════════════════
    // Comment Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether the platform supports `#` as a single-line comment delimiter.
    ///
    /// Default: `false`. A dialect whose engine accepts `#` as a single-line
    /// comment delimiter overrides this.
    fn supports_hash_comments(&self) -> bool {
        false
    }

    // ═══════════════════════════════════════════════════════════════
    // Script Formatting
    // ═══════════════════════════════════════════════════════════════

    /// Batch separator keyword required between DDL statements in a script.
    ///
    /// SQL Server / T-SQL requires `GO` between `CREATE FUNCTION`, `CREATE VIEW`,
    /// and `CREATE PROCEDURE` statements. Other platforms return `None` and use
    /// double-newlines between statements.
    fn batch_separator(&self) -> Option<&'static str> {
        None
    }

    // ═══════════════════════════════════════════════════════════════
    // Transaction Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether several statements in a script can be committed or discarded
    /// together as one unit.
    ///
    /// A generated load is a sequence of writes that only make sense finished.
    /// An SCD-2 load, for instance, closes the standing version into `_history`
    /// and then re-opens `_current` on the new attributes; a process that dies
    /// between the two leaves a closed version that `_current` still holds open,
    /// and because `_history` is keyed on (surrogate, version start), the next
    /// load writes the same key again and the engine refuses it. Every load
    /// after the crash fails until somebody deletes that row by hand.
    ///
    /// Wrapping the load in one transaction is what makes the crash a no-op
    /// instead. This flag says whether the platform offers that at all. It
    /// defaults to `true` because a transaction spanning several statements is
    /// core SQL and nearly every engine has it; a platform that does not
    /// overrides it, and the load script then says plainly that the operator
    /// owns the boundary.
    fn supports_multi_statement_transactions(&self) -> bool {
        true
    }

    /// How this platform opens a transaction.
    ///
    /// The ANSI spelling, which `MySQL` and `MariaDB` also use. `DuckDB`,
    /// `SQLite`, `SQL Server` and `Snowflake` say `BEGIN TRANSACTION`;
    /// `PostgreSQL` and `Citus` say `BEGIN`.
    fn begin_transaction_keyword(&self) -> &'static str {
        "START TRANSACTION"
    }

    /// How this platform commits one.
    ///
    /// `COMMIT` everywhere razeri reaches except `SQL Server`, which spells it
    /// `COMMIT TRANSACTION`.
    fn commit_transaction_keyword(&self) -> &'static str {
        "COMMIT"
    }

    /// **Whether this engine's begin statement leaves the commit to the
    /// client.**
    ///
    /// On most engines [`begin_transaction_keyword`](Self::begin_transaction_keyword)
    /// opens a transaction that holds every statement after it until the
    /// commit, whatever the client does. On some it only names the
    /// transaction — Oracle's and SAP HANA's `SET TRANSACTION READ WRITE` —
    /// and a driver that commits each statement on its own still does, so a
    /// load run that way keeps what it wrote when it stops part way.
    ///
    /// Razeri's own deploy scripts drive clients whose commit is off. Answer
    /// `true` where the engine needs that of the client, and the bundle tells
    /// whoever runs a load another way — a scheduler running the task list —
    /// to turn its client's commit off. The default is `false`.
    fn begin_leaves_the_commit_to_the_client(&self) -> bool {
        false
    }

    /// Whether emptying a table with `TRUNCATE` ends the open transaction.
    ///
    /// On some engines `TRUNCATE TABLE` commits everything before it and
    /// cannot be rolled back: `MySQL` and `MariaDB`, which treat it as a
    /// schema change, and Oracle, SAP HANA, `BigQuery` and Redshift. A
    /// generated load empties its staging table only as its last statement,
    /// after every write it makes, so on those engines the clear commits the
    /// load with it and each load stands on its own; a load that stops before
    /// it leaves nothing behind. Everywhere else `TRUNCATE` is an ordinary
    /// statement inside the transaction.
    fn truncate_commits_implicitly(&self) -> bool {
        false
    }

    /// **Whether a load's refusal stops the statement that asks it.**
    ///
    /// A generated load stops itself by building a sentence about the rows it
    /// refuses and asking the engine for
    /// [`ExpressionRenderer::render_refusal`](crate::ExpressionRenderer::render_refusal)
    /// of it: the engine refuses and quotes the sentence back in its error.
    /// Most engines do. `MySQL` and `MariaDB` answer the default refusal, a
    /// conversion to a number, with a warning and `0`, and Spark answers
    /// `NULL` where ANSI mode is off. There the load stops on a second
    /// statement instead, in the engine's own words and without the sentence,
    /// so a deploy script reads the refused rows back and prints them itself.
    ///
    /// The default is `true`, the answer of every engine whose refusal stops.
    fn refusal_stops_the_statement(&self) -> bool {
        true
    }

    /// **Whether this engine's file reader may read a field holding just the
    /// word `NULL` as a missing value** rather than as the four letters.
    ///
    /// A design names the words that mean "no value" in each file, and a
    /// binding that names none calls `NULL` missing, which every engine then
    /// agrees on. A file that keeps `NULL` as text cannot be read that way
    /// here, so the bundle names the file, and a reconciliation does not
    /// compare the characters of a text column holding the word. The default
    /// is `false`: the engine keeps the text, as every engine's own file
    /// reader does except `MySQL`'s and `MariaDB`'s `LOAD DATA`.
    fn delimited_file_reads_null_word_as_missing(&self) -> bool {
        false
    }

    // ═══════════════════════════════════════════════════════════════
    // Storage / Partition / Compression Capabilities
    // ═══════════════════════════════════════════════════════════════

    /// Whether the platform supports a server-side partition function definable
    /// at design time (`T-SQL` `PARTITION FUNCTION`, `PostgreSQL` `PARTITION BY`,
    /// `MySQL` `PARTITION BY`, `ClickHouse` `PARTITION BY`).
    ///
    /// `Snowflake` / `DuckDB` return `false` because micro-partitioning is automatic
    /// and not user-definable.
    fn supports_partition_function(&self) -> bool {
        false
    }

    /// Whether the platform supports adding/removing partition boundaries on a
    /// live table (`T-SQL` `ALTER PARTITION FUNCTION SPLIT/MERGE RANGE`,
    /// `PostgreSQL` `ATTACH/DETACH PARTITION`, `MySQL` `REORGANIZE PARTITION`).
    fn supports_partition_split_merge(&self) -> bool {
        false
    }

    /// Whether the platform supports a columnstore index (`T-SQL` clustered/non-clustered
    /// columnstore; `ClickHouse` via `MergeTree` engine; not natively in `PostgreSQL` / `MySQL`).
    fn supports_columnstore_index(&self) -> bool {
        false
    }

    /// Whether the platform realizes a columnstore as a **table storage engine**
    /// rather than an index (`MariaDB` `ENGINE=ColumnStore`). This is deliberately
    /// distinct from [`Self::supports_columnstore_index`]: a design that asks for
    /// `index: { kind: clustered_columnstore }` is honoured on such a platform by
    /// selecting the engine, but it must NOT inherit the `T-SQL`
    /// index machinery — the composite-PK demotion to `UNIQUE NONCLUSTERED` keys
    /// off `supports_columnstore_index`, and an engine-columnstore keeps its
    /// ordinary primary key. So the two capabilities are separate axes: "supports
    /// columnstore at all" is the disjunction of them.
    fn columnstore_is_table_engine(&self) -> bool {
        false
    }

    /// Whether the platform has a clustering-key concept distinct from primary key
    /// (`Snowflake` `CLUSTER BY`, Delta Liquid Clustering / `Z-ORDER`, `ClickHouse` `ORDER BY`).
    fn supports_clustering_key(&self) -> bool {
        false
    }

    /// Whether the platform supports user-controllable table compression
    /// (`T-SQL` `DATA_COMPRESSION = PAGE/ROW/COLUMNSTORE`, `MySQL` `ROW_FORMAT=COMPRESSED`,
    /// `ClickHouse` `CODEC(ZSTD)`, Delta `delta.compressionCodec`).
    fn supports_table_compression(&self) -> bool {
        false
    }

    /// Whether the platform requires every column referenced by the partition
    /// key to also appear in the table's PRIMARY KEY (or any UNIQUE
    /// constraint).
    ///
    /// `PostgreSQL` enforces this with `SQLSTATE 0A000` ("unique constraint on
    /// partitioned table must include all partitioning columns"). `T-SQL`,
    /// `MySQL`, `ClickHouse`, `Snowflake`, and `DuckDB` do not impose this
    /// restriction.
    fn partition_requires_pk_includes_field(&self) -> bool {
        false
    }
}

/// **How much of a deployed schema Razeri's reconciliation can read back from
/// this engine's catalogue**, answered by
/// [`DialectCapabilities::catalogue_reach`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CatalogueReach {
    /// **Every check.** The engine runs the query that compares its catalogue
    /// with the design in one measurement: `information_schema.columns`, a
    /// `FULL OUTER JOIN`, and a table value constructor with a derived column
    /// list.
    Whole,
    /// **The columns it holds, and not the comparison.** The engine has
    /// `information_schema.columns` and lacks what the one-measurement
    /// comparison needs, so the reconciliation asks only whether each designed
    /// column is held. The sentence says what it lacks; a warning carries it.
    HeldColumnsOnly(&'static str),
    /// **No schema check.** The sentence says why, in a reader's words; a
    /// warning carries it.
    Nothing(&'static str),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::merge_shape::MergeRestrictions;

    struct DefaultDialect;
    impl DialectCapabilities for DefaultDialect {}

    /// **A dialect that states no question asks none, and the first word of
    /// an answer is its version.**
    #[test]
    fn the_server_version_is_the_first_word_of_the_answer() {
        let d = DefaultDialect;
        assert_eq!(d.server_version_query(), None);
        let read = d.parse_server_version("17 17.2");
        assert_eq!(read.map(|v| v.to_string()), Some("17".to_owned()));
        assert_eq!(d.parse_server_version("  8.4 MySQL Community Server"), "8.4".parse().ok());
        assert_eq!(d.parse_server_version(""), None);
        assert_eq!(d.parse_server_version("PostgreSQL 17.2"), None);
    }

    /// Assert default DML capability flags are conservative.
    /// Parameters:
    /// - d: Dialect capabilities implementation under test.
    fn assert_default_dml_capabilities(d: &impl DialectCapabilities) {
        assert_eq!(d.merge_shape(), MergeShape::None);
        assert!(!d.supports_on_conflict());
        assert!(!d.supports_insert_overwrite());
        assert!(!d.supports_update_from());
        assert!(!d.supports_returning());
    }

    /// Assert default query capability flags and ANSI-safe behavior.
    /// Parameters:
    /// - d: Dialect capabilities implementation under test.
    fn assert_default_query_capabilities(d: &impl DialectCapabilities) {
        assert!(d.supports_cte());
        assert!(d.supports_recursive_cte());
        assert!(d.supports_window_functions());
        assert!(d.supports_named_windows());
        assert!(!d.supports_qualify());
        assert!(!d.supports_groups_frame());
        assert!(d.supports_nulls_ordering());
    }

    /// Assert default DDL capability and type flags are conservative.
    /// Parameters:
    /// - d: Dialect capabilities implementation under test.
    fn assert_default_ddl_and_type_capabilities(d: &impl DialectCapabilities) {
        assert!(!d.supports_identity());
        assert!(!d.supports_sequences());
        assert!(d.supports_schemas());
        assert!(!d.supports_bulk_load());
        assert!(!d.supports_stored_procedures());
        // The two routine-form questions default the other way on purpose:
        // answering `false` REFUSES a build, so it is never the answer an
        // unknown platform falls into.
        assert!(d.supports_stored_functions());
        assert!(d.supports_table_functions());
        assert!(!d.supports_tasks());
        assert!(d.supports_partitioning());
        assert!(d.supports_materialized_views());
        assert!(d.supports_generated_columns());
        assert!(d.supports_json());
        assert!(!d.supports_unsigned_integers());
        assert!(!d.supports_arrays());
        assert!(d.supports_boolean());
    }

    /// Assert default platform limits and storage capability flags.
    /// Parameters:
    /// - d: Dialect capabilities implementation under test.
    fn assert_default_limits_and_storage_capabilities(d: &impl DialectCapabilities) {
        assert_eq!(d.default_schema(), "public");
        assert_eq!(d.max_identifier_length(), 63);
        assert_eq!(d.max_columns(), 10000);
        assert_eq!(d.max_parameters(), 0);
        assert!(!d.supports_partition_function());
        assert!(!d.supports_partition_split_merge());
        assert!(!d.supports_columnstore_index());
        assert!(!d.supports_clustering_key());
        assert!(!d.supports_table_compression());
    }

    #[test]
    fn defaults_are_conservative() {
        let d = DefaultDialect;
        assert_default_dml_capabilities(&d);
        assert_default_query_capabilities(&d);
        assert_default_ddl_and_type_capabilities(&d);
        assert_default_limits_and_storage_capabilities(&d);
    }

    #[test]
    fn overrides_work() {
        struct PostgresLike;
        impl DialectCapabilities for PostgresLike {
            fn merge_shape(&self) -> MergeShape {
                MergeShape::Merge(MergeRestrictions::none())
            }
            fn supports_on_conflict(&self) -> bool {
                true
            }
            fn supports_returning(&self) -> bool {
                true
            }
            fn supports_identity(&self) -> bool {
                true
            }
            fn supports_sequences(&self) -> bool {
                true
            }
            fn supports_arrays(&self) -> bool {
                true
            }
            fn max_columns(&self) -> usize {
                1600
            }
        }

        let d = PostgresLike;
        assert!(d.merge_shape().merges());
        assert!(d.supports_on_conflict());
        assert!(d.supports_returning());
        assert!(d.supports_identity());
        assert!(d.supports_sequences());
        assert!(d.supports_arrays());
        assert_eq!(d.max_columns(), 1600);
        // Untouched defaults
        assert!(!d.supports_insert_overwrite());
        assert!(d.supports_cte());
    }

    #[test]
    fn new_capability_defaults_are_conservative() {
        let d = DefaultDialect;
        // Drop capabilities
        assert!(d.supports_cascade_drop()); // true = ANSI default
        assert!(!d.supports_function_overloading());
        assert!(!d.supports_sync_drop());
        assert!(!d.supports_force_drop());
        // DML extended
        assert!(!d.supports_compound_assignment());
        assert!(!d.supports_window_frame_exclude());
        assert!(!d.supports_merge_not_matched_by_source());
        assert_eq!(d.merge_not_matched_keyword(), "WHEN NOT MATCHED");
        assert!(!d.supports_merge_star_syntax());
        assert!(!d.uses_alter_table_update());
        assert!(!d.supports_multi_table_insert());
        // DDL / Namespace
        assert_eq!(d.schema_namespace_keyword(), "SCHEMA");
    }

    /// The default transaction answer is the ANSI one: a load can be wrapped,
    /// in the standard spelling, and clearing a staging table stays inside the
    /// wrap. Every platform that differs says so on its own dialect.
    #[test]
    fn the_default_load_wrap_is_the_ansi_one() {
        let d = DefaultDialect;
        assert!(d.supports_multi_statement_transactions());
        assert_eq!(d.begin_transaction_keyword(), "START TRANSACTION");
        assert_eq!(d.commit_transaction_keyword(), "COMMIT");
        assert!(!d.truncate_commits_implicitly());
        assert!(!d.begin_leaves_the_commit_to_the_client());
    }

    /// **A bound on the digits before the point is its own refusal**, and the
    /// nearest type that fits keeps the scale and gives up whole digits.
    #[test]
    fn digits_before_the_point_have_their_own_bound() {
        let bignumeric = DecimalLimits {
            max_precision: 76,
            max_scale: 38,
            scale_within_precision: true,
            max_integer_digits: Some(38),
        };
        assert_eq!(bignumeric.misfit(38, 0), None);
        assert_eq!(bignumeric.misfit(76, 38), None);
        assert_eq!(
            bignumeric.misfit(39, 0).as_deref(),
            Some("its decimals hold at most 38 digits before the point, and this asks for 39")
        );
        assert_eq!(bignumeric.nearest(39, 0), (38, 0));
        assert_eq!(bignumeric.nearest(60, 10), (48, 10));
        assert_eq!(bignumeric.nearest(99, 40), (76, 38));
        for (precision, scale) in [(39, 0), (60, 10), (99, 40), (5, 6), (0, 0)] {
            let (p, s) = bignumeric.nearest(precision, scale);
            assert_eq!(bignumeric.misfit(p, s), None, "nearest({precision}, {scale}) fits");
        }

        let unbounded = DecimalLimits { max_integer_digits: None, ..bignumeric };
        assert_eq!(unbounded.misfit(76, 0), None, "the digits in all are the only bound");
    }
}