Skip to main content

schema_reverse_engineer/
xml_writer.rs

1use schema_model::model::column::Column;
2use schema_model::model::constraint::Constraint;
3use schema_model::model::database_model::DatabaseModel;
4use schema_model::model::enum_type::EnumType;
5use schema_model::model::key::Key;
6use schema_model::model::relation::Relation;
7use schema_model::model::schema::Schema;
8use schema_model::model::table::Table;
9use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode, KeyType};
10use schema_model::model::view::View;
11use std::fmt::Write as _;
12
13const NAMESPACE: &str = "http://stano.com/database";
14
15/// Serializes a `DatabaseModel` to the schema-rs XML schema definition format (see
16/// `schema-xsd/schema.xsd`), the inverse of `schema_parser::parse_database_xml`.
17pub fn write_database_xml(model: &DatabaseModel) -> String {
18    let mut out = String::new();
19    out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
20    let _ = writeln!(
21        out,
22        "<database xmlns=\"{}\" foreignKeyMode=\"{}\" booleanMode=\"{}\">",
23        NAMESPACE,
24        foreign_key_mode_str(model.foreign_key_mode()),
25        boolean_mode_str(model.boolean_mode())
26    );
27
28    for schema in model.schemas() {
29        match schema.schema_name() {
30            Some(name) => {
31                push_indent(&mut out, 1);
32                let _ = writeln!(out, "<schema name=\"{}\">", xml_escape_attr(name));
33                write_schema_body(&mut out, schema, 2);
34                push_indent(&mut out, 1);
35                out.push_str("</schema>\n");
36            }
37            None => write_schema_body(&mut out, schema, 1),
38        }
39    }
40
41    out.push_str("</database>\n");
42    out
43}
44
45fn write_schema_body(out: &mut String, schema: &Schema, indent: usize) {
46    for enum_type in schema.enum_types() {
47        write_enum(out, enum_type, indent);
48    }
49    for table in schema.tables() {
50        write_table(out, table, indent);
51    }
52    for view in schema.all_views() {
53        write_view(out, view, indent);
54    }
55    for function in schema.functions() {
56        write_routine(
57            out,
58            "function",
59            function.name(),
60            function.database_type(),
61            function.sql(),
62            indent,
63        );
64    }
65    for procedure in schema.procedures() {
66        write_routine(
67            out,
68            "procedure",
69            procedure.name(),
70            procedure.database_type(),
71            procedure.sql(),
72            indent,
73        );
74    }
75}
76
77fn write_routine(
78    out: &mut String,
79    tag: &str,
80    name: &str,
81    database_type: DatabaseType,
82    sql: &str,
83    indent: usize,
84) {
85    push_indent(out, indent);
86    let _ = writeln!(out, "<{} name=\"{}\">", tag, xml_escape_attr(name));
87    push_indent(out, indent + 1);
88    let _ = write!(
89        out,
90        "<sql databaseType=\"{}\">",
91        database_type_str(database_type)
92    );
93    write_cdata(out, sql);
94    out.push_str("</sql>\n");
95    push_indent(out, indent);
96    let _ = writeln!(out, "</{}>\n", tag);
97}
98
99fn write_enum(out: &mut String, enum_type: &EnumType, indent: usize) {
100    push_indent(out, indent);
101    let _ = writeln!(out, "<enum name=\"{}\">", xml_escape_attr(enum_type.name()));
102    for value in enum_type.values() {
103        push_indent(out, indent + 1);
104        let _ = write!(out, "<value name=\"{}\"", xml_escape_attr(value.name()));
105        if value.code() != value.name() {
106            let _ = write!(out, " code=\"{}\"", xml_escape_attr(value.code()));
107        }
108        out.push_str("/>\n");
109    }
110    push_indent(out, indent);
111    out.push_str("</enum>\n\n");
112}
113
114fn write_view(out: &mut String, view: &View, indent: usize) {
115    push_indent(out, indent);
116    let _ = writeln!(out, "<view name=\"{}\">", xml_escape_attr(view.name()));
117    push_indent(out, indent + 1);
118    write_cdata(out, view.sql());
119    out.push('\n');
120    push_indent(out, indent);
121    out.push_str("</view>\n\n");
122}
123
124fn write_table(out: &mut String, table: &Table, indent: usize) {
125    push_indent(out, indent);
126    let _ = writeln!(out, "<table name=\"{}\">", xml_escape_attr(table.name()));
127
128    write_columns(out, table.columns(), indent + 1);
129    write_keys(out, table, indent + 1);
130    write_relations(out, table.relations(), table.schema_name(), indent + 1);
131    write_constraints(out, table.constraints(), indent + 1);
132
133    push_indent(out, indent);
134    out.push_str("</table>\n\n");
135}
136
137fn write_columns(out: &mut String, columns: &[Column], indent: usize) {
138    push_indent(out, indent);
139    out.push_str("<columns>\n");
140    for column in columns {
141        write_column(out, column, indent + 1);
142    }
143    push_indent(out, indent);
144    out.push_str("</columns>\n");
145}
146
147fn write_column(out: &mut String, column: &Column, indent: usize) {
148    push_indent(out, indent);
149    let _ = write!(
150        out,
151        "<column name=\"{}\" type=\"{}\"",
152        xml_escape_attr(column.name()),
153        column.column_type().name().to_lowercase()
154    );
155    if column.length() > 0 {
156        let _ = write!(out, " length=\"{}\"", column.length());
157    }
158    if column.scale() > 0 {
159        let _ = write!(out, " scale=\"{}\"", column.scale());
160    }
161    if column.required() {
162        out.push_str(" required=\"true\"");
163    }
164    if let Some(default) = column.default_constraint() {
165        let _ = write!(out, " default=\"{}\"", xml_escape_attr(default));
166    }
167    if let Some(generated) = column.generated() {
168        let _ = write!(out, " generated=\"{}\"", xml_escape_attr(generated));
169    }
170    if let Some(enum_type) = column.enum_type() {
171        let _ = write!(out, " enumType=\"{}\"", xml_escape_attr(enum_type));
172    }
173    if let Some(element_type) = column.element_type() {
174        let _ = write!(out, " elementType=\"{}\"", xml_escape_attr(element_type));
175    }
176    if let Some(min_value) = column.min_value() {
177        let _ = write!(out, " minValue=\"{}\"", min_value);
178    }
179    if let Some(max_value) = column.max_value() {
180        let _ = write!(out, " maxValue=\"{}\"", max_value);
181    }
182
183    if let Some(check) = column.check_constraint() {
184        out.push_str(">\n");
185        push_indent(out, indent + 1);
186        let _ = writeln!(out, "<check>{}</check>", xml_escape(check));
187        push_indent(out, indent);
188        out.push_str("</column>\n");
189    } else {
190        out.push_str("/>\n");
191    }
192}
193
194fn write_keys(out: &mut String, table: &Table, indent: usize) {
195    // The XSD requires a <primary> element whenever <keys> is present, so a table with no
196    // primary key can't emit unique keys or indexes either. They are skipped with a warning
197    // (like the other things the model/XSD can't represent) rather than failing the run.
198    let Some(primary) = table.primary_key() else {
199        for key in table
200            .keys()
201            .iter()
202            .filter(|k| k.key_type() == KeyType::Unique)
203        {
204            eprintln!(
205                "warning: table {} has no primary key, so its unique key on ({}) can't be written -- skipping it",
206                table.name(),
207                key.columns_as_string()
208            );
209        }
210        for index in table.indexes() {
211            eprintln!(
212                "warning: table {} has no primary key, so its index on ({}) can't be written -- skipping it",
213                table.name(),
214                index.columns_as_string()
215            );
216        }
217        return;
218    };
219
220    push_indent(out, indent);
221    out.push_str("<keys>\n");
222    write_key_columns(out, "primary", primary, indent + 1);
223    for unique in table
224        .keys()
225        .iter()
226        .filter(|k| k.key_type() == KeyType::Unique)
227    {
228        write_key_columns(out, "unique", unique, indent + 1);
229    }
230    for index in table.indexes() {
231        write_index(out, index, indent + 1);
232    }
233    push_indent(out, indent);
234    out.push_str("</keys>\n");
235}
236
237fn write_key_columns(out: &mut String, tag: &str, key: &Key, indent: usize) {
238    push_indent(out, indent);
239    let _ = writeln!(out, "<{}>", tag);
240    for column in key.columns() {
241        push_indent(out, indent + 1);
242        let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape_attr(column.name()));
243    }
244    push_indent(out, indent);
245    let _ = writeln!(out, "</{}>", tag);
246}
247
248fn write_index(out: &mut String, index: &Key, indent: usize) {
249    push_indent(out, indent);
250    let _ = write!(out, "<index");
251    if index.is_unique() {
252        out.push_str(" unique=\"true\"");
253    }
254    if let Some(include) = index.include() {
255        let _ = write!(out, " include=\"{}\"", xml_escape_attr(include));
256    }
257    if let Some(filter) = index.filter() {
258        let _ = write!(out, " where=\"{}\"", xml_escape_attr(filter));
259    }
260    out.push_str(">\n");
261    for column in index.columns() {
262        push_indent(out, indent + 1);
263        let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape_attr(column.name()));
264    }
265    push_indent(out, indent);
266    out.push_str("</index>\n");
267}
268
269/// Relation targets inside a named `<schema>` must be written schema-qualified, since the
270/// parser resolves a bare name against the default schema. A target that is already
271/// qualified (a cross-schema FK) is written as-is.
272fn write_relations(
273    out: &mut String,
274    relations: &[Relation],
275    schema_name: Option<&str>,
276    indent: usize,
277) {
278    let target = |table: &str| match schema_name {
279        Some(schema) if !table.contains('.') => format!("{schema}.{table}"),
280        _ => table.to_string(),
281    };
282    if relations.is_empty() {
283        return;
284    }
285    push_indent(out, indent);
286    out.push_str("<relations>\n");
287    for relation in relations {
288        if relation.is_composite() {
289            push_indent(out, indent + 1);
290            let _ = writeln!(
291                out,
292                "<compositeRelation table=\"{}\" type=\"{}\">",
293                xml_escape_attr(&target(relation.to_table_name())),
294                relation_type_str(relation.relation_type())
295            );
296            for (from_column, to_column) in relation.column_pairs() {
297                push_indent(out, indent + 2);
298                let _ = writeln!(
299                    out,
300                    "<column src=\"{}\" name=\"{}\"/>",
301                    xml_escape_attr(from_column),
302                    xml_escape_attr(to_column)
303                );
304            }
305            push_indent(out, indent + 1);
306            out.push_str("</compositeRelation>\n");
307        } else {
308            push_indent(out, indent + 1);
309            let _ = writeln!(
310                out,
311                "<relation src=\"{}\" table=\"{}\" column=\"{}\" type=\"{}\"/>",
312                xml_escape_attr(relation.from_column_name()),
313                xml_escape_attr(&target(relation.to_table_name())),
314                xml_escape_attr(relation.to_column_name()),
315                relation_type_str(relation.relation_type())
316            );
317        }
318    }
319    push_indent(out, indent);
320    out.push_str("</relations>\n");
321}
322
323fn write_constraints(out: &mut String, constraints: &[Constraint], indent: usize) {
324    if constraints.is_empty() {
325        return;
326    }
327    push_indent(out, indent);
328    out.push_str("<constraints>\n");
329    for constraint in constraints {
330        push_indent(out, indent + 1);
331        let _ = writeln!(
332            out,
333            "<constraint name=\"{}\" databaseType=\"{}\">",
334            xml_escape_attr(constraint.name()),
335            database_type_str(constraint.database_type())
336        );
337        push_indent(out, indent + 2);
338        write_cdata(out, constraint.sql());
339        out.push('\n');
340        push_indent(out, indent + 1);
341        out.push_str("</constraint>\n");
342    }
343    push_indent(out, indent);
344    out.push_str("</constraints>\n");
345}
346
347fn relation_type_str(relation_type: schema_model::model::types::RelationType) -> &'static str {
348    use schema_model::model::types::RelationType;
349    match relation_type {
350        RelationType::Cascade => "cascade",
351        RelationType::Enforce => "enforce",
352        RelationType::SetNull => "setnull",
353        RelationType::DoNothing => "donothing",
354    }
355}
356
357fn boolean_mode_str(mode: BooleanMode) -> &'static str {
358    match mode {
359        BooleanMode::Native => "native",
360        BooleanMode::YesNo => "yesno",
361        BooleanMode::YN => "yn",
362    }
363}
364
365fn database_type_str(database_type: schema_model::model::types::DatabaseType) -> &'static str {
366    use schema_model::model::types::DatabaseType;
367    match database_type {
368        DatabaseType::Postgresql => "postgresql",
369        DatabaseType::Sqlite => "sqlite",
370        DatabaseType::SqlServer => "sqlserver",
371    }
372}
373
374fn foreign_key_mode_str(mode: ForeignKeyMode) -> &'static str {
375    match mode {
376        ForeignKeyMode::None => "none",
377        ForeignKeyMode::Relations => "relations",
378        ForeignKeyMode::Triggers => "triggers",
379    }
380}
381
382fn push_indent(out: &mut String, indent: usize) {
383    for _ in 0..indent {
384        out.push_str("  ");
385    }
386}
387
388/// Writes `content` as a `<![CDATA[...]]>` section, splitting any embedded `]]>` across
389/// adjacent CDATA sections first. The literal sequence `]]>` is illegal inside XML
390/// character data (not just "outside CDATA") - e.g. SQL text containing an array-slice
391/// like `arr[1:2]]>x` would otherwise close the CDATA section early and produce
392/// non-well-formed XML that fails to parse back.
393fn write_cdata(out: &mut String, content: &str) {
394    out.push_str("<![CDATA[");
395    out.push_str(&content.replace("]]>", "]]]]><![CDATA[>"));
396    out.push_str("]]>");
397}
398
399/// XML-escapes attribute and text content consistently (the Java writer inconsistently escaped
400/// index/unique key column names but not primary key column names -- here every column name and
401/// text value goes through the same escaping).
402fn xml_escape(value: &str) -> String {
403    let mut escaped = String::with_capacity(value.len());
404    for ch in value.chars() {
405        match ch {
406            '&' => escaped.push_str("&amp;"),
407            '<' => escaped.push_str("&lt;"),
408            '>' => escaped.push_str("&gt;"),
409            '"' => escaped.push_str("&quot;"),
410            '\'' => escaped.push_str("&apos;"),
411            _ => escaped.push(ch),
412        }
413    }
414    escaped
415}
416
417/// Escapes `value` for use inside a double-quoted attribute. On top of `xml_escape`, the
418/// whitespace characters that XML attribute-value normalization would otherwise collapse to
419/// a plain space on re-parse (newline, carriage return, tab) are written as character
420/// references, so a multi-line default expression round-trips unchanged.
421fn xml_escape_attr(value: &str) -> String {
422    let mut escaped = String::with_capacity(value.len());
423    for ch in xml_escape(value).chars() {
424        match ch {
425            '\n' => escaped.push_str("&#10;"),
426            '\r' => escaped.push_str("&#13;"),
427            '\t' => escaped.push_str("&#9;"),
428            _ => escaped.push(ch),
429        }
430    }
431    escaped
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437    use schema_model::builder::{ColumnBuilder, KeyBuilder, SchemaBuilder, TableBuilder};
438    use schema_model::model::column_type::ColumnType;
439    use schema_model::model::enum_type::EnumValue;
440    use schema_model::model::relation::Relation;
441    use schema_model::model::types::{DatabaseType, RelationType};
442
443    #[test]
444    fn writes_table_with_columns_pk_and_relation() {
445        let parent = TableBuilder::new(None::<&str>, "parent")
446            .add_column(
447                ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence)
448                    .required(true)
449                    .build(),
450            )
451            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
452            .build();
453
454        let child = TableBuilder::new(None::<&str>, "child")
455            .add_column(
456                ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence)
457                    .required(true)
458                    .build(),
459            )
460            .add_column(
461                ColumnBuilder::new(None::<&str>, "parent_id", ColumnType::Int)
462                    .required(true)
463                    .build(),
464            )
465            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
466            .add_relation(Relation::new(
467                "parent",
468                "id",
469                "child",
470                "parent_id",
471                RelationType::Cascade,
472                false,
473            ))
474            .build();
475
476        let schema = SchemaBuilder::new(None::<&str>)
477            .add_table(parent)
478            .add_table(child)
479            .add_enum_type(EnumType::new(
480                "mood",
481                vec![EnumValue::new("HAPPY", None::<String>)],
482            ))
483            .add_view(View::new(
484                None::<&str>,
485                "v1",
486                "select 1",
487                Some(DatabaseType::Postgresql),
488            ))
489            .build();
490
491        let model =
492            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
493        let xml = write_database_xml(&model);
494
495        assert!(xml.contains("<database xmlns=\"http://stano.com/database\""));
496        assert!(xml.contains("<table name=\"parent\">"));
497        assert!(xml.contains("<column name=\"id\" type=\"sequence\" required=\"true\"/>"));
498        assert!(xml.contains(
499            "<relation src=\"parent_id\" table=\"parent\" column=\"id\" type=\"cascade\"/>"
500        ));
501        assert!(xml.contains("<enum name=\"mood\">"));
502        assert!(xml.contains("<view name=\"v1\">"));
503    }
504
505    #[test]
506    fn write_cdata_splits_embedded_close_sequence() {
507        let mut out = String::new();
508        write_cdata(&mut out, "select arr[1:2]]>x from t");
509        assert!(
510            !out.contains("2]]>x"),
511            "the literal ]]> must not survive unescaped inside one CDATA block: {out}"
512        );
513        assert!(out.starts_with("<![CDATA["));
514        assert!(out.ends_with("]]>"));
515    }
516
517    #[test]
518    fn view_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
519        let view = View::new(
520            None::<&str>,
521            "v1",
522            "select * from t where arr[1:2]]>x",
523            None,
524        );
525        let schema = SchemaBuilder::new(None::<&str>).add_view(view).build();
526        let model =
527            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
528        let xml = write_database_xml(&model);
529
530        let reparsed = schema_parser::parse_database_xml(&xml)
531            .expect("XML containing a ]]> sequence inside a view's SQL must still be well-formed");
532        let reparsed_view = &reparsed.default_schema().all_views()[0];
533        assert_eq!(reparsed_view.sql(), "select * from t where arr[1:2]]>x");
534    }
535
536    #[test]
537    fn functions_and_procedures_round_trip_through_the_real_parser() {
538        use schema_model::model::function::Function;
539        use schema_model::model::procedure::Procedure;
540        let schema = SchemaBuilder::new(None::<&str>)
541            .add_functions(vec![Function::new(
542                None,
543                "f1",
544                DatabaseType::Postgresql,
545                "create or replace function f1() returns int as $$ select arr[1:2]]>1 $$",
546            )])
547            .add_procedures(vec![Procedure::new(
548                None,
549                "p1",
550                DatabaseType::Postgresql,
551                "create or replace procedure p1() language sql as $$ select 1 $$",
552            )])
553            .build();
554        let model =
555            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
556        let xml = write_database_xml(&model);
557
558        let reparsed = schema_parser::parse_database_xml(&xml).expect("routines must be valid XML");
559        let default_schema = reparsed.default_schema();
560        assert_eq!(default_schema.functions()[0].name(), "f1");
561        assert!(default_schema.functions()[0].sql().contains("arr[1:2]]>1"));
562        assert_eq!(
563            default_schema.functions()[0].database_type(),
564            DatabaseType::Postgresql
565        );
566        assert_eq!(default_schema.procedures()[0].name(), "p1");
567    }
568
569    #[test]
570    fn constraint_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
571        let table = TableBuilder::new(None::<&str>, "t")
572            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
573            .add_constraint(schema_model::model::constraint::Constraint::new(
574                "ck_a",
575                "check (a[1:2]]>0)",
576                DatabaseType::Postgresql,
577            ))
578            .build();
579        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
580        let model =
581            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
582        let xml = write_database_xml(&model);
583
584        let reparsed = schema_parser::parse_database_xml(&xml).expect(
585            "XML containing a ]]> sequence inside a constraint's SQL must still be well-formed",
586        );
587        let reparsed_table = reparsed.default_schema().get_table("t");
588        assert_eq!(reparsed_table.constraints()[0].sql(), "check (a[1:2]]>0)");
589    }
590
591    #[test]
592    fn multi_line_default_expression_round_trips_through_the_real_parser() {
593        let default = "case\n\twhen a > 0 then 1\r\n  else 0\nend";
594        let table = TableBuilder::new(None::<&str>, "t")
595            .add_column(
596                ColumnBuilder::new(None::<&str>, "a", ColumnType::Int)
597                    .default_constraint(Some(default.to_string()))
598                    .build(),
599            )
600            .build();
601        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
602        let model =
603            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
604        let xml = write_database_xml(&model);
605
606        let reparsed = schema_parser::parse_database_xml(&xml).unwrap();
607        let column = reparsed.default_schema().get_table("t").column("a");
608        assert_eq!(column.default_constraint(), Some(default));
609    }
610
611    #[test]
612    fn omits_keys_when_no_primary_key_present() {
613        let table = TableBuilder::new(None::<&str>, "t")
614            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
615            .build();
616        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
617        let model =
618            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
619        let xml = write_database_xml(&model);
620        assert!(!xml.contains("<keys>"));
621    }
622
623    #[test]
624    fn pk_less_table_keys_and_indexes_are_skipped() {
625        let table = TableBuilder::new(None::<&str>, "t")
626            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
627            .add_key(KeyBuilder::new(KeyType::Unique).add_column("a").build())
628            .add_index(KeyBuilder::new(KeyType::Index).add_column("a").build())
629            .build();
630        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
631        let model =
632            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
633
634        let xml = write_database_xml(&model);
635        assert!(!xml.contains("<keys>"), "got: {xml}");
636        assert!(schema_parser::parse_database_xml(&xml).is_ok());
637    }
638
639    #[test]
640    fn writes_and_round_trips_a_composite_relation() {
641        let parent = TableBuilder::new(None::<&str>, "Property")
642            .add_column(
643                ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence)
644                    .required(true)
645                    .build(),
646            )
647            .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
648            .build();
649
650        let child = TableBuilder::new(None::<&str>, "Assignment")
651            .add_column(
652                ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence)
653                    .required(true)
654                    .build(),
655            )
656            .add_column(
657                ColumnBuilder::new(None::<&str>, "PropertyID", ColumnType::Int)
658                    .required(true)
659                    .build(),
660            )
661            .add_column(
662                ColumnBuilder::new(None::<&str>, "ParentAssignmentID", ColumnType::Int).build(),
663            )
664            .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
665            .add_relation(
666                Relation::new_composite(
667                    "Assignment",
668                    "Assignment",
669                    vec![("ParentAssignmentID", "ID"), ("PropertyID", "PropertyID")],
670                    RelationType::Cascade,
671                    false,
672                )
673                .unwrap(),
674            )
675            .build();
676
677        let schema = SchemaBuilder::new(None::<&str>)
678            .add_table(parent)
679            .add_table(child)
680            .build();
681        let model =
682            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
683        let xml = write_database_xml(&model);
684
685        assert!(xml.contains("<compositeRelation table=\"Assignment\" type=\"cascade\">"));
686        assert!(xml.contains("<column src=\"ParentAssignmentID\" name=\"ID\"/>"));
687        assert!(xml.contains("<column src=\"PropertyID\" name=\"PropertyID\"/>"));
688
689        let reparsed = schema_parser::parse_database_xml(&xml)
690            .expect("round-tripped composite relation XML must be well-formed");
691        let reparsed_table = reparsed.default_schema().get_table("Assignment");
692        let relation = &reparsed_table.relations()[0];
693        assert!(relation.is_composite());
694        assert_eq!(
695            relation.column_pairs(),
696            &[
697                ("ParentAssignmentID".to_string(), "ID".to_string()),
698                ("PropertyID".to_string(), "PropertyID".to_string()),
699            ]
700        );
701    }
702
703    #[test]
704    fn wraps_tables_in_a_schema_element_when_the_schema_is_named() {
705        let table = TableBuilder::new(Some("sales"), "orders")
706            .add_column(
707                ColumnBuilder::new(Some("sales"), "id", ColumnType::Sequence)
708                    .required(true)
709                    .build(),
710            )
711            .build();
712        let schema = SchemaBuilder::new(Some("sales")).add_table(table).build();
713        let model =
714            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
715
716        let xml = write_database_xml(&model);
717        assert!(xml.contains("<schema name=\"sales\">"));
718        assert!(xml.contains("<table name=\"orders\">"));
719        assert!(xml.contains("</schema>"));
720
721        let reparsed = schema_parser::parse_database_xml(&xml)
722            .expect("round-tripped XML must still be well-formed");
723        assert_eq!(
724            reparsed.find_schema(Some("sales")).schema_name(),
725            Some("sales")
726        );
727    }
728}