Skip to main content

larust_convert/models/
schema.rs

1//! Reads Phase 1's **own already-converted `.sql` output** (not raw PHP,
2//! and not `migrations.rs`'s internal `Column` struct, which isn't
3//! `pub`) - the authoritative source of a model's fields. Two reasons:
4//!
5//! 1. **Consistency.** Phase 1 already decided which Blueprint columns
6//!    survive conversion (an unrecognized Blueprint method is dropped
7//!    from the emitted SQL, not guessed at). Re-deriving fields from raw
8//!    PHP independently could disagree with what Phase 1's migrations
9//!    will actually create - exactly the `sqlx::FromRow`/`SELECT *`
10//!    mismatch this whole sub-phase's whole-struct safety exists to
11//!    prevent.
12//! 2. **Schema accumulation.** A table's real column set can span
13//!    multiple migration files (verified against `demo/database/
14//!    migrations/`: one file creates 3 columns, a later one `ALTER
15//!    TABLE ... ADD COLUMN`s a 4th) - replaying every `.sql` file
16//!    touching a table, in filename-sort order (matching
17//!    `larust_orm::migrate`'s own apply order), is how a model's true,
18//!    final column set is recovered.
19//!
20//! Parses only the exact shapes `migrations.rs`'s own `render()` emits -
21//! this is a controlled, self-consistent format this crate wrote, not a
22//! general SQL parser. That includes all three of `migrations.rs`'s own
23//! `TargetDriver`-specific id-column spellings (`INTEGER PRIMARY KEY
24//! AUTOINCREMENT` / `... AUTO_INCREMENT` / `SERIAL PRIMARY KEY`) - a real
25//! gap once, caught before it shipped: `SERIAL PRIMARY KEY` doesn't even
26//! start with `INTEGER`, so a Postgres-targeted `id()` column fell all the
27//! way to `SqlType::Unknown`, which rejects the *whole model* (see
28//! `models::fields`) - every model in a Postgres-sourced app would have
29//! failed to convert. `AUTO_INCREMENT` (MySQL) undershot more quietly: it
30//! matched the plain `"INTEGER"` prefix check below it and silently lost
31//! primary-key recognition instead of being rejected outright.
32
33use std::collections::HashMap;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum SqlType {
37    IntegerPrimaryKey,
38    Integer,
39    Text,
40    /// A column shape this phase doesn't recognize - never guessed at;
41    /// a table with any `Unknown` column rejects the whole model (see
42    /// `models::fields`).
43    Unknown,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct SqlColumn {
48    pub name: String,
49    pub sql_type: SqlType,
50    pub not_null: bool,
51}
52
53/// Replays every migration file's content, in the order given (callers
54/// pass them filename-sorted, matching `larust_orm::migrate`'s own apply
55/// order), accumulating each table's column list across `CREATE TABLE`
56/// and `ALTER TABLE ... ADD COLUMN` statements.
57pub fn accumulate_schema<'a>(
58    sql_contents: impl IntoIterator<Item = &'a str>,
59) -> HashMap<String, Vec<SqlColumn>> {
60    let mut tables: HashMap<String, Vec<SqlColumn>> = HashMap::new();
61    for content in sql_contents {
62        apply_statements(content, &mut tables);
63    }
64    tables
65}
66
67fn apply_statements(content: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
68    for statement in content.split(';') {
69        let statement = statement.trim();
70        if statement.is_empty() {
71            continue;
72        }
73        if let Some(rest) = statement.strip_prefix("CREATE TABLE ") {
74            apply_create_table(rest, tables);
75        } else if let Some(rest) = statement.strip_prefix("ALTER TABLE ") {
76            apply_alter_table(rest, tables);
77        }
78    }
79}
80
81fn apply_create_table(rest: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
82    let Some(paren_start) = rest.find('(') else {
83        return;
84    };
85    let Some(paren_end) = rest.rfind(')') else {
86        return;
87    };
88    if paren_end <= paren_start {
89        return;
90    }
91    let table_name = rest[..paren_start].trim().to_string();
92    let body = &rest[paren_start + 1..paren_end];
93    let columns = body
94        .split(",\n")
95        .filter_map(|entry| parse_column_entry(entry.trim()));
96    tables.entry(table_name).or_default().extend(columns);
97}
98
99fn apply_alter_table(rest: &str, tables: &mut HashMap<String, Vec<SqlColumn>>) {
100    const MARKER: &str = " ADD COLUMN ";
101    let Some(marker_pos) = rest.find(MARKER) else {
102        return;
103    };
104    let table_name = rest[..marker_pos].trim().to_string();
105    let column_def = rest[marker_pos + MARKER.len()..].trim();
106    if let Some(column) = parse_column_entry(column_def) {
107        tables.entry(table_name).or_default().push(column);
108    }
109}
110
111/// One `name TYPE [modifiers...]` entry - `None` for a
112/// `PRIMARY KEY (a, b)` composite-key constraint line (not a column at
113/// all; the individual columns it names already carry their own type
114/// info from their own entries).
115fn parse_column_entry(entry: &str) -> Option<SqlColumn> {
116    let entry = entry.trim();
117    if entry.is_empty() || entry.starts_with("PRIMARY KEY") {
118        return None;
119    }
120    let mut parts = entry.splitn(2, ' ');
121    let name = parts.next()?.to_string();
122    let rest = parts.next().unwrap_or("").trim();
123    let not_null = entry.contains(" NOT NULL");
124    // Order matters: `SERIAL PRIMARY KEY` must be checked before the plain
125    // `"INTEGER"` fallback below (it doesn't start with `INTEGER` at all),
126    // and `AUTO_INCREMENT` (MySQL) must be checked before it too (it does
127    // start with `"INTEGER"`, and would otherwise match that arm first and
128    // lose its primary-key recognition) - see this module's own doc
129    // comment for the real regression this ordering fixes.
130    let sql_type = if rest.starts_with("INTEGER PRIMARY KEY AUTOINCREMENT")
131        || rest.starts_with("INTEGER PRIMARY KEY AUTO_INCREMENT")
132        || rest.starts_with("SERIAL PRIMARY KEY")
133    {
134        SqlType::IntegerPrimaryKey
135    } else if rest.starts_with("INTEGER") {
136        SqlType::Integer
137    } else if rest.starts_with("TEXT") || rest.starts_with("VARCHAR") {
138        // `VARCHAR(255)` is `migrations.rs`'s MySQL-only rendering of
139        // Laravel's `$table->string()` (see that module's `ColumnType::
140        // String` doc comment) - same Rust field type as `TEXT`
141        // (`String`/`Option<String>`; see `models::fields`), just a
142        // different SQL type name for the same underlying column shape.
143        SqlType::Text
144    } else {
145        SqlType::Unknown
146    };
147    Some(SqlColumn {
148        name,
149        sql_type,
150        not_null,
151    })
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn accumulates_columns_from_a_single_create_table() {
160        let sql = "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    user_id INTEGER NOT NULL REFERENCES users(id),\n    title TEXT NOT NULL\n);\n";
161        let tables = accumulate_schema([sql]);
162        let posts = tables.get("posts").unwrap();
163        assert_eq!(posts.len(), 3);
164        assert_eq!(posts[0].sql_type, SqlType::IntegerPrimaryKey);
165        assert_eq!(posts[1].name, "user_id");
166        assert!(posts[1].not_null);
167        assert_eq!(posts[2].sql_type, SqlType::Text);
168    }
169
170    #[test]
171    fn accumulates_a_later_alter_table_add_column_onto_the_same_table() {
172        let create = "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTOINCREMENT\n);\n";
173        let alter = "ALTER TABLE posts ADD COLUMN content TEXT NOT NULL DEFAULT '';\n";
174        let tables = accumulate_schema([create, alter]);
175        let posts = tables.get("posts").unwrap();
176        assert_eq!(posts.len(), 2);
177        assert_eq!(posts[1].name, "content");
178        assert_eq!(posts[1].sql_type, SqlType::Text);
179        assert!(posts[1].not_null);
180    }
181
182    #[test]
183    fn a_pivot_tables_composite_primary_key_line_is_not_read_as_a_column() {
184        let sql = "CREATE TABLE post_tag (\n    post_id INTEGER NOT NULL REFERENCES posts(id),\n    tag_id INTEGER NOT NULL REFERENCES tags(id),\n    PRIMARY KEY (post_id, tag_id)\n);\n";
185        let tables = accumulate_schema([sql]);
186        let post_tag = tables.get("post_tag").unwrap();
187        assert_eq!(post_tag.len(), 2);
188        assert!(post_tag.iter().all(|c| c.name != "PRIMARY"));
189    }
190
191    #[test]
192    fn a_nullable_column_has_no_not_null_flag() {
193        let sql = "CREATE TABLE posts (\n    published_count INTEGER\n);\n";
194        let tables = accumulate_schema([sql]);
195        assert!(!tables.get("posts").unwrap()[0].not_null);
196    }
197
198    #[test]
199    fn an_unrecognized_column_type_is_flagged_unknown_not_guessed_at() {
200        let sql = "CREATE TABLE posts (\n    metadata BLOB\n);\n";
201        let tables = accumulate_schema([sql]);
202        assert_eq!(tables.get("posts").unwrap()[0].sql_type, SqlType::Unknown);
203    }
204
205    #[test]
206    fn mysqls_auto_increment_id_column_is_still_recognized_as_the_primary_key() {
207        let sql = "CREATE TABLE posts (\n    id INTEGER PRIMARY KEY AUTO_INCREMENT\n);\n";
208        let tables = accumulate_schema([sql]);
209        assert_eq!(
210            tables.get("posts").unwrap()[0].sql_type,
211            SqlType::IntegerPrimaryKey
212        );
213    }
214
215    #[test]
216    fn postgres_serial_id_column_is_recognized_as_the_primary_key_not_unknown() {
217        let sql = "CREATE TABLE posts (\n    id SERIAL PRIMARY KEY\n);\n";
218        let tables = accumulate_schema([sql]);
219        assert_eq!(
220            tables.get("posts").unwrap()[0].sql_type,
221            SqlType::IntegerPrimaryKey
222        );
223    }
224
225    #[test]
226    fn mysqls_varchar_string_column_maps_to_the_same_text_type_as_everywhere_else() {
227        let sql = "CREATE TABLE users (\n    email VARCHAR(255) NOT NULL UNIQUE\n);\n";
228        let tables = accumulate_schema([sql]);
229        let column = &tables.get("users").unwrap()[0];
230        assert_eq!(column.sql_type, SqlType::Text);
231        assert!(column.not_null);
232    }
233}