Skip to main content

mz_mysql_util/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! MySQL utility library.
11
12mod tunnel;
13use std::time::Duration;
14
15use mz_aws_util::rds::RdsTokenError;
16pub use tunnel::{
17    Config, DEFAULT_CONNECT_TIMEOUT, DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT,
18    DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME, DEFAULT_SNAPSHOT_WAIT_TIMEOUT, DEFAULT_TCP_KEEPALIVE,
19    MySqlConn, TimeoutConfig, TunnelConfig,
20};
21
22mod desc;
23pub use desc::{
24    MySqlColumnDesc, MySqlKeyDesc, MySqlTableDesc, ProtoMySqlColumnDesc, ProtoMySqlKeyDesc,
25    ProtoMySqlTableDesc,
26};
27
28pub mod schema_change;
29pub use schema_change::{SchemaChange, SchemaChangeError};
30
31mod replication;
32pub use replication::{
33    ensure_full_row_binlog_format, ensure_gtid_consistency, ensure_replication_commit_order,
34    query_sys_var,
35};
36
37pub mod schemas;
38pub use schemas::{
39    MySqlTableSchema, QualifiedTableRef, SYSTEM_SCHEMAS, SchemaRequest, schema_info,
40};
41
42pub mod privileges;
43pub use privileges::validate_source_privileges;
44
45pub mod decoding;
46pub use decoding::pack_mysql_row;
47
48pub mod probe;
49pub use probe::{KeyProber, MAX_KEY_LENGTH};
50
51pub mod partition;
52pub use partition::{PartitionParams, partition_table};
53
54#[derive(Debug, Clone)]
55pub struct UnsupportedDataType {
56    pub column_type: String,
57    pub qualified_table_name: String,
58    pub column_name: String,
59    pub intended_type: Option<String>,
60}
61
62impl std::fmt::Display for UnsupportedDataType {
63    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
64        match &self.intended_type {
65            Some(intended_type) => write!(
66                f,
67                "'{}.{}' of type '{}' represented as: '{}'",
68                self.qualified_table_name, self.column_name, self.column_type, intended_type
69            ),
70            None => write!(
71                f,
72                "'{}.{}' of type '{}'",
73                self.qualified_table_name, self.column_name, self.column_type
74            ),
75        }
76    }
77}
78
79#[derive(Debug, Clone)]
80pub struct MissingPrivilege {
81    pub privilege: String,
82    pub qualified_table_name: String,
83}
84
85impl std::fmt::Display for MissingPrivilege {
86    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
87        write!(
88            f,
89            "Missing privilege '{}' for '{}'",
90            self.privilege, self.qualified_table_name
91        )
92    }
93}
94
95#[derive(Debug, thiserror::Error)]
96pub enum MySqlError {
97    #[error("error validating privileges: {}", itertools::join(.0, ", "))]
98    MissingPrivileges(Vec<MissingPrivilege>),
99    #[error("error creating mysql connection with config: {0}")]
100    InvalidClientConfig(String),
101    #[error("error setting up ssh: {0}")]
102    Ssh(#[source] anyhow::Error),
103    #[error("error decoding value for '{qualified_table_name}' column '{column_name}': {error}")]
104    ValueDecodeError {
105        column_name: String,
106        qualified_table_name: String,
107        error: String,
108    },
109    #[error("non-UTF-8 key value in '{qualified_table_name}' column '{column_name}': {error}")]
110    NonUtf8KeyValue {
111        qualified_table_name: String,
112        column_name: String,
113        error: String,
114    },
115    #[error(
116        "missing row estimate in '{qualified_table_name}' for key range ({lower_bound}, {upper_bound})"
117    )]
118    MissingRowEstimate {
119        qualified_table_name: String,
120        /// Redacted at construction, safe to log.
121        lower_bound: String,
122        /// Redacted at construction, safe to log.
123        upper_bound: String,
124    },
125    #[error("unsupported data types: {}", itertools::join(.columns, ", "))]
126    UnsupportedDataTypes { columns: Vec<UnsupportedDataType> },
127    #[error(
128        "duplicated column names in table '{qualified_table_name}': {}",
129        itertools::join(.columns, ", ")
130    )]
131    DuplicatedColumnNames {
132        qualified_table_name: String,
133        columns: Vec<String>,
134    },
135    #[error("invalid mysql system setting '{setting}'. Expected '{expected}'. Got '{actual}'.")]
136    InvalidSystemSetting {
137        setting: String,
138        expected: String,
139        actual: String,
140    },
141    /// Any other error we bail on.
142    #[error(transparent)]
143    Generic(#[from] anyhow::Error),
144    /// A mysql_async error.
145    #[error(transparent)]
146    MySql(#[from] mysql_async::Error),
147    #[error("connection attempt timed out after {0:?}")]
148    ConnectionTimeout(Duration),
149    /// The MySQL client panicked while connecting, for example on an
150    /// authentication exchange it does not support.
151    #[error("connection attempt failed, the MySQL client panicked: {0}")]
152    ConnectionPanicked(String),
153    /// Error retrieving AWS authorization token
154    #[error(transparent)]
155    AwsTokenError(#[from] RdsTokenError),
156}
157
158/// Quotes MySQL identifiers. [See MySQL quote_identifier()](https://github.com/mysql/mysql-sys/blob/master/functions/quote_identifier.sql)
159pub fn quote_identifier(identifier: &str) -> String {
160    let mut escaped = identifier.replace("`", "``");
161    escaped.insert(0, '`');
162    escaped.push('`');
163    escaped
164}
165
166// NOTE: this error was renamed between MySQL 5.7 and 8.0
167// https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html#error_er_source_fatal_error_reading_binlog
168// https://dev.mysql.com/doc/mysql-errors/5.7/en/server-error-reference.html#error_er_master_fatal_error_reading_binlog
169pub const ER_SOURCE_FATAL_ERROR_READING_BINLOG_CODE: u16 = 1236;
170
171// https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html#error_er_no_such_table
172pub const ER_NO_SUCH_TABLE: u16 = 1146;
173
174#[cfg(test)]
175mod tests {
176
177    use super::quote_identifier;
178    #[mz_ore::test]
179    fn test_identifier_quoting() {
180        let expected = vec!["`a`", "`naughty``sql`", "```;naughty;sql;```"];
181        let input = ["a", "naughty`sql", "`;naughty;sql;`"]
182            .iter()
183            .map(|raw_str| quote_identifier(raw_str))
184            .collect::<Vec<_>>();
185        assert_eq!(expected, input);
186    }
187}