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::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    // Exact fixed-point (DECIMAL/NUMERIC) becomes a binary float (REAL) on
75    // SQLite, silently losing precision.
76    if (lower.contains("decimal") || lower.contains("numeric")) && to == SqlDialect::Sqlite {
77        return true;
78    }
79    // A time-zone-bearing timestamp loses its zone when mapped to MySQL
80    // DATETIME (which has no tz). MSSQL keeps it via DATETIMEOFFSET, and the
81    // SQLite mapping renders TEXT that retains the zoned literal.
82    // ("without time zone" does not contain the substring "with time zone".)
83    if (lower.contains("timestamptz") || lower.contains("with time zone"))
84        && to == SqlDialect::MySql
85    {
86        return true;
87    }
88    false
89}
90
91/// Type mapper for converting between dialects
92pub struct TypeMapper;
93
94impl TypeMapper {
95    /// Convert all data types in a statement
96    pub fn convert(stmt: &str, from: SqlDialect, to: SqlDialect) -> String {
97        match (from, to) {
98            (SqlDialect::MySql, SqlDialect::Postgres) => Self::mysql_to_postgres(stmt),
99            (SqlDialect::MySql, SqlDialect::Sqlite) => Self::mysql_to_sqlite(stmt),
100            (SqlDialect::MySql, SqlDialect::Mssql) => Self::mysql_to_mssql(stmt),
101            (SqlDialect::Postgres, SqlDialect::MySql) => Self::postgres_to_mysql(stmt),
102            (SqlDialect::Postgres, SqlDialect::Sqlite) => Self::postgres_to_sqlite(stmt),
103            (SqlDialect::Postgres, SqlDialect::Mssql) => Self::postgres_to_mssql(stmt),
104            (SqlDialect::Sqlite, SqlDialect::MySql) => Self::sqlite_to_mysql(stmt),
105            (SqlDialect::Sqlite, SqlDialect::Postgres) => Self::sqlite_to_postgres(stmt),
106            (SqlDialect::Sqlite, SqlDialect::Mssql) => Self::sqlite_to_mssql(stmt),
107            (SqlDialect::Mssql, SqlDialect::MySql) => Self::mssql_to_mysql(stmt),
108            (SqlDialect::Mssql, SqlDialect::Postgres) => Self::mssql_to_postgres(stmt),
109            (SqlDialect::Mssql, SqlDialect::Sqlite) => Self::mssql_to_sqlite(stmt),
110            _ => stmt.to_string(),
111        }
112    }
113
114    /// Convert MySQL types to PostgreSQL
115    fn mysql_to_postgres(stmt: &str) -> String {
116        let mut result = stmt.to_string();
117
118        // Integer types - strip display width, PostgreSQL doesn't use it
119        result = RE_TINYINT_BOOL.replace_all(&result, "BOOLEAN").to_string();
120        result = RE_TINYINT.replace_all(&result, "SMALLINT").to_string();
121        result = RE_SMALLINT.replace_all(&result, "SMALLINT").to_string();
122        result = RE_MEDIUMINT.replace_all(&result, "INTEGER").to_string();
123        result = RE_INT_SIZE.replace_all(&result, "INTEGER").to_string();
124        result = RE_BIGINT_SIZE.replace_all(&result, "BIGINT").to_string();
125
126        // Float types
127        result = RE_DOUBLE
128            .replace_all(&result, "DOUBLE PRECISION")
129            .to_string();
130        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
131
132        // Text types
133        result = RE_LONGTEXT.replace_all(&result, "TEXT").to_string();
134        result = RE_MEDIUMTEXT.replace_all(&result, "TEXT").to_string();
135        result = RE_TINYTEXT.replace_all(&result, "TEXT").to_string();
136
137        // Binary types
138        result = RE_LONGBLOB.replace_all(&result, "BYTEA").to_string();
139        result = RE_MEDIUMBLOB.replace_all(&result, "BYTEA").to_string();
140        result = RE_TINYBLOB.replace_all(&result, "BYTEA").to_string();
141        result = RE_BLOB.replace_all(&result, "BYTEA").to_string();
142        result = RE_VARBINARY.replace_all(&result, "BYTEA").to_string();
143        result = RE_BINARY.replace_all(&result, "BYTEA").to_string();
144
145        // Date/time types
146        result = RE_DATETIME.replace_all(&result, "TIMESTAMP").to_string();
147
148        // JSON
149        result = RE_JSON.replace_all(&result, "JSONB").to_string();
150
151        // ENUM - convert to VARCHAR (with warning)
152        result = RE_ENUM.replace_all(&result, "VARCHAR(255)").to_string();
153
154        // SET - convert to VARCHAR (with warning)
155        result = RE_SET.replace_all(&result, "VARCHAR(255)").to_string();
156
157        // UNSIGNED - remove
158        result = RE_UNSIGNED.replace_all(&result, "").to_string();
159
160        // ZEROFILL - remove
161        result = RE_ZEROFILL.replace_all(&result, "").to_string();
162
163        result
164    }
165
166    /// Convert MySQL types to SQLite
167    fn mysql_to_sqlite(stmt: &str) -> String {
168        let mut result = stmt.to_string();
169
170        // SQLite is lenient with types, but we normalize for consistency
171
172        // Integer types - SQLite uses INTEGER
173        result = RE_TINYINT.replace_all(&result, "INTEGER").to_string();
174        result = RE_SMALLINT.replace_all(&result, "INTEGER").to_string();
175        result = RE_MEDIUMINT.replace_all(&result, "INTEGER").to_string();
176        result = RE_INT_SIZE.replace_all(&result, "INTEGER").to_string();
177        result = RE_BIGINT_SIZE.replace_all(&result, "INTEGER").to_string();
178
179        // Float types - SQLite uses REAL
180        result = RE_DOUBLE.replace_all(&result, "REAL").to_string();
181        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
182        result = RE_DECIMAL.replace_all(&result, "REAL").to_string();
183
184        // Text types - all become TEXT
185        result = RE_LONGTEXT.replace_all(&result, "TEXT").to_string();
186        result = RE_MEDIUMTEXT.replace_all(&result, "TEXT").to_string();
187        result = RE_TINYTEXT.replace_all(&result, "TEXT").to_string();
188        result = RE_VARCHAR.replace_all(&result, "TEXT").to_string();
189        result = RE_CHAR.replace_all(&result, "TEXT").to_string();
190
191        // Binary types - SQLite uses BLOB
192        result = RE_LONGBLOB.replace_all(&result, "BLOB").to_string();
193        result = RE_MEDIUMBLOB.replace_all(&result, "BLOB").to_string();
194        result = RE_TINYBLOB.replace_all(&result, "BLOB").to_string();
195        result = RE_VARBINARY.replace_all(&result, "BLOB").to_string();
196        result = RE_BINARY.replace_all(&result, "BLOB").to_string();
197
198        // Date/time - SQLite stores as TEXT or INTEGER
199        result = RE_DATETIME.replace_all(&result, "TEXT").to_string();
200        result = RE_TIMESTAMP.replace_all(&result, "TEXT").to_string();
201        result = RE_DATE.replace_all(&result, "TEXT").to_string();
202        result = RE_TIME.replace_all(&result, "TEXT").to_string();
203
204        // JSON - SQLite stores as TEXT
205        result = RE_JSON.replace_all(&result, "TEXT").to_string();
206
207        // ENUM/SET - convert to TEXT
208        result = RE_ENUM.replace_all(&result, "TEXT").to_string();
209        result = RE_SET.replace_all(&result, "TEXT").to_string();
210
211        // UNSIGNED - remove
212        result = RE_UNSIGNED.replace_all(&result, "").to_string();
213
214        // ZEROFILL - remove
215        result = RE_ZEROFILL.replace_all(&result, "").to_string();
216
217        result
218    }
219
220    /// Convert PostgreSQL types to MySQL
221    fn postgres_to_mysql(stmt: &str) -> String {
222        let mut result = stmt.to_string();
223
224        // SERIAL → INT AUTO_INCREMENT
225        result = RE_BIGSERIAL
226            .replace_all(&result, "BIGINT AUTO_INCREMENT")
227            .to_string();
228        result = RE_SERIAL
229            .replace_all(&result, "INT AUTO_INCREMENT")
230            .to_string();
231        result = RE_SMALLSERIAL
232            .replace_all(&result, "SMALLINT AUTO_INCREMENT")
233            .to_string();
234
235        // BYTEA → LONGBLOB
236        result = RE_BYTEA.replace_all(&result, "LONGBLOB").to_string();
237
238        // DOUBLE PRECISION → DOUBLE
239        result = RE_DOUBLE_PRECISION
240            .replace_all(&result, "DOUBLE")
241            .to_string();
242
243        // REAL → FLOAT
244        result = RE_REAL.replace_all(&result, "FLOAT").to_string();
245
246        // BOOLEAN → TINYINT(1)
247        result = RE_BOOLEAN.replace_all(&result, "TINYINT(1)").to_string();
248
249        // TIMESTAMPTZ → DATETIME
250        result = RE_TIMESTAMPTZ.replace_all(&result, "DATETIME").to_string();
251
252        // TIMESTAMP WITH TIME ZONE → DATETIME
253        result = RE_TIMESTAMP_WITH_TZ
254            .replace_all(&result, "DATETIME")
255            .to_string();
256
257        // TIMESTAMP WITHOUT TIME ZONE → DATETIME
258        result = RE_TIMESTAMP_NO_TZ
259            .replace_all(&result, "DATETIME")
260            .to_string();
261
262        // JSONB → JSON
263        result = RE_JSONB.replace_all(&result, "JSON").to_string();
264
265        // UUID → VARCHAR(36)
266        result = RE_UUID.replace_all(&result, "VARCHAR(36)").to_string();
267
268        result
269    }
270
271    /// Convert PostgreSQL types to SQLite
272    fn postgres_to_sqlite(stmt: &str) -> String {
273        let mut result = stmt.to_string();
274
275        // SERIAL → INTEGER (SQLite auto-increments INTEGER PRIMARY KEY)
276        result = RE_BIGSERIAL.replace_all(&result, "INTEGER").to_string();
277        result = RE_SERIAL.replace_all(&result, "INTEGER").to_string();
278        result = RE_SMALLSERIAL.replace_all(&result, "INTEGER").to_string();
279
280        // BYTEA → BLOB
281        result = RE_BYTEA.replace_all(&result, "BLOB").to_string();
282
283        // DOUBLE PRECISION → REAL
284        result = RE_DOUBLE_PRECISION.replace_all(&result, "REAL").to_string();
285
286        // BOOLEAN → INTEGER
287        result = RE_BOOLEAN.replace_all(&result, "INTEGER").to_string();
288
289        // Timestamps → TEXT
290        result = RE_TIMESTAMPTZ.replace_all(&result, "TEXT").to_string();
291        result = RE_TIMESTAMP_WITH_TZ
292            .replace_all(&result, "TEXT")
293            .to_string();
294        result = RE_TIMESTAMP_NO_TZ.replace_all(&result, "TEXT").to_string();
295
296        // JSONB/JSON → TEXT
297        result = RE_JSONB.replace_all(&result, "TEXT").to_string();
298        result = RE_JSON.replace_all(&result, "TEXT").to_string();
299
300        // UUID → TEXT
301        result = RE_UUID.replace_all(&result, "TEXT").to_string();
302
303        // VARCHAR → TEXT
304        result = RE_VARCHAR.replace_all(&result, "TEXT").to_string();
305
306        result
307    }
308
309    /// Convert SQLite types to MySQL
310    fn sqlite_to_mysql(stmt: &str) -> String {
311        let mut result = stmt.to_string();
312
313        // SQLite uses TEXT for everything, but we can preserve some type info
314        // REAL → DOUBLE
315        result = RE_REAL.replace_all(&result, "DOUBLE").to_string();
316
317        // BLOB stays BLOB
318        // TEXT stays TEXT
319        // INTEGER stays INTEGER (MySQL will handle it)
320
321        result
322    }
323
324    /// Convert SQLite types to PostgreSQL
325    fn sqlite_to_postgres(stmt: &str) -> String {
326        let mut result = stmt.to_string();
327
328        // REAL → DOUBLE PRECISION
329        result = RE_REAL.replace_all(&result, "DOUBLE PRECISION").to_string();
330
331        // BLOB → BYTEA
332        result = RE_BLOB.replace_all(&result, "BYTEA").to_string();
333
334        // INTEGER stays INTEGER
335        // TEXT stays TEXT
336
337        result
338    }
339
340    /// Convert MySQL types to MSSQL
341    fn mysql_to_mssql(stmt: &str) -> String {
342        let mut result = stmt.to_string();
343
344        // AUTO_INCREMENT → IDENTITY(1,1) (handled elsewhere in convert_auto_increment)
345
346        // Integer types - strip display width
347        result = RE_TINYINT_BOOL.replace_all(&result, "BIT").to_string();
348        result = RE_TINYINT.replace_all(&result, "TINYINT").to_string();
349        result = RE_SMALLINT.replace_all(&result, "SMALLINT").to_string();
350        result = RE_MEDIUMINT.replace_all(&result, "INT").to_string();
351        result = RE_INT_SIZE.replace_all(&result, "INT").to_string();
352        result = RE_BIGINT_SIZE.replace_all(&result, "BIGINT").to_string();
353
354        // Float types
355        result = RE_DOUBLE.replace_all(&result, "FLOAT").to_string();
356        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
357
358        // Text types
359        result = RE_LONGTEXT
360            .replace_all(&result, "NVARCHAR(MAX)")
361            .to_string();
362        result = RE_MEDIUMTEXT
363            .replace_all(&result, "NVARCHAR(MAX)")
364            .to_string();
365        result = RE_TINYTEXT
366            .replace_all(&result, "NVARCHAR(255)")
367            .to_string();
368
369        // Binary types
370        result = RE_LONGBLOB
371            .replace_all(&result, "VARBINARY(MAX)")
372            .to_string();
373        result = RE_MEDIUMBLOB
374            .replace_all(&result, "VARBINARY(MAX)")
375            .to_string();
376        result = RE_TINYBLOB
377            .replace_all(&result, "VARBINARY(255)")
378            .to_string();
379        result = RE_BLOB.replace_all(&result, "VARBINARY(MAX)").to_string();
380
381        // Date/time types
382        result = RE_DATETIME.replace_all(&result, "DATETIME2").to_string();
383
384        // JSON → NVARCHAR(MAX)
385        result = RE_JSON.replace_all(&result, "NVARCHAR(MAX)").to_string();
386
387        // ENUM → NVARCHAR(255)
388        result = RE_ENUM.replace_all(&result, "NVARCHAR(255)").to_string();
389
390        // SET → NVARCHAR(255)
391        result = RE_SET.replace_all(&result, "NVARCHAR(255)").to_string();
392
393        // UNSIGNED - remove
394        result = RE_UNSIGNED.replace_all(&result, "").to_string();
395
396        // ZEROFILL - remove
397        result = RE_ZEROFILL.replace_all(&result, "").to_string();
398
399        result
400    }
401
402    /// Convert PostgreSQL types to MSSQL
403    fn postgres_to_mssql(stmt: &str) -> String {
404        let mut result = stmt.to_string();
405
406        // SERIAL → INT IDENTITY(1,1)
407        result = RE_BIGSERIAL
408            .replace_all(&result, "BIGINT IDENTITY(1,1)")
409            .to_string();
410        result = RE_SERIAL
411            .replace_all(&result, "INT IDENTITY(1,1)")
412            .to_string();
413        result = RE_SMALLSERIAL
414            .replace_all(&result, "SMALLINT IDENTITY(1,1)")
415            .to_string();
416
417        // BYTEA → VARBINARY(MAX)
418        result = RE_BYTEA.replace_all(&result, "VARBINARY(MAX)").to_string();
419
420        // DOUBLE PRECISION → FLOAT
421        result = RE_DOUBLE_PRECISION
422            .replace_all(&result, "FLOAT")
423            .to_string();
424
425        // REAL stays REAL
426
427        // BOOLEAN → BIT
428        result = RE_BOOLEAN.replace_all(&result, "BIT").to_string();
429
430        // TIMESTAMPTZ → DATETIMEOFFSET
431        result = RE_TIMESTAMPTZ
432            .replace_all(&result, "DATETIMEOFFSET")
433            .to_string();
434
435        // TIMESTAMP WITH TIME ZONE → DATETIMEOFFSET
436        result = RE_TIMESTAMP_WITH_TZ
437            .replace_all(&result, "DATETIMEOFFSET")
438            .to_string();
439
440        // TIMESTAMP WITHOUT TIME ZONE → DATETIME2
441        result = RE_TIMESTAMP_NO_TZ
442            .replace_all(&result, "DATETIME2")
443            .to_string();
444
445        // JSONB → NVARCHAR(MAX)
446        result = RE_JSONB.replace_all(&result, "NVARCHAR(MAX)").to_string();
447
448        // JSON → NVARCHAR(MAX)
449        result = RE_JSON.replace_all(&result, "NVARCHAR(MAX)").to_string();
450
451        // UUID → UNIQUEIDENTIFIER
452        result = RE_UUID.replace_all(&result, "UNIQUEIDENTIFIER").to_string();
453
454        // TEXT → NVARCHAR(MAX)
455        result = RE_TEXT.replace_all(&result, "NVARCHAR(MAX)").to_string();
456
457        result
458    }
459
460    /// Convert SQLite types to MSSQL
461    fn sqlite_to_mssql(stmt: &str) -> String {
462        let mut result = stmt.to_string();
463
464        // REAL → FLOAT
465        result = RE_REAL.replace_all(&result, "FLOAT").to_string();
466
467        // BLOB → VARBINARY(MAX)
468        result = RE_BLOB.replace_all(&result, "VARBINARY(MAX)").to_string();
469
470        // TEXT → NVARCHAR(MAX)
471        result = RE_TEXT.replace_all(&result, "NVARCHAR(MAX)").to_string();
472
473        result
474    }
475
476    /// Convert MSSQL types to MySQL
477    fn mssql_to_mysql(stmt: &str) -> String {
478        let mut result = stmt.to_string();
479
480        // IDENTITY → AUTO_INCREMENT (handled elsewhere)
481
482        // BIT → TINYINT(1)
483        result = RE_BIT.replace_all(&result, "TINYINT(1)").to_string();
484
485        // NVARCHAR(MAX) → LONGTEXT
486        result = RE_NVARCHAR_MAX.replace_all(&result, "LONGTEXT").to_string();
487
488        // NVARCHAR(n) → VARCHAR(n)
489        result = RE_NVARCHAR.replace_all(&result, "VARCHAR$1").to_string();
490
491        // NCHAR(n) → CHAR(n)
492        result = RE_NCHAR.replace_all(&result, "CHAR$1").to_string();
493
494        // NTEXT → LONGTEXT
495        result = RE_NTEXT.replace_all(&result, "LONGTEXT").to_string();
496
497        // VARCHAR(MAX) → LONGTEXT
498        result = RE_VARCHAR_MAX.replace_all(&result, "LONGTEXT").to_string();
499
500        // VARBINARY(MAX) → LONGBLOB
501        result = RE_VARBINARY_MAX
502            .replace_all(&result, "LONGBLOB")
503            .to_string();
504
505        // IMAGE → LONGBLOB
506        result = RE_IMAGE.replace_all(&result, "LONGBLOB").to_string();
507
508        // DATETIME2 → DATETIME(6)
509        result = RE_DATETIME2.replace_all(&result, "DATETIME(6)").to_string();
510
511        // DATETIMEOFFSET → DATETIME
512        result = RE_DATETIMEOFFSET
513            .replace_all(&result, "DATETIME")
514            .to_string();
515
516        // SMALLDATETIME → DATETIME
517        result = RE_SMALLDATETIME
518            .replace_all(&result, "DATETIME")
519            .to_string();
520
521        // MONEY → DECIMAL(19,4)
522        result = RE_MONEY.replace_all(&result, "DECIMAL(19,4)").to_string();
523
524        // SMALLMONEY → DECIMAL(10,4)
525        result = RE_SMALLMONEY
526            .replace_all(&result, "DECIMAL(10,4)")
527            .to_string();
528
529        // UNIQUEIDENTIFIER → VARCHAR(36)
530        result = RE_UNIQUEIDENTIFIER
531            .replace_all(&result, "VARCHAR(36)")
532            .to_string();
533
534        // XML → LONGTEXT
535        result = RE_XML.replace_all(&result, "LONGTEXT").to_string();
536
537        // ROWVERSION/MSSQL TIMESTAMP → BINARY(8)
538        result = RE_MSSQL_TIMESTAMP_BRACKETED
539            .replace_all(&result, "BINARY(8)")
540            .to_string();
541        result = RE_ROWVERSION_ONLY
542            .replace_all(&result, "BINARY(8)")
543            .to_string();
544
545        // Strip MSSQL-specific clauses
546        result = RE_ON_PRIMARY.replace_all(&result, "").to_string();
547        result = RE_CLUSTERED.replace_all(&result, "").to_string();
548        result = RE_NONCLUSTERED.replace_all(&result, "").to_string();
549
550        result
551    }
552
553    /// Convert MSSQL types to PostgreSQL
554    fn mssql_to_postgres(stmt: &str) -> String {
555        let mut result = stmt.to_string();
556
557        // IDENTITY → SERIAL (handled elsewhere)
558
559        // IMPORTANT: Handle ROWVERSION first (before any TIMESTAMP conversion)
560        // In MSSQL, TIMESTAMP is an alias for ROWVERSION (a binary type, not datetime!)
561        // Use a more specific regex that matches MSSQL TIMESTAMP but not PostgreSQL TIMESTAMP
562        result = RE_MSSQL_TIMESTAMP_BRACKETED
563            .replace_all(&result, "BYTEA")
564            .to_string();
565        result = RE_ROWVERSION_ONLY.replace_all(&result, "BYTEA").to_string();
566
567        // BIT → BOOLEAN
568        result = RE_BIT.replace_all(&result, "BOOLEAN").to_string();
569
570        // NVARCHAR(MAX) → TEXT
571        result = RE_NVARCHAR_MAX.replace_all(&result, "TEXT").to_string();
572
573        // NVARCHAR(n) → VARCHAR(n)
574        result = RE_NVARCHAR.replace_all(&result, "VARCHAR$1").to_string();
575
576        // NCHAR(n) → CHAR(n)
577        result = RE_NCHAR.replace_all(&result, "CHAR$1").to_string();
578
579        // NTEXT → TEXT
580        result = RE_NTEXT.replace_all(&result, "TEXT").to_string();
581
582        // VARCHAR(MAX) → TEXT
583        result = RE_VARCHAR_MAX.replace_all(&result, "TEXT").to_string();
584
585        // VARBINARY(MAX) → BYTEA
586        result = RE_VARBINARY_MAX.replace_all(&result, "BYTEA").to_string();
587
588        // VARBINARY(n) → BYTEA
589        result = RE_VARBINARY.replace_all(&result, "BYTEA").to_string();
590
591        // IMAGE → BYTEA
592        result = RE_IMAGE.replace_all(&result, "BYTEA").to_string();
593
594        // DATETIME2 → TIMESTAMP
595        result = RE_DATETIME2.replace_all(&result, "TIMESTAMP").to_string();
596
597        // DATETIME → TIMESTAMP (but not MSSQL TIMESTAMP which is already converted)
598        result = RE_DATETIME.replace_all(&result, "TIMESTAMP").to_string();
599
600        // DATETIMEOFFSET → TIMESTAMPTZ
601        result = RE_DATETIMEOFFSET
602            .replace_all(&result, "TIMESTAMPTZ")
603            .to_string();
604
605        // SMALLDATETIME → TIMESTAMP
606        result = RE_SMALLDATETIME
607            .replace_all(&result, "TIMESTAMP")
608            .to_string();
609
610        // MONEY → DECIMAL(19,4)
611        result = RE_MONEY.replace_all(&result, "DECIMAL(19,4)").to_string();
612
613        // SMALLMONEY → DECIMAL(10,4)
614        result = RE_SMALLMONEY
615            .replace_all(&result, "DECIMAL(10,4)")
616            .to_string();
617
618        // UNIQUEIDENTIFIER → UUID
619        result = RE_UNIQUEIDENTIFIER.replace_all(&result, "UUID").to_string();
620
621        // XML → XML (PostgreSQL supports XML type)
622
623        // FLOAT → DOUBLE PRECISION
624        result = RE_FLOAT
625            .replace_all(&result, "DOUBLE PRECISION")
626            .to_string();
627
628        // Strip MSSQL-specific clauses
629        result = RE_ON_PRIMARY.replace_all(&result, "").to_string();
630        result = RE_CLUSTERED.replace_all(&result, "").to_string();
631        result = RE_NONCLUSTERED.replace_all(&result, "").to_string();
632
633        result
634    }
635
636    /// Convert MSSQL types to SQLite
637    fn mssql_to_sqlite(stmt: &str) -> String {
638        let mut result = stmt.to_string();
639
640        // BIT → INTEGER
641        result = RE_BIT.replace_all(&result, "INTEGER").to_string();
642
643        // NVARCHAR → TEXT
644        result = RE_NVARCHAR_MAX.replace_all(&result, "TEXT").to_string();
645        result = RE_NVARCHAR.replace_all(&result, "TEXT").to_string();
646
647        // NCHAR → TEXT
648        result = RE_NCHAR.replace_all(&result, "TEXT").to_string();
649
650        // NTEXT → TEXT
651        result = RE_NTEXT.replace_all(&result, "TEXT").to_string();
652
653        // VARCHAR(MAX) → TEXT
654        result = RE_VARCHAR_MAX.replace_all(&result, "TEXT").to_string();
655
656        // VARBINARY → BLOB
657        result = RE_VARBINARY_MAX.replace_all(&result, "BLOB").to_string();
658        result = RE_VARBINARY.replace_all(&result, "BLOB").to_string();
659
660        // IMAGE → BLOB
661        result = RE_IMAGE.replace_all(&result, "BLOB").to_string();
662
663        // Date/time → TEXT
664        result = RE_DATETIME2.replace_all(&result, "TEXT").to_string();
665        result = RE_DATETIME.replace_all(&result, "TEXT").to_string();
666        result = RE_DATETIMEOFFSET.replace_all(&result, "TEXT").to_string();
667        result = RE_SMALLDATETIME.replace_all(&result, "TEXT").to_string();
668
669        // MONEY → REAL
670        result = RE_MONEY.replace_all(&result, "REAL").to_string();
671        result = RE_SMALLMONEY.replace_all(&result, "REAL").to_string();
672
673        // UNIQUEIDENTIFIER → TEXT
674        result = RE_UNIQUEIDENTIFIER.replace_all(&result, "TEXT").to_string();
675
676        // XML → TEXT
677        result = RE_XML.replace_all(&result, "TEXT").to_string();
678
679        // ROWVERSION/MSSQL TIMESTAMP → BLOB
680        result = RE_MSSQL_TIMESTAMP_BRACKETED
681            .replace_all(&result, "BLOB")
682            .to_string();
683        result = RE_ROWVERSION_ONLY.replace_all(&result, "BLOB").to_string();
684
685        // FLOAT → REAL
686        result = RE_FLOAT.replace_all(&result, "REAL").to_string();
687
688        // Strip MSSQL-specific clauses
689        result = RE_ON_PRIMARY.replace_all(&result, "").to_string();
690        result = RE_CLUSTERED.replace_all(&result, "").to_string();
691        result = RE_NONCLUSTERED.replace_all(&result, "").to_string();
692
693        result
694    }
695}
696
697// Pre-compiled regexes for type matching
698static RE_TINYINT_BOOL: Lazy<Regex> =
699    Lazy::new(|| Regex::new(r"(?i)\bTINYINT\s*\(\s*1\s*\)").unwrap());
700static RE_TINYINT: Lazy<Regex> =
701    Lazy::new(|| Regex::new(r"(?i)\bTINYINT\s*(\(\s*\d+\s*\))?").unwrap());
702static RE_SMALLINT: Lazy<Regex> =
703    Lazy::new(|| Regex::new(r"(?i)\bSMALLINT\s*(\(\s*\d+\s*\))?").unwrap());
704static RE_MEDIUMINT: Lazy<Regex> =
705    Lazy::new(|| Regex::new(r"(?i)\bMEDIUMINT\s*(\(\s*\d+\s*\))?").unwrap());
706static RE_INT_SIZE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bINT\s*\(\s*\d+\s*\)").unwrap());
707static RE_BIGINT_SIZE: Lazy<Regex> =
708    Lazy::new(|| Regex::new(r"(?i)\bBIGINT\s*\(\s*\d+\s*\)").unwrap());
709
710static RE_DOUBLE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bDOUBLE\b").unwrap());
711static RE_FLOAT: Lazy<Regex> =
712    Lazy::new(|| Regex::new(r"(?i)\bFLOAT\s*(\(\s*\d+\s*(,\s*\d+\s*)?\))?").unwrap());
713static RE_DECIMAL: Lazy<Regex> =
714    Lazy::new(|| Regex::new(r"(?i)\bDECIMAL\s*\(\s*\d+\s*(,\s*\d+\s*)?\)").unwrap());
715
716static RE_LONGTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bLONGTEXT\b").unwrap());
717static RE_MEDIUMTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bMEDIUMTEXT\b").unwrap());
718static RE_TINYTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTINYTEXT\b").unwrap());
719static RE_VARCHAR: Lazy<Regex> =
720    Lazy::new(|| Regex::new(r"(?i)\bVARCHAR\s*\(\s*\d+\s*\)").unwrap());
721static RE_CHAR: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCHAR\s*\(\s*\d+\s*\)").unwrap());
722
723static RE_LONGBLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bLONGBLOB\b").unwrap());
724static RE_MEDIUMBLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bMEDIUMBLOB\b").unwrap());
725static RE_TINYBLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTINYBLOB\b").unwrap());
726static RE_BLOB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBLOB\b").unwrap());
727static RE_VARBINARY: Lazy<Regex> =
728    Lazy::new(|| Regex::new(r"(?i)\bVARBINARY\s*\(\s*\d+\s*\)").unwrap());
729static RE_BINARY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBINARY\s*\(\s*\d+\s*\)").unwrap());
730
731static RE_DATETIME: Lazy<Regex> =
732    Lazy::new(|| Regex::new(r"(?i)\bDATETIME(\(\s*\d+\s*\))?").unwrap());
733static RE_TIMESTAMP: Lazy<Regex> =
734    Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMP\s*(\(\s*\d+\s*\))?").unwrap());
735static RE_DATE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bDATE\b").unwrap());
736static RE_TIME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTIME\s*(\(\s*\d+\s*\))?").unwrap());
737
738static RE_JSON: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bJSON\b").unwrap());
739
740static RE_ENUM: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bENUM\s*\([^)]+\)").unwrap());
741static RE_SET: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSET\s*\([^)]+\)").unwrap());
742
743static RE_UNSIGNED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s+UNSIGNED\b").unwrap());
744static RE_ZEROFILL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\s+ZEROFILL\b").unwrap());
745
746// PostgreSQL specific types
747static RE_SERIAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSERIAL\b").unwrap());
748static RE_BIGSERIAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBIGSERIAL\b").unwrap());
749static RE_SMALLSERIAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSMALLSERIAL\b").unwrap());
750static RE_BYTEA: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBYTEA\b").unwrap());
751static RE_DOUBLE_PRECISION: Lazy<Regex> =
752    Lazy::new(|| Regex::new(r"(?i)\bDOUBLE\s+PRECISION\b").unwrap());
753static RE_REAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bREAL\b").unwrap());
754static RE_BOOLEAN: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBOOLEAN\b").unwrap());
755static RE_TIMESTAMPTZ: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMPTZ\b").unwrap());
756static RE_TIMESTAMP_WITH_TZ: Lazy<Regex> =
757    Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMP\s+WITH\s+TIME\s+ZONE\b").unwrap());
758static RE_TIMESTAMP_NO_TZ: Lazy<Regex> =
759    Lazy::new(|| Regex::new(r"(?i)\bTIMESTAMP\s+WITHOUT\s+TIME\s+ZONE\b").unwrap());
760static RE_JSONB: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bJSONB\b").unwrap());
761static RE_UUID: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bUUID\b").unwrap());
762static RE_TEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bTEXT\b").unwrap());
763
764// MSSQL specific types
765static RE_BIT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bBIT\b").unwrap());
766static RE_NVARCHAR_MAX: Lazy<Regex> =
767    Lazy::new(|| Regex::new(r"(?i)\bNVARCHAR\s*\(\s*MAX\s*\)").unwrap());
768static RE_NVARCHAR: Lazy<Regex> =
769    Lazy::new(|| Regex::new(r"(?i)\bNVARCHAR\s*(\(\s*\d+\s*\))").unwrap());
770static RE_NCHAR: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNCHAR\s*(\(\s*\d+\s*\))").unwrap());
771static RE_NTEXT: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNTEXT\b").unwrap());
772static RE_VARCHAR_MAX: Lazy<Regex> =
773    Lazy::new(|| Regex::new(r"(?i)\bVARCHAR\s*\(\s*MAX\s*\)").unwrap());
774static RE_VARBINARY_MAX: Lazy<Regex> =
775    Lazy::new(|| Regex::new(r"(?i)\bVARBINARY\s*\(\s*MAX\s*\)").unwrap());
776static RE_IMAGE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bIMAGE\b").unwrap());
777static RE_DATETIME2: Lazy<Regex> =
778    Lazy::new(|| Regex::new(r"(?i)\bDATETIME2\s*(\(\s*\d+\s*\))?").unwrap());
779static RE_DATETIMEOFFSET: Lazy<Regex> =
780    Lazy::new(|| Regex::new(r"(?i)\bDATETIMEOFFSET\s*(\(\s*\d+\s*\))?").unwrap());
781static RE_SMALLDATETIME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSMALLDATETIME\b").unwrap());
782static RE_MONEY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bMONEY\b").unwrap());
783static RE_SMALLMONEY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bSMALLMONEY\b").unwrap());
784static RE_UNIQUEIDENTIFIER: Lazy<Regex> =
785    Lazy::new(|| Regex::new(r"(?i)\bUNIQUEIDENTIFIER\b").unwrap());
786static RE_XML: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bXML\b").unwrap());
787// MSSQL TIMESTAMP type (binary versioning, NOT datetime) - only match bracketed [TIMESTAMP]
788// or as column type after brackets. We can't match unbracketed standalone TIMESTAMP safely
789// because it would conflict with PostgreSQL TIMESTAMP result. So we rely on context.
790static RE_MSSQL_TIMESTAMP_BRACKETED: Lazy<Regex> =
791    Lazy::new(|| Regex::new(r"(?i)\[\s*TIMESTAMP\s*\]").unwrap());
792static RE_ROWVERSION_ONLY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bROWVERSION\b").unwrap());
793
794// MSSQL-specific clauses to strip when converting to other dialects
795static RE_ON_PRIMARY: Lazy<Regex> =
796    Lazy::new(|| Regex::new(r"(?i)\s*ON\s*\[\s*PRIMARY\s*\]").unwrap());
797static RE_CLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bCLUSTERED\s+").unwrap());
798static RE_NONCLUSTERED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNONCLUSTERED\s+").unwrap());
799
800#[cfg(test)]
801mod map_column_type_tests {
802    use super::*;
803
804    #[test]
805    fn same_dialect_is_identity_and_warning_free() {
806        let mut warnings = WarningCollector::new();
807        let mapped = map_column_type(
808            "VARCHAR(255)",
809            SqlDialect::MySql,
810            SqlDialect::MySql,
811            &mut warnings,
812        );
813        assert_eq!(mapped, "VARCHAR(255)");
814        assert!(!warnings.has_warnings());
815    }
816
817    #[test]
818    fn cross_dialect_reuses_the_statement_level_regex_rules() {
819        let mut warnings = WarningCollector::new();
820        let mapped = map_column_type(
821            "BIGINT(20)",
822            SqlDialect::MySql,
823            SqlDialect::Postgres,
824            &mut warnings,
825        );
826        assert_eq!(mapped, "BIGINT");
827    }
828
829    #[test]
830    fn narrowing_enum_to_a_plain_string_records_a_lossy_warning() {
831        let mut warnings = WarningCollector::new();
832        let mapped = map_column_type(
833            "ENUM('a','b')",
834            SqlDialect::MySql,
835            SqlDialect::Postgres,
836            &mut warnings,
837        );
838        assert_eq!(mapped, "VARCHAR(255)");
839        assert!(warnings.has_warnings());
840        assert!(matches!(
841            warnings.warnings()[0],
842            ConvertWarning::LossyConversion { .. }
843        ));
844    }
845
846    #[test]
847    fn json_to_an_engine_without_a_json_type_is_lossy() {
848        let mut warnings = WarningCollector::new();
849        map_column_type("JSON", SqlDialect::MySql, SqlDialect::Sqlite, &mut warnings);
850        assert!(warnings.has_warnings());
851
852        // PostgreSQL keeps a native JSON type, so the same source is not lossy.
853        let mut kept = WarningCollector::new();
854        map_column_type("JSON", SqlDialect::MySql, SqlDialect::Postgres, &mut kept);
855        assert!(!kept.has_warnings());
856    }
857
858    #[test]
859    fn uuid_stored_as_text_is_lossy() {
860        let mut warnings = WarningCollector::new();
861        map_column_type(
862            "UUID",
863            SqlDialect::Postgres,
864            SqlDialect::MySql,
865            &mut warnings,
866        );
867        assert!(warnings.has_warnings());
868
869        // MSSQL has UNIQUEIDENTIFIER, so a UUID keeps its native domain there.
870        let mut kept = WarningCollector::new();
871        map_column_type("UUID", SqlDialect::Postgres, SqlDialect::Mssql, &mut kept);
872        assert!(!kept.has_warnings());
873    }
874
875    #[test]
876    fn decimal_to_sqlite_real_is_lossy() {
877        // SQLite has no exact fixed-point type; the mapper renders DECIMAL as
878        // REAL (binary float), silently losing exact precision.
879        let mut warnings = WarningCollector::new();
880        map_column_type(
881            "DECIMAL(10,2)",
882            SqlDialect::MySql,
883            SqlDialect::Sqlite,
884            &mut warnings,
885        );
886        assert!(warnings.has_warnings());
887
888        // PostgreSQL keeps a native DECIMAL, so the same source is not lossy.
889        let mut kept = WarningCollector::new();
890        map_column_type(
891            "DECIMAL(10,2)",
892            SqlDialect::MySql,
893            SqlDialect::Postgres,
894            &mut kept,
895        );
896        assert!(!kept.has_warnings());
897    }
898
899    #[test]
900    fn timestamptz_to_mysql_drops_the_timezone_and_is_lossy() {
901        // MySQL DATETIME has no time-zone component, so the tz is dropped.
902        let mut warnings = WarningCollector::new();
903        map_column_type(
904            "TIMESTAMPTZ",
905            SqlDialect::Postgres,
906            SqlDialect::MySql,
907            &mut warnings,
908        );
909        assert!(warnings.has_warnings());
910
911        // MSSQL DATETIMEOFFSET preserves the time zone, so it is not lossy.
912        let mut kept = WarningCollector::new();
913        map_column_type(
914            "TIMESTAMPTZ",
915            SqlDialect::Postgres,
916            SqlDialect::Mssql,
917            &mut kept,
918        );
919        assert!(!kept.has_warnings());
920    }
921}