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