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