Skip to main content

schema_reverse_engineer/
xml_writer.rs

1use crate::error::SchemaReverseEngineerError;
2use schema_model::model::column::Column;
3use schema_model::model::constraint::Constraint;
4use schema_model::model::database_model::DatabaseModel;
5use schema_model::model::enum_type::EnumType;
6use schema_model::model::key::Key;
7use schema_model::model::relation::Relation;
8use schema_model::model::schema::Schema;
9use schema_model::model::table::Table;
10use schema_model::model::types::{BooleanMode, ForeignKeyMode, KeyType};
11use schema_model::model::view::View;
12use std::fmt::Write as _;
13
14const NAMESPACE: &str = "http://stano.com/database";
15
16/// Serializes a `DatabaseModel` to the schema-rs XML schema definition format (see
17/// `schema-xsd/schema.xsd`), the inverse of `schema_parser::parse_database_xml`.
18pub fn write_database_xml(model: &DatabaseModel) -> Result<String, SchemaReverseEngineerError> {
19    let mut out = String::new();
20    out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
21    let _ = writeln!(
22        out,
23        "<database xmlns=\"{}\" foreignKeyMode=\"{}\" booleanMode=\"{}\">",
24        NAMESPACE,
25        foreign_key_mode_str(model.foreign_key_mode()),
26        boolean_mode_str(model.boolean_mode())
27    );
28
29    for schema in model.schemas() {
30        match schema.schema_name() {
31            Some(name) => {
32                push_indent(&mut out, 1);
33                let _ = writeln!(out, "<schema name=\"{}\">", xml_escape(name));
34                write_schema_body(&mut out, schema, 2)?;
35                push_indent(&mut out, 1);
36                out.push_str("</schema>\n");
37            }
38            None => write_schema_body(&mut out, schema, 1)?,
39        }
40    }
41
42    out.push_str("</database>\n");
43    Ok(out)
44}
45
46fn write_schema_body(out: &mut String, schema: &Schema, indent: usize) -> Result<(), SchemaReverseEngineerError> {
47    for enum_type in schema.enum_types() {
48        write_enum(out, enum_type, indent);
49    }
50    for table in schema.tables() {
51        write_table(out, table, indent)?;
52    }
53    for view in schema.all_views() {
54        write_view(out, view, indent);
55    }
56    Ok(())
57}
58
59fn write_enum(out: &mut String, enum_type: &EnumType, indent: usize) {
60    push_indent(out, indent);
61    let _ = writeln!(out, "<enum name=\"{}\">", xml_escape(enum_type.name()));
62    for value in enum_type.values() {
63        push_indent(out, indent + 1);
64        let _ = write!(out, "<value name=\"{}\"", xml_escape(value.name()));
65        if value.code() != value.name() {
66            let _ = write!(out, " code=\"{}\"", xml_escape(value.code()));
67        }
68        out.push_str("/>\n");
69    }
70    push_indent(out, indent);
71    out.push_str("</enum>\n\n");
72}
73
74fn write_view(out: &mut String, view: &View, indent: usize) {
75    push_indent(out, indent);
76    let _ = writeln!(out, "<view name=\"{}\">", xml_escape(view.name()));
77    push_indent(out, indent + 1);
78    write_cdata(out, view.sql());
79    out.push('\n');
80    push_indent(out, indent);
81    out.push_str("</view>\n\n");
82}
83
84fn write_table(out: &mut String, table: &Table, indent: usize) -> Result<(), SchemaReverseEngineerError> {
85    push_indent(out, indent);
86    let _ = writeln!(out, "<table name=\"{}\">", xml_escape(table.name()));
87
88    write_columns(out, table.columns(), indent + 1);
89    write_keys(out, table, indent + 1)?;
90    write_relations(out, table.relations(), indent + 1);
91    write_constraints(out, table.constraints(), indent + 1);
92
93    push_indent(out, indent);
94    out.push_str("</table>\n\n");
95    Ok(())
96}
97
98fn write_columns(out: &mut String, columns: &[Column], indent: usize) {
99    push_indent(out, indent);
100    out.push_str("<columns>\n");
101    for column in columns {
102        write_column(out, column, indent + 1);
103    }
104    push_indent(out, indent);
105    out.push_str("</columns>\n");
106}
107
108fn write_column(out: &mut String, column: &Column, indent: usize) {
109    push_indent(out, indent);
110    let _ = write!(
111        out,
112        "<column name=\"{}\" type=\"{}\"",
113        xml_escape(column.name()),
114        column.column_type().name().to_lowercase()
115    );
116    if column.length() > 0 {
117        let _ = write!(out, " length=\"{}\"", column.length());
118    }
119    if column.scale() > 0 {
120        let _ = write!(out, " scale=\"{}\"", column.scale());
121    }
122    if column.required() {
123        out.push_str(" required=\"true\"");
124    }
125    if let Some(default) = column.default_constraint() {
126        let _ = write!(out, " default=\"{}\"", xml_escape(default));
127    }
128    if let Some(generated) = column.generated() {
129        let _ = write!(out, " generated=\"{}\"", xml_escape(generated));
130    }
131    if let Some(enum_type) = column.enum_type() {
132        let _ = write!(out, " enumType=\"{}\"", xml_escape(enum_type));
133    }
134    if let Some(element_type) = column.element_type() {
135        let _ = write!(out, " elementType=\"{}\"", xml_escape(element_type));
136    }
137    if let Some(min_value) = column.min_value() {
138        let _ = write!(out, " minValue=\"{}\"", min_value);
139    }
140    if let Some(max_value) = column.max_value() {
141        let _ = write!(out, " maxValue=\"{}\"", max_value);
142    }
143
144    if let Some(check) = column.check_constraint() {
145        out.push_str(">\n");
146        push_indent(out, indent + 1);
147        let _ = writeln!(out, "<check>{}</check>", xml_escape(check));
148        push_indent(out, indent);
149        out.push_str("</column>\n");
150    } else {
151        out.push_str("/>\n");
152    }
153}
154
155fn write_keys(out: &mut String, table: &Table, indent: usize) -> Result<(), SchemaReverseEngineerError> {
156    // The XSD requires a <primary> element whenever <keys> is present, so a table with no
157    // primary key can't emit unique/index keys either. Silently dropping them would lose data
158    // from the round trip, so a PK-less table with unique keys or indexes is a hard error
159    // instead (per the project's prefer-error-over-silent-coercion direction).
160    let Some(primary) = table.primary_key() else {
161        if table.keys().iter().any(|k| k.key_type() == KeyType::Unique) || !table.indexes().is_empty() {
162            return Err(SchemaReverseEngineerError::PkLessTableHasKeys(table.name().to_string()));
163        }
164        return Ok(());
165    };
166
167    push_indent(out, indent);
168    out.push_str("<keys>\n");
169    write_key_columns(out, "primary", primary, indent + 1);
170    for unique in table.keys().iter().filter(|k| k.key_type() == KeyType::Unique) {
171        write_key_columns(out, "unique", unique, indent + 1);
172    }
173    for index in table.indexes() {
174        write_index(out, index, indent + 1);
175    }
176    push_indent(out, indent);
177    out.push_str("</keys>\n");
178    Ok(())
179}
180
181fn write_key_columns(out: &mut String, tag: &str, key: &Key, indent: usize) {
182    push_indent(out, indent);
183    let _ = writeln!(out, "<{}>", tag);
184    for column in key.columns() {
185        push_indent(out, indent + 1);
186        let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape(column.name()));
187    }
188    push_indent(out, indent);
189    let _ = writeln!(out, "</{}>", tag);
190}
191
192fn write_index(out: &mut String, index: &Key, indent: usize) {
193    push_indent(out, indent);
194    let _ = write!(out, "<index");
195    if index.is_unique() {
196        out.push_str(" unique=\"true\"");
197    }
198    if let Some(include) = index.include() {
199        let _ = write!(out, " include=\"{}\"", xml_escape(include));
200    }
201    if let Some(filter) = index.filter() {
202        let _ = write!(out, " where=\"{}\"", xml_escape(filter));
203    }
204    out.push_str(">\n");
205    for column in index.columns() {
206        push_indent(out, indent + 1);
207        let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape(column.name()));
208    }
209    push_indent(out, indent);
210    out.push_str("</index>\n");
211}
212
213fn write_relations(out: &mut String, relations: &[Relation], indent: usize) {
214    if relations.is_empty() {
215        return;
216    }
217    push_indent(out, indent);
218    out.push_str("<relations>\n");
219    for relation in relations {
220        if relation.is_composite() {
221            push_indent(out, indent + 1);
222            let _ = writeln!(
223                out,
224                "<compositeRelation table=\"{}\" type=\"{}\">",
225                xml_escape(relation.to_table_name()),
226                relation_type_str(relation.relation_type())
227            );
228            for (from_column, to_column) in relation.column_pairs() {
229                push_indent(out, indent + 2);
230                let _ = writeln!(
231                    out,
232                    "<column src=\"{}\" name=\"{}\"/>",
233                    xml_escape(from_column),
234                    xml_escape(to_column)
235                );
236            }
237            push_indent(out, indent + 1);
238            out.push_str("</compositeRelation>\n");
239        } else {
240            push_indent(out, indent + 1);
241            let _ = writeln!(
242                out,
243                "<relation src=\"{}\" table=\"{}\" column=\"{}\" type=\"{}\"/>",
244                xml_escape(relation.from_column_name()),
245                xml_escape(relation.to_table_name()),
246                xml_escape(relation.to_column_name()),
247                relation_type_str(relation.relation_type())
248            );
249        }
250    }
251    push_indent(out, indent);
252    out.push_str("</relations>\n");
253}
254
255fn write_constraints(out: &mut String, constraints: &[Constraint], indent: usize) {
256    if constraints.is_empty() {
257        return;
258    }
259    push_indent(out, indent);
260    out.push_str("<constraints>\n");
261    for constraint in constraints {
262        push_indent(out, indent + 1);
263        let _ = writeln!(
264            out,
265            "<constraint name=\"{}\" databaseType=\"{}\">",
266            xml_escape(constraint.name()),
267            database_type_str(constraint.database_type())
268        );
269        push_indent(out, indent + 2);
270        write_cdata(out, constraint.sql());
271        out.push('\n');
272        push_indent(out, indent + 1);
273        out.push_str("</constraint>\n");
274    }
275    push_indent(out, indent);
276    out.push_str("</constraints>\n");
277}
278
279fn relation_type_str(relation_type: schema_model::model::types::RelationType) -> &'static str {
280    use schema_model::model::types::RelationType;
281    match relation_type {
282        RelationType::Cascade => "cascade",
283        RelationType::Enforce => "enforce",
284        RelationType::SetNull => "setnull",
285        RelationType::DoNothing => "donothing",
286    }
287}
288
289fn boolean_mode_str(mode: BooleanMode) -> &'static str {
290    match mode {
291        BooleanMode::Native => "native",
292        BooleanMode::YesNo => "yesno",
293        BooleanMode::YN => "yn",
294    }
295}
296
297fn database_type_str(database_type: schema_model::model::types::DatabaseType) -> &'static str {
298    use schema_model::model::types::DatabaseType;
299    match database_type {
300        DatabaseType::Postgresql => "postgresql",
301        DatabaseType::Sqlite => "sqlite",
302        DatabaseType::SqlServer => "sqlserver",
303    }
304}
305
306fn foreign_key_mode_str(mode: ForeignKeyMode) -> &'static str {
307    match mode {
308        ForeignKeyMode::None => "none",
309        ForeignKeyMode::Relations => "relations",
310        ForeignKeyMode::Triggers => "triggers",
311    }
312}
313
314fn push_indent(out: &mut String, indent: usize) {
315    for _ in 0..indent {
316        out.push_str("  ");
317    }
318}
319
320/// Writes `content` as a `<![CDATA[...]]>` section, splitting any embedded `]]>` across
321/// adjacent CDATA sections first. The literal sequence `]]>` is illegal inside XML
322/// character data (not just "outside CDATA") - e.g. SQL text containing an array-slice
323/// like `arr[1:2]]>x` would otherwise close the CDATA section early and produce
324/// non-well-formed XML that fails to parse back.
325fn write_cdata(out: &mut String, content: &str) {
326    out.push_str("<![CDATA[");
327    out.push_str(&content.replace("]]>", "]]]]><![CDATA[>"));
328    out.push_str("]]>");
329}
330
331/// XML-escapes attribute and text content consistently (the Java writer inconsistently escaped
332/// index/unique key column names but not primary key column names -- here every column name and
333/// text value goes through the same escaping).
334fn xml_escape(value: &str) -> String {
335    let mut escaped = String::with_capacity(value.len());
336    for ch in value.chars() {
337        match ch {
338            '&' => escaped.push_str("&amp;"),
339            '<' => escaped.push_str("&lt;"),
340            '>' => escaped.push_str("&gt;"),
341            '"' => escaped.push_str("&quot;"),
342            '\'' => escaped.push_str("&apos;"),
343            _ => escaped.push(ch),
344        }
345    }
346    escaped
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352    use schema_model::builder::{ColumnBuilder, KeyBuilder, SchemaBuilder, TableBuilder};
353    use schema_model::model::column_type::ColumnType;
354    use schema_model::model::enum_type::EnumValue;
355    use schema_model::model::relation::Relation;
356    use schema_model::model::types::{DatabaseType, RelationType};
357
358    #[test]
359    fn writes_table_with_columns_pk_and_relation() {
360        let parent = TableBuilder::new(None::<&str>, "parent")
361            .add_column(ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence).required(true).build())
362            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
363            .build();
364
365        let child = TableBuilder::new(None::<&str>, "child")
366            .add_column(ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence).required(true).build())
367            .add_column(ColumnBuilder::new(None::<&str>, "parent_id", ColumnType::Int).required(true).build())
368            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
369            .add_relation(Relation::new("parent", "id", "child", "parent_id", RelationType::Cascade, false))
370            .build();
371
372        let schema = SchemaBuilder::new(None::<&str>)
373            .add_table(parent)
374            .add_table(child)
375            .add_enum_type(EnumType::new("mood", vec![EnumValue::new("HAPPY", None::<String>)]))
376            .add_view(View::new(None::<&str>, "v1", "select 1", Some(DatabaseType::Postgresql)))
377            .build();
378
379        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
380        let xml = write_database_xml(&model).unwrap();
381
382        assert!(xml.contains("<database xmlns=\"http://stano.com/database\""));
383        assert!(xml.contains("<table name=\"parent\">"));
384        assert!(xml.contains("<column name=\"id\" type=\"sequence\" required=\"true\"/>"));
385        assert!(xml.contains("<relation src=\"parent_id\" table=\"parent\" column=\"id\" type=\"cascade\"/>"));
386        assert!(xml.contains("<enum name=\"mood\">"));
387        assert!(xml.contains("<view name=\"v1\">"));
388    }
389
390    #[test]
391    fn write_cdata_splits_embedded_close_sequence() {
392        let mut out = String::new();
393        write_cdata(&mut out, "select arr[1:2]]>x from t");
394        assert!(!out.contains("2]]>x"), "the literal ]]> must not survive unescaped inside one CDATA block: {out}");
395        assert!(out.starts_with("<![CDATA["));
396        assert!(out.ends_with("]]>"));
397    }
398
399    #[test]
400    fn view_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
401        let view = View::new(
402            None::<&str>,
403            "v1",
404            "select * from t where arr[1:2]]>x",
405            None,
406        );
407        let schema = SchemaBuilder::new(None::<&str>).add_view(view).build();
408        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
409        let xml = write_database_xml(&model).unwrap();
410
411        let reparsed = schema_parser::parse_database_xml(&xml)
412            .expect("XML containing a ]]> sequence inside a view's SQL must still be well-formed");
413        let reparsed_view = &reparsed.default_schema().all_views()[0];
414        assert_eq!(reparsed_view.sql(), "select * from t where arr[1:2]]>x");
415    }
416
417    #[test]
418    fn constraint_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
419        let table = TableBuilder::new(None::<&str>, "t")
420            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
421            .add_constraint(schema_model::model::constraint::Constraint::new(
422                "ck_a",
423                "check (a[1:2]]>0)",
424                DatabaseType::Postgresql,
425            ))
426            .build();
427        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
428        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
429        let xml = write_database_xml(&model).unwrap();
430
431        let reparsed = schema_parser::parse_database_xml(&xml)
432            .expect("XML containing a ]]> sequence inside a constraint's SQL must still be well-formed");
433        let reparsed_table = reparsed.default_schema().get_table("t");
434        assert_eq!(reparsed_table.constraints()[0].sql(), "check (a[1:2]]>0)");
435    }
436
437    #[test]
438    fn omits_keys_when_no_primary_key_present() {
439        let table = TableBuilder::new(None::<&str>, "t")
440            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
441            .build();
442        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
443        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
444        let xml = write_database_xml(&model).unwrap();
445        assert!(!xml.contains("<keys>"));
446    }
447
448    #[test]
449    fn pk_less_table_with_a_unique_key_is_a_hard_error() {
450        let table = TableBuilder::new(None::<&str>, "t")
451            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
452            .add_key(KeyBuilder::new(KeyType::Unique).add_column("a").build())
453            .build();
454        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
455        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
456
457        let err = write_database_xml(&model).unwrap_err();
458        assert!(matches!(err, SchemaReverseEngineerError::PkLessTableHasKeys(name) if name == "t"));
459    }
460
461    #[test]
462    fn pk_less_table_with_an_index_is_a_hard_error() {
463        let table = TableBuilder::new(None::<&str>, "t")
464            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
465            .add_index(KeyBuilder::new(KeyType::Index).add_column("a").build())
466            .build();
467        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
468        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
469
470        let err = write_database_xml(&model).unwrap_err();
471        assert!(matches!(err, SchemaReverseEngineerError::PkLessTableHasKeys(name) if name == "t"));
472    }
473
474    #[test]
475    fn writes_and_round_trips_a_composite_relation() {
476        let parent = TableBuilder::new(None::<&str>, "Property")
477            .add_column(ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence).required(true).build())
478            .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
479            .build();
480
481        let child = TableBuilder::new(None::<&str>, "Assignment")
482            .add_column(ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence).required(true).build())
483            .add_column(ColumnBuilder::new(None::<&str>, "PropertyID", ColumnType::Int).required(true).build())
484            .add_column(ColumnBuilder::new(None::<&str>, "ParentAssignmentID", ColumnType::Int).build())
485            .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
486            .add_relation(
487                Relation::new_composite(
488                    "Assignment",
489                    "Assignment",
490                    vec![("ParentAssignmentID", "ID"), ("PropertyID", "PropertyID")],
491                    RelationType::Cascade,
492                    false,
493                )
494                .unwrap(),
495            )
496            .build();
497
498        let schema = SchemaBuilder::new(None::<&str>).add_table(parent).add_table(child).build();
499        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
500        let xml = write_database_xml(&model).unwrap();
501
502        assert!(xml.contains("<compositeRelation table=\"Assignment\" type=\"cascade\">"));
503        assert!(xml.contains("<column src=\"ParentAssignmentID\" name=\"ID\"/>"));
504        assert!(xml.contains("<column src=\"PropertyID\" name=\"PropertyID\"/>"));
505
506        let reparsed = schema_parser::parse_database_xml(&xml).expect("round-tripped composite relation XML must be well-formed");
507        let reparsed_table = reparsed.default_schema().get_table("Assignment");
508        let relation = &reparsed_table.relations()[0];
509        assert!(relation.is_composite());
510        assert_eq!(
511            relation.column_pairs(),
512            &[
513                ("ParentAssignmentID".to_string(), "ID".to_string()),
514                ("PropertyID".to_string(), "PropertyID".to_string()),
515            ]
516        );
517    }
518
519    #[test]
520    fn wraps_tables_in_a_schema_element_when_the_schema_is_named() {
521        let table = TableBuilder::new(Some("sales"), "orders")
522            .add_column(ColumnBuilder::new(Some("sales"), "id", ColumnType::Sequence).required(true).build())
523            .build();
524        let schema = SchemaBuilder::new(Some("sales")).add_table(table).build();
525        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
526
527        let xml = write_database_xml(&model).unwrap();
528        assert!(xml.contains("<schema name=\"sales\">"));
529        assert!(xml.contains("<table name=\"orders\">"));
530        assert!(xml.contains("</schema>"));
531
532        let reparsed = schema_parser::parse_database_xml(&xml).expect("round-tripped XML must still be well-formed");
533        assert_eq!(reparsed.find_schema(Some("sales")).schema_name(), Some("sales"));
534    }
535}