1use 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
40const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
43const QUERY_TIMEOUT: Duration = Duration::from_secs(10);
44
45#[derive(Debug, Clone, PartialEq)]
47pub struct RelationalColumn {
48 pub name: String,
49 pub data_type: ConcreteDataType,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct MySqlColumnType {
55 pub data_type: String,
57 pub unsigned: bool,
59 pub precision: Option<u64>,
61 pub scale: Option<i64>,
63 pub fsp: Option<u8>,
65}
66
67#[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
104pub 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 "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 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 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
189fn parse_host_literal(host: &str) -> Option<IpAddr> {
193 let stripped = host.trim_matches(|c| c == '[' || c == ']');
194 stripped.parse::<IpAddr>().ok()
195}
196
197async 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
240async 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 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 Ok(mysql_async::Opts::from(
263 mysql_async::OptsBuilder::from_opts(opts).resolved_ips(Some(ips)),
264 ))
265}
266
267type RawColumnRow = (
270 String,
271 String,
272 String,
273 Option<i64>,
274 Option<i64>,
275 Option<i64>,
276);
277
278pub 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
356pub 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
380fn 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
401fn 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 assert_eq!(split_remote_table(".table"), (Some(""), "table"));
423 assert_eq!(split_remote_table("db."), (Some("db"), ""));
425 assert_eq!(split_remote_table("a.b.c"), (Some("a.b"), "c"));
427 }
428
429 #[test]
430 fn test_parse_host_literal() {
431 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 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 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 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 let selected: std::collections::HashSet<&str> = ["id", "shape"].into_iter().collect();
597 assert!(map_mysql_columns(&raw, Some(&selected)).is_err());
598
599 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 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}