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
17pub 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 if let Some(check) = column.check_constraint() {
200 out.push_str(">\n");
201 push_indent(out, indent + 1);
202 let _ = writeln!(out, "<check>{}</check>", xml_escape(check));
203 push_indent(out, indent);
204 out.push_str("</column>\n");
205 } else {
206 out.push_str("/>\n");
207 }
208}
209
210fn write_keys(out: &mut String, table: &Table, indent: usize) {
211 let Some(primary) = table.primary_key() else {
215 for key in table
216 .keys()
217 .iter()
218 .filter(|k| k.key_type() == KeyType::Unique)
219 {
220 eprintln!(
221 "warning: table {} has no primary key, so its unique key on ({}) can't be written -- skipping it",
222 table.name(),
223 key.columns_as_string()
224 );
225 }
226 for index in table.indexes() {
227 eprintln!(
228 "warning: table {} has no primary key, so its index on ({}) can't be written -- skipping it",
229 table.name(),
230 index.columns_as_string()
231 );
232 }
233 return;
234 };
235
236 push_indent(out, indent);
237 out.push_str("<keys>\n");
238 write_key_columns(out, "primary", primary, indent + 1);
239 for unique in table
240 .keys()
241 .iter()
242 .filter(|k| k.key_type() == KeyType::Unique)
243 {
244 write_key_columns(out, "unique", unique, indent + 1);
245 }
246 for index in table.indexes() {
247 write_index(out, index, indent + 1);
248 }
249 push_indent(out, indent);
250 out.push_str("</keys>\n");
251}
252
253fn write_key_columns(out: &mut String, tag: &str, key: &Key, indent: usize) {
254 push_indent(out, indent);
255 let _ = writeln!(out, "<{}>", tag);
256 for column in key.columns() {
257 push_indent(out, indent + 1);
258 let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape_attr(column.name()));
259 }
260 push_indent(out, indent);
261 let _ = writeln!(out, "</{}>", tag);
262}
263
264fn write_index(out: &mut String, index: &Key, indent: usize) {
265 push_indent(out, indent);
266 let _ = write!(out, "<index");
267 if index.is_unique() {
268 out.push_str(" unique=\"true\"");
269 }
270 if let Some(include) = index.include() {
271 let _ = write!(out, " include=\"{}\"", xml_escape_attr(include));
272 }
273 if let Some(filter) = index.filter() {
274 let _ = write!(out, " where=\"{}\"", xml_escape_attr(filter));
275 }
276 out.push_str(">\n");
277 for column in index.columns() {
278 push_indent(out, indent + 1);
279 let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape_attr(column.name()));
280 }
281 push_indent(out, indent);
282 out.push_str("</index>\n");
283}
284
285fn write_relations(
289 out: &mut String,
290 relations: &[Relation],
291 schema_name: Option<&str>,
292 indent: usize,
293) {
294 let target = |table: &str| match schema_name {
295 Some(schema) if !table.contains('.') => format!("{schema}.{table}"),
296 _ => table.to_string(),
297 };
298 if relations.is_empty() {
299 return;
300 }
301 push_indent(out, indent);
302 out.push_str("<relations>\n");
303 for relation in relations {
304 if relation.is_composite() {
305 push_indent(out, indent + 1);
306 let _ = writeln!(
307 out,
308 "<compositeRelation table=\"{}\" type=\"{}\">",
309 xml_escape_attr(&target(relation.to_table_name())),
310 relation_type_str(relation.relation_type())
311 );
312 for (from_column, to_column) in relation.column_pairs() {
313 push_indent(out, indent + 2);
314 let _ = writeln!(
315 out,
316 "<column src=\"{}\" name=\"{}\"/>",
317 xml_escape_attr(from_column),
318 xml_escape_attr(to_column)
319 );
320 }
321 push_indent(out, indent + 1);
322 out.push_str("</compositeRelation>\n");
323 } else {
324 push_indent(out, indent + 1);
325 let _ = writeln!(
326 out,
327 "<relation src=\"{}\" table=\"{}\" column=\"{}\" type=\"{}\"/>",
328 xml_escape_attr(relation.from_column_name()),
329 xml_escape_attr(&target(relation.to_table_name())),
330 xml_escape_attr(relation.to_column_name()),
331 relation_type_str(relation.relation_type())
332 );
333 }
334 }
335 push_indent(out, indent);
336 out.push_str("</relations>\n");
337}
338
339fn write_constraints(out: &mut String, constraints: &[Constraint], indent: usize) {
340 if constraints.is_empty() {
341 return;
342 }
343 push_indent(out, indent);
344 out.push_str("<constraints>\n");
345 for constraint in constraints {
346 push_indent(out, indent + 1);
347 let _ = writeln!(
348 out,
349 "<constraint name=\"{}\" databaseType=\"{}\">",
350 xml_escape_attr(constraint.name()),
351 database_type_str(constraint.database_type())
352 );
353 push_indent(out, indent + 2);
354 write_cdata(out, constraint.sql());
355 out.push('\n');
356 push_indent(out, indent + 1);
357 out.push_str("</constraint>\n");
358 }
359 push_indent(out, indent);
360 out.push_str("</constraints>\n");
361}
362
363fn relation_type_str(relation_type: schema_model::model::types::RelationType) -> &'static str {
364 use schema_model::model::types::RelationType;
365 match relation_type {
366 RelationType::Cascade => "cascade",
367 RelationType::Enforce => "enforce",
368 RelationType::SetNull => "setnull",
369 RelationType::DoNothing => "donothing",
370 }
371}
372
373fn boolean_mode_str(mode: BooleanMode) -> &'static str {
374 match mode {
375 BooleanMode::Native => "native",
376 BooleanMode::YesNo => "yesno",
377 BooleanMode::YN => "yn",
378 }
379}
380
381fn database_type_str(database_type: schema_model::model::types::DatabaseType) -> &'static str {
382 use schema_model::model::types::DatabaseType;
383 match database_type {
384 DatabaseType::Postgresql => "postgresql",
385 DatabaseType::Sqlite => "sqlite",
386 DatabaseType::SqlServer => "sqlserver",
387 }
388}
389
390fn foreign_key_mode_str(mode: ForeignKeyMode) -> &'static str {
391 match mode {
392 ForeignKeyMode::None => "none",
393 ForeignKeyMode::Relations => "relations",
394 ForeignKeyMode::Triggers => "triggers",
395 }
396}
397
398fn push_indent(out: &mut String, indent: usize) {
399 for _ in 0..indent {
400 out.push_str(" ");
401 }
402}
403
404fn write_cdata(out: &mut String, content: &str) {
410 out.push_str("<![CDATA[");
411 out.push_str(&content.replace("]]>", "]]]]><![CDATA[>"));
412 out.push_str("]]>");
413}
414
415fn xml_escape(value: &str) -> String {
419 let mut escaped = String::with_capacity(value.len());
420 for ch in value.chars() {
421 match ch {
422 '&' => escaped.push_str("&"),
423 '<' => escaped.push_str("<"),
424 '>' => escaped.push_str(">"),
425 '"' => escaped.push_str("""),
426 '\'' => escaped.push_str("'"),
427 _ => escaped.push(ch),
428 }
429 }
430 escaped
431}
432
433fn xml_escape_attr(value: &str) -> String {
438 let mut escaped = String::with_capacity(value.len());
439 for ch in xml_escape(value).chars() {
440 match ch {
441 '\n' => escaped.push_str(" "),
442 '\r' => escaped.push_str(" "),
443 '\t' => escaped.push_str("	"),
444 _ => escaped.push(ch),
445 }
446 }
447 escaped
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453 use schema_model::builder::{ColumnBuilder, KeyBuilder, SchemaBuilder, TableBuilder};
454 use schema_model::model::column_type::ColumnType;
455 use schema_model::model::enum_type::EnumValue;
456 use schema_model::model::relation::Relation;
457 use schema_model::model::types::{DatabaseType, RelationType};
458
459 #[test]
460 fn writes_table_with_columns_pk_and_relation() {
461 let parent = TableBuilder::new(None::<&str>, "parent")
462 .add_column(
463 ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence)
464 .required(true)
465 .build(),
466 )
467 .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
468 .build();
469
470 let child = TableBuilder::new(None::<&str>, "child")
471 .add_column(
472 ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence)
473 .required(true)
474 .build(),
475 )
476 .add_column(
477 ColumnBuilder::new(None::<&str>, "parent_id", ColumnType::Int)
478 .required(true)
479 .build(),
480 )
481 .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
482 .add_relation(Relation::new(
483 "parent",
484 "id",
485 "child",
486 "parent_id",
487 RelationType::Cascade,
488 false,
489 ))
490 .build();
491
492 let schema = SchemaBuilder::new(None::<&str>)
493 .add_table(parent)
494 .add_table(child)
495 .add_enum_type(EnumType::new(
496 "mood",
497 vec![EnumValue::new("HAPPY", None::<String>)],
498 ))
499 .add_view(View::new(
500 None::<&str>,
501 "v1",
502 "select 1",
503 Some(DatabaseType::Postgresql),
504 ))
505 .build();
506
507 let model =
508 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
509 let xml = write_database_xml(&model);
510
511 assert!(xml.contains("<database xmlns=\"http://stano.com/database\""));
512 assert!(xml.contains("<table name=\"parent\">"));
513 assert!(xml.contains("<column name=\"id\" type=\"sequence\" required=\"true\"/>"));
514 assert!(xml.contains(
515 "<relation src=\"parent_id\" table=\"parent\" column=\"id\" type=\"cascade\"/>"
516 ));
517 assert!(xml.contains("<enum name=\"mood\">"));
518 assert!(xml.contains("<view name=\"v1\">"));
519 }
520
521 #[test]
522 fn write_cdata_splits_embedded_close_sequence() {
523 let mut out = String::new();
524 write_cdata(&mut out, "select arr[1:2]]>x from t");
525 assert!(
526 !out.contains("2]]>x"),
527 "the literal ]]> must not survive unescaped inside one CDATA block: {out}"
528 );
529 assert!(out.starts_with("<![CDATA["));
530 assert!(out.ends_with("]]>"));
531 }
532
533 #[test]
534 fn view_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
535 let view = View::new(
536 None::<&str>,
537 "v1",
538 "select * from t where arr[1:2]]>x",
539 None,
540 );
541 let schema = SchemaBuilder::new(None::<&str>).add_view(view).build();
542 let model =
543 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
544 let xml = write_database_xml(&model);
545
546 let reparsed = schema_parser::parse_database_xml(&xml)
547 .expect("XML containing a ]]> sequence inside a view's SQL must still be well-formed");
548 let reparsed_view = &reparsed.default_schema().all_views()[0];
549 assert_eq!(reparsed_view.sql(), "select * from t where arr[1:2]]>x");
550 }
551
552 #[test]
553 fn other_sql_round_trips_through_the_real_parser() {
554 use schema_model::model::other_sql::OtherSql;
555 let schema = SchemaBuilder::new(None::<&str>)
556 .add_other_sql(OtherSql::new(
557 DatabaseType::SqlServer,
558 OtherSqlOrder::Bottom,
559 "create trigger trg on t after insert as select 1 where 'a]]>b' = 'x'",
560 ))
561 .build();
562 let model =
563 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
564 let xml = write_database_xml(&model);
565
566 let reparsed = schema_parser::parse_database_xml(&xml).expect("otherSql must be valid XML");
567 let other = &reparsed.default_schema().other_sql()[0];
568 assert_eq!(other.database_type(), DatabaseType::SqlServer);
569 assert_eq!(other.order(), OtherSqlOrder::Bottom);
570 assert!(other.sql().contains("a]]>b"));
571 }
572
573 #[test]
574 fn functions_and_procedures_round_trip_through_the_real_parser() {
575 use schema_model::model::function::Function;
576 use schema_model::model::procedure::Procedure;
577 let schema = SchemaBuilder::new(None::<&str>)
578 .add_functions(vec![Function::new(
579 None,
580 "f1",
581 DatabaseType::Postgresql,
582 "create or replace function f1() returns int as $$ select arr[1:2]]>1 $$",
583 )])
584 .add_procedures(vec![Procedure::new(
585 None,
586 "p1",
587 DatabaseType::Postgresql,
588 "create or replace procedure p1() language sql as $$ select 1 $$",
589 )])
590 .build();
591 let model =
592 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
593 let xml = write_database_xml(&model);
594
595 let reparsed = schema_parser::parse_database_xml(&xml).expect("routines must be valid XML");
596 let default_schema = reparsed.default_schema();
597 assert_eq!(default_schema.functions()[0].name(), "f1");
598 assert!(default_schema.functions()[0].sql().contains("arr[1:2]]>1"));
599 assert_eq!(
600 default_schema.functions()[0].database_type(),
601 DatabaseType::Postgresql
602 );
603 assert_eq!(default_schema.procedures()[0].name(), "p1");
604 }
605
606 #[test]
607 fn constraint_sql_containing_cdata_close_sequence_round_trips_through_the_real_parser() {
608 let table = TableBuilder::new(None::<&str>, "t")
609 .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
610 .add_constraint(schema_model::model::constraint::Constraint::new(
611 "ck_a",
612 "check (a[1:2]]>0)",
613 DatabaseType::Postgresql,
614 ))
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
621 let reparsed = schema_parser::parse_database_xml(&xml).expect(
622 "XML containing a ]]> sequence inside a constraint's SQL must still be well-formed",
623 );
624 let reparsed_table = reparsed.default_schema().get_table("t");
625 assert_eq!(reparsed_table.constraints()[0].sql(), "check (a[1:2]]>0)");
626 }
627
628 #[test]
629 fn multi_line_default_expression_round_trips_through_the_real_parser() {
630 let default = "case\n\twhen a > 0 then 1\r\n else 0\nend";
631 let table = TableBuilder::new(None::<&str>, "t")
632 .add_column(
633 ColumnBuilder::new(None::<&str>, "a", ColumnType::Int)
634 .default_constraint(Some(default.to_string()))
635 .build(),
636 )
637 .build();
638 let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
639 let model =
640 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
641 let xml = write_database_xml(&model);
642
643 let reparsed = schema_parser::parse_database_xml(&xml).unwrap();
644 let column = reparsed.default_schema().get_table("t").column("a");
645 assert_eq!(column.default_constraint(), Some(default));
646 }
647
648 #[test]
649 fn omits_keys_when_no_primary_key_present() {
650 let table = TableBuilder::new(None::<&str>, "t")
651 .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
652 .build();
653 let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
654 let model =
655 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
656 let xml = write_database_xml(&model);
657 assert!(!xml.contains("<keys>"));
658 }
659
660 #[test]
661 fn pk_less_table_keys_and_indexes_are_skipped() {
662 let table = TableBuilder::new(None::<&str>, "t")
663 .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
664 .add_key(KeyBuilder::new(KeyType::Unique).add_column("a").build())
665 .add_index(KeyBuilder::new(KeyType::Index).add_column("a").build())
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
671 let xml = write_database_xml(&model);
672 assert!(!xml.contains("<keys>"), "got: {xml}");
673 assert!(schema_parser::parse_database_xml(&xml).is_ok());
674 }
675
676 #[test]
677 fn writes_and_round_trips_a_composite_relation() {
678 let parent = TableBuilder::new(None::<&str>, "Property")
679 .add_column(
680 ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence)
681 .required(true)
682 .build(),
683 )
684 .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
685 .build();
686
687 let child = TableBuilder::new(None::<&str>, "Assignment")
688 .add_column(
689 ColumnBuilder::new(None::<&str>, "ID", ColumnType::Sequence)
690 .required(true)
691 .build(),
692 )
693 .add_column(
694 ColumnBuilder::new(None::<&str>, "PropertyID", ColumnType::Int)
695 .required(true)
696 .build(),
697 )
698 .add_column(
699 ColumnBuilder::new(None::<&str>, "ParentAssignmentID", ColumnType::Int).build(),
700 )
701 .add_key(KeyBuilder::new(KeyType::Primary).add_column("ID").build())
702 .add_relation(
703 Relation::new_composite(
704 "Assignment",
705 "Assignment",
706 vec![("ParentAssignmentID", "ID"), ("PropertyID", "PropertyID")],
707 RelationType::Cascade,
708 false,
709 )
710 .unwrap(),
711 )
712 .build();
713
714 let schema = SchemaBuilder::new(None::<&str>)
715 .add_table(parent)
716 .add_table(child)
717 .build();
718 let model =
719 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
720 let xml = write_database_xml(&model);
721
722 assert!(xml.contains("<compositeRelation table=\"Assignment\" type=\"cascade\">"));
723 assert!(xml.contains("<column src=\"ParentAssignmentID\" name=\"ID\"/>"));
724 assert!(xml.contains("<column src=\"PropertyID\" name=\"PropertyID\"/>"));
725
726 let reparsed = schema_parser::parse_database_xml(&xml)
727 .expect("round-tripped composite relation XML must be well-formed");
728 let reparsed_table = reparsed.default_schema().get_table("Assignment");
729 let relation = &reparsed_table.relations()[0];
730 assert!(relation.is_composite());
731 assert_eq!(
732 relation.column_pairs(),
733 &[
734 ("ParentAssignmentID".to_string(), "ID".to_string()),
735 ("PropertyID".to_string(), "PropertyID".to_string()),
736 ]
737 );
738 }
739
740 #[test]
741 fn wraps_tables_in_a_schema_element_when_the_schema_is_named() {
742 let table = TableBuilder::new(Some("sales"), "orders")
743 .add_column(
744 ColumnBuilder::new(Some("sales"), "id", ColumnType::Sequence)
745 .required(true)
746 .build(),
747 )
748 .build();
749 let schema = SchemaBuilder::new(Some("sales")).add_table(table).build();
750 let model =
751 DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
752
753 let xml = write_database_xml(&model);
754 assert!(xml.contains("<schema name=\"sales\">"));
755 assert!(xml.contains("<table name=\"orders\">"));
756 assert!(xml.contains("</schema>"));
757
758 let reparsed = schema_parser::parse_database_xml(&xml)
759 .expect("round-tripped XML must still be well-formed");
760 assert_eq!(
761 reparsed.find_schema(Some("sales")).schema_name(),
762 Some("sales")
763 );
764 }
765}