Skip to main content

sql_splitter/convert/
types.rs

1//! Data type mapping between SQL dialects.
2//!
3//! Handles conversion of data types including:
4//! - Integer types (TINYINT, SMALLINT, INT, BIGINT)
5//! - Float types (FLOAT, DOUBLE, DECIMAL)
6//! - String types (CHAR, VARCHAR, TEXT)
7//! - Binary types (BLOB, BYTEA)
8//! - Date/time types (DATE, DATETIME, TIMESTAMP)
9//! - Special types (ENUM, SET, JSON)
10
11use crate::parser::SqlDialect;
12use once_cell::sync::Lazy;
13use regex::{Captures, Regex};
14
15use super::warnings::{ConvertWarning, WarningCollector};
16
17/// Map a single column's `source_type` from `from` to `to`, reusing the same
18/// regex-driven rules [`TypeMapper::convert`] applies to a whole statement.
19///
20/// This is the seam the synthetic-data renderer (`render::ddl`) calls
21/// instead of maintaining its own generation-only type mapping: a column's
22/// `source_type` (e.g. `"VARCHAR(255)"`) is itself a valid input to
23/// [`TypeMapper::convert`], since every rule matches on the type token with
24/// word boundaries rather than requiring surrounding `CREATE TABLE` context.
25///
26/// Same-dialect conversions are the identity (returned as-is, no warning).
27/// A conversion that narrows a MySQL `ENUM`/`SET` to a plain string type
28/// records a [`ConvertWarning::LossyConversion`] so callers that surface
29/// warnings (e.g. `--emit-config`) can report it.
30pub(crate) fn map_column_type(
31    source_type: &str,
32    from: SqlDialect,
33    to: SqlDialect,
34    warnings: &mut WarningCollector,
35) -> String {
36    if from == to {
37        return source_type.to_string();
38    }
39    let mapped = TypeMapper::convert(source_type, from, to);
40    if is_narrowed_by_conversion(source_type, to) {
41        warnings.add(ConvertWarning::LossyConversion {
42            from_type: source_type.to_string(),
43            to_type: mapped.clone(),
44            table: None,
45            column: None,
46        });
47    }
48    mapped
49}
50
51/// Whether mapping `source_type` to the `to` dialect loses type semantics the
52/// target cannot preserve — a lossy conversion the caller should warn about (and
53/// fail under `--strict`):
54///
55/// * `ENUM`/`SET` have no equivalent outside MySQL and always collapse to a
56///   plain string, for every target dialect.
57/// * `JSON`/`JSONB` become an unvalidated text column on engines without a JSON
58///   type (SQLite, MSSQL).
59/// * `UUID`/`UNIQUEIDENTIFIER` lose their fixed 128-bit domain when stored as
60///   text (MySQL, SQLite).
61fn is_narrowed_by_conversion(source_type: &str, to: SqlDialect) -> bool {
62    let lower = source_type.to_lowercase();
63    if lower.contains("enum(") || lower.contains("set(") {
64        return true;
65    }
66    if lower.contains("json") && matches!(to, SqlDialect::Sqlite | SqlDialect::Mssql) {
67        return true;
68    }
69    if (lower.contains("uuid") || lower.contains("uniqueidentifier"))
70        && matches!(to, SqlDialect::MySql | SqlDialect::Sqlite)
71    {
72        return true;
73    }
74    // An unbounded VARCHAR holds up to 1GB in PostgreSQL and is unlimited in
75    // SQLite, but MySQL and SQL Server both require a width and have no
76    // unbounded alternative legal in every position, so it maps to
77    // VARCHAR(255) — anything longer is truncated at load time.
78    if is_unbounded_varchar(source_type) && matches!(to, SqlDialect::MySql | SqlDialect::Mssql) {
79        return true;
80    }
81    // Exact fixed-point (DECIMAL/NUMERIC) becomes a binary float (REAL) on
82    // SQLite, silently losing precision.
83    if (lower.contains("decimal") || lower.contains("numeric")) && to == SqlDialect::Sqlite {
84        return true;
85    }
86    // A time-zone-bearing timestamp loses its zone when mapped to MySQL
87    // DATETIME (which has no tz). MSSQL keeps it via DATETIMEOFFSET, and the
88    // SQLite mapping renders TEXT that retains the zoned literal.
89    // ("without time zone" does not contain the substring "with time zone".)
90    if (lower.contains("timestamptz") || lower.contains("with time zone"))
91        && to == SqlDialect::MySql
92    {
93        return true;
94    }
95    false
96}
97
98/// Whether `source_type` is a variable-length string type declared without a
99/// length (`VARCHAR`, `CHARACTER VARYING`, …) — the form PostgreSQL allows and
100/// MySQL does not.
101fn is_unbounded_varchar(source_type: &str) -> bool {
102    RE_VARCHAR_DECL
103        .captures(source_type)
104        .is_some_and(|caps| caps.name("len").is_none())
105}
106
107/// Give every length-less VARCHAR declaration an explicit width, for targets
108/// that cannot store one without.
109///
110/// 255 rather than an unbounded type because every unbounded alternative is
111/// invalid in some position a column can occupy: MySQL `TEXT` cannot carry a
112/// DEFAULT (ERROR 1101) or be a key without a prefix length (ERROR 1170), and
113/// SQL Server `VARCHAR(MAX)` cannot be an index key at all. pg_dump emits
114/// PRIMARY KEY and UNIQUE as separate ALTER statements, so the column
115/// definition alone never reveals whether a key is coming — only a width valid
116/// everywhere is safe. It also matches the ENUM and UUID rules alongside it.
117///
118/// Declarations that already carry a length are left exactly as they are, as is
119/// a `::` cast: those are removed wholesale by `strip_postgres_casts`, which
120/// matches bare identifiers and would leave a dangling `(255)` behind.
121///
122/// ponytail: fixed 255 truncates longer values (`map_column_type` records a
123/// LossyConversion for it); a configurable width is the upgrade path.
124fn size_unbounded_varchar(stmt: &str) -> String {
125    RE_VARCHAR_DECL
126        .replace_all(stmt, |caps: &Captures| {
127            if caps.name("cast").is_some() || caps.name("len").is_some() {
128                caps[0].to_string()
129            } else {
130                "VARCHAR(255)".to_string()
131            }
132        })
133        .to_string()
134}
135
136/// Type mapper for converting between dialects
137pub struct TypeMapper;
138
139impl TypeMapper {
140    /// Convert all data types in a statement
141    pub fn convert(stmt: &str, from: SqlDialect, to: SqlDialect) -> String {
142        let converted = Self::convert_dialect_pair(stmt, from, to);
143        if from == to {
144            return converted;
145        }
146
147        // MySQL and SQL Server both require an explicit length on VARCHAR, and
148        // they fail differently: MySQL rejects a bare declaration with ERROR
149        // 1064, while SQL Server quietly reads it as VARCHAR(1) and then throws
150        // Msg 2628 on the first row that does not fit. Applied per target rather
151        // than per dialect pair because every source that permits an unbounded
152        // declaration — PostgreSQL and SQLite — reaches both of them.
153        match to {
154            SqlDialect::MySql | SqlDialect::Mssql => size_unbounded_varchar(&converted),
155            _ => converted,
156        }
157    }
158
159    fn convert_dialect_pair(stmt: &str, from: SqlDialect, to: SqlDialect) -> String {
160        match (from, to) {
161            (SqlDialect::MySql, SqlDialect::Postgres) => Self::mysql_to_postgres(stmt),
162            (SqlDialect::MySql, SqlDialect::Sqlite) => Self::mysql_to_sqlite(stmt),
163            (SqlDialect::MySql, SqlDialect::Mssql) => Self::mysql_to_mssql(stmt),
164            (SqlDialect::Postgres, SqlDialect::MySql) => Self::postgres_to_mysql(stmt),
165            (SqlDialect::Postgres, SqlDialect::Sqlite) => Self::postgres_to_sqlite(stmt),
166            (SqlDialect::Postgres, SqlDialect::Mssql) => Self::postgres_to_mssql(stmt),
167            (SqlDialect::Sqlite, SqlDialect::MySql) => Self::sqlite_to_mysql(stmt),
168            (SqlDialect::Sqlite, SqlDialect::Postgres) => Self::sqlite_to_postgres(stmt),
169            (SqlDialect::Sqlite, SqlDialect::Mssql) => Self::sqlite_to_mssql(stmt),
170            (SqlDialect::Mssql, SqlDialect::MySql) => Self::mssql_to_mysql(stmt),
171            (SqlDialect::Mssql, SqlDialect::Postgres) => Self::mssql_to_postgres(stmt),
172            (SqlDialect::Mssql, SqlDialect::Sqlite) => Self::mssql_to_sqlite(stmt),
173            _ => stmt.to_string(),
174        }
175    }
176
177    /// Convert MySQL types to PostgreSQL
178    fn mysql_to_postgres(stmt: &str) -> String {
179        let mut result = stmt.to_string();
180
181        // Integer types - strip display width, PostgreSQL doesn't use it
182        result = RE_TINYINT_BOOL.replace_all(&result, "BOOLEAN").to_string();
183        result = RE_TINYINT.replace_all(&result, "SMALLINT").to_string();
184        result = RE_SMALLINT.replace_all(&result, "SMALLINT").to_string();
185        result = RE_MEDIUMINT.replace_all(&result, "INTEGER").to_string();
186        result = RE_INT_SIZE.replace_all(&result, "INTEGER").to_string();
187        result = RE_BIGINT_SIZE.replace_all(&result, "BIGINT").to_string();
188
189        // Float types
190        result = RE_DOUBLE
191            .replace_all(&result, "DOUBLE PRECISION")
192            .to_string();
193        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
194
195        // Text types
196        result = RE_LONGTEXT.replace_all(&result, "TEXT").to_string();
197        result = RE_MEDIUMTEXT.replace_all(&result, "TEXT").to_string();
198        result = RE_TINYTEXT.replace_all(&result, "TEXT").to_string();
199
200        // Binary types
201        result = RE_LONGBLOB.replace_all(&result, "BYTEA").to_string();
202        result = RE_MEDIUMBLOB.replace_all(&result, "BYTEA").to_string();
203        result = RE_TINYBLOB.replace_all(&result, "BYTEA").to_string();
204        result = RE_BLOB.replace_all(&result, "BYTEA").to_string();
205        result = RE_VARBINARY.replace_all(&result, "BYTEA").to_string();
206        result = RE_BINARY.replace_all(&result, "BYTEA").to_string();
207
208        // Date/time types
209        result = RE_DATETIME.replace_all(&result, "TIMESTAMP").to_string();
210
211        // JSON
212        result = RE_JSON.replace_all(&result, "JSONB").to_string();
213
214        // ENUM - convert to VARCHAR (with warning)
215        result = RE_ENUM.replace_all(&result, "VARCHAR(255)").to_string();
216
217        // SET - convert to VARCHAR (with warning)
218        result = RE_SET.replace_all(&result, "VARCHAR(255)").to_string();
219
220        // UNSIGNED - remove
221        result = RE_UNSIGNED.replace_all(&result, "").to_string();
222
223        // ZEROFILL - remove
224        result = RE_ZEROFILL.replace_all(&result, "").to_string();
225
226        result
227    }
228
229    /// Convert MySQL types to SQLite
230    fn mysql_to_sqlite(stmt: &str) -> String {
231        let mut result = stmt.to_string();
232
233        // SQLite is lenient with types, but we normalize for consistency
234
235        // Integer types - SQLite uses INTEGER
236        result = RE_TINYINT.replace_all(&result, "INTEGER").to_string();
237        result = RE_SMALLINT.replace_all(&result, "INTEGER").to_string();
238        result = RE_MEDIUMINT.replace_all(&result, "INTEGER").to_string();
239        result = RE_INT_SIZE.replace_all(&result, "INTEGER").to_string();
240        result = RE_BIGINT_SIZE.replace_all(&result, "INTEGER").to_string();
241
242        // Float types - SQLite uses REAL
243        result = RE_DOUBLE.replace_all(&result, "REAL").to_string();
244        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
245        result = RE_DECIMAL.replace_all(&result, "REAL").to_string();
246
247        // Text types - all become TEXT
248        result = RE_LONGTEXT.replace_all(&result, "TEXT").to_string();
249        result = RE_MEDIUMTEXT.replace_all(&result, "TEXT").to_string();
250        result = RE_TINYTEXT.replace_all(&result, "TEXT").to_string();
251        result = RE_VARCHAR.replace_all(&result, "TEXT").to_string();
252        result = RE_CHAR.replace_all(&result, "TEXT").to_string();
253
254        // Binary types - SQLite uses BLOB
255        result = RE_LONGBLOB.replace_all(&result, "BLOB").to_string();
256        result = RE_MEDIUMBLOB.replace_all(&result, "BLOB").to_string();
257        result = RE_TINYBLOB.replace_all(&result, "BLOB").to_string();
258        result = RE_VARBINARY.replace_all(&result, "BLOB").to_string();
259        result = RE_BINARY.replace_all(&result, "BLOB").to_string();
260
261        // Date/time - SQLite stores as TEXT or INTEGER
262        result = RE_DATETIME.replace_all(&result, "TEXT").to_string();
263        result = RE_TIMESTAMP.replace_all(&result, "TEXT").to_string();
264        result = RE_DATE.replace_all(&result, "TEXT").to_string();
265        result = RE_TIME.replace_all(&result, "TEXT").to_string();
266
267        // JSON - SQLite stores as TEXT
268        result = RE_JSON.replace_all(&result, "TEXT").to_string();
269
270        // ENUM/SET - convert to TEXT
271        result = RE_ENUM.replace_all(&result, "TEXT").to_string();
272        result = RE_SET.replace_all(&result, "TEXT").to_string();
273
274        // UNSIGNED - remove
275        result = RE_UNSIGNED.replace_all(&result, "").to_string();
276
277        // ZEROFILL - remove
278        result = RE_ZEROFILL.replace_all(&result, "").to_string();
279
280        result
281    }
282
283    /// Convert PostgreSQL types to MySQL
284    fn postgres_to_mysql(stmt: &str) -> String {
285        let mut result = stmt.to_string();
286
287        // SERIAL → INT AUTO_INCREMENT
288        result = RE_BIGSERIAL
289            .replace_all(&result, "BIGINT AUTO_INCREMENT")
290            .to_string();
291        result = RE_SERIAL
292            .replace_all(&result, "INT AUTO_INCREMENT")
293            .to_string();
294        result = RE_SMALLSERIAL
295            .replace_all(&result, "SMALLINT AUTO_INCREMENT")
296            .to_string();
297
298        // BYTEA → LONGBLOB
299        result = RE_BYTEA.replace_all(&result, "LONGBLOB").to_string();
300
301        // DOUBLE PRECISION → DOUBLE
302        result = RE_DOUBLE_PRECISION
303            .replace_all(&result, "DOUBLE")
304            .to_string();
305
306        // REAL → FLOAT
307        result = RE_REAL.replace_all(&result, "FLOAT").to_string();
308
309        // BOOLEAN → TINYINT(1)
310        result = RE_BOOLEAN.replace_all(&result, "TINYINT(1)").to_string();
311
312        // TIMESTAMPTZ → DATETIME
313        result = RE_TIMESTAMPTZ.replace_all(&result, "DATETIME").to_string();
314
315        // TIMESTAMP WITH TIME ZONE → DATETIME
316        result = RE_TIMESTAMP_WITH_TZ
317            .replace_all(&result, "DATETIME")
318            .to_string();
319
320        // TIMESTAMP WITHOUT TIME ZONE → DATETIME
321        result = RE_TIMESTAMP_NO_TZ
322            .replace_all(&result, "DATETIME")
323            .to_string();
324
325        // JSONB → JSON
326        result = RE_JSONB.replace_all(&result, "JSON").to_string();
327
328        // UUID → VARCHAR(36)
329        result = RE_UUID.replace_all(&result, "VARCHAR(36)").to_string();
330
331        result
332    }
333
334    /// Convert PostgreSQL types to SQLite
335    fn postgres_to_sqlite(stmt: &str) -> String {
336        let mut result = stmt.to_string();
337
338        // SERIAL → INTEGER (SQLite auto-increments INTEGER PRIMARY KEY)
339        result = RE_BIGSERIAL.replace_all(&result, "INTEGER").to_string();
340        result = RE_SERIAL.replace_all(&result, "INTEGER").to_string();
341        result = RE_SMALLSERIAL.replace_all(&result, "INTEGER").to_string();
342
343        // BYTEA → BLOB
344        result = RE_BYTEA.replace_all(&result, "BLOB").to_string();
345
346        // DOUBLE PRECISION → REAL
347        result = RE_DOUBLE_PRECISION.replace_all(&result, "REAL").to_string();
348
349        // BOOLEAN → INTEGER
350        result = RE_BOOLEAN.replace_all(&result, "INTEGER").to_string();
351
352        // Timestamps → TEXT
353        result = RE_TIMESTAMPTZ.replace_all(&result, "TEXT").to_string();
354        result = RE_TIMESTAMP_WITH_TZ
355            .replace_all(&result, "TEXT")
356            .to_string();
357        result = RE_TIMESTAMP_NO_TZ.replace_all(&result, "TEXT").to_string();
358
359        // JSONB/JSON → TEXT
360        result = RE_JSONB.replace_all(&result, "TEXT").to_string();
361        result = RE_JSON.replace_all(&result, "TEXT").to_string();
362
363        // UUID → TEXT
364        result = RE_UUID.replace_all(&result, "TEXT").to_string();
365
366        // VARCHAR → TEXT
367        result = RE_VARCHAR.replace_all(&result, "TEXT").to_string();
368
369        result
370    }
371
372    /// Convert SQLite types to MySQL
373    fn sqlite_to_mysql(stmt: &str) -> String {
374        let mut result = stmt.to_string();
375
376        // SQLite uses TEXT for everything, but we can preserve some type info
377        // REAL → DOUBLE
378        result = RE_REAL.replace_all(&result, "DOUBLE").to_string();
379
380        // BLOB stays BLOB
381        // TEXT stays TEXT
382        // INTEGER stays INTEGER (MySQL will handle it)
383
384        result
385    }
386
387    /// Convert SQLite types to PostgreSQL
388    fn sqlite_to_postgres(stmt: &str) -> String {
389        let mut result = stmt.to_string();
390
391        // REAL → DOUBLE PRECISION
392        result = RE_REAL.replace_all(&result, "DOUBLE PRECISION").to_string();
393
394        // BLOB → BYTEA
395        result = RE_BLOB.replace_all(&result, "BYTEA").to_string();
396
397        // INTEGER stays INTEGER
398        // TEXT stays TEXT
399
400        result
401    }
402
403    /// Convert MySQL types to MSSQL
404    fn mysql_to_mssql(stmt: &str) -> String {
405        let mut result = stmt.to_string();
406
407        // AUTO_INCREMENT → IDENTITY(1,1) (handled elsewhere in convert_auto_increment)
408
409        // Integer types - strip display width
410        result = RE_TINYINT_BOOL.replace_all(&result, "BIT").to_string();
411        result = RE_TINYINT.replace_all(&result, "TINYINT").to_string();
412        result = RE_SMALLINT.replace_all(&result, "SMALLINT").to_string();
413        result = RE_MEDIUMINT.replace_all(&result, "INT").to_string();
414        result = RE_INT_SIZE.replace_all(&result, "INT").to_string();
415        result = RE_BIGINT_SIZE.replace_all(&result, "BIGINT").to_string();
416
417        // Float types
418        result = RE_DOUBLE.replace_all(&result, "FLOAT").to_string();
419        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
420
421        // Text types
422        result = RE_LONGTEXT
423            .replace_all(&result, "NVARCHAR(MAX)")
424            .to_string();
425        result = RE_MEDIUMTEXT
426            .replace_all(&result, "NVARCHAR(MAX)")
427            .to_string();
428        result = RE_TINYTEXT
429            .replace_all(&result, "NVARCHAR(255)")
430            .to_string();
431
432        // Binary types
433        result = RE_LONGBLOB
434            .replace_all(&result, "VARBINARY(MAX)")
435            .to_string();
436        result = RE_MEDIUMBLOB
437            .replace_all(&result, "VARBINARY(MAX)")
438            .to_string();
439        result = RE_TINYBLOB
440            .replace_all(&result, "VARBINARY(255)")
441            .to_string();
442        result = RE_BLOB.replace_all(&result, "VARBINARY(MAX)").to_string();
443
444        // Date/time types
445        result = RE_DATETIME.replace_all(&result, "DATETIME2").to_string();
446
447        // JSON → NVARCHAR(MAX)
448        result = RE_JSON.replace_all(&result, "NVARCHAR(MAX)").to_string();
449
450        // ENUM → NVARCHAR(255)
451        result = RE_ENUM.replace_all(&result, "NVARCHAR(255)").to_string();
452
453        // SET → NVARCHAR(255)
454        result = RE_SET.replace_all(&result, "NVARCHAR(255)").to_string();
455
456        // UNSIGNED - remove
457        result = RE_UNSIGNED.replace_all(&result, "").to_string();
458
459        // ZEROFILL - remove
460        result = RE_ZEROFILL.replace_all(&result, "").to_string();
461
462        result
463    }
464
465    /// Convert PostgreSQL types to MSSQL
466    fn postgres_to_mssql(stmt: &str) -> String {
467        let mut result = stmt.to_string();
468
469        // SERIAL → INT IDENTITY(1,1)
470        result = RE_BIGSERIAL
471            .replace_all(&result, "BIGINT IDENTITY(1,1)")
472            .to_string();
473        result = RE_SERIAL
474            .replace_all(&result, "INT IDENTITY(1,1)")
475            .to_string();
476        result = RE_SMALLSERIAL
477            .replace_all(&result, "SMALLINT IDENTITY(1,1)")
478            .to_string();
479
480        // BYTEA → VARBINARY(MAX)
481        result = RE_BYTEA.replace_all(&result, "VARBINARY(MAX)").to_string();
482
483        // DOUBLE PRECISION → FLOAT
484        result = RE_DOUBLE_PRECISION
485            .replace_all(&result, "FLOAT")
486            .to_string();
487
488        // REAL stays REAL
489
490        // BOOLEAN → BIT
491        result = RE_BOOLEAN.replace_all(&result, "BIT").to_string();
492
493        // TIMESTAMPTZ → DATETIMEOFFSET
494        result = RE_TIMESTAMPTZ
495            .replace_all(&result, "DATETIMEOFFSET")
496            .to_string();
497
498        // TIMESTAMP WITH TIME ZONE → DATETIMEOFFSET
499        result = RE_TIMESTAMP_WITH_TZ
500            .replace_all(&result, "DATETIMEOFFSET")
501            .to_string();
502
503        // TIMESTAMP WITHOUT TIME ZONE → DATETIME2
504        result = RE_TIMESTAMP_NO_TZ
505            .replace_all(&result, "DATETIME2")
506            .to_string();
507
508        // JSONB → NVARCHAR(MAX)
509        result = RE_JSONB.replace_all(&result, "NVARCHAR(MAX)").to_string();
510
511        // JSON → NVARCHAR(MAX)
512        result = RE_JSON.replace_all(&result, "NVARCHAR(MAX)").to_string();
513
514        // UUID → UNIQUEIDENTIFIER
515        result = RE_UUID.replace_all(&result, "UNIQUEIDENTIFIER").to_string();
516
517        // TEXT → NVARCHAR(MAX)
518        result = RE_TEXT.replace_all(&result, "NVARCHAR(MAX)").to_string();
519
520        result
521    }
522
523    /// Convert SQLite types to MSSQL
524    fn sqlite_to_mssql(stmt: &str) -> String {
525        let mut result = stmt.to_string();
526
527        // REAL → FLOAT
528        result = RE_REAL.replace_all(&result, "FLOAT").to_string();
529
530        // BLOB → VARBINARY(MAX)
531        result = RE_BLOB.replace_all(&result, "VARBINARY(MAX)").to_string();
532
533        // TEXT → NVARCHAR(MAX)
534        result = RE_TEXT.replace_all(&result, "NVARCHAR(MAX)").to_string();
535
536        result
537    }
538
539    /// Convert MSSQL types to MySQL
540    fn mssql_to_mysql(stmt: &str) -> String {
541        let mut result = stmt.to_string();
542
543        // IDENTITY → AUTO_INCREMENT (handled elsewhere)
544
545        // BIT → TINYINT(1)
546        result = RE_BIT.replace_all(&result, "TINYINT(1)").to_string();
547
548        // NVARCHAR(MAX) → LONGTEXT
549        result = RE_NVARCHAR_MAX.replace_all(&result, "LONGTEXT").to_string();
550
551        // NVARCHAR(n) → VARCHAR(n)
552        result = RE_NVARCHAR.replace_all(&result, "VARCHAR$1").to_string();
553
554        // NCHAR(n) → CHAR(n)
555        result = RE_NCHAR.replace_all(&result, "CHAR$1").to_string();
556
557        // NTEXT → LONGTEXT
558        result = RE_NTEXT.replace_all(&result, "LONGTEXT").to_string();
559
560        // VARCHAR(MAX) → LONGTEXT
561        result = RE_VARCHAR_MAX.replace_all(&result, "LONGTEXT").to_string();
562
563        // VARBINARY(MAX) → LONGBLOB
564        result = RE_VARBINARY_MAX
565            .replace_all(&result, "LONGBLOB")
566            .to_string();
567
568        // IMAGE → LONGBLOB
569        result = RE_IMAGE.replace_all(&result, "LONGBLOB").to_string();
570
571        // DATETIME2 → DATETIME(6)
572        result = RE_DATETIME2.replace_all(&result, "DATETIME(6)").to_string();
573
574        // DATETIMEOFFSET → DATETIME
575        result = RE_DATETIMEOFFSET
576            .replace_all(&result, "DATETIME")
577            .to_string();
578
579        // SMALLDATETIME → DATETIME
580        result = RE_SMALLDATETIME
581            .replace_all(&result, "DATETIME")
582            .to_string();
583
584        // MONEY → DECIMAL(19,4)
585        result = RE_MONEY.replace_all(&result, "DECIMAL(19,4)").to_string();
586
587        // SMALLMONEY → DECIMAL(10,4)
588        result = RE_SMALLMONEY
589            .replace_all(&result, "DECIMAL(10,4)")
590            .to_string();
591
592        // UNIQUEIDENTIFIER → VARCHAR(36)
593        result = RE_UNIQUEIDENTIFIER
594            .replace_all(&result, "VARCHAR(36)")
595            .to_string();
596
597        // XML → LONGTEXT
598        result = RE_XML.replace_all(&result, "LONGTEXT").to_string();
599
600        // ROWVERSION/MSSQL TIMESTAMP → BINARY(8)
601        result = RE_MSSQL_TIMESTAMP_BRACKETED
602            .replace_all(&result, "BINARY(8)")
603            .to_string();
604        result = RE_ROWVERSION_ONLY
605            .replace_all(&result, "BINARY(8)")
606            .to_string();
607
608        // Strip MSSQL-specific clauses
609        result = RE_ON_PRIMARY.replace_all(&result, "").to_string();
610        result = RE_CLUSTERED.replace_all(&result, "").to_string();
611        result = RE_NONCLUSTERED.replace_all(&result, "").to_string();
612
613        result
614    }
615
616    /// Convert MSSQL types to PostgreSQL
617    fn mssql_to_postgres(stmt: &str) -> String {
618        let mut result = stmt.to_string();
619
620        // IDENTITY → SERIAL (handled elsewhere)
621
622        // IMPORTANT: Handle ROWVERSION first (before any TIMESTAMP conversion)
623        // In MSSQL, TIMESTAMP is an alias for ROWVERSION (a binary type, not datetime!)
624        // Use a more specific regex that matches MSSQL TIMESTAMP but not PostgreSQL TIMESTAMP
625        result = RE_MSSQL_TIMESTAMP_BRACKETED
626            .replace_all(&result, "BYTEA")
627            .to_string();
628        result = RE_ROWVERSION_ONLY.replace_all(&result, "BYTEA").to_string();
629
630        // BIT → BOOLEAN
631        result = RE_BIT.replace_all(&result, "BOOLEAN").to_string();
632
633        // NVARCHAR(MAX) → TEXT
634        result = RE_NVARCHAR_MAX.replace_all(&result, "TEXT").to_string();
635
636        // NVARCHAR(n) → VARCHAR(n)
637        result = RE_NVARCHAR.replace_all(&result, "VARCHAR$1").to_string();
638
639        // NCHAR(n) → CHAR(n)
640        result = RE_NCHAR.replace_all(&result, "CHAR$1").to_string();
641
642        // NTEXT → TEXT
643        result = RE_NTEXT.replace_all(&result, "TEXT").to_string();
644
645        // VARCHAR(MAX) → TEXT
646        result = RE_VARCHAR_MAX.replace_all(&result, "TEXT").to_string();
647
648        // VARBINARY(MAX) → BYTEA
649        result = RE_VARBINARY_MAX.replace_all(&result, "BYTEA").to_string();
650
651        // VARBINARY(n) → BYTEA
652        result = RE_VARBINARY.replace_all(&result, "BYTEA").to_string();
653
654        // IMAGE → BYTEA
655        result = RE_IMAGE.replace_all(&result, "BYTEA").to_string();
656
657        // DATETIME2 → TIMESTAMP
658        result = RE_DATETIME2.replace_all(&result, "TIMESTAMP").to_string();
659
660        // DATETIME → TIMESTAMP (but not MSSQL TIMESTAMP which is already converted)
661        result = RE_DATETIME.replace_all(&result, "TIMESTAMP").to_string();
662
663        // DATETIMEOFFSET → TIMESTAMPTZ
664        result = RE_DATETIMEOFFSET
665            .replace_all(&result, "TIMESTAMPTZ")
666            .to_string();
667
668        // SMALLDATETIME → TIMESTAMP
669        result = RE_SMALLDATETIME
670            .replace_all(&result, "TIMESTAMP")
671            .to_string();
672
673        // MONEY → DECIMAL(19,4)
674        result = RE_MONEY.replace_all(&result, "DECIMAL(19,4)").to_string();
675
676        // SMALLMONEY → DECIMAL(10,4)
677        result = RE_SMALLMONEY
678            .replace_all(&result, "DECIMAL(10,4)")
679            .to_string();
680
681        // UNIQUEIDENTIFIER → UUID
682        result = RE_UNIQUEIDENTIFIER.replace_all(&result, "UUID").to_string();
683
684        // XML → XML (PostgreSQL supports XML type)
685
686        // FLOAT → DOUBLE PRECISION
687        result = RE_FLOAT
688            .replace_all(&result, "DOUBLE PRECISION")
689            .to_string();
690
691        // Strip MSSQL-specific clauses
692        result = RE_ON_PRIMARY.replace_all(&result, "").to_string();
693        result = RE_CLUSTERED.replace_all(&result, "").to_string();
694        result = RE_NONCLUSTERED.replace_all(&result, "").to_string();
695
696        result
697    }
698
699    /// Convert MSSQL types to SQLite
700    fn mssql_to_sqlite(stmt: &str) -> String {
701        let mut result = stmt.to_string();
702
703        // BIT → INTEGER
704        result = RE_BIT.replace_all(&result, "INTEGER").to_string();
705
706        // NVARCHAR → TEXT
707        result = RE_NVARCHAR_MAX.replace_all(&result, "TEXT").to_string();
708        result = RE_NVARCHAR.replace_all(&result, "TEXT").to_string();
709
710        // NCHAR → TEXT
711        result = RE_NCHAR.replace_all(&result, "TEXT").to_string();
712
713        // NTEXT → TEXT
714        result = RE_NTEXT.replace_all(&result, "TEXT").to_string();
715
716        // VARCHAR(MAX) → TEXT
717        result = RE_VARCHAR_MAX.replace_all(&result, "TEXT").to_string();
718
719        // VARBINARY → BLOB
720        result = RE_VARBINARY_MAX.replace_all(&result, "BLOB").to_string();
721        result = RE_VARBINARY.replace_all(&result, "BLOB").to_string();
722
723        // IMAGE → BLOB
724        result = RE_IMAGE.replace_all(&result, "BLOB").to_string();
725
726        // Date/time → TEXT
727        result = RE_DATETIME2.replace_all(&result, "TEXT").to_string();
728        result = RE_DATETIME.replace_all(&result, "TEXT").to_string();
729        result = RE_DATETIMEOFFSET.replace_all(&result, "TEXT").to_string();
730        result = RE_SMALLDATETIME.replace_all(&result, "TEXT").to_string();
731
732        // MONEY → REAL
733        result = RE_MONEY.replace_all(&result, "REAL").to_string();
734        result = RE_SMALLMONEY.replace_all(&result, "REAL").to_string();
735
736        // UNIQUEIDENTIFIER → TEXT
737        result = RE_UNIQUEIDENTIFIER.replace_all(&result, "TEXT").to_string();
738
739        // XML → TEXT
740        result = RE_XML.replace_all(&result, "TEXT").to_string();
741
742        // ROWVERSION/MSSQL TIMESTAMP → BLOB
743        result = RE_MSSQL_TIMESTAMP_BRACKETED
744            .replace_all(&result, "BLOB")
745            .to_string();
746        result = RE_ROWVERSION_ONLY.replace_all(&result, "BLOB").to_string();
747
748        // FLOAT → REAL
749        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
750
751        // Strip MSSQL-specific clauses
752        result = RE_ON_PRIMARY.replace_all(&result, "").to_string();
753        result = RE_CLUSTERED.replace_all(&result, "").to_string();
754        result = RE_NONCLUSTERED.replace_all(&result, "").to_string();
755
756        result
757    }
758}
759
760// Pre-compiled regexes for type matching
761static RE_TINYINT_BOOL: Lazy<Regex> =
762    Lazy::new(|| Regex::new(r"(?i)\bTINYINT\s*\(\s*1\s*\)").unwrap());
763static RE_TINYINT: Lazy<Regex> =
764    Lazy::new(|| Regex::new(r"(?i)\bTINYINT\s*(\(\s*\d+\s*\))?").unwrap());
765static RE_SMALLINT: Lazy<Regex> =
766    Lazy::new(|| Regex::new(r"(?i)\bSMALLINT\s*(\(\s*\d+\s*\))?").unwrap());
767static RE_MEDIUMINT: Lazy<Regex> =
768    Lazy::new(|| Regex::new(r"(?i)\bMEDIUMINT\s*(\(\s*\d+\s*\))?").unwrap());
769static RE_INT_SIZE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bINT\s*\(\s*\d+\s*\)").unwrap());
770static RE_BIGINT_SIZE: Lazy<Regex> =
771    Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s*\(\s*\d+\s*\)").unwrap());
772
773static RE_DOUBLE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bDOUBLE\b").unwrap());
774static RE_FLOAT: Lazy<Regex> =
775    Lazy::new(|| Regex::new(r"(?i)\bFLOAT\s*(\(\s*\d+\s*(,\s*\d+\s*)?\))?").unwrap());
776static RE_DECIMAL: Lazy<Regex> =
777    Lazy::new(|| Regex::new(r"(?i)\bDECIMAL\s*\(\s*\d+\s*(,\s*\d+\s*)?\)").unwrap());
778
779static RE_LONGTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bLONGTEXT\b").unwrap());
780static RE_MEDIUMTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bMEDIUMTEXT\b").unwrap());
781static RE_TINYTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTINYTEXT\b").unwrap());
782static RE_VARCHAR: Lazy<Regex> =
783    Lazy::new(|| Regex::new(r"(?i)\bVARCHAR\s*\(\s*\d+\s*\)").unwrap());
784/// A PostgreSQL variable-length string declaration in any of its spellings,
785/// with the length (if declared) captured as `len` and a leading `::` cast
786/// marker captured as `cast`.
787///
788/// `pg_dump` writes `character varying`, never `varchar`, so the long spellings
789/// are the ones that actually turn up in real dumps. Matching the optional
790/// `::` prefix is what keeps the rewrite out of a cast such as
791/// `DEFAULT 'active'::character varying`: those are removed wholesale later by
792/// `strip_postgres_casts`, which matches bare identifiers and would leave a
793/// dangling `(255)` behind if the type inside it had been rewritten.
794static RE_VARCHAR_DECL: Lazy<Regex> = Lazy::new(|| {
795    Regex::new(
796        r"(?i)(?P<cast>::\s*)?\b(?:VARCHAR|(?:NATIONAL\s+)?(?:CHARACTER|CHAR)\s+VARYING)(?P<len>\s*\(\s*\d+\s*\))?",
797    )
798    .unwrap()
799});
800static RE_CHAR: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCHAR\s*\(\s*\d+\s*\)").unwrap());
801
802static RE_LONGBLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bLONGBLOB\b").unwrap());
803static RE_MEDIUMBLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bMEDIUMBLOB\b").unwrap());
804static RE_TINYBLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTINYBLOB\b").unwrap());
805static RE_BLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBLOB\b").unwrap());
806static RE_VARBINARY: Lazy<Regex> =
807    Lazy::new(|| Regex::new(r"(?i)\bVARBINARY\s*\(\s*\d+\s*\)").unwrap());
808static RE_BINARY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBINARY\s*\(\s*\d+\s*\)").unwrap());
809
810static RE_DATETIME: Lazy<Regex> =
811    Lazy::new(|| Regex::new(r"(?i)\bDATETIME(\(\s*\d+\s*\))?").unwrap());
812static RE_TIMESTAMP: Lazy<Regex> =
813    Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMP\s*(\(\s*\d+\s*\))?").unwrap());
814static RE_DATE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bDATE\b").unwrap());
815static RE_TIME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTIME\s*(\(\s*\d+\s*\))?").unwrap());
816
817static RE_JSON: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bJSON\b").unwrap());
818
819static RE_ENUM: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bENUM\s*\([^)]+\)").unwrap());
820static RE_SET: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSET\s*\([^)]+\)").unwrap());
821
822static RE_UNSIGNED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s+UNSIGNED\b").unwrap());
823static RE_ZEROFILL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s+ZEROFILL\b").unwrap());
824
825// PostgreSQL specific types
826static RE_SERIAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSERIAL\b").unwrap());
827static RE_BIGSERIAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBIGSERIAL\b").unwrap());
828static RE_SMALLSERIAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSMALLSERIAL\b").unwrap());
829static RE_BYTEA: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBYTEA\b").unwrap());
830static RE_DOUBLE_PRECISION: Lazy<Regex> =
831    Lazy::new(|| Regex::new(r"(?i)\bDOUBLE\s+PRECISION\b").unwrap());
832static RE_REAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bREAL\b").unwrap());
833static RE_BOOLEAN: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBOOLEAN\b").unwrap());
834static RE_TIMESTAMPTZ: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMPTZ\b").unwrap());
835static RE_TIMESTAMP_WITH_TZ: Lazy<Regex> =
836    Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMP\s+WITH\s+TIME\s+ZONE\b").unwrap());
837static RE_TIMESTAMP_NO_TZ: Lazy<Regex> =
838    Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMP\s+WITHOUT\s+TIME\s+ZONE\b").unwrap());
839static RE_JSONB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bJSONB\b").unwrap());
840static RE_UUID: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bUUID\b").unwrap());
841static RE_TEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTEXT\b").unwrap());
842
843// MSSQL specific types
844static RE_BIT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBIT\b").unwrap());
845static RE_NVARCHAR_MAX: Lazy<Regex> =
846    Lazy::new(|| Regex::new(r"(?i)\bNVARCHAR\s*\(\s*MAX\s*\)").unwrap());
847static RE_NVARCHAR: Lazy<Regex> =
848    Lazy::new(|| Regex::new(r"(?i)\bNVARCHAR\s*(\(\s*\d+\s*\))").unwrap());
849static RE_NCHAR: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNCHAR\s*(\(\s*\d+\s*\))").unwrap());
850static RE_NTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNTEXT\b").unwrap());
851static RE_VARCHAR_MAX: Lazy<Regex> =
852    Lazy::new(|| Regex::new(r"(?i)\bVARCHAR\s*\(\s*MAX\s*\)").unwrap());
853static RE_VARBINARY_MAX: Lazy<Regex> =
854    Lazy::new(|| Regex::new(r"(?i)\bVARBINARY\s*\(\s*MAX\s*\)").unwrap());
855static RE_IMAGE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bIMAGE\b").unwrap());
856static RE_DATETIME2: Lazy<Regex> =
857    Lazy::new(|| Regex::new(r"(?i)\bDATETIME2\s*(\(\s*\d+\s*\))?").unwrap());
858static RE_DATETIMEOFFSET: Lazy<Regex> =
859    Lazy::new(|| Regex::new(r"(?i)\bDATETIMEOFFSET\s*(\(\s*\d+\s*\))?").unwrap());
860static RE_SMALLDATETIME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSMALLDATETIME\b").unwrap());
861static RE_MONEY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bMONEY\b").unwrap());
862static RE_SMALLMONEY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSMALLMONEY\b").unwrap());
863static RE_UNIQUEIDENTIFIER: Lazy<Regex> =
864    Lazy::new(|| Regex::new(r"(?i)\bUNIQUEIDENTIFIER\b").unwrap());
865static RE_XML: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bXML\b").unwrap());
866// MSSQL TIMESTAMP type (binary versioning, NOT datetime) - only match bracketed [TIMESTAMP]
867// or as column type after brackets. We can't match unbracketed standalone TIMESTAMP safely
868// because it would conflict with PostgreSQL TIMESTAMP result. So we rely on context.
869static RE_MSSQL_TIMESTAMP_BRACKETED: Lazy<Regex> =
870    Lazy::new(|| Regex::new(r"(?i)\[\s*TIMESTAMP\s*\]").unwrap());
871static RE_ROWVERSION_ONLY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bROWVERSION\b").unwrap());
872
873// MSSQL-specific clauses to strip when converting to other dialects
874static RE_ON_PRIMARY: Lazy<Regex> =
875    Lazy::new(|| Regex::new(r"(?i)\s*ON\s*\[\s*PRIMARY\s*\]").unwrap());
876static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
877static RE_NONCLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
878
879#[cfg(test)]
880mod map_column_type_tests {
881    use super::*;
882
883    #[test]
884    fn same_dialect_is_identity_and_warning_free() {
885        let mut warnings = WarningCollector::new();
886        let mapped = map_column_type(
887            "VARCHAR(255)",
888            SqlDialect::MySql,
889            SqlDialect::MySql,
890            &mut warnings,
891        );
892        assert_eq!(mapped, "VARCHAR(255)");
893        assert!(!warnings.has_warnings());
894    }
895
896    #[test]
897    fn cross_dialect_reuses_the_statement_level_regex_rules() {
898        let mut warnings = WarningCollector::new();
899        let mapped = map_column_type(
900            "BIGINT(20)",
901            SqlDialect::MySql,
902            SqlDialect::Postgres,
903            &mut warnings,
904        );
905        assert_eq!(mapped, "BIGINT");
906    }
907
908    #[test]
909    fn postgres_unbounded_varchar_maps_to_a_sized_mysql_varchar() {
910        for source in [
911            "varchar",
912            "VARCHAR",
913            "character varying",
914            "CHARACTER VARYING",
915            "char varying",
916        ] {
917            let mut warnings = WarningCollector::new();
918            let mapped = map_column_type(
919                source,
920                SqlDialect::Postgres,
921                SqlDialect::MySql,
922                &mut warnings,
923            );
924            assert_eq!(mapped, "VARCHAR(255)", "source: {source}");
925            // PostgreSQL stores up to 1GB in an unbounded VARCHAR, so pinning it
926            // to 255 truncates: callers surfacing warnings (and --strict) must
927            // see this rather than discover it at load time.
928            assert!(warnings.has_warnings(), "source: {source}");
929            assert!(matches!(
930                warnings.warnings()[0],
931                ConvertWarning::LossyConversion { .. }
932            ));
933        }
934    }
935
936    #[test]
937    fn postgres_sized_varchar_is_already_valid_mysql_and_is_left_alone() {
938        for source in ["varchar(255)", "character varying(120)", "VARCHAR (64)"] {
939            let mut warnings = WarningCollector::new();
940            let mapped = map_column_type(
941                source,
942                SqlDialect::Postgres,
943                SqlDialect::MySql,
944                &mut warnings,
945            );
946            assert_eq!(mapped, source, "source: {source}");
947            assert!(!warnings.has_warnings(), "source: {source}");
948        }
949    }
950
951    #[test]
952    fn narrowing_enum_to_a_plain_string_records_a_lossy_warning() {
953        let mut warnings = WarningCollector::new();
954        let mapped = map_column_type(
955            "ENUM('a','b')",
956            SqlDialect::MySql,
957            SqlDialect::Postgres,
958            &mut warnings,
959        );
960        assert_eq!(mapped, "VARCHAR(255)");
961        assert!(warnings.has_warnings());
962        assert!(matches!(
963            warnings.warnings()[0],
964            ConvertWarning::LossyConversion { .. }
965        ));
966    }
967
968    #[test]
969    fn json_to_an_engine_without_a_json_type_is_lossy() {
970        let mut warnings = WarningCollector::new();
971        map_column_type("JSON", SqlDialect::MySql, SqlDialect::Sqlite, &mut warnings);
972        assert!(warnings.has_warnings());
973
974        // PostgreSQL keeps a native JSON type, so the same source is not lossy.
975        let mut kept = WarningCollector::new();
976        map_column_type("JSON", SqlDialect::MySql, SqlDialect::Postgres, &mut kept);
977        assert!(!kept.has_warnings());
978    }
979
980    #[test]
981    fn uuid_stored_as_text_is_lossy() {
982        let mut warnings = WarningCollector::new();
983        map_column_type(
984            "UUID",
985            SqlDialect::Postgres,
986            SqlDialect::MySql,
987            &mut warnings,
988        );
989        assert!(warnings.has_warnings());
990
991        // MSSQL has UNIQUEIDENTIFIER, so a UUID keeps its native domain there.
992        let mut kept = WarningCollector::new();
993        map_column_type("UUID", SqlDialect::Postgres, SqlDialect::Mssql, &mut kept);
994        assert!(!kept.has_warnings());
995    }
996
997    #[test]
998    fn decimal_to_sqlite_real_is_lossy() {
999        // SQLite has no exact fixed-point type; the mapper renders DECIMAL as
1000        // REAL (binary float), silently losing exact precision.
1001        let mut warnings = WarningCollector::new();
1002        map_column_type(
1003            "DECIMAL(10,2)",
1004            SqlDialect::MySql,
1005            SqlDialect::Sqlite,
1006            &mut warnings,
1007        );
1008        assert!(warnings.has_warnings());
1009
1010        // PostgreSQL keeps a native DECIMAL, so the same source is not lossy.
1011        let mut kept = WarningCollector::new();
1012        map_column_type(
1013            "DECIMAL(10,2)",
1014            SqlDialect::MySql,
1015            SqlDialect::Postgres,
1016            &mut kept,
1017        );
1018        assert!(!kept.has_warnings());
1019    }
1020
1021    #[test]
1022    fn timestamptz_to_mysql_drops_the_timezone_and_is_lossy() {
1023        // MySQL DATETIME has no time-zone component, so the tz is dropped.
1024        let mut warnings = WarningCollector::new();
1025        map_column_type(
1026            "TIMESTAMPTZ",
1027            SqlDialect::Postgres,
1028            SqlDialect::MySql,
1029            &mut warnings,
1030        );
1031        assert!(warnings.has_warnings());
1032
1033        // MSSQL DATETIMEOFFSET preserves the time zone, so it is not lossy.
1034        let mut kept = WarningCollector::new();
1035        map_column_type(
1036            "TIMESTAMPTZ",
1037            SqlDialect::Postgres,
1038            SqlDialect::Mssql,
1039            &mut kept,
1040        );
1041        assert!(!kept.has_warnings());
1042    }
1043}