Skip to main content

larust_convert/
migrations.rs

1//! `database/migrations/*.php` (`Schema::create`/`Schema::table` +
2//! `Blueprint`) → Larust's own migration format, which is raw SQL files
3//! (`NNNN_snake_case_description.sql`, applied in filename-sort order -
4//! see `larust_orm::migrate`), not a DSL. Column-type mapping verified
5//! against the real files under `demo/database/migrations/`.
6//!
7//! **`$table->timestamps()` is emitted, but never counted as fully
8//! converted** - the schema half (`created_at INTEGER`/`updated_at
9//! INTEGER`) is real, but `#[derive(Model)]`'s own `#[timestamps]`
10//! (auto-population, matching Eloquent's default auto-touch behavior) is
11//! a separate, opt-in attribute the corresponding model still needs
12//! adding by hand, so a silent "converted automatically" count would
13//! misleadingly imply that second step already happened. Every migration
14//! using it adds a manual-review report note pointing at `#[timestamps]`
15//! instead.
16//!
17//! **Backend-aware since this crate's own DB_CONNECTION recognition grew
18//! real Postgres/MySQL/MariaDB support** (see `env.rs`'s own doc comment):
19//! this module used to emit SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT`
20//! unconditionally, regardless of the source app's actual driver - a real,
21//! silent gap, since that syntax is invalid on both MySQL (`AUTOINCREMENT`
22//! isn't a MySQL keyword; the equivalent is `AUTO_INCREMENT`) and Postgres
23//! (no `AUTOINCREMENT`/`AUTO_INCREMENT` at all; the idiomatic equivalent is
24//! a `SERIAL` column).
25//!
26//! **Every [`TargetDriver`]-specific rendering decision here was found by
27//! actually running the generated SQL against a real server**, not by
28//! reading documentation alone - each one failed loudly the first time,
29//! against a real Postgres 16 and MySQL 8.4 container, before being fixed:
30//! - The id-column syntax above (`sql_type_text`'s `ColumnType::Id` arms).
31//! - MySQL rejects `UNIQUE` on a bare `TEXT` column (error 1170 - "BLOB/TEXT
32//!   column used in key specification without a key length"), so Laravel's
33//!   *bounded* `$table->string()` renders as `VARCHAR(255)` on MySQL
34//!   specifically (`ColumnType::String` - see its own doc comment); every
35//!   other driver, and every genuinely unbounded `text()`/`longText()`/
36//!   `mediumText()`/`json()` column, still renders as plain `TEXT`.
37//! - MySQL 8.0.13+ still rejects a bare-literal `DEFAULT ''` on a `TEXT`
38//!   column (error 1101), and only accepts one wrapped as an *expression*
39//!   default, `DEFAULT ('')` - see [`column_sql`]'s own doc comment.
40//!
41//! `INTEGER`, `REFERENCES`, and a plain (non-defaulted, non-MySQL-`TEXT`)
42//! `UNIQUE` render identically across all three - [`TargetDriver`] changes
43//! exactly the three things above, not the whole conversion.
44
45use crate::php::{self, CallStep};
46use anyhow::Result;
47
48/// The SQL dialect a converted migration's id-column syntax should target -
49/// derived from the source Laravel app's own `DB_CONNECTION` (see
50/// [`TargetDriver::from_db_connection`]), not guessed independently of it.
51/// Deliberately a small, local enum rather than a dependency on
52/// `larust_orm::config::Driver`/`Backend`: this crate does no runtime DB
53/// work at all (it only ever emits `.sql` text), so pulling in `larust-orm`
54/// (and transitively `sqlx`) just for a 3-variant enum would be a real,
55/// unjustified dependency-weight increase for a text-in/text-out module.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum TargetDriver {
58    Sqlite,
59    MySql,
60    Postgres,
61}
62
63impl TargetDriver {
64    /// Maps a Laravel `DB_CONNECTION` value the same way `env.rs`'s own
65    /// `SUPPORTED_DB_CONNECTIONS` does (`mariadb` is a pure MySQL alias -
66    /// same wire protocol, same DDL). A `DB_CONNECTION` this crate doesn't
67    /// recognize at all (`sqlsrv`, anything else, or no `.env` present)
68    /// falls back to `Sqlite` - not because that's a good guess at the
69    /// real target, but because it's the same "this migration can't
70    /// actually run against the app's real database anyway" situation
71    /// `env.rs`'s own `resolve_database_connection` already reports a
72    /// dedicated note for; there is no meaningfully-more-correct fallback
73    /// to pick instead.
74    pub fn from_db_connection(value: &str) -> Self {
75        match value {
76            "mysql" | "mariadb" => Self::MySql,
77            "pgsql" => Self::Postgres,
78            _ => Self::Sqlite,
79        }
80    }
81
82    /// The matching `larust-support` sqlx-driver feature name (see
83    /// `larust-orm/Cargo.toml`'s own `[features]` comment) - `xr convert`
84    /// pushes this into the generated app's own `Cargo.toml` so a
85    /// converted app keeps whichever driver the source Laravel app
86    /// actually used, rather than silently falling back to the scaffold's
87    /// `"sqlite"` default.
88    pub fn support_feature(self) -> &'static str {
89        match self {
90            Self::Sqlite => "sqlite",
91            Self::MySql => "mysql",
92            Self::Postgres => "postgres",
93        }
94    }
95}
96
97/// What a column's SQL type ultimately renders as - kept driver-agnostic
98/// here so `classify_chain`/`build_column` (which run once, before the
99/// target driver is even known further down the call stack in a future
100/// refactor) never need to care about it; only [`column_sql`] resolves a
101/// `ColumnType` + [`TargetDriver`] pair into real SQL text.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103enum ColumnType {
104    /// Laravel's `$table->id()` - an auto-incrementing primary key. The
105    /// only column type whose actual SQL text varies by driver at all;
106    /// see [`column_sql`].
107    Id,
108    /// Laravel's `$table->string()` - a *bounded* string, `VARCHAR(255)`
109    /// by Laravel's own default. Kept distinct from [`ColumnType::Text`]
110    /// (see that variant's own doc comment for why the split matters) -
111    /// live-verified via a real MySQL container the hard way: `xr migrate`
112    /// failed with MySQL error 1170 ("BLOB/TEXT column used in key
113    /// specification without a key length") the first time a Blueprint's
114    /// `$table->string('email')->unique()` rendered as unbounded `TEXT` on
115    /// a MySQL target, because `UNIQUE` on MySQL `TEXT`/`BLOB` needs an
116    /// explicit index prefix length MySQL DDL alone can't express inline.
117    String,
118    /// Laravel's `$table->text()`/`longText()`/`mediumText()`/`json()` - a
119    /// genuinely unbounded column. Rendered identically across every
120    /// driver (`TEXT` - see [`sql_type_text`]), unlike [`ColumnType::String`],
121    /// which needs `VARCHAR(255)` on MySQL specifically.
122    Text,
123    Integer,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
127struct Column {
128    name: String,
129    sql_type: ColumnType,
130    nullable: bool,
131    default: Option<String>,
132    unique: bool,
133    references: Option<String>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137enum Statement {
138    Column(Column),
139    /// `created_at`/`updated_at`, both `INTEGER` (Unix seconds - matching
140    /// this codebase's existing convention for every other framework-owned
141    /// timestamp-shaped column, e.g. `cache_items.expires_at`).
142    Timestamps,
143    PrimaryKey(Vec<String>),
144    /// A Blueprint method this phase doesn't recognize (e.g. `dropColumn`,
145    /// `softDeletes`) - the column/statement is skipped, and the whole
146    /// migration gets a manual-review flag naming it, rather than
147    /// silently emitting an incomplete table.
148    Unrecognized(String),
149}
150
151pub struct ConvertedMigration {
152    pub sql: String,
153    pub uses_timestamps: bool,
154    pub unrecognized: Vec<String>,
155}
156
157/// Converts one migration file's source. Returns `Ok(None)` if the file
158/// has a syntax error (flagged by the caller, not guessed at) or contains
159/// no `Schema::create`/`Schema::table` call at all (nothing to convert -
160/// e.g. a migration that only runs raw DB statements Laravel-side).
161pub fn convert(source: &str, driver: TargetDriver) -> Result<Option<ConvertedMigration>> {
162    let tree = php::parse(source)?;
163    if php::has_syntax_error(&tree) {
164        return Ok(None);
165    }
166
167    let query = r#"
168        (scoped_call_expression
169            scope: (name) @scope
170            name: (name) @method) @call
171    "#;
172    let calls = php::query_nodes(&tree, source, query, "call")?;
173
174    for call in calls {
175        let Some(scope) = call.child_by_field_name("scope") else {
176            continue;
177        };
178        if scope.utf8_text(source.as_bytes()).unwrap_or("") != "Schema" {
179            continue;
180        }
181        let Some(method) = call.child_by_field_name("name") else {
182            continue;
183        };
184        let method = method.utf8_text(source.as_bytes()).unwrap_or("");
185        let is_create = method == "create";
186        let is_alter = method == "table";
187        if !is_create && !is_alter {
188            continue;
189        }
190
191        let Some(table_arg) = php::argument_node(call, 0) else {
192            continue;
193        };
194        let table = php::unquote(table_arg.utf8_text(source.as_bytes()).unwrap_or(""));
195
196        let Some(closure_arg) = php::argument_node(call, 1) else {
197            continue;
198        };
199        let Some(body) = php::closure_body(closure_arg) else {
200            continue;
201        };
202
203        let statements = parse_blueprint_body(body, source);
204        return Ok(Some(render(&table, is_create, &statements, driver)));
205    }
206
207    Ok(None)
208}
209
210fn parse_blueprint_body(body: tree_sitter::Node, source: &str) -> Vec<Statement> {
211    php::statement_expressions(body)
212        .into_iter()
213        .filter_map(|expr| php::walk_call_chain(expr, source))
214        .map(|chain| classify_chain(&chain))
215        .collect()
216}
217
218fn classify_chain(chain: &[CallStep]) -> Statement {
219    let Some(base) = chain.first() else {
220        return Statement::Unrecognized(String::new());
221    };
222
223    match base.method.as_str() {
224        "timestamps" => Statement::Timestamps,
225        "primary" => {
226            let cols = base
227                .args
228                .first()
229                .map(|arg| parse_string_array(arg))
230                .unwrap_or_default();
231            Statement::PrimaryKey(cols)
232        }
233        "id" => {
234            let name = base
235                .args
236                .first()
237                .map(|a| php::unquote(a))
238                .unwrap_or_else(|| "id".to_string());
239            Statement::Column(Column {
240                name,
241                sql_type: ColumnType::Id,
242                nullable: false,
243                default: None,
244                unique: false,
245                references: None,
246            })
247        }
248        // `longText`/`mediumText` are MySQL/Postgres storage-size hints
249        // Laravel exposes on `Blueprint` for parity - SQLite has no
250        // matching distinction (a `TEXT` column has no length limit), so
251        // they render identically to `text` (see `ColumnType::Text`'s own
252        // doc comment for why `string` - bounded, `VARCHAR(255)` - is kept
253        // separate rather than folded in here too). `json` renders the
254        // same way: a faithful, un-decoded `TEXT` column, matching this
255        // whole module's mechanical-conversion philosophy (see the module
256        // doc comment) rather than guessing at whatever `$casts` array
257        // entry the original Eloquent model may or may not have had for
258        // it - Larust's own model field ends up `Option<String>`, same as
259        // any other nullable text column, with encode/decode left as an
260        // explicit manual step rather than assumed.
261        "string" => build_column(chain, ColumnType::String),
262        "text" | "longText" | "mediumText" | "json" => build_column(chain, ColumnType::Text),
263        "integer" | "bigInteger" | "unsignedBigInteger" => build_column(chain, ColumnType::Integer),
264        "boolean" => build_column(chain, ColumnType::Integer),
265        "foreignId" => build_column(chain, ColumnType::Integer),
266        other => Statement::Unrecognized(other.to_string()),
267    }
268}
269
270/// Builds a `Column` from a chain whose base call names the column (e.g.
271/// `string('title')`, `foreignId('user_id')`) and whose remaining links
272/// are modifiers (`->nullable()`, `->default(...)`, `->unique()`,
273/// `->constrained(...)`) applied in whatever order Laravel source wrote
274/// them - order doesn't matter for the SQL these produce, only presence.
275fn build_column(chain: &[CallStep], sql_type: ColumnType) -> Statement {
276    let base = &chain[0];
277    let name = base
278        .args
279        .first()
280        .map(|a| php::unquote(a))
281        .unwrap_or_default();
282
283    let mut nullable = false;
284    let mut default = None;
285    let mut unique = false;
286    let mut references = None;
287
288    for step in &chain[1..] {
289        match step.method.as_str() {
290            "nullable" => nullable = true,
291            "unique" => unique = true,
292            "default" => {
293                default = step.args.first().map(|raw| render_default(raw));
294            }
295            "constrained" => {
296                references = Some(
297                    step.args
298                        .first()
299                        .map(|a| php::unquote(a))
300                        .unwrap_or_else(|| infer_referenced_table(&name)),
301                );
302            }
303            _ => {}
304        }
305    }
306
307    Statement::Column(Column {
308        name,
309        sql_type,
310        nullable,
311        default,
312        unique,
313        references,
314    })
315}
316
317/// A PHP string literal default (`'foo'`) is already valid SQL string
318/// literal syntax verbatim; anything else (a bare number, `true`/`false`)
319/// is passed through as written - SQLite has no dedicated boolean literal,
320/// but `default(true)`/`default(false)` don't appear in this framework's
321/// own migrations today, and this phase never claims to translate every
322/// possible Blueprint default expression, only the common literal case.
323fn render_default(raw: &str) -> String {
324    raw.to_string()
325}
326
327/// Laravel's own `foreignId('user_id')->constrained()` (no explicit table
328/// argument) infers the referenced table by stripping a trailing `_id`
329/// and pluralizing what's left - `user_id` -> `users`, matching
330/// `codegen::pluralize`'s existing heuristic, reused here rather than
331/// duplicated.
332fn infer_referenced_table(column_name: &str) -> String {
333    let stem = column_name.strip_suffix("_id").unwrap_or(column_name);
334    crate::codegen::pluralize(stem)
335}
336
337/// A bare `[a, b]`/`['a', 'b']` PHP array literal of strings - the shape
338/// `$table->primary([...])`'s single argument always takes in real Laravel
339/// migrations. Not a general PHP-array parser: no nested arrays, no
340/// associative keys, no trailing-comma edge cases beyond a plain split.
341fn parse_string_array(text: &str) -> Vec<String> {
342    let inner = text.trim().trim_start_matches('[').trim_end_matches(']');
343    inner
344        .split(',')
345        .map(str::trim)
346        .filter(|s| !s.is_empty())
347        .map(php::unquote)
348        .collect()
349}
350
351fn render(
352    table: &str,
353    is_create: bool,
354    statements: &[Statement],
355    driver: TargetDriver,
356) -> ConvertedMigration {
357    let mut lines = Vec::new();
358    let mut uses_timestamps = false;
359    let mut unrecognized = Vec::new();
360
361    for statement in statements {
362        match statement {
363            Statement::Column(col) => lines.push(column_sql(col, driver)),
364            Statement::Timestamps => {
365                uses_timestamps = true;
366                lines.push("created_at INTEGER".to_string());
367                lines.push("updated_at INTEGER".to_string());
368            }
369            Statement::PrimaryKey(cols) => {
370                if !cols.is_empty() {
371                    lines.push(format!("PRIMARY KEY ({})", cols.join(", ")));
372                }
373            }
374            Statement::Unrecognized(method) => {
375                if !method.is_empty() {
376                    unrecognized.push(method.clone());
377                }
378            }
379        }
380    }
381
382    let sql = if is_create {
383        format!(
384            "CREATE TABLE {table} (\n{}\n);\n",
385            lines
386                .iter()
387                .map(|l| format!("    {l}"))
388                .collect::<Vec<_>>()
389                .join(",\n")
390        )
391    } else {
392        lines
393            .iter()
394            .map(|l| format!("ALTER TABLE {table} ADD COLUMN {l};\n"))
395            .collect::<String>()
396    };
397
398    ConvertedMigration {
399        sql,
400        uses_timestamps,
401        unrecognized,
402    }
403}
404
405fn column_sql(col: &Column, driver: TargetDriver) -> String {
406    let mut s = format!("{} {}", col.name, sql_type_text(col.sql_type, driver));
407    if !col.nullable && col.sql_type != ColumnType::Id {
408        s.push_str(" NOT NULL");
409    }
410    if let Some(table) = &col.references {
411        s.push_str(&format!(" REFERENCES {table}(id)"));
412    }
413    if col.unique {
414        s.push_str(" UNIQUE");
415    }
416    if let Some(default) = &col.default {
417        // MySQL 8.0.13+ only accepts a `TEXT` column default when it's an
418        // *expression* default - a literal wrapped in parens, `DEFAULT
419        // ('')` - not a bare `DEFAULT ''`; a bare literal fails with error
420        // 1101 ("BLOB, TEXT, GEOMETRY or JSON column can't have a default
421        // value"), live-caught against a real MySQL 8.4 container (the
422        // pre-8.0.13 restriction's own error text, still raised for the
423        // bare-literal spelling even though the restriction itself was
424        // lifted). `VARCHAR` (`ColumnType::String`) has no such
425        // restriction on any driver, so this only touches `Text`+MySQL.
426        if driver == TargetDriver::MySql && col.sql_type == ColumnType::Text {
427            s.push_str(&format!(" DEFAULT ({default})"));
428        } else {
429            s.push_str(&format!(" DEFAULT {default}"));
430        }
431    }
432    s
433}
434
435/// The only place a `TargetDriver` actually changes anything: `Id`'s
436/// auto-increment syntax. SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` is
437/// invalid on both other backends - MySQL spells it `AUTO_INCREMENT` (and
438/// still needs the `INTEGER`/`PRIMARY KEY` around it); Postgres has no
439/// auto-increment keyword at all, `SERIAL PRIMARY KEY` (an `INTEGER`
440/// column backed by an implicit sequence) is its idiomatic equivalent, and
441/// already implies `NOT NULL` on its own (see `column_sql`'s own
442/// `ColumnType::Id` exclusion above). `Text`/`Integer` render identically
443/// across all three - plain `TEXT`/`INTEGER` are valid, unbounded-length
444/// column types on SQLite, MySQL, and Postgres alike.
445///
446/// `String` is the second place a driver actually matters, live-caught the
447/// hard way (see `ColumnType::String`'s own doc comment): MySQL needs
448/// `VARCHAR(255)` specifically so `UNIQUE` (and any future index) can be
449/// declared on it inline - MySQL's `TEXT`/`BLOB` types need an explicit
450/// index *prefix length* MySQL DDL can't express as a bare column-level
451/// `UNIQUE` keyword. SQLite and Postgres have no such restriction (neither
452/// distinguishes an indexable bounded string from unbounded `TEXT`), so
453/// both keep rendering it as plain `TEXT`, matching `ColumnType::Text`.
454fn sql_type_text(sql_type: ColumnType, driver: TargetDriver) -> &'static str {
455    match (sql_type, driver) {
456        (ColumnType::Id, TargetDriver::Sqlite) => "INTEGER PRIMARY KEY AUTOINCREMENT",
457        (ColumnType::Id, TargetDriver::MySql) => "INTEGER PRIMARY KEY AUTO_INCREMENT",
458        (ColumnType::Id, TargetDriver::Postgres) => "SERIAL PRIMARY KEY",
459        (ColumnType::String, TargetDriver::MySql) => "VARCHAR(255)",
460        (ColumnType::String, TargetDriver::Sqlite | TargetDriver::Postgres) => "TEXT",
461        (ColumnType::Text, _) => "TEXT",
462        (ColumnType::Integer, _) => "INTEGER",
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn converts_a_create_with_foreign_key_and_default() {
472        let source = r#"<?php
473
474use Illuminate\Database\Migrations\Migration;
475use Illuminate\Database\Schema\Blueprint;
476use Illuminate\Support\Facades\Schema;
477
478return new class extends Migration {
479    public function up(): void
480    {
481        Schema::create('posts', function (Blueprint $table) {
482            $table->id();
483            $table->foreignId('user_id')->constrained();
484            $table->string('title');
485            $table->text('content')->default('');
486        });
487    }
488};
489"#;
490        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
491        assert_eq!(
492            result.sql,
493            "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    user_id INTEGER NOT NULL REFERENCES users(id),\n    title TEXT NOT NULL,\n    content TEXT NOT NULL DEFAULT ''\n);\n"
494        );
495        assert!(!result.uses_timestamps);
496        assert!(result.unrecognized.is_empty());
497    }
498
499    #[test]
500    fn converts_a_unique_column() {
501        let source = r#"<?php
502Schema::create('users', function (Blueprint $table) {
503    $table->id();
504    $table->string('email')->unique();
505});
506"#;
507        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
508        assert!(result.sql.contains("email TEXT NOT NULL UNIQUE"));
509    }
510
511    #[test]
512    fn converts_a_pivot_table_with_composite_primary_key() {
513        let source = r#"<?php
514Schema::create('post_tag', function (Blueprint $table) {
515    $table->foreignId('post_id')->constrained();
516    $table->foreignId('tag_id')->constrained();
517    $table->primary(['post_id', 'tag_id']);
518});
519"#;
520        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
521        assert!(result
522            .sql
523            .contains("post_id INTEGER NOT NULL REFERENCES posts(id)"));
524        assert!(result
525            .sql
526            .contains("tag_id INTEGER NOT NULL REFERENCES tags(id)"));
527        assert!(result.sql.contains("PRIMARY KEY (post_id, tag_id)"));
528    }
529
530    #[test]
531    fn timestamps_are_emitted_and_flagged() {
532        let source = r#"<?php
533Schema::create('posts', function (Blueprint $table) {
534    $table->id();
535    $table->timestamps();
536});
537"#;
538        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
539        assert!(result.sql.contains("created_at INTEGER"));
540        assert!(result.sql.contains("updated_at INTEGER"));
541        assert!(result.uses_timestamps);
542    }
543
544    #[test]
545    fn schema_table_emits_alter_statements() {
546        let source = r#"<?php
547Schema::table('posts', function (Blueprint $table) {
548    $table->text('content')->default('');
549});
550"#;
551        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
552        assert_eq!(
553            result.sql,
554            "ALTER TABLE posts ADD COLUMN content TEXT NOT NULL DEFAULT '';\n"
555        );
556    }
557
558    #[test]
559    fn nullable_column_drops_not_null() {
560        let source = r#"<?php
561Schema::create('posts', function (Blueprint $table) {
562    $table->boolean('published')->nullable();
563});
564"#;
565        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
566        assert!(
567            result.sql.contains("published INTEGER\n") || result.sql.contains("published INTEGER)")
568        );
569        assert!(!result.sql.contains("published INTEGER NOT NULL"));
570    }
571
572    #[test]
573    fn unrecognized_blueprint_method_is_flagged_not_silently_dropped() {
574        let source = r#"<?php
575Schema::create('posts', function (Blueprint $table) {
576    $table->id();
577    $table->softDeletes();
578});
579"#;
580        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
581        assert_eq!(result.unrecognized, vec!["softDeletes".to_string()]);
582    }
583
584    #[test]
585    fn long_text_medium_text_and_json_columns_convert_as_text_not_dropped() {
586        let source = r#"<?php
587Schema::create('settings', function (Blueprint $table) {
588    $table->id();
589    $table->string('key')->unique();
590    $table->longText('value')->nullable();
591    $table->mediumText('notes')->nullable();
592    $table->json('metadata')->nullable();
593});
594"#;
595        let result = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
596        assert!(result.unrecognized.is_empty());
597        assert!(result.sql.contains("value TEXT\n") || result.sql.contains("value TEXT,"));
598        assert!(result.sql.contains("notes TEXT\n") || result.sql.contains("notes TEXT,"));
599        assert!(result.sql.contains("metadata TEXT"));
600        assert!(!result.sql.contains("value TEXT NOT NULL"));
601    }
602
603    #[test]
604    fn returns_none_for_a_file_with_no_schema_call() {
605        let source = "<?php\n\n$x = 1;\n";
606        assert!(convert(source, TargetDriver::Sqlite).unwrap().is_none());
607    }
608
609    #[test]
610    fn mysql_target_wraps_a_text_columns_default_in_parens() {
611        // Live-caught against a real MySQL 8.4 container: a bare
612        // `content TEXT NOT NULL DEFAULT ''` fails with error 1101. See
613        // `column_sql`'s own doc comment for the expression-default fix.
614        let source = r#"<?php
615Schema::create('posts', function (Blueprint $table) {
616    $table->text('content')->default('');
617});
618"#;
619        let result = convert(source, TargetDriver::MySql).unwrap().unwrap();
620        assert!(result.sql.contains("content TEXT NOT NULL DEFAULT ('')"));
621    }
622
623    #[test]
624    fn sqlite_and_postgres_do_not_wrap_text_defaults_in_parens() {
625        let source = r#"<?php
626Schema::create('posts', function (Blueprint $table) {
627    $table->text('content')->default('');
628});
629"#;
630        for driver in [TargetDriver::Sqlite, TargetDriver::Postgres] {
631            let result = convert(source, driver).unwrap().unwrap();
632            assert!(result.sql.contains("content TEXT NOT NULL DEFAULT ''"));
633            assert!(!result.sql.contains("DEFAULT ('')"));
634        }
635    }
636
637    #[test]
638    fn mysql_target_renders_auto_increment_instead_of_sqlites_autoincrement() {
639        let source = r#"<?php
640Schema::create('posts', function (Blueprint $table) {
641    $table->id();
642});
643"#;
644        let result = convert(source, TargetDriver::MySql).unwrap().unwrap();
645        assert!(result.sql.contains("id INTEGER PRIMARY KEY AUTO_INCREMENT"));
646        assert!(!result.sql.contains("AUTOINCREMENT"));
647    }
648
649    #[test]
650    fn postgres_target_renders_serial_primary_key() {
651        let source = r#"<?php
652Schema::create('posts', function (Blueprint $table) {
653    $table->id();
654    $table->foreignId('user_id')->constrained();
655});
656"#;
657        let result = convert(source, TargetDriver::Postgres).unwrap().unwrap();
658        assert!(result.sql.contains("id SERIAL PRIMARY KEY"));
659        // `SERIAL PRIMARY KEY` already implies NOT NULL - the id column
660        // should never get a redundant explicit `NOT NULL` appended.
661        assert!(!result.sql.contains("id SERIAL PRIMARY KEY NOT NULL"));
662        assert!(result
663            .sql
664            .contains("user_id INTEGER NOT NULL REFERENCES users(id)"));
665    }
666
667    #[test]
668    fn text_and_integer_columns_render_identically_across_every_target_driver() {
669        // Deliberately no `string()` column here - see the next two tests
670        // for why that one *does* diverge by driver.
671        let source = r#"<?php
672Schema::create('posts', function (Blueprint $table) {
673    $table->text('content')->nullable();
674    $table->boolean('published')->default(0);
675});
676"#;
677        let sqlite = convert(source, TargetDriver::Sqlite).unwrap().unwrap();
678        let mysql = convert(source, TargetDriver::MySql).unwrap().unwrap();
679        let postgres = convert(source, TargetDriver::Postgres).unwrap().unwrap();
680        assert_eq!(sqlite.sql, mysql.sql);
681        assert_eq!(sqlite.sql, postgres.sql);
682    }
683
684    #[test]
685    fn mysql_target_renders_string_as_varchar_so_unique_can_be_indexed() {
686        // Live-caught against a real MySQL container: `email TEXT UNIQUE`
687        // fails with MySQL error 1170 ("BLOB/TEXT column used in key
688        // specification without a key length"). `VARCHAR(255)` needs no
689        // explicit key length to be indexed.
690        let source = r#"<?php
691Schema::create('users', function (Blueprint $table) {
692    $table->string('email')->unique();
693});
694"#;
695        let result = convert(source, TargetDriver::MySql).unwrap().unwrap();
696        assert!(result.sql.contains("email VARCHAR(255) NOT NULL UNIQUE"));
697        assert!(!result.sql.contains("email TEXT"));
698    }
699
700    #[test]
701    fn sqlite_and_postgres_still_render_string_as_plain_text() {
702        let source = r#"<?php
703Schema::create('users', function (Blueprint $table) {
704    $table->string('email')->unique();
705});
706"#;
707        for driver in [TargetDriver::Sqlite, TargetDriver::Postgres] {
708            let result = convert(source, driver).unwrap().unwrap();
709            assert!(result.sql.contains("email TEXT NOT NULL UNIQUE"));
710        }
711    }
712
713    #[test]
714    fn target_driver_from_db_connection_recognizes_mysql_family_and_postgres() {
715        assert_eq!(
716            TargetDriver::from_db_connection("mysql"),
717            TargetDriver::MySql
718        );
719        assert_eq!(
720            TargetDriver::from_db_connection("mariadb"),
721            TargetDriver::MySql
722        );
723        assert_eq!(
724            TargetDriver::from_db_connection("pgsql"),
725            TargetDriver::Postgres
726        );
727        assert_eq!(
728            TargetDriver::from_db_connection("sqlite"),
729            TargetDriver::Sqlite
730        );
731    }
732
733    #[test]
734    fn target_driver_from_db_connection_falls_back_to_sqlite_for_sqlsrv_and_unknown() {
735        // Neither is actually runnable through Larust's ORM (see env.rs's
736        // own `resolve_database_connection`, which already flags both with
737        // a manual-review note) - SQLite syntax is the least-wrong fallback
738        // here, not a claim that it's the real target.
739        assert_eq!(
740            TargetDriver::from_db_connection("sqlsrv"),
741            TargetDriver::Sqlite
742        );
743        assert_eq!(
744            TargetDriver::from_db_connection("oracle"),
745            TargetDriver::Sqlite
746        );
747    }
748}