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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Structured name types for SQL objects.

use anyhow::anyhow;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use mz_compute_client::controller::ComputeInstanceId;
use mz_expr::LocalId;
use mz_ore::str::StrExt;
use mz_repr::GlobalId;

use crate::ast::display::{AstDisplay, AstFormatter};
use crate::ast::fold::{Fold, FoldNode};
use crate::ast::visit::{Visit, VisitNode};
use crate::ast::visit_mut::VisitMut;
use crate::ast::{
    self, AstInfo, Cte, Ident, Query, Raw, RawClusterName, RawDataType, RawObjectName, Statement,
    UnresolvedObjectName,
};
use crate::catalog::{CatalogItemType, CatalogTypeDetails, SessionCatalog};
use crate::normalize;
use crate::plan::PlanError;

/// A fully-qualified human readable name of an item in the catalog.
///
/// Catalog names compare case sensitively. Use
/// [`normalize::unresolved_object_name`] to
/// perform proper case folding if converting an [`UnresolvedObjectName`] to a
/// `FullObjectName`.
///
/// [`normalize::unresolved_object_name`]: crate::normalize::unresolved_object_name
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct FullObjectName {
    /// The database name.
    pub database: RawDatabaseSpecifier,
    /// The schema name.
    pub schema: String,
    /// The item name.
    pub item: String,
}

impl fmt::Display for FullObjectName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let RawDatabaseSpecifier::Name(database) = &self.database {
            write!(f, "{}.", database)?;
        }
        write!(f, "{}.{}", self.schema, self.item)
    }
}

impl From<FullObjectName> for UnresolvedObjectName {
    fn from(full_name: FullObjectName) -> UnresolvedObjectName {
        let mut name_parts = Vec::new();
        if let RawDatabaseSpecifier::Name(database) = full_name.database {
            name_parts.push(Ident::new(database));
        }
        name_parts.push(Ident::new(full_name.schema));
        name_parts.push(Ident::new(full_name.item));
        UnresolvedObjectName(name_parts)
    }
}

/// A fully-qualified non-human readable name of an item in the catalog using IDs for the database
/// and schema.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct QualifiedObjectName {
    pub qualifiers: ObjectQualifiers,
    pub item: String,
}

impl fmt::Display for QualifiedObjectName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let ResolvedDatabaseSpecifier::Id(id) = &self.qualifiers.database_spec {
            write!(f, "{}.", id)?;
        }
        write!(f, "{}.{}", self.qualifiers.schema_spec, self.item)
    }
}

/// An optionally-qualified human-readable name of an item in the catalog.
///
/// This is like a [`FullObjectName`], but either the database or schema name may be
/// omitted.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct PartialObjectName {
    pub database: Option<String>,
    pub schema: Option<String>,
    pub item: String,
}

impl PartialObjectName {
    // Whether either self or other might be a (possibly differently qualified)
    // version of the other.
    pub fn matches(&self, other: &Self) -> bool {
        match (&self.database, &other.database) {
            (Some(d1), Some(d2)) if d1 != d2 => return false,
            _ => (),
        }
        match (&self.schema, &other.schema) {
            (Some(s1), Some(s2)) if s1 != s2 => return false,
            _ => (),
        }
        self.item == other.item
    }
}

impl fmt::Display for PartialObjectName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(database) = &self.database {
            write!(f, "{}.", database)?;
        }
        if let Some(schema) = &self.schema {
            write!(f, "{}.", schema)?;
        }
        write!(f, "{}", self.item)
    }
}

impl From<FullObjectName> for PartialObjectName {
    fn from(n: FullObjectName) -> PartialObjectName {
        let database = match n.database {
            RawDatabaseSpecifier::Ambient => None,
            RawDatabaseSpecifier::Name(name) => Some(name),
        };
        PartialObjectName {
            database,
            schema: Some(n.schema),
            item: n.item,
        }
    }
}

impl From<String> for PartialObjectName {
    fn from(item: String) -> Self {
        PartialObjectName {
            database: None,
            schema: None,
            item,
        }
    }
}

/// A fully-qualified human readable name of a schema in the catalog.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct FullSchemaName {
    /// The database name
    pub database: RawDatabaseSpecifier,
    /// The schema name
    pub schema: String,
}

impl fmt::Display for FullSchemaName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let RawDatabaseSpecifier::Name(database) = &self.database {
            write!(f, "{}.", database)?;
        }
        write!(f, "{}", self.schema)
    }
}

/// The fully-qualified non-human readable name of a schema in the catalog.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct QualifiedSchemaName {
    pub database: ResolvedDatabaseSpecifier,
    pub schema: String,
}

impl fmt::Display for QualifiedSchemaName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.database {
            ResolvedDatabaseSpecifier::Ambient => f.write_str(&self.schema),
            ResolvedDatabaseSpecifier::Id(id) => write!(f, "{}.{}", id, self.schema),
        }
    }
}

/// An optionally-qualified name of an schema in the catalog.
///
/// This is like a [`FullSchemaName`], but either the database or schema name may be
/// omitted.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct PartialSchemaName {
    pub database: Option<String>,
    pub schema: String,
}

impl fmt::Display for PartialSchemaName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(database) = &self.database {
            write!(f, "{}.", database)?;
        }
        write!(f, "{}", self.schema)
    }
}

/// A human readable name of a database.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum RawDatabaseSpecifier {
    /// The "ambient" database, which is always present and is not named
    /// explicitly, but by omission.
    Ambient,
    /// A normal database with a name.
    Name(String),
}

impl fmt::Display for RawDatabaseSpecifier {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Ambient => f.write_str("<none>"),
            Self::Name(name) => f.write_str(name),
        }
    }
}

impl From<Option<String>> for RawDatabaseSpecifier {
    fn from(s: Option<String>) -> RawDatabaseSpecifier {
        match s {
            None => Self::Ambient,
            Some(name) => Self::Name(name),
        }
    }
}

/// An id of a database.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum ResolvedDatabaseSpecifier {
    /// The "ambient" database, which is always present and is not named
    /// explicitly, but by omission.
    Ambient,
    /// A normal database with a name.
    Id(DatabaseId),
}

impl fmt::Display for ResolvedDatabaseSpecifier {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Ambient => f.write_str("<none>"),
            Self::Id(id) => write!(f, "{}", id),
        }
    }
}

impl AstDisplay for ResolvedDatabaseSpecifier {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_str(format!("{}", self));
    }
}

impl From<u64> for ResolvedDatabaseSpecifier {
    fn from(id: u64) -> Self {
        Self::Id(DatabaseId(id))
    }
}

/*
 * TODO(jkosh44) It's possible that in order to fix
 * https://github.com/MaterializeInc/materialize/issues/8805 we will need to assign temporary
 * schemas unique Ids. If/when that happens we can remove this enum and refer to all schemas by
 * their Id.
 */
/// An id of a schema.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum SchemaSpecifier {
    /// A temporary schema
    Temporary,
    /// A normal database with a name.
    Id(SchemaId),
}

impl SchemaSpecifier {
    const TEMPORARY_SCHEMA_ID: u64 = 0;
}

impl fmt::Display for SchemaSpecifier {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Temporary => f.write_str(format!("{}", Self::TEMPORARY_SCHEMA_ID).as_str()),
            Self::Id(id) => write!(f, "{}", id),
        }
    }
}

impl AstDisplay for SchemaSpecifier {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_str(format!("{}", self));
    }
}

impl From<u64> for SchemaSpecifier {
    fn from(id: u64) -> Self {
        if id == Self::TEMPORARY_SCHEMA_ID {
            Self::Temporary
        } else {
            Self::Id(SchemaId(id))
        }
    }
}

impl From<&SchemaSpecifier> for SchemaId {
    fn from(schema_spec: &SchemaSpecifier) -> Self {
        match schema_spec {
            SchemaSpecifier::Temporary => SchemaId(SchemaSpecifier::TEMPORARY_SCHEMA_ID),
            SchemaSpecifier::Id(id) => id.clone(),
        }
    }
}

impl From<SchemaSpecifier> for SchemaId {
    fn from(schema_spec: SchemaSpecifier) -> Self {
        match schema_spec {
            SchemaSpecifier::Temporary => SchemaId(SchemaSpecifier::TEMPORARY_SCHEMA_ID),
            SchemaSpecifier::Id(id) => id,
        }
    }
}

impl From<&SchemaSpecifier> for u64 {
    fn from(schema_spec: &SchemaSpecifier) -> Self {
        SchemaId::from(schema_spec).0
    }
}

impl From<SchemaSpecifier> for u64 {
    fn from(schema_spec: SchemaSpecifier) -> Self {
        SchemaId::from(schema_spec).0
    }
}

// Aug is the type variable assigned to an AST that has already been
// name-resolved. An AST in this state has global IDs populated next to table
// names, and local IDs assigned to CTE definitions and references.
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Default)]
pub struct Aug;

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ObjectQualifiers {
    pub database_spec: ResolvedDatabaseSpecifier,
    pub schema_spec: SchemaSpecifier,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ResolvedObjectName {
    Object {
        id: GlobalId,
        qualifiers: ObjectQualifiers,
        full_name: FullObjectName,
        // Whether this object, when printed out, should use [id AS name] syntax. We
        // want this for things like tables and sources, but not for things like
        // types.
        print_id: bool,
    },
    Cte {
        id: LocalId,
        name: String,
    },
    Error,
}

impl ResolvedObjectName {
    pub fn full_name_str(&self) -> String {
        match self {
            ResolvedObjectName::Object { full_name, .. } => full_name.to_string(),
            ResolvedObjectName::Cte { name, .. } => name.clone(),
            ResolvedObjectName::Error => "error in name resolution".to_string(),
        }
    }
}

impl AstDisplay for ResolvedObjectName {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match self {
            ResolvedObjectName::Object {
                id,
                qualifiers: _,
                full_name,
                print_id,
            } => {
                if *print_id {
                    f.write_str(format!("[{} AS ", id));
                }
                if let RawDatabaseSpecifier::Name(database) = &full_name.database {
                    f.write_node(&Ident::new(database));
                    f.write_str(".");
                }
                f.write_node(&Ident::new(&full_name.schema));
                f.write_str(".");
                f.write_node(&Ident::new(&full_name.item));
                if *print_id {
                    f.write_str("]");
                }
            }
            ResolvedObjectName::Cte { name, .. } => f.write_node(&Ident::new(name)),
            ResolvedObjectName::Error => {}
        }
    }
}

impl std::fmt::Display for ResolvedObjectName {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str(self.to_ast_string().as_str())
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ResolvedSchemaName {
    Schema {
        database_spec: ResolvedDatabaseSpecifier,
        schema_spec: SchemaSpecifier,
        full_name: FullSchemaName,
    },
    Error,
}

impl ResolvedSchemaName {
    /// Panics if this is `Self::Error`.
    pub fn schema_spec(&self) -> &SchemaSpecifier {
        match self {
            ResolvedSchemaName::Schema { schema_spec, .. } => schema_spec,
            ResolvedSchemaName::Error => {
                unreachable!("should have been handled by name resolution")
            }
        }
    }
}

impl AstDisplay for ResolvedSchemaName {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match self {
            ResolvedSchemaName::Schema { full_name, .. } => {
                if let RawDatabaseSpecifier::Name(database) = &full_name.database {
                    f.write_node(&Ident::new(database));
                    f.write_str(".");
                }
                f.write_node(&Ident::new(&full_name.schema));
            }
            ResolvedSchemaName::Error => {}
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ResolvedDatabaseName {
    Database { id: DatabaseId, name: String },
    Error,
}

impl AstDisplay for ResolvedDatabaseName {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match self {
            ResolvedDatabaseName::Database { name, .. } => f.write_node(&Ident::new(name)),
            ResolvedDatabaseName::Error => {}
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ResolvedClusterName {
    pub id: ComputeInstanceId,
    /// If set, a name to print in the `AstDisplay` implementation instead of
    /// `None`. This is only meant to be used by the `NameSimplifier`.
    ///
    /// NOTE(benesch): it would be much clearer if the `NameSimplifier` folded
    /// the AST into a different metadata type, to avoid polluting the resolved
    /// AST with this field.
    pub print_name: Option<String>,
}

impl AstDisplay for ResolvedClusterName {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        if let Some(print_name) = &self.print_name {
            f.write_node(&Ident::new(print_name))
        } else {
            f.write_str(format!("[{}]", self.id))
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ResolvedDataType {
    AnonymousList(Box<ResolvedDataType>),
    AnonymousMap {
        key_type: Box<ResolvedDataType>,
        value_type: Box<ResolvedDataType>,
    },
    Named {
        id: GlobalId,
        qualifiers: ObjectQualifiers,
        full_name: FullObjectName,
        modifiers: Vec<i64>,
        print_id: bool,
    },
    Error,
}

impl AstDisplay for ResolvedDataType {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match self {
            ResolvedDataType::AnonymousList(element_type) => {
                element_type.fmt(f);
                f.write_str(" list");
            }
            ResolvedDataType::AnonymousMap {
                key_type,
                value_type,
            } => {
                f.write_str("map[");
                key_type.fmt(f);
                f.write_str("=>");
                value_type.fmt(f);
                f.write_str("]");
            }
            ResolvedDataType::Named {
                id,
                full_name,
                modifiers,
                print_id,
                ..
            } => {
                if *print_id {
                    f.write_str(format!("[{} AS ", id));
                }
                if let RawDatabaseSpecifier::Name(database) = &full_name.database {
                    f.write_node(&Ident::new(database));
                    f.write_str(".");
                }

                f.write_node(&Ident::new(&full_name.schema));
                f.write_str(".");

                f.write_node(&Ident::new(&full_name.item));
                if *print_id {
                    f.write_str("]");
                }
                if modifiers.len() > 0 {
                    f.write_str("(");
                    f.write_node(&ast::display::comma_separated(modifiers));
                    f.write_str(")");
                }
            }
            ResolvedDataType::Error => {}
        }
    }
}

impl ResolvedDataType {
    /// Return the name of `self`'s item without qualification or IDs.
    ///
    /// This is used to generate to generate default column names for cast operations.
    pub fn unqualified_item_name(&self) -> String {
        let mut res = String::new();
        match self {
            ResolvedDataType::AnonymousList(element_type) => {
                res += &element_type.unqualified_item_name();
                res += " list";
            }
            ResolvedDataType::AnonymousMap {
                key_type,
                value_type,
            } => {
                res += "map[";
                res += &key_type.unqualified_item_name();
                res += "=>";
                res += &value_type.unqualified_item_name();
                res += "]";
            }
            ResolvedDataType::Named { full_name, .. } => {
                res += &full_name.item;
            }
            ResolvedDataType::Error => {}
        }
        res
    }
}

impl fmt::Display for ResolvedDataType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.to_ast_string().as_str())
    }
}

impl AstInfo for Aug {
    type NestedStatement = Statement<Raw>;
    type ObjectName = ResolvedObjectName;
    type SchemaName = ResolvedSchemaName;
    type DatabaseName = ResolvedDatabaseName;
    type ClusterName = ResolvedClusterName;
    type DataType = ResolvedDataType;
    type CteId = LocalId;
}

/// The identifier for a schema.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct SchemaId(pub u64);

impl SchemaId {
    /// Constructs a new schema identifier. It is the caller's responsibility
    /// to provide a unique `id`.
    pub fn new(id: u64) -> Self {
        SchemaId(id)
    }
}

impl fmt::Display for SchemaId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for SchemaId {
    type Err = PlanError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let val: u64 = s.parse()?;
        Ok(SchemaId(val))
    }
}

/// The identifier for a database.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct DatabaseId(pub u64);

impl DatabaseId {
    /// Constructs a new database identifier. It is the caller's responsibility
    /// to provide a unique `id`.
    pub fn new(id: u64) -> Self {
        DatabaseId(id)
    }
}

impl fmt::Display for DatabaseId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for DatabaseId {
    type Err = PlanError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let val: u64 = s.parse()?;
        Ok(DatabaseId(val))
    }
}

/// The identifier for a role.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum RoleId {
    System(u64),
    User(u64),
}

impl RoleId {
    pub fn is_system(&self) -> bool {
        matches!(self, Self::System(_))
    }

    pub fn is_user(&self) -> bool {
        matches!(self, Self::User(_))
    }
}

impl FromStr for RoleId {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() < 2 {
            return Err(anyhow!("couldn't parse role id {}", s));
        }
        let val: u64 = s[1..].parse()?;
        match s.chars().next().unwrap() {
            's' => Ok(Self::System(val)),
            'u' => Ok(Self::User(val)),
            _ => Err(anyhow!("couldn't parse role id {}", s)),
        }
    }
}

impl fmt::Display for RoleId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::System(id) => write!(f, "s{}", id),
            Self::User(id) => write!(f, "u{}", id),
        }
    }
}

#[derive(Debug)]
pub struct NameResolver<'a> {
    catalog: &'a dyn SessionCatalog,
    ctes: HashMap<String, LocalId>,
    status: Result<(), PlanError>,
    ids: HashSet<GlobalId>,
}

impl<'a> NameResolver<'a> {
    fn new(catalog: &'a dyn SessionCatalog) -> NameResolver {
        NameResolver {
            catalog,
            ctes: HashMap::new(),
            status: Ok(()),
            ids: HashSet::new(),
        }
    }

    fn fold_data_type_internal(
        &mut self,
        data_type: <Raw as AstInfo>::DataType,
    ) -> Result<<Aug as AstInfo>::DataType, PlanError> {
        match data_type {
            RawDataType::Array(elem_type) => {
                let name = elem_type.to_string();
                match self.fold_data_type_internal(*elem_type)? {
                    ResolvedDataType::AnonymousList(_) | ResolvedDataType::AnonymousMap { .. } => {
                        sql_bail!("type \"{}[]\" does not exist", name)
                    }
                    ResolvedDataType::Named { id, modifiers, .. } => {
                        let element_item = self.catalog.get_item(&id);
                        let array_item = match element_item.type_details() {
                            Some(CatalogTypeDetails {
                                array_id: Some(array_id),
                                ..
                            }) => self.catalog.get_item(array_id),
                            Some(_) => sql_bail!("type \"{}[]\" does not exist", name),
                            None => sql_bail!(
                                "{} does not refer to a type",
                                self.catalog
                                    .resolve_full_name(element_item.name())
                                    .to_string()
                                    .quoted()
                            ),
                        };
                        Ok(ResolvedDataType::Named {
                            id: array_item.id(),
                            qualifiers: array_item.name().qualifiers.clone(),
                            full_name: self.catalog.resolve_full_name(array_item.name()),
                            modifiers,
                            print_id: true,
                        })
                    }
                    ResolvedDataType::Error => sql_bail!("type \"{}[]\" does not exist", name),
                }
            }
            RawDataType::List(elem_type) => {
                let elem_type = self.fold_data_type_internal(*elem_type)?;
                Ok(ResolvedDataType::AnonymousList(Box::new(elem_type)))
            }
            RawDataType::Map {
                key_type,
                value_type,
            } => {
                let key_type = self.fold_data_type_internal(*key_type)?;
                let value_type = self.fold_data_type_internal(*value_type)?;
                Ok(ResolvedDataType::AnonymousMap {
                    key_type: Box::new(key_type),
                    value_type: Box::new(value_type),
                })
            }
            RawDataType::Other { name, typ_mod } => {
                let (full_name, item) = match name {
                    RawObjectName::Name(name) => {
                        let name = normalize::unresolved_object_name(name)?;
                        let item = self.catalog.resolve_item(&name)?;
                        let full_name = self.catalog.resolve_full_name(item.name());
                        (full_name, item)
                    }
                    RawObjectName::Id(id, name) => {
                        let gid: GlobalId = id.parse()?;
                        let item = self.catalog.get_item(&gid);
                        let full_name = normalize::full_name(name)?;
                        (full_name, item)
                    }
                };
                self.ids.insert(item.id());
                Ok(ResolvedDataType::Named {
                    id: item.id(),
                    qualifiers: item.name().qualifiers.clone(),
                    full_name,
                    modifiers: typ_mod,
                    print_id: true,
                })
            }
        }
    }
}

impl<'a> Fold<Raw, Aug> for NameResolver<'a> {
    fn fold_nested_statement(
        &mut self,
        stmt: <Raw as AstInfo>::NestedStatement,
    ) -> <Aug as AstInfo>::NestedStatement {
        stmt
    }

    fn fold_query(&mut self, q: Query<Raw>) -> Query<Aug> {
        // Retain the old values of various CTE names so that we can restore them after we're done
        // planning this SELECT.
        let mut old_cte_values = Vec::new();
        // A single WITH block cannot use the same name multiple times.
        let mut used_names = HashSet::new();
        let mut ctes = Vec::new();
        for cte in q.ctes {
            let cte_name = normalize::ident(cte.alias.name.clone());

            if used_names.contains(&cte_name) {
                self.status = Err(sql_err!(
                    "WITH query name \"{}\" specified more than once",
                    cte_name
                ));
            }
            used_names.insert(cte_name.clone());

            let id = LocalId::new(self.ctes.len() as u64);
            ctes.push(Cte {
                alias: cte.alias,
                id,
                query: self.fold_query(cte.query),
            });
            let old_val = self.ctes.insert(cte_name.clone(), id);
            old_cte_values.push((cte_name, old_val));
        }
        let result = Query {
            ctes,
            body: self.fold_set_expr(q.body),
            limit: q.limit.map(|l| self.fold_limit(l)),
            offset: q.offset.map(|l| self.fold_expr(l)),
            order_by: q
                .order_by
                .into_iter()
                .map(|c| self.fold_order_by_expr(c))
                .collect(),
        };

        // Restore the old values of the CTEs.
        for (name, value) in old_cte_values.iter() {
            match value {
                Some(value) => {
                    self.ctes.insert(name.to_string(), value.clone());
                }
                None => {
                    self.ctes.remove(name);
                }
            };
        }

        result
    }

    fn fold_cte_id(&mut self, _id: <Raw as AstInfo>::CteId) -> <Aug as AstInfo>::CteId {
        panic!("this should have been handled when walking the CTE");
    }

    fn fold_object_name(
        &mut self,
        object_name: <Raw as AstInfo>::ObjectName,
    ) -> <Aug as AstInfo>::ObjectName {
        match object_name {
            RawObjectName::Name(raw_name) => {
                let raw_name = match normalize::unresolved_object_name(raw_name) {
                    Ok(raw_name) => raw_name,
                    Err(e) => {
                        if self.status.is_ok() {
                            self.status = Err(e);
                        }
                        return ResolvedObjectName::Error;
                    }
                };

                // Check if unqualified name refers to a CTE.
                if raw_name.database.is_none() && raw_name.schema.is_none() {
                    let norm_name = normalize::ident(Ident::new(&raw_name.item));
                    if let Some(id) = self.ctes.get(&norm_name) {
                        return ResolvedObjectName::Cte {
                            id: *id,
                            name: norm_name,
                        };
                    }
                }

                match self.catalog.resolve_item(&raw_name) {
                    Ok(item) => {
                        self.ids.insert(item.id());
                        let print_id = !matches!(
                            item.item_type(),
                            CatalogItemType::Func | CatalogItemType::Type
                        );
                        ResolvedObjectName::Object {
                            id: item.id(),
                            qualifiers: item.name().qualifiers.clone(),
                            full_name: self.catalog.resolve_full_name(item.name()),
                            print_id,
                        }
                    }
                    Err(e) => {
                        if self.status.is_ok() {
                            self.status = Err(e.into());
                        }
                        ResolvedObjectName::Error
                    }
                }
            }
            RawObjectName::Id(id, raw_name) => {
                let gid: GlobalId = match id.parse() {
                    Ok(id) => id,
                    Err(e) => {
                        if self.status.is_ok() {
                            self.status = Err(e.into());
                        }
                        return ResolvedObjectName::Error;
                    }
                };
                let item = match self.catalog.try_get_item(&gid) {
                    Some(item) => item,
                    None => {
                        if self.status.is_ok() {
                            self.status = Err(sql_err!("invalid id {}", &gid));
                        }
                        return ResolvedObjectName::Error;
                    }
                };

                self.ids.insert(gid.clone());
                let full_name = match normalize::full_name(raw_name) {
                    Ok(full_name) => full_name,
                    Err(e) => {
                        if self.status.is_ok() {
                            self.status = Err(e);
                        }
                        return ResolvedObjectName::Error;
                    }
                };
                ResolvedObjectName::Object {
                    id: gid,
                    qualifiers: item.name().qualifiers.clone(),
                    full_name,
                    print_id: true,
                }
            }
        }
    }

    fn fold_data_type(
        &mut self,
        data_type: <Raw as AstInfo>::DataType,
    ) -> <Aug as AstInfo>::DataType {
        match self.fold_data_type_internal(data_type) {
            Ok(data_type) => data_type,
            Err(e) => {
                if self.status.is_ok() {
                    self.status = Err(e);
                }
                ResolvedDataType::Error
            }
        }
    }

    fn fold_schema_name(
        &mut self,
        name: <Raw as AstInfo>::SchemaName,
    ) -> <Aug as AstInfo>::SchemaName {
        let norm_name = match normalize::unresolved_schema_name(name) {
            Ok(norm_name) => norm_name,
            Err(e) => {
                if self.status.is_ok() {
                    self.status = Err(e);
                }
                return ResolvedSchemaName::Error;
            }
        };
        match self
            .catalog
            .resolve_schema(norm_name.database.as_deref(), norm_name.schema.as_str())
        {
            Ok(schema) => {
                let raw_database_spec = match schema.database() {
                    ResolvedDatabaseSpecifier::Ambient => RawDatabaseSpecifier::Ambient,
                    ResolvedDatabaseSpecifier::Id(id) => {
                        RawDatabaseSpecifier::Name(self.catalog.get_database(id).name().to_string())
                    }
                };
                ResolvedSchemaName::Schema {
                    database_spec: schema.database().clone(),
                    schema_spec: schema.id().clone(),
                    full_name: FullSchemaName {
                        database: raw_database_spec,
                        schema: schema.name().schema.clone(),
                    },
                }
            }
            Err(e) => {
                if self.status.is_ok() {
                    self.status = Err(e.into());
                }
                ResolvedSchemaName::Error
            }
        }
    }

    fn fold_database_name(
        &mut self,
        database_name: <Raw as AstInfo>::DatabaseName,
    ) -> <Aug as AstInfo>::DatabaseName {
        match self.catalog.resolve_database(database_name.0.as_str()) {
            Ok(database) => ResolvedDatabaseName::Database {
                id: database.id(),
                name: database_name.0.into_string(),
            },
            Err(e) => {
                if self.status.is_ok() {
                    self.status = Err(e.into());
                }
                ResolvedDatabaseName::Error
            }
        }
    }

    fn fold_cluster_name(
        &mut self,
        cluster_name: <Raw as AstInfo>::ClusterName,
    ) -> <Aug as AstInfo>::ClusterName {
        match cluster_name {
            RawClusterName::Unresolved(ident) => {
                match self.catalog.resolve_compute_instance(Some(ident.as_str())) {
                    Ok(cluster) => ResolvedClusterName {
                        id: cluster.id(),
                        print_name: None,
                    },
                    Err(e) => {
                        self.status = Err(e.into());
                        ResolvedClusterName {
                            // The id is arbitrary here, we just need some dummy value to return.
                            id: ComputeInstanceId::System(0),
                            print_name: None,
                        }
                    }
                }
            }
            RawClusterName::Resolved(ident) => match ident.parse() {
                Ok(id) => ResolvedClusterName {
                    id,
                    print_name: None,
                },
                Err(e) => {
                    self.status = Err(e.into());
                    ResolvedClusterName {
                        // The id is arbitrary here, we just need some dummy value to return.
                        id: ComputeInstanceId::System(0),
                        print_name: None,
                    }
                }
            },
        }
    }

    fn fold_with_option_value(
        &mut self,
        node: mz_sql_parser::ast::WithOptionValue<Raw>,
    ) -> mz_sql_parser::ast::WithOptionValue<Aug> {
        use mz_sql_parser::ast::WithOptionValue::*;
        match node {
            Sequence(vs) => Sequence(
                vs.into_iter()
                    .map(|v| self.fold_with_option_value(v))
                    .collect(),
            ),
            Value(v) => Value(self.fold_value(v)),
            Ident(i) => Ident(self.fold_ident(i)),
            DataType(dt) => DataType(self.fold_data_type(dt)),
            Secret(secret) => {
                let object_name = self.fold_object_name(secret);
                match &object_name {
                    ResolvedObjectName::Object { id, .. } => {
                        let item = self.catalog.get_item(id);
                        if item.item_type() != CatalogItemType::Secret {
                            self.status = Err(PlanError::InvalidSecret(object_name.clone()));
                        }
                    }
                    ResolvedObjectName::Cte { .. } => {
                        self.status = Err(PlanError::InvalidSecret(object_name.clone()));
                    }
                    ResolvedObjectName::Error => {}
                }
                Secret(object_name)
            }
            Object(obj) => {
                let object_name = self.fold_object_name(obj);
                match &object_name {
                    ResolvedObjectName::Object { .. } => {}
                    ResolvedObjectName::Cte { .. } => {
                        self.status = Err(PlanError::InvalidObject(object_name.clone()));
                    }
                    ResolvedObjectName::Error => {}
                }
                Object(object_name)
            }
            UnresolvedObjectName(name) => {
                UnresolvedObjectName(self.fold_unresolved_object_name(name))
            }
            ClusterReplicas(replicas) => ClusterReplicas(
                replicas
                    .into_iter()
                    .map(|r| self.fold_replica_definition(r))
                    .collect(),
            ),
            ConnectionKafkaBroker(broker) => ConnectionKafkaBroker(self.fold_kafka_broker(broker)),
        }
    }
}

/// Resolves names in an AST node using the provided catalog.
#[tracing::instrument(
    target = "compiler",
    level = "trace",
    name = "ast_resolve_names",
    skip_all
)]
pub fn resolve<N>(
    catalog: &dyn SessionCatalog,
    node: N,
) -> Result<(N::Folded, HashSet<GlobalId>), PlanError>
where
    N: FoldNode<Raw, Aug>,
{
    let mut resolver = NameResolver::new(catalog);
    let result = node.fold(&mut resolver);
    resolver.status?;
    Ok((result, resolver.ids))
}

#[derive(Debug)]
/// An AST visitor that transforms an AST that contains temporary GlobalId references to one where
/// every temporary GlobalId has been replaced by its final allocated id, as dictated by the
/// provided `allocation`
///
/// This is useful when trying to create multiple objects in a single DDL transaction and the
/// objects that are about to be don't have allocated GlobalIds yet. What we can do in that case is
/// for the planner to assign temporary `GlobalId::Transient` identifiers to all the objects that
/// it wants to create and use those for any interelationships.
///
/// Then, when the coordinator receives the list of plans to be executed it can batch allocate
/// the final `GlobalIds` and use this TransientResolver to walk through all the ASTs and make them
/// refer to the final GlobalIds of the objects.
pub struct TransientResolver<'a> {
    /// A HashMap mapping each transient global id to its final non-transient global id
    allocation: &'a HashMap<GlobalId, GlobalId>,
    status: Result<(), PlanError>,
}

impl<'a> TransientResolver<'a> {
    fn new(allocation: &'a HashMap<GlobalId, GlobalId>) -> Self {
        TransientResolver {
            allocation,
            status: Ok(()),
        }
    }
}

impl Fold<Aug, Aug> for TransientResolver<'_> {
    fn fold_object_name(&mut self, object_name: ResolvedObjectName) -> ResolvedObjectName {
        match object_name {
            ResolvedObjectName::Object {
                id: transient_id @ GlobalId::Transient(_),
                qualifiers,
                full_name,
                print_id,
            } => {
                let id = match self.allocation.get(&transient_id) {
                    Some(id) => *id,
                    None => {
                        let obj = ResolvedObjectName::Object {
                            id: transient_id,
                            qualifiers: qualifiers.clone(),
                            full_name: full_name.clone(),
                            print_id,
                        };
                        self.status = Err(PlanError::InvalidObject(obj));
                        transient_id
                    }
                };
                ResolvedObjectName::Object {
                    id,
                    qualifiers,
                    full_name,
                    print_id,
                }
            }
            other => other,
        }
    }
    fn fold_cluster_name(
        &mut self,
        node: <Aug as AstInfo>::ClusterName,
    ) -> <Aug as AstInfo>::ClusterName {
        node
    }
    fn fold_cte_id(&mut self, node: <Aug as AstInfo>::CteId) -> <Aug as AstInfo>::CteId {
        node
    }
    fn fold_data_type(&mut self, node: <Aug as AstInfo>::DataType) -> <Aug as AstInfo>::DataType {
        node
    }
    fn fold_database_name(
        &mut self,
        node: <Aug as AstInfo>::DatabaseName,
    ) -> <Aug as AstInfo>::DatabaseName {
        node
    }
    fn fold_nested_statement(
        &mut self,
        node: <Aug as AstInfo>::NestedStatement,
    ) -> <Aug as AstInfo>::NestedStatement {
        node
    }
    fn fold_schema_name(
        &mut self,
        node: <Aug as AstInfo>::SchemaName,
    ) -> <Aug as AstInfo>::SchemaName {
        node
    }
}

pub fn resolve_transient_ids<N>(
    allocation: &HashMap<GlobalId, GlobalId>,
    node: N,
) -> Result<N::Folded, PlanError>
where
    N: FoldNode<Aug, Aug>,
{
    let mut resolver = TransientResolver::new(allocation);
    let result = node.fold(&mut resolver);
    resolver.status?;
    Ok(result)
}

#[derive(Debug, Default)]
pub struct DependencyVisitor {
    ids: HashSet<GlobalId>,
}

impl<'ast> Visit<'ast, Aug> for DependencyVisitor {
    fn visit_object_name(&mut self, object_name: &'ast <Aug as AstInfo>::ObjectName) {
        if let ResolvedObjectName::Object { id, .. } = object_name {
            self.ids.insert(*id);
        }
    }

    fn visit_data_type(&mut self, data_type: &'ast <Aug as AstInfo>::DataType) {
        match data_type {
            ResolvedDataType::AnonymousList(data_type) => self.visit_data_type(data_type),
            ResolvedDataType::AnonymousMap {
                key_type,
                value_type,
            } => {
                self.visit_data_type(key_type);
                self.visit_data_type(value_type);
            }
            ResolvedDataType::Named { id, .. } => {
                self.ids.insert(*id);
            }
            ResolvedDataType::Error => {}
        }
    }
}

pub fn visit_dependencies<'ast, N>(node: &'ast N) -> HashSet<GlobalId>
where
    N: VisitNode<'ast, Aug> + 'ast,
{
    let mut visitor = DependencyVisitor::default();
    node.visit(&mut visitor);
    visitor.ids
}

// Used when displaying a view's source for human creation. If the name
// specified is the same as the name in the catalog, we don't use the ID format.
#[derive(Debug)]
pub struct NameSimplifier<'a> {
    pub catalog: &'a dyn SessionCatalog,
}

impl<'ast, 'a> VisitMut<'ast, Aug> for NameSimplifier<'a> {
    fn visit_cluster_name_mut(&mut self, node: &mut ResolvedClusterName) {
        node.print_name = Some(self.catalog.get_compute_instance(node.id).name().into());
    }

    fn visit_object_name_mut(&mut self, name: &mut ResolvedObjectName) {
        if let ResolvedObjectName::Object {
            id,
            full_name,
            print_id,
            ..
        } = name
        {
            let item = self.catalog.get_item(id);
            let catalog_full_name = self.catalog.resolve_full_name(item.name());
            if catalog_full_name == *full_name {
                *print_id = false;
            }
        }
    }

    fn visit_data_type_mut(&mut self, name: &mut ResolvedDataType) {
        if let ResolvedDataType::Named {
            id,
            full_name,
            print_id,
            ..
        } = name
        {
            let item = self.catalog.get_item(id);
            let catalog_full_name = self.catalog.resolve_full_name(item.name());
            if catalog_full_name == *full_name {
                *print_id = false;
            }
        }
    }
}