Skip to main content

sql_splitter/differ/output/
sql.rs

1//! SQL migration output formatter for diff results.
2//!
3//! Generates DDL statements for schema changes.
4
5use crate::differ::DiffResult;
6use crate::parser::SqlDialect;
7use crate::transform_common::{quote_ident, quote_identifier};
8
9/// Format diff result as SQL migration script
10pub fn format_sql(result: &DiffResult, dialect: SqlDialect) -> String {
11    let mut output = String::new();
12
13    output.push_str("-- SQL Migration Script\n");
14    output.push_str(&format!(
15        "-- Generated by sql-splitter diff (dialect: {})\n",
16        dialect
17    ));
18    output.push_str("--\n\n");
19
20    let Some(ref schema) = result.schema else {
21        output.push_str("-- No schema changes detected\n");
22        return output;
23    };
24
25    if !schema.has_changes() {
26        output.push_str("-- No schema changes detected\n");
27        return output;
28    }
29
30    // New tables - use CREATE TABLE statement if available
31    for table in &schema.tables_added {
32        output.push_str(&format!("-- New table: {}\n", table.name));
33        if let Some(ref stmt) = table.create_statement {
34            output.push_str(stmt.trim());
35            if !stmt.trim().ends_with(';') {
36                output.push(';');
37            }
38            output.push_str("\n\n");
39        } else {
40            // Generate CREATE TABLE from column info
41            output.push_str(&format!(
42                "CREATE TABLE {} (\n",
43                quote_ident(dialect, &table.name)
44            ));
45
46            let col_defs: Vec<String> = table
47                .columns
48                .iter()
49                .map(|col| {
50                    let nullable = if col.is_nullable { "" } else { " NOT NULL" };
51                    format!(
52                        "  {} {}{}",
53                        quote_identifier(dialect, &col.name),
54                        col.col_type,
55                        nullable
56                    )
57                })
58                .collect();
59
60            output.push_str(&col_defs.join(",\n"));
61
62            if !table.primary_key.is_empty() {
63                let pk_cols: Vec<String> = table
64                    .primary_key
65                    .iter()
66                    .map(|column| quote_identifier(dialect, column))
67                    .collect();
68                output.push_str(&format!(",\n  PRIMARY KEY ({})", pk_cols.join(", ")));
69            }
70
71            output.push_str("\n);\n\n");
72        }
73    }
74
75    // Removed tables
76    for table_name in &schema.tables_removed {
77        output.push_str(&format!("-- Removed table: {}\n", table_name));
78        output.push_str(&format!(
79            "DROP TABLE IF EXISTS {};\n\n",
80            quote_ident(dialect, table_name)
81        ));
82    }
83
84    // Modified tables
85    for modification in &schema.tables_modified {
86        let has_changes = !modification.columns_added.is_empty()
87            || !modification.columns_removed.is_empty()
88            || !modification.columns_modified.is_empty()
89            || !modification.fks_added.is_empty()
90            || !modification.fks_removed.is_empty()
91            || !modification.indexes_added.is_empty()
92            || !modification.indexes_removed.is_empty();
93
94        if !has_changes && !modification.pk_changed {
95            continue;
96        }
97
98        output.push_str(&format!("-- Modified table: {}\n", modification.table_name));
99
100        // Add columns
101        for col in &modification.columns_added {
102            let nullable = if col.is_nullable { "" } else { " NOT NULL" };
103            output.push_str(&format!(
104                "ALTER TABLE {} ADD COLUMN {} {}{};\n",
105                quote_ident(dialect, &modification.table_name),
106                quote_identifier(dialect, &col.name),
107                col.col_type,
108                nullable
109            ));
110        }
111
112        // Drop columns
113        for col in &modification.columns_removed {
114            output.push_str(&format!(
115                "ALTER TABLE {} DROP COLUMN {};\n",
116                quote_ident(dialect, &modification.table_name),
117                quote_identifier(dialect, &col.name)
118            ));
119        }
120
121        // Modify columns
122        for change in &modification.columns_modified {
123            let new_type = change.new_type.as_deref().unwrap_or("-- unknown type");
124            let nullable = match change.new_nullable {
125                Some(true) => "",
126                Some(false) => " NOT NULL",
127                None => "",
128            };
129
130            match dialect {
131                SqlDialect::MySql => {
132                    output.push_str(&format!(
133                        "ALTER TABLE {} MODIFY COLUMN {} {}{};\n",
134                        quote_ident(dialect, &modification.table_name),
135                        quote_identifier(dialect, &change.name),
136                        new_type,
137                        nullable
138                    ));
139                }
140                SqlDialect::Postgres => {
141                    // PostgreSQL uses separate commands for type and nullability
142                    if change.new_type.is_some() {
143                        output.push_str(&format!(
144                            "ALTER TABLE {} ALTER COLUMN {} TYPE {};\n",
145                            quote_ident(dialect, &modification.table_name),
146                            quote_identifier(dialect, &change.name),
147                            new_type
148                        ));
149                    }
150                    if let Some(is_nullable) = change.new_nullable {
151                        let constraint = if is_nullable {
152                            "DROP NOT NULL"
153                        } else {
154                            "SET NOT NULL"
155                        };
156                        output.push_str(&format!(
157                            "ALTER TABLE {} ALTER COLUMN {} {};\n",
158                            quote_ident(dialect, &modification.table_name),
159                            quote_identifier(dialect, &change.name),
160                            constraint
161                        ));
162                    }
163                }
164                SqlDialect::Sqlite => {
165                    output.push_str(&format!(
166                        "-- SQLite does not support ALTER COLUMN; manual migration required for {}.{}\n",
167                        modification.table_name, change.name
168                    ));
169                }
170                SqlDialect::Mssql => {
171                    output.push_str(&format!(
172                        "ALTER TABLE {} ALTER COLUMN {} {}{};\n",
173                        quote_ident(dialect, &modification.table_name),
174                        quote_identifier(dialect, &change.name),
175                        new_type,
176                        nullable
177                    ));
178                }
179            }
180        }
181
182        // Add foreign keys
183        for fk in &modification.fks_added {
184            let fk_cols: Vec<String> = fk
185                .columns
186                .iter()
187                .map(|column| quote_identifier(dialect, column))
188                .collect();
189            let ref_cols: Vec<String> = fk
190                .referenced_columns
191                .iter()
192                .map(|column| quote_identifier(dialect, column))
193                .collect();
194
195            let constraint_name = fk
196                .name
197                .as_ref()
198                .map(|name| format!("CONSTRAINT {} ", quote_identifier(dialect, name)))
199                .unwrap_or_default();
200
201            output.push_str(&format!(
202                "ALTER TABLE {} ADD {}FOREIGN KEY ({}) REFERENCES {}({});\n",
203                quote_ident(dialect, &modification.table_name),
204                constraint_name,
205                fk_cols.join(", "),
206                quote_ident(dialect, &fk.referenced_table),
207                ref_cols.join(", ")
208            ));
209        }
210
211        // Drop foreign keys
212        for fk in &modification.fks_removed {
213            if let Some(ref name) = fk.name {
214                match dialect {
215                    SqlDialect::MySql => {
216                        output.push_str(&format!(
217                            "ALTER TABLE {} DROP FOREIGN KEY {};\n",
218                            quote_ident(dialect, &modification.table_name),
219                            quote_identifier(dialect, name)
220                        ));
221                    }
222                    SqlDialect::Postgres | SqlDialect::Mssql => {
223                        output.push_str(&format!(
224                            "ALTER TABLE {} DROP CONSTRAINT {};\n",
225                            quote_ident(dialect, &modification.table_name),
226                            quote_identifier(dialect, name)
227                        ));
228                    }
229                    SqlDialect::Sqlite => {
230                        output.push_str(&format!(
231                            "-- SQLite does not support DROP CONSTRAINT; manual migration required for FK {}\n",
232                            name
233                        ));
234                    }
235                }
236            } else {
237                output.push_str(&format!(
238                    "-- Cannot drop unnamed FK ({}) -> {}.({}) without constraint name\n",
239                    fk.columns.join(", "),
240                    fk.referenced_table,
241                    fk.referenced_columns.join(", ")
242                ));
243            }
244        }
245
246        // Add indexes
247        for idx in &modification.indexes_added {
248            let unique = if idx.is_unique { "UNIQUE " } else { "" };
249            let idx_cols: Vec<String> = idx
250                .columns
251                .iter()
252                .map(|column| quote_identifier(dialect, column))
253                .collect();
254
255            match dialect {
256                SqlDialect::Postgres => {
257                    let using = idx
258                        .index_type
259                        .as_ref()
260                        .map(|t| format!(" USING {}", t.to_lowercase()))
261                        .unwrap_or_default();
262                    output.push_str(&format!(
263                        "CREATE {}INDEX {} ON {}{}({});\n",
264                        unique,
265                        quote_identifier(dialect, &idx.name),
266                        quote_ident(dialect, &modification.table_name),
267                        using,
268                        idx_cols.join(", ")
269                    ));
270                }
271                _ => {
272                    output.push_str(&format!(
273                        "CREATE {}INDEX {} ON {}({});\n",
274                        unique,
275                        quote_identifier(dialect, &idx.name),
276                        quote_ident(dialect, &modification.table_name),
277                        idx_cols.join(", ")
278                    ));
279                }
280            }
281        }
282
283        // Drop indexes
284        for idx in &modification.indexes_removed {
285            match dialect {
286                SqlDialect::MySql => {
287                    output.push_str(&format!(
288                        "DROP INDEX {} ON {};\n",
289                        quote_identifier(dialect, &idx.name),
290                        quote_ident(dialect, &modification.table_name)
291                    ));
292                }
293                SqlDialect::Postgres | SqlDialect::Sqlite => {
294                    output.push_str(&format!(
295                        "DROP INDEX IF EXISTS {};\n",
296                        quote_identifier(dialect, &idx.name)
297                    ));
298                }
299                SqlDialect::Mssql => {
300                    output.push_str(&format!(
301                        "DROP INDEX {} ON {};\n",
302                        quote_identifier(dialect, &idx.name),
303                        quote_ident(dialect, &modification.table_name)
304                    ));
305                }
306            }
307        }
308
309        // PK changes (complex - often requires table recreation)
310        if modification.pk_changed {
311            let old_pk = modification
312                .old_pk
313                .as_ref()
314                .map(|pk| pk.join(", "))
315                .unwrap_or_else(|| "(none)".to_string());
316            let new_pk = modification
317                .new_pk
318                .as_ref()
319                .map(|pk| pk.join(", "))
320                .unwrap_or_else(|| "(none)".to_string());
321
322            output.push_str(&format!(
323                "-- WARNING: PRIMARY KEY change ({}) -> ({}) may require table recreation\n",
324                old_pk, new_pk
325            ));
326
327            match dialect {
328                SqlDialect::MySql => {
329                    output.push_str(&format!(
330                        "ALTER TABLE {} DROP PRIMARY KEY;\n",
331                        quote_ident(dialect, &modification.table_name)
332                    ));
333                    if let Some(ref new_pk_cols) = modification.new_pk {
334                        if !new_pk_cols.is_empty() {
335                            let pk_cols: Vec<String> = new_pk_cols
336                                .iter()
337                                .map(|column| quote_identifier(dialect, column))
338                                .collect();
339                            output.push_str(&format!(
340                                "ALTER TABLE {} ADD PRIMARY KEY ({});\n",
341                                quote_ident(dialect, &modification.table_name),
342                                pk_cols.join(", ")
343                            ));
344                        }
345                    }
346                }
347                SqlDialect::Postgres | SqlDialect::Mssql => {
348                    output.push_str(&format!(
349                        "ALTER TABLE {} DROP CONSTRAINT IF EXISTS {}_pkey;\n",
350                        quote_ident(dialect, &modification.table_name),
351                        modification.table_name
352                    ));
353                    if let Some(ref new_pk_cols) = modification.new_pk {
354                        if !new_pk_cols.is_empty() {
355                            let pk_cols: Vec<String> = new_pk_cols
356                                .iter()
357                                .map(|column| quote_identifier(dialect, column))
358                                .collect();
359                            output.push_str(&format!(
360                                "ALTER TABLE {} ADD PRIMARY KEY ({});\n",
361                                quote_ident(dialect, &modification.table_name),
362                                pk_cols.join(", ")
363                            ));
364                        }
365                    }
366                }
367                SqlDialect::Sqlite => {
368                    output.push_str(
369                        "-- SQLite does not support ALTER PRIMARY KEY; table recreation required\n",
370                    );
371                }
372            }
373        }
374
375        output.push('\n');
376    }
377
378    // Note about data changes
379    if let Some(ref data) = result.data {
380        let has_data_changes = data
381            .tables
382            .values()
383            .any(|t| t.added_count > 0 || t.removed_count > 0 || t.modified_count > 0);
384
385        if has_data_changes {
386            output.push_str("-- Data changes detected but not included in migration script\n");
387            output.push_str("-- Use text or JSON output format for data diff details\n");
388        }
389    }
390
391    output
392}