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
// 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.

use std::sync::Arc;

use mz_ccsr::ListError;
use mz_repr::adt::system::Oid;
use mz_sql_parser::ast::display::AstDisplay;
use mz_sql_parser::ast::{ExternalReferences, UnresolvedItemName};
use mz_storage_types::errors::{ContextCreationError, CsrConnectError};

use crate::names::{FullItemName, PartialItemName};

/// Logical errors detectable during purification for a POSTGRES SOURCE.
#[derive(Debug, Clone, thiserror::Error)]
pub enum PgSourcePurificationError {
    #[error("CREATE SOURCE specifies DETAILS option")]
    UserSpecifiedDetails,
    #[error("{0} option is unnecessary when no tables are added")]
    UnnecessaryOptionsWithoutReferences(String),
    #[error("PUBLICATION {0} is empty")]
    EmptyPublication(String),
    #[error("database {database} missing referenced schemas")]
    DatabaseMissingFilteredSchemas {
        database: String,
        schemas: Vec<String>,
    },
    #[error("missing TABLES specification")]
    RequiresExternalReferences,
    #[error("insufficient privileges")]
    UserLacksUsageOnSchemas { user: String, schemas: Vec<String> },
    #[error("insufficient privileges")]
    UserLacksSelectOnTables { user: String, tables: Vec<String> },
    #[error("referenced items not tables with REPLICA IDENTITY FULL")]
    NotTablesWReplicaIdentityFull { items: Vec<String> },
    #[error("TEXT COLUMNS refers to table not currently being added")]
    DanglingTextColumns { items: Vec<PartialItemName> },
    #[error("referenced tables use unsupported types")]
    UnrecognizedTypes { cols: Vec<(String, Oid)> },
    #[error("{0} is not a POSTGRES CONNECTION")]
    NotPgConnection(FullItemName),
    #[error("{0} is not a YUGABYTE CONNECTION")]
    NotYugabyteConnection(FullItemName),
    #[error("CONNECTION must specify PUBLICATION")]
    ConnectionMissingPublication,
    #[error("PostgreSQL server has insufficient number of replication slots available")]
    InsufficientReplicationSlotsAvailable { count: usize },
    #[error("server must have wal_level >= logical, but has {wal_level}")]
    InsufficientWalLevel {
        wal_level: mz_postgres_util::replication::WalLevel,
    },
    #[error("replication disabled on server")]
    ReplicationDisabled,
}

impl PgSourcePurificationError {
    pub fn detail(&self) -> Option<String> {
        match self {
            Self::DanglingTextColumns { items } => Some(format!(
                "the following tables are referenced but not added: {}",
                itertools::join(items, ", ")
            )),
            Self::DatabaseMissingFilteredSchemas {
                database: _,
                schemas,
            } => Some(format!(
                "missing schemas: {}",
                itertools::join(schemas.iter(), ", ")
            )),
            Self::UserLacksUsageOnSchemas { user, schemas } => Some(format!(
                "user {} lacks USAGE privileges for schemas {}",
                user,
                schemas.join(", ")
            )),
            Self::UserLacksSelectOnTables { user, tables } => Some(format!(
                "user {} lacks SELECT privileges for tables {}",
                user,
                tables.join(", ")
            )),
            Self::NotTablesWReplicaIdentityFull { items } => {
                Some(format!("referenced items: {}", items.join(", ")))
            }
            Self::UnrecognizedTypes { cols } => Some(format!(
                "the following columns contain unsupported types:\n{}",
                itertools::join(
                    cols.into_iter()
                        .map(|(col, Oid(oid))| format!("{} (OID {})", col, oid)),
                    "\n"
                )
            )),
            Self::InsufficientReplicationSlotsAvailable { count } => Some(format!(
                "executing this statement requires {} replication slot{}",
                count,
                if *count == 1 { "" } else { "s" }
            )),
            _ => None,
        }
    }

    pub fn hint(&self) -> Option<String> {
        match self {
            Self::UserSpecifiedDetails => Some(
                "If trying to use the output of SHOW CREATE SOURCE, remove the DETAILS option."
                    .into(),
            ),
            Self::RequiresExternalReferences => {
                Some("provide a FOR TABLES (..), FOR SCHEMAS (..), or FOR ALL TABLES clause".into())
            }
            Self::UnrecognizedTypes {
                cols: _,
            } => Some(
                "Use the TEXT COLUMNS option naming the listed columns, and Materialize can ingest their values \
                as text."
                    .into(),
            ),
            Self::InsufficientReplicationSlotsAvailable { .. } => Some(
                "you might be able to wait for other sources to finish snapshotting and try again".into()
            ),
            Self::ReplicationDisabled => Some("set max_wal_senders to a value > 0".into()),
            Self::UnnecessaryOptionsWithoutReferences(option) => Some(format!(
                "Remove the {} option, as no tables are being added.",
                option
            )),
            _ => None,
        }
    }
}

/// Logical errors detectable during purification for a KAFKA SOURCE.
#[derive(Debug, Clone, thiserror::Error)]
pub enum KafkaSourcePurificationError {
    #[error("{} is only valid for multi-output sources", .0.to_ast_string())]
    ReferencedSubsources(ExternalReferences),
    #[error("KAFKA CONNECTION without TOPIC")]
    ConnectionMissingTopic,
    #[error("{0} is not a KAFKA CONNECTION")]
    NotKafkaConnection(FullItemName),
    #[error("failed to create and connect Kafka consumer")]
    KafkaConsumerError(String),
    #[error("Referenced kafka connection uses a different topic '{0}' than specified: '{1}'")]
    WrongKafkaTopic(String, UnresolvedItemName),
}

impl KafkaSourcePurificationError {
    pub fn detail(&self) -> Option<String> {
        match self {
            Self::KafkaConsumerError(e) => Some(e.clone()),
            _ => None,
        }
    }

    pub fn hint(&self) -> Option<String> {
        None
    }
}

/// Logical errors detectable during purification for a LOAD GENERATOR SOURCE.
#[derive(Debug, Clone, thiserror::Error)]
pub enum LoadGeneratorSourcePurificationError {
    #[error("FOR ALL TABLES is only valid for multi-output sources")]
    ForAllTables,
    #[error("FOR SCHEMAS (..) unsupported")]
    ForSchemas,
    #[error("FOR TABLES (..) unsupported")]
    ForTables,
    #[error("multi-output sources require a FOR TABLES (..) or FOR ALL TABLES statement")]
    MultiOutputRequiresForAllTables,
    #[error("multi-output sources require an external reference")]
    MultiOutputRequiresExternalReference,
    #[error("Referenced load generator is different '{0}' than specified: '{1}'")]
    WrongLoadGenerator(String, UnresolvedItemName),
}

impl LoadGeneratorSourcePurificationError {
    pub fn detail(&self) -> Option<String> {
        match self {
            _ => None,
        }
    }

    pub fn hint(&self) -> Option<String> {
        match self {
            _ => None,
        }
    }
}

/// Logical errors detectable during purification for a KAFKA SINK.
#[derive(Debug, Clone, thiserror::Error)]
pub enum KafkaSinkPurificationError {
    #[error("{0} is not a KAFKA CONNECTION")]
    NotKafkaConnection(FullItemName),
    #[error("admin client errored")]
    AdminClientError(Arc<ContextCreationError>),
    #[error("zero brokers discovered in metadata request")]
    ZeroBrokers,
}

impl KafkaSinkPurificationError {
    pub fn detail(&self) -> Option<String> {
        match self {
            Self::AdminClientError(e) => Some(e.to_string_with_causes()),
            _ => None,
        }
    }

    pub fn hint(&self) -> Option<String> {
        None
    }
}

use mz_ore::error::ErrorExt;

/// Logical errors detectable during purification for Confluent Schema Registry.
#[derive(Debug, Clone, thiserror::Error)]
pub enum CsrPurificationError {
    #[error("{0} is not a CONFLUENT SCHEMA REGISTRY CONNECTION")]
    NotCsrConnection(FullItemName),
    #[error("client errored")]
    ClientError(Arc<CsrConnectError>),
    #[error("list subjects failed")]
    ListSubjectsError(Arc<ListError>),
}

impl CsrPurificationError {
    pub fn detail(&self) -> Option<String> {
        match self {
            Self::ClientError(e) => Some(e.to_string_with_causes()),
            Self::ListSubjectsError(e) => Some(e.to_string_with_causes()),
            _ => None,
        }
    }

    pub fn hint(&self) -> Option<String> {
        None
    }
}

/// Logical errors detectable during purification for a MySQL SOURCE.
#[derive(Debug, Clone, thiserror::Error)]
pub enum MySqlSourcePurificationError {
    #[error("User lacks required MySQL privileges")]
    UserLacksPrivileges(Vec<(String, String)>),
    #[error("CREATE SOURCE specifies DETAILS option")]
    UserSpecifiedDetails,
    #[error("{0} option is unnecessary when no tables are added")]
    UnnecessaryOptionsWithoutReferences(String),
    #[error("{0} is not a MYSQL CONNECTION")]
    NotMySqlConnection(FullItemName),
    #[error("Invalid MySQL system replication settings")]
    ReplicationSettingsError(Vec<(String, String, String)>),
    #[error("referenced tables use unsupported types")]
    UnrecognizedTypes { cols: Vec<(String, String, String)> },
    #[error("duplicated column name references in table {0}: {1:?}")]
    DuplicatedColumnNames(String, Vec<String>),
    #[error("{option_name} refers to table not currently being added")]
    DanglingColumns {
        option_name: String,
        items: Vec<UnresolvedItemName>,
    },
    #[error("Invalid MySQL table reference: {0}")]
    InvalidTableReference(String),
    #[error("No tables found for provided reference")]
    EmptyDatabase,
    #[error("missing TABLES specification")]
    RequiresExternalReferences,
    #[error("No tables found in referenced schemas")]
    NoTablesFoundForSchemas(Vec<String>),
}

impl MySqlSourcePurificationError {
    pub fn detail(&self) -> Option<String> {
        match self {
            Self::UserLacksPrivileges(missing) => Some(format!(
                "Missing MySQL privileges: {}",
                itertools::join(
                    missing
                        .iter()
                        .map(|(privilege, table)| format!("'{}' on '{}'", privilege, table)),
                    ", "
                )
            )),
            Self::DanglingColumns {
                option_name: _,
                items,
            } => Some(format!(
                "the following columns are referenced but not added: {}",
                itertools::join(items, ", ")
            )),
            Self::ReplicationSettingsError(settings) => Some(format!(
                "Invalid MySQL system replication settings: {}",
                itertools::join(
                    settings.iter().map(|(setting, expected, actual)| format!(
                        "{}: expected {}, got {}",
                        setting, expected, actual
                    )),
                    "; "
                )
            )),
            Self::UnrecognizedTypes { cols } => Some(format!(
                "the following columns contain unsupported types:\n{}",
                itertools::join(
                    cols.into_iter().map(|(table, column, data_type)| format!(
                        "'{}' for {}.{}",
                        data_type, column, table
                    )),
                    "\n"
                )
            )),
            Self::NoTablesFoundForSchemas(schemas) => Some(format!(
                "missing schemas: {}",
                itertools::join(schemas.iter(), ", ")
            )),
            _ => None,
        }
    }

    pub fn hint(&self) -> Option<String> {
        match self {
            Self::UserSpecifiedDetails => Some(
                "If trying to use the output of SHOW CREATE SOURCE, remove the DETAILS option."
                    .into(),
            ),
            Self::ReplicationSettingsError(_) => {
                Some("Set the necessary MySQL database system settings.".into())
            }
            Self::RequiresExternalReferences => {
                Some("provide a FOR TABLES (..), FOR SCHEMAS (..), or FOR ALL TABLES clause".into())
            }
            Self::InvalidTableReference(_) => Some(
                "Specify tables names as SCHEMA_NAME.TABLE_NAME in a FOR TABLES (..) clause".into(),
            ),
            Self::UnrecognizedTypes { cols: _ } => Some(
                "Check the docs -- some types can be supported using the TEXT COLUMNS option to \
                ingest their values as text, or ignored using EXCLUDE COLUMNS."
                    .into(),
            ),
            Self::EmptyDatabase => Some(
                "No tables were found to replicate. This could be because \
                the user does not have privileges on the intended tables."
                    .into(),
            ),
            Self::UnnecessaryOptionsWithoutReferences(option) => Some(format!(
                "Remove the {} option, as no tables are being added.",
                option
            )),
            _ => None,
        }
    }
}