Skip to main content

operator/
relational.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Schema inference for the relational (external table) engine: connects to a
16//! remote MySQL database and maps its column types to GreptimeDB
17//! [`ConcreteDataType`]s at `CREATE EXTERNAL TABLE` time.
18//!
19//! Types that cannot be mapped faithfully (e.g. `BIT`, spatial types, a
20//! `DECIMAL` wider than 38 digits, or `TIME`) are rejected rather than
21//! silently degraded. A few types map with documented caveats — `DATETIME`
22//! and `TIMESTAMP` lose their timezone semantics (see `map_timestamp`).
23
24use std::collections::HashSet;
25use std::net::{IpAddr, ToSocketAddrs};
26use std::time::Duration;
27
28use common_error::ext::{BoxedError, PlainError};
29use common_error::status_code::StatusCode;
30use datatypes::prelude::ConcreteDataType;
31use mysql_async::prelude::Queryable;
32use snafu::{ResultExt, ensure};
33use table::requests::redact_connection;
34
35use crate::error::{
36    ConnectRemoteSnafu, FetchMetadataSnafu, InvalidRemoteTableSnafu, MissingRemoteSchemaSnafu,
37    NotSupportedSnafu, RemoteTableNotFoundSnafu, Result,
38};
39
40/// Connect + handshake timeout for `CREATE EXTERNAL TABLE`; a silently
41/// dropping host would otherwise hang the DDL until the OS timeout.
42const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
43const QUERY_TIMEOUT: Duration = Duration::from_secs(10);
44
45/// A remote column already mapped to a GreptimeDB [`ConcreteDataType`].
46#[derive(Debug, Clone, PartialEq)]
47pub struct RelationalColumn {
48    pub name: String,
49    pub data_type: ConcreteDataType,
50}
51
52/// A MySQL column type as reported by `INFORMATION_SCHEMA.COLUMNS`.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct MySqlColumnType {
55    /// `DATA_TYPE` in lowercase, e.g. `tinyint`, `bigint`, `decimal`, `varchar`.
56    pub data_type: String,
57    /// Whether `UNSIGNED` is present (from `COLUMN_TYPE`, e.g. `bigint unsigned`).
58    pub unsigned: bool,
59    /// `NUMERIC_PRECISION` for `decimal` / `numeric`.
60    pub precision: Option<u64>,
61    /// `NUMERIC_SCALE` for `decimal` / `numeric`.
62    pub scale: Option<i64>,
63    /// `DATETIME_PRECISION` for `time` / `datetime` / `timestamp`.
64    pub fsp: Option<u8>,
65}
66
67/// A remote column read from `INFORMATION_SCHEMA.COLUMNS`, before its type is
68/// mapped to a GreptimeDB [`ConcreteDataType`].
69#[derive(Debug, Clone, PartialEq)]
70pub struct MySqlColumn {
71    pub name: String,
72    pub column_type: MySqlColumnType,
73}
74
75#[cfg(test)]
76impl MySqlColumnType {
77    pub fn new(data_type: impl Into<String>) -> Self {
78        Self {
79            data_type: data_type.into(),
80            unsigned: false,
81            precision: None,
82            scale: None,
83            fsp: None,
84        }
85    }
86
87    pub fn with_unsigned(mut self, unsigned: bool) -> Self {
88        self.unsigned = unsigned;
89        self
90    }
91
92    pub fn with_decimal(mut self, precision: u64, scale: i64) -> Self {
93        self.precision = Some(precision);
94        self.scale = Some(scale);
95        self
96    }
97
98    pub fn with_fsp(mut self, fsp: u8) -> Self {
99        self.fsp = Some(fsp);
100        self
101    }
102}
103
104/// Maps a MySQL column type to a GreptimeDB [`ConcreteDataType`].
105pub fn map_mysql_column_type(col: &MySqlColumnType) -> Result<ConcreteDataType> {
106    let unsigned = col.unsigned;
107    match col.data_type.as_str() {
108        "tinyint" => Ok(if unsigned {
109            ConcreteDataType::uint8_datatype()
110        } else {
111            ConcreteDataType::int8_datatype()
112        }),
113        "smallint" => Ok(if unsigned {
114            ConcreteDataType::uint16_datatype()
115        } else {
116            ConcreteDataType::int16_datatype()
117        }),
118        "mediumint" => Ok(if unsigned {
119            ConcreteDataType::uint32_datatype()
120        } else {
121            ConcreteDataType::int32_datatype()
122        }),
123        "int" | "integer" => Ok(if unsigned {
124            ConcreteDataType::uint32_datatype()
125        } else {
126            ConcreteDataType::int32_datatype()
127        }),
128        "bigint" => Ok(if unsigned {
129            ConcreteDataType::uint64_datatype()
130        } else {
131            ConcreteDataType::int64_datatype()
132        }),
133        "float" => Ok(ConcreteDataType::float32_datatype()),
134        // `REAL` is an alias for `DOUBLE` unless the `REAL_AS_FLOAT` SQL mode
135        // is enabled, in which case it means `FLOAT` (4 bytes). We always map
136        // it to float64 — a harmless widening under that mode (no data lost).
137        "double" | "real" => Ok(ConcreteDataType::float64_datatype()),
138        "decimal" | "numeric" => map_decimal(col.precision, col.scale),
139        "char" | "varchar" | "tinytext" | "text" | "mediumtext" | "longtext" | "enum" | "set" => {
140            Ok(ConcreteDataType::string_datatype())
141        }
142        "binary" | "varbinary" | "tinyblob" | "blob" | "mediumblob" | "longblob" => {
143            Ok(ConcreteDataType::binary_datatype())
144        }
145        "date" => Ok(ConcreteDataType::date_datatype()),
146        "datetime" | "timestamp" => Ok(map_timestamp(col.fsp)),
147        "year" => Ok(ConcreteDataType::int16_datatype()),
148        "json" => Ok(ConcreteDataType::json_datatype()),
149        other => unsupported(other),
150    }
151}
152
153fn map_decimal(precision: Option<u64>, scale: Option<i64>) -> Result<ConcreteDataType> {
154    // MySQL `DECIMAL` defaults to (10, 0).
155    let precision = precision.unwrap_or(10);
156    let scale = scale.unwrap_or(0);
157    if precision > 38 {
158        return unsupported(format!("`DECIMAL({precision}, {scale})` (precision > 38)"));
159    }
160    if scale < 0 || scale as u64 > precision {
161        return unsupported(format!("`DECIMAL({precision}, {scale})` (invalid scale)"));
162    }
163    Ok(ConcreteDataType::decimal128_datatype(
164        precision as u8,
165        scale as i8,
166    ))
167}
168
169fn map_timestamp(fsp: Option<u8>) -> ConcreteDataType {
170    // NOTE: MySQL `DATETIME` is a literal wall-clock value while `TIMESTAMP` is
171    // normalized to UTC on the server (and converted back on read using the
172    // session `time_zone`). Both are mapped to GreptimeDB's timezone-less
173    // `Timestamp`; callers that need to distinguish them should consult the
174    // original `DATA_TYPE`.
175    match fsp.unwrap_or(0) {
176        0 => ConcreteDataType::timestamp_second_datatype(),
177        1..=3 => ConcreteDataType::timestamp_millisecond_datatype(),
178        _ => ConcreteDataType::timestamp_microsecond_datatype(),
179    }
180}
181
182fn unsupported(what: impl std::fmt::Display) -> Result<ConcreteDataType> {
183    NotSupportedSnafu {
184        feat: format!("map MySQL type {what}"),
185    }
186    .fail()
187}
188
189/// Parses `host` as a literal IP address, stripping the URL-level brackets that
190/// wrap an IPv6 literal (e.g. `[::1]` → `::1`). Returns `None` when `host` is a
191/// hostname rather than a literal.
192fn parse_host_literal(host: &str) -> Option<IpAddr> {
193    let stripped = host.trim_matches(|c| c == '[' || c == ']');
194    stripped.parse::<IpAddr>().ok()
195}
196
197/// Resolves `host` to the full list of IP addresses the TCP dial should try, so
198/// a host backed by several A/AAAA records can fall back when one is unreachable.
199///
200/// A literal IP address is returned as a single-element list without a DNS
201/// lookup; otherwise the hostname is resolved to all of its addresses.
202async fn resolve_host_ips(connection: &str, host: &str) -> Result<Vec<IpAddr>> {
203    if let Some(ip) = parse_host_literal(host) {
204        return Ok(vec![ip]);
205    }
206
207    let host_owned = host.to_owned();
208    let addrs = tokio::time::timeout(
209        CONNECT_TIMEOUT,
210        tokio::task::spawn_blocking(move || {
211            (host_owned.as_str(), 0)
212                .to_socket_addrs()
213                .map(|it| it.collect::<Vec<_>>())
214        }),
215    )
216    .await
217    .map_err(|_| box_timeout_error("resolving the remote host", CONNECT_TIMEOUT))
218    .and_then(|res| res.map_err(|e| box_foreign_error(e, connection)))
219    .and_then(|res| res.map_err(|e| box_foreign_error(e, connection)))
220    .with_context(|_| ConnectRemoteSnafu {
221        connection: redact_connection(connection),
222    })?;
223
224    let ips: Vec<IpAddr> = addrs.into_iter().map(|addr| addr.ip()).collect();
225    if ips.is_empty() {
226        return Err(box_foreign_error(
227            std::io::Error::new(
228                std::io::ErrorKind::AddrNotAvailable,
229                format!("the host `{host}` resolved to no IP addresses"),
230            ),
231            connection,
232        ))
233        .context(ConnectRemoteSnafu {
234            connection: redact_connection(connection),
235        });
236    }
237    Ok(ips)
238}
239
240/// Parses the connection DSN and, for TCP connections, resolves the host to
241/// candidate IP addresses. When an explicit Unix socket is configured
242/// (`?socket=/path`), mysql_async dials the socket path directly, so the host
243/// is a placeholder and DNS resolution is skipped entirely.
244async fn build_mysql_opts(connection: &str) -> Result<mysql_async::Opts> {
245    let opts = mysql_async::Opts::from_url(connection)
246        .map_err(|e| box_foreign_error(e, connection))
247        .with_context(|_| ConnectRemoteSnafu {
248            connection: redact_connection(connection),
249        })?;
250
251    // A Unix-socket connection has no TCP host to resolve; an unresolvable
252    // placeholder hostname must not prevent connecting via the socket path.
253    if opts.socket().is_some() {
254        return Ok(opts);
255    }
256
257    let host = opts.ip_or_hostname().to_owned();
258    let ips = resolve_host_ips(connection, &host).await?;
259    // Keep the original hostname in the URL: TLS uses it for SNI and
260    // certificate (SAN) validation, so it must not be replaced by an IP. The
261    // resolved IPs are handed to the TCP layer separately via `resolved_ips`.
262    Ok(mysql_async::Opts::from(
263        mysql_async::OptsBuilder::from_opts(opts).resolved_ips(Some(ips)),
264    ))
265}
266
267/// A raw `INFORMATION_SCHEMA.COLUMNS` row decoded by the driver:
268/// (`name`, `data_type`, `column_type`, `precision`, `scale`, `fsp`).
269type RawColumnRow = (
270    String,
271    String,
272    String,
273    Option<i64>,
274    Option<i64>,
275    Option<i64>,
276);
277
278/// Connects to the remote MySQL instance and reads the column list of
279/// `remote_table` from `INFORMATION_SCHEMA.COLUMNS`. Each column keeps its
280/// driver-reported type, so callers decide which columns to map to a
281/// GreptimeDB [`ConcreteDataType`].
282pub async fn fetch_mysql_columns(connection: &str, remote_table: &str) -> Result<Vec<MySqlColumn>> {
283    let (schema, table) = split_remote_table(remote_table);
284    ensure!(
285        !table.is_empty(),
286        InvalidRemoteTableSnafu {
287            remote_table: remote_table.to_string(),
288        }
289    );
290
291    let opts = build_mysql_opts(connection).await?;
292    let default_schema = opts.db_name().map(str::to_string);
293    let mut conn = tokio::time::timeout(CONNECT_TIMEOUT, mysql_async::Conn::new(opts))
294        .await
295        .map_err(|_| box_timeout_error("connecting to the remote database", CONNECT_TIMEOUT))
296        .and_then(|res| res.map_err(|e| box_foreign_error(e, connection)))
297        .with_context(|_| ConnectRemoteSnafu {
298            connection: redact_connection(connection),
299        })?;
300    let schema = schema
301        .filter(|s| !s.is_empty())
302        .map(str::to_string)
303        .or(default_schema)
304        .unwrap_or_default();
305    ensure!(
306        !schema.is_empty(),
307        MissingRemoteSchemaSnafu {
308            remote_table: remote_table.to_string(),
309        }
310    );
311    let table = table.to_string();
312
313    let sql = "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, \
314               CAST(NUMERIC_PRECISION AS SIGNED), CAST(NUMERIC_SCALE AS SIGNED), \
315               CAST(DATETIME_PRECISION AS SIGNED) \
316               FROM INFORMATION_SCHEMA.COLUMNS \
317               WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION";
318
319    let rows: Vec<RawColumnRow> =
320        tokio::time::timeout(QUERY_TIMEOUT, conn.exec(sql, (schema, table)))
321            .await
322            .map_err(|_| {
323                box_timeout_error(
324                    "fetching column metadata from the remote database",
325                    QUERY_TIMEOUT,
326                )
327            })
328            .and_then(|res| res.map_err(|e| box_foreign_error(e, connection)))
329            .context(FetchMetadataSnafu {
330                remote_table: remote_table.to_string(),
331            })?;
332    let _ = conn.disconnect().await;
333
334    ensure!(
335        !rows.is_empty(),
336        RemoteTableNotFoundSnafu {
337            table: remote_table.to_string(),
338        }
339    );
340
341    let mut columns = Vec::with_capacity(rows.len());
342    for (name, data_type, column_type, precision, scale, fsp) in rows {
343        let column_type = MySqlColumnType {
344            data_type: data_type.to_ascii_lowercase(),
345            unsigned: column_type.to_ascii_lowercase().contains("unsigned"),
346            precision: precision.map(|v| v as u64),
347            scale,
348            fsp: fsp.map(|v| v as u8),
349        };
350        columns.push(MySqlColumn { name, column_type });
351    }
352
353    Ok(columns)
354}
355
356/// Maps raw MySQL columns to GreptimeDB [`ConcreteDataType`]s via
357/// [`map_mysql_column_type`].
358///
359/// `selected` controls which columns are mapped:
360/// - `Some(names)`: map only the named columns, ignoring the rest. This is the
361///   declared form of `CREATE EXTERNAL TABLE`, where the user lists a subset of
362///   the remote table's columns.
363/// - `None`: map every column, preserving their remote order. This is the
364///   inferred form, which exposes the whole remote table.
365pub fn map_mysql_columns(
366    raw: &[MySqlColumn],
367    selected: Option<&HashSet<&str>>,
368) -> Result<Vec<RelationalColumn>> {
369    raw.iter()
370        .filter(|column| selected.is_none_or(|names| names.contains(column.name.as_str())))
371        .map(|column| {
372            Ok(RelationalColumn {
373                name: column.name.clone(),
374                data_type: map_mysql_column_type(&column.column_type)?,
375            })
376        })
377        .collect()
378}
379
380/// Boxes a foreign driver error into a [`BoxedError`]. The message is scrubbed:
381/// if the driver echoes the connection DSN (which carries the password), it is
382/// replaced by its redacted form so credentials never leak.
383fn box_foreign_error(
384    e: impl std::error::Error + Send + Sync + 'static,
385    connection: &str,
386) -> BoxedError {
387    let mut message = e.to_string();
388    if message.contains(connection) {
389        message = message.replace(connection, &redact_connection(connection));
390    }
391    BoxedError::new(PlainError::new(message, StatusCode::Internal))
392}
393
394fn box_timeout_error(what: &str, timeout: Duration) -> BoxedError {
395    BoxedError::new(PlainError::new(
396        format!("{what} timed out after {timeout:?}"),
397        StatusCode::DeadlineExceeded,
398    ))
399}
400
401/// Splits `remote_table` into an optional schema qualifier and the bare table
402/// name: `"schema.table"` → `(Some("schema"), "table")`, `"table"` → `(None, "table")`.
403fn split_remote_table(remote_table: &str) -> (Option<&str>, &str) {
404    match remote_table.rfind('.') {
405        Some(i) => (Some(&remote_table[..i]), &remote_table[i + 1..]),
406        None => (None, remote_table),
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413
414    #[test]
415    fn test_split_remote_table() {
416        assert_eq!(split_remote_table("table"), (None, "table"));
417        assert_eq!(
418            split_remote_table("schema.table"),
419            (Some("schema"), "table")
420        );
421        // Leading dot yields an empty schema; callers must treat it as "no schema".
422        assert_eq!(split_remote_table(".table"), (Some(""), "table"));
423        // Trailing dot yields an empty table; callers must reject it.
424        assert_eq!(split_remote_table("db."), (Some("db"), ""));
425        // `rfind` splits on the last dot.
426        assert_eq!(split_remote_table("a.b.c"), (Some("a.b"), "c"));
427    }
428
429    #[test]
430    fn test_parse_host_literal() {
431        // IPv6 literals arrive from URL parsing wrapped in brackets; the brackets
432        // are URL-level notation and must be stripped before parsing.
433        assert_eq!(
434            parse_host_literal("[::1]"),
435            Some(IpAddr::V6(std::net::Ipv6Addr::LOCALHOST))
436        );
437        assert_eq!(
438            parse_host_literal("::1"),
439            Some(IpAddr::V6(std::net::Ipv6Addr::LOCALHOST))
440        );
441        assert_eq!(
442            parse_host_literal("127.0.0.1"),
443            Some(IpAddr::V4(std::net::Ipv4Addr::LOCALHOST))
444        );
445        // Hostnames are left to DNS resolution.
446        assert_eq!(parse_host_literal("db.example.com"), None);
447        assert_eq!(parse_host_literal(""), None);
448    }
449
450    #[test]
451    fn test_integer_types() {
452        assert_eq!(
453            map_mysql_column_type(&MySqlColumnType::new("tinyint")).unwrap(),
454            ConcreteDataType::int8_datatype()
455        );
456        assert_eq!(
457            map_mysql_column_type(&MySqlColumnType::new("tinyint").with_unsigned(true)).unwrap(),
458            ConcreteDataType::uint8_datatype()
459        );
460        assert_eq!(
461            map_mysql_column_type(&MySqlColumnType::new("mediumint")).unwrap(),
462            ConcreteDataType::int32_datatype()
463        );
464        assert_eq!(
465            map_mysql_column_type(&MySqlColumnType::new("bigint")).unwrap(),
466            ConcreteDataType::int64_datatype()
467        );
468        assert_eq!(
469            map_mysql_column_type(&MySqlColumnType::new("bigint").with_unsigned(true)).unwrap(),
470            ConcreteDataType::uint64_datatype()
471        );
472    }
473
474    #[test]
475    fn test_float_and_decimal() {
476        assert_eq!(
477            map_mysql_column_type(&MySqlColumnType::new("float")).unwrap(),
478            ConcreteDataType::float32_datatype()
479        );
480        assert_eq!(
481            map_mysql_column_type(&MySqlColumnType::new("double")).unwrap(),
482            ConcreteDataType::float64_datatype()
483        );
484        assert_eq!(
485            map_mysql_column_type(&MySqlColumnType::new("real")).unwrap(),
486            ConcreteDataType::float64_datatype()
487        );
488        assert_eq!(
489            map_mysql_column_type(&MySqlColumnType::new("decimal").with_decimal(12, 2)).unwrap(),
490            ConcreteDataType::decimal128_datatype(12, 2)
491        );
492        // Precision > 38 is rejected rather than silently degraded.
493        assert!(
494            map_mysql_column_type(&MySqlColumnType::new("decimal").with_decimal(65, 30)).is_err()
495        );
496    }
497
498    #[test]
499    fn test_string_and_binary() {
500        assert_eq!(
501            map_mysql_column_type(&MySqlColumnType::new("varchar")).unwrap(),
502            ConcreteDataType::string_datatype()
503        );
504        assert_eq!(
505            map_mysql_column_type(&MySqlColumnType::new("char")).unwrap(),
506            ConcreteDataType::string_datatype()
507        );
508        assert_eq!(
509            map_mysql_column_type(&MySqlColumnType::new("text")).unwrap(),
510            ConcreteDataType::string_datatype()
511        );
512        assert_eq!(
513            map_mysql_column_type(&MySqlColumnType::new("enum")).unwrap(),
514            ConcreteDataType::string_datatype()
515        );
516        assert_eq!(
517            map_mysql_column_type(&MySqlColumnType::new("set")).unwrap(),
518            ConcreteDataType::string_datatype()
519        );
520        assert_eq!(
521            map_mysql_column_type(&MySqlColumnType::new("blob")).unwrap(),
522            ConcreteDataType::binary_datatype()
523        );
524        assert_eq!(
525            map_mysql_column_type(&MySqlColumnType::new("binary")).unwrap(),
526            ConcreteDataType::binary_datatype()
527        );
528    }
529
530    #[test]
531    fn test_datetime_types() {
532        assert_eq!(
533            map_mysql_column_type(&MySqlColumnType::new("date")).unwrap(),
534            ConcreteDataType::date_datatype()
535        );
536        assert_eq!(
537            map_mysql_column_type(&MySqlColumnType::new("datetime")).unwrap(),
538            ConcreteDataType::timestamp_second_datatype()
539        );
540        assert_eq!(
541            map_mysql_column_type(&MySqlColumnType::new("datetime").with_fsp(3)).unwrap(),
542            ConcreteDataType::timestamp_millisecond_datatype()
543        );
544        assert_eq!(
545            map_mysql_column_type(&MySqlColumnType::new("datetime").with_fsp(6)).unwrap(),
546            ConcreteDataType::timestamp_microsecond_datatype()
547        );
548        assert_eq!(
549            map_mysql_column_type(&MySqlColumnType::new("timestamp")).unwrap(),
550            ConcreteDataType::timestamp_second_datatype()
551        );
552        assert!(map_mysql_column_type(&MySqlColumnType::new("time")).is_err());
553        assert_eq!(
554            map_mysql_column_type(&MySqlColumnType::new("year")).unwrap(),
555            ConcreteDataType::int16_datatype()
556        );
557    }
558
559    #[test]
560    fn test_json_and_rejected() {
561        assert_eq!(
562            map_mysql_column_type(&MySqlColumnType::new("json")).unwrap(),
563            ConcreteDataType::json_datatype()
564        );
565        assert!(map_mysql_column_type(&MySqlColumnType::new("bit")).is_err());
566        assert!(map_mysql_column_type(&MySqlColumnType::new("geometry")).is_err());
567        assert!(map_mysql_column_type(&MySqlColumnType::new("point")).is_err());
568    }
569
570    #[test]
571    fn test_map_mysql_columns_selected_subset() {
572        let raw = vec![
573            MySqlColumn {
574                name: "id".into(),
575                column_type: MySqlColumnType::new("int"),
576            },
577            MySqlColumn {
578                name: "ts".into(),
579                column_type: MySqlColumnType::new("timestamp"),
580            },
581            MySqlColumn {
582                name: "shape".into(),
583                column_type: MySqlColumnType::new("geometry"),
584            },
585        ];
586
587        // Declared form: mapping a subset skips the unselected, unsupported
588        // `shape` column.
589        let selected: std::collections::HashSet<&str> = ["id", "ts"].into_iter().collect();
590        let mapped = map_mysql_columns(&raw, Some(&selected)).unwrap();
591        assert_eq!(2, mapped.len());
592        let names: Vec<&str> = mapped.iter().map(|column| column.name.as_str()).collect();
593        assert_eq!(names, ["id", "ts"]);
594
595        // Declared form: selecting the unsupported column maps it and fails.
596        let selected: std::collections::HashSet<&str> = ["id", "shape"].into_iter().collect();
597        assert!(map_mysql_columns(&raw, Some(&selected)).is_err());
598
599        // Inferred form: every column is mapped, so the unsupported column
600        // still fails.
601        assert!(map_mysql_columns(&raw, None).is_err());
602    }
603
604    #[tokio::test]
605    async fn test_build_mysql_opts_skips_dns_for_socket() {
606        // `unresolvable.invalid` (RFC 2606) has no DNS record; if the socket
607        // branch did not short-circuit, `resolve_host_ips` would fail here.
608        let opts = build_mysql_opts(
609            "mysql://root:secret@unresolvable.invalid/db?socket=%2Ftmp%2Fmysql.sock",
610        )
611        .await
612        .unwrap();
613        assert_eq!(opts.socket(), Some("/tmp/mysql.sock"));
614        assert!(opts.resolved_ips().is_none());
615    }
616}