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    out.push_str(">\n");
202    for column in index.columns() {
203        push_indent(out, indent + 1);
204        let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape(column.name()));
205    }
206    push_indent(out, indent);
207    out.push_str("</index>\n");
208}
209
210fn write_relations(out: &mut String, relations: &[Relation], indent: usize) {
211    if relations.is_empty() {
212        return;
213    }
214    push_indent(out, indent);
215    out.push_str("<relations>\n");
216    for relation in relations {
217        if relation.is_composite() {
218            push_indent(out, indent + 1);
219            let _ = writeln!(
220                out,
221                "<compositeRelation table=\"{}\" type=\"{}\">",
222                xml_escape(relation.to_table_name()),
223                relation_type_str(relation.relation_type())
224            );
225            for (from_column, to_column) in relation.column_pairs() {
226                push_indent(out, indent + 2);
227                let _ = writeln!(
228                    out,
229                    "<column src=\"{}\" name=\"{}\"/>",
230                    xml_escape(from_column),
231                    xml_escape(to_column)
232                );
233            }
234            push_indent(out, indent + 1);
235            out.push_str("</compositeRelation>\n");
236        } else {
237            push_indent(out, indent + 1);
238            let _ = writeln!(
239                out,
240                "<relation src=\"{}\" table=\"{}\" column=\"{}\" type=\"{}\"/>",
241                xml_escape(relation.from_column_name()),
242                xml_escape(relation.to_table_name()),
243                xml_escape(relation.to_column_name()),
244                relation_type_str(relation.relation_type())
245            );
246        }
247    }
248    push_indent(out, indent);
249    out.push_str("</relations>\n");
250}
251
252fn write_constraints(out: &mut String, constraints: &[Constraint], indent: usize) {
253    if constraints.is_empty() {
254        return;
255    }
256    push_indent(out, indent);
257    out.push_str("<constraints>\n");
258    for constraint in constraints {
259        push_indent(out, indent + 1);
260        let _ = writeln!(
261            out,
262            "<constraint name=\"{}\" databaseType=\"{}\">",
263            xml_escape(constraint.name()),
264            database_type_str(constraint.database_type())
265        );
266        push_indent(out, indent + 2);
267        write_cdata(out, constraint.sql());
268        out.push('\n');
269        push_indent(out, indent + 1);
270        out.push_str("</constraint>\n");
271    }
272    push_indent(out, indent);
273    out.push_str("</constraints>\n");
274}
275
276fn relation_type_str(relation_type: schema_model::model::types::RelationType) -> &'static str {
277    use schema_model::model::types::RelationType;
278    match relation_type {
279        RelationType::Cascade => "cascade",
280        RelationType::Enforce => "enforce",
281        RelationType::SetNull => "setnull",
282        RelationType::DoNothing => "donothing",
283    }
284}
285
286fn boolean_mode_str(mode: BooleanMode) -> &'static str {
287    match mode {
288        BooleanMode::Native => "native",
289        BooleanMode::YesNo => "yesno",
290        BooleanMode::YN => "yn",
291    }
292}
293
294fn database_type_str(database_type: schema_model::model::types::DatabaseType) -> &'static str {
295    use schema_model::model::types::DatabaseType;
296    match database_type {
297        DatabaseType::Postgresql => "postgresql",
298        DatabaseType::Sqlite => "sqlite",
299        DatabaseType::SqlServer => "sqlserver",
300    }
301}
302
303fn foreign_key_mode_str(mode: ForeignKeyMode) -> &'static str {
304    match mode {
305        ForeignKeyMode::None => "none",
306        ForeignKeyMode::Relations => "relations",
307        ForeignKeyMode::Triggers => "triggers",
308    }
309}
310
311fn push_indent(out: &mut String, indent: usize) {
312    for _ in 0..indent {
313        out.push_str("  ");
314    }
315}
316
317/// Writes `content` as a `<![CDATA[...]]>` section, splitting any embedded `]]>` across
318/// adjacent CDATA sections first. The literal sequence `]]>` is illegal inside XML
319/// character data (not just "outside CDATA") - e.g. SQL text containing an array-slice
320/// like `arr[1:2]]>x` would otherwise close the CDATA section early and produce
321/// non-well-formed XML that fails to parse back.
322fn write_cdata(out: &mut String, content: &str) {
323    out.push_str("<![CDATA[");
324    out.push_str(&content.replace("]]>", "]]]]><![CDATA[>"));
325    out.push_str("]]>");
326}
327
328/// XML-escapes attribute and text content consistently (the Java writer inconsistently escaped
329/// index/unique key column names but not primary key column names -- here every column name and
330/// text value goes through the same escaping).
331fn xml_escape(value: &str) -> String {
332    let mut escaped = String::with_capacity(value.len());
333    for ch in value.chars() {
334        match ch {
335            '&' => escaped.push_str("&amp;"),
336            '<' => escaped.push_str("&lt;"),
337            '>' => escaped.push_str("&gt;"),
338            '"' => escaped.push_str("&quot;"),
339            '\'' => escaped.push_str("&apos;"),
340            _ => escaped.push(ch),
341        }
342    }
343    escaped
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349    use schema_model::builder::{ColumnBuilder, KeyBuilder, SchemaBuilder, TableBuilder};
350    use schema_model::model::column_type::ColumnType;
351    use schema_model::model::enum_type::EnumValue;
352    use schema_model::model::relation::Relation;
353    use schema_model::model::types::{DatabaseType, RelationType};
354
355    #[test]
356    fn writes_table_with_columns_pk_and_relation() {
357        let parent = TableBuilder::new(None::<&str>, "parent")
358            .add_column(ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence).required(true).build())
359            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
360            .build();
361
362        let child = TableBuilder::new(None::<&str>, "child")
363            .add_column(ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence).required(true).build())
364            .add_column(ColumnBuilder::new(None::<&str>, "parent_id", ColumnType::Int).required(true).build())
365            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
366            .add_relation(Relation::new("parent", "id", "child", "parent_id", RelationType::Cascade, false))
367            .build();
368
369        let schema = SchemaBuilder::new(None::<&str>)
370            .add_table(parent)
371            .add_table(child)
372            .add_enum_type(EnumType::new("mood", vec![EnumValue::new("HAPPY", None::<String>)]))
373            .add_view(View::new(None::<&str>, "v1", "select 1", Some(DatabaseType::Postgresql)))
374            .build();
375
376        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
377        let xml = write_database_xml(&model).unwrap();
378
379        assert!(xml.contains("<database xmlns=\"http://stano.com/database\""));
380        assert!(xml.contains("<table name=\"parent\">"));
381        assert!(xml.contains("<column name=\"id\" type=\"sequence\" required=\"true\"/>"));
382        assert!(xml.contains("<relation src=\"parent_id\" table=\"parent\" column=\"id\" type=\"cascade\"/>"));
383        assert!(xml.contains("<enum name=\"mood\">"));
384        assert!(xml.contains("<view name=\"v1\">"));
385    }
386
387    #[test]
388    fn write_cdata_splits_embedded_close_sequence() {
389        let mut out = String::new();
390        write_cdata(&mut out, "select arr[1:2]]>x from t");
391        assert!(!out.contains("2]]>x"), "the literal ]]> must not survive unescaped inside one CDATA block: {out}");
392        assert!(out.starts_with("<![CDATA["));
393        assert!(out.ends_with("]]>"));
394    }
395
396    #[test]
397    fn view_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
398        let view = View::new(
399            None::<&str>,
400            "v1",
401            "select * from t where arr[1:2]]>x",
402            None,
403        );
404        let schema = SchemaBuilder::new(None::<&str>).add_view(view).build();
405        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
406        let xml = write_database_xml(&model).unwrap();
407
408        let reparsed = schema_parser::parse_database_xml(&xml)
409            .expect("XML containing a ]]> sequence inside a view's SQL must still be well-formed");
410        let reparsed_view = &reparsed.default_schema().all_views()[0];
411        assert_eq!(reparsed_view.sql(), "select * from t where arr[1:2]]>x");
412    }
413
414    #[test]
415    fn constraint_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
416        let table = TableBuilder::new(None::<&str>, "t")
417            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
418            .add_constraint(schema_model::model::constraint::Constraint::new(
419                "ck_a",
420                "check (a[1:2]]>0)",
421                DatabaseType::Postgresql,
422            ))
423            .build();
424        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
425        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
426        let xml = write_database_xml(&model).unwrap();
427
428        let reparsed = schema_parser::parse_database_xml(&xml)
429            .expect("XML containing a ]]> sequence inside a constraint's SQL must still be well-formed");
430        let reparsed_table = reparsed.default_schema().get_table("t");
431        assert_eq!(reparsed_table.constraints()[0].sql(), "check (a[1:2]]>0)");
432    }
433
434    #[test]
435    fn omits_keys_when_no_primary_key_present() {
436        let table = TableBuilder::new(None::<&str>, "t")
437            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
438            .build();
439        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
440        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
441        let xml = write_database_xml(&model).unwrap();
442        assert!(!xml.contains("<keys>"));
443    }
444
445    #[test]
446    fn pk_less_table_with_a_unique_key_is_a_hard_error() {
447        let table = TableBuilder::new(None::<&str>, "t")
448            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
449            .add_key(KeyBuilder::new(KeyType::Unique).add_column("a").build())
450            .build();
451        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
452        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
453
454        let err = write_database_xml(&model).unwrap_err();
455        assert!(matches!(err, SchemaReverseEngineerError::PkLessTableHasKeys(name) if name == "t"));
456    }
457
458    #[test]
459    fn pk_less_table_with_an_index_is_a_hard_error() {
460        let table = TableBuilder::new(None::<&str>, "t")
461            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
462            .add_index(KeyBuilder::new(KeyType::Index).add_column("a").build())
463            .build();
464        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
465        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
466
467        let err = write_database_xml(&model).unwrap_err();
468        assert!(matches!(err, SchemaReverseEngineerError::PkLessTableHasKeys(name) if name == "t"));
469    }
470
471    #[test]
472    fn writes_and_round_trips_a_composite_relation() {
473        let parent = TableBuilder::new(None::<&str>, "Property")
474            .add_column(ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence).required(true).build())
475            .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
476            .build();
477
478        let child = TableBuilder::new(None::<&str>, "Assignment")
479            .add_column(ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence).required(true).build())
480            .add_column(ColumnBuilder::new(None::<&str>, "PropertyID", ColumnType::Int).required(true).build())
481            .add_column(ColumnBuilder::new(None::<&str>, "ParentAssignmentID", ColumnType::Int).build())
482            .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
483            .add_relation(
484                Relation::new_composite(
485                    "Assignment",
486                    "Assignment",
487                    vec![("ParentAssignmentID", "ID"), ("PropertyID", "PropertyID")],
488                    RelationType::Cascade,
489                    false,
490                )
491                .unwrap(),
492            )
493            .build();
494
495        let schema = SchemaBuilder::new(None::<&str>).add_table(parent).add_table(child).build();
496        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
497        let xml = write_database_xml(&model).unwrap();
498
499        assert!(xml.contains("<compositeRelation table=\"Assignment\" type=\"cascade\">"));
500        assert!(xml.contains("<column src=\"ParentAssignmentID\" name=\"ID\"/>"));
501        assert!(xml.contains("<column src=\"PropertyID\" name=\"PropertyID\"/>"));
502
503        let reparsed = schema_parser::parse_database_xml(&xml).expect("round-tripped composite relation XML must be well-formed");
504        let reparsed_table = reparsed.default_schema().get_table("Assignment");
505        let relation = &reparsed_table.relations()[0];
506        assert!(relation.is_composite());
507        assert_eq!(
508            relation.column_pairs(),
509            &[
510                ("ParentAssignmentID".to_string(), "ID".to_string()),
511                ("PropertyID".to_string(), "PropertyID".to_string()),
512            ]
513        );
514    }
515
516    #[test]
517    fn wraps_tables_in_a_schema_element_when_the_schema_is_named() {
518        let table = TableBuilder::new(Some("sales"), "orders")
519            .add_column(ColumnBuilder::new(Some("sales"), "id", ColumnType::Sequence).required(true).build())
520            .build();
521        let schema = SchemaBuilder::new(Some("sales")).add_table(table).build();
522        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
523
524        let xml = write_database_xml(&model).unwrap();
525        assert!(xml.contains("<schema name=\"sales\">"));
526        assert!(xml.contains("<table name=\"orders\">"));
527        assert!(xml.contains("</schema>"));
528
529        let reparsed = schema_parser::parse_database_xml(&xml).expect("round-tripped XML must still be well-formed");
530        assert_eq!(reparsed.find_schema(Some("sales")).schema_name(), Some("sales"));
531    }
532}