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, 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        write_schema_body(&mut out, schema, 1);
30    }
31
32    out.push_str("</database>\n");
33    out
34}
35
36fn write_schema_body(out: &mut String, schema: &Schema, indent: usize) {
37    for enum_type in schema.enum_types() {
38        write_enum(out, enum_type, indent);
39    }
40    for table in schema.tables() {
41        write_table(out, table, indent);
42    }
43    for view in schema.all_views() {
44        write_view(out, view, indent);
45    }
46}
47
48fn write_enum(out: &mut String, enum_type: &EnumType, indent: usize) {
49    push_indent(out, indent);
50    let _ = writeln!(out, "<enum name=\"{}\">", xml_escape(enum_type.name()));
51    for value in enum_type.values() {
52        push_indent(out, indent + 1);
53        let _ = write!(out, "<value name=\"{}\"", xml_escape(value.name()));
54        if value.code() != value.name() {
55            let _ = write!(out, " code=\"{}\"", xml_escape(value.code()));
56        }
57        out.push_str("/>\n");
58    }
59    push_indent(out, indent);
60    out.push_str("</enum>\n\n");
61}
62
63fn write_view(out: &mut String, view: &View, indent: usize) {
64    push_indent(out, indent);
65    let _ = writeln!(out, "<view name=\"{}\">", xml_escape(view.name()));
66    push_indent(out, indent + 1);
67    let _ = writeln!(out, "<![CDATA[{}]]>", view.sql());
68    push_indent(out, indent);
69    out.push_str("</view>\n\n");
70}
71
72fn write_table(out: &mut String, table: &Table, indent: usize) {
73    push_indent(out, indent);
74    let _ = writeln!(out, "<table name=\"{}\">", xml_escape(table.name()));
75
76    write_columns(out, table.columns(), indent + 1);
77    write_keys(out, table, indent + 1);
78    write_relations(out, table.relations(), indent + 1);
79    write_constraints(out, table.constraints(), indent + 1);
80
81    push_indent(out, indent);
82    out.push_str("</table>\n\n");
83}
84
85fn write_columns(out: &mut String, columns: &[Column], indent: usize) {
86    push_indent(out, indent);
87    out.push_str("<columns>\n");
88    for column in columns {
89        write_column(out, column, indent + 1);
90    }
91    push_indent(out, indent);
92    out.push_str("</columns>\n");
93}
94
95fn write_column(out: &mut String, column: &Column, indent: usize) {
96    push_indent(out, indent);
97    let _ = write!(
98        out,
99        "<column name=\"{}\" type=\"{}\"",
100        xml_escape(column.name()),
101        column.column_type().name().to_lowercase()
102    );
103    if column.length() > 0 {
104        let _ = write!(out, " length=\"{}\"", column.length());
105    }
106    if column.scale() > 0 {
107        let _ = write!(out, " scale=\"{}\"", column.scale());
108    }
109    if column.required() {
110        out.push_str(" required=\"true\"");
111    }
112    if let Some(default) = column.default_constraint() {
113        let _ = write!(out, " default=\"{}\"", xml_escape(default));
114    }
115    if let Some(generated) = column.generated() {
116        let _ = write!(out, " generated=\"{}\"", xml_escape(generated));
117    }
118    if let Some(enum_type) = column.enum_type() {
119        let _ = write!(out, " enumType=\"{}\"", xml_escape(enum_type));
120    }
121    if let Some(element_type) = column.element_type() {
122        let _ = write!(out, " elementType=\"{}\"", xml_escape(element_type));
123    }
124    if let Some(min_value) = column.min_value() {
125        let _ = write!(out, " minValue=\"{}\"", min_value);
126    }
127    if let Some(max_value) = column.max_value() {
128        let _ = write!(out, " maxValue=\"{}\"", max_value);
129    }
130
131    if let Some(check) = column.check_constraint() {
132        out.push_str(">\n");
133        push_indent(out, indent + 1);
134        let _ = writeln!(out, "<check>{}</check>", xml_escape(check));
135        push_indent(out, indent);
136        out.push_str("</column>\n");
137    } else {
138        out.push_str("/>\n");
139    }
140}
141
142fn write_keys(out: &mut String, table: &Table, indent: usize) {
143    // The XSD requires a <primary> element whenever <keys> is present, so a table with no
144    // primary key (and no promoted single-unique-key) can't emit unique/index keys either.
145    let Some(primary) = table.primary_key() else {
146        return;
147    };
148
149    push_indent(out, indent);
150    out.push_str("<keys>\n");
151    write_key_columns(out, "primary", primary, indent + 1);
152    for unique in table.keys().iter().filter(|k| k.key_type() == KeyType::Unique) {
153        write_key_columns(out, "unique", unique, indent + 1);
154    }
155    for index in table.indexes() {
156        write_index(out, index, indent + 1);
157    }
158    push_indent(out, indent);
159    out.push_str("</keys>\n");
160}
161
162fn write_key_columns(out: &mut String, tag: &str, key: &Key, indent: usize) {
163    push_indent(out, indent);
164    let _ = writeln!(out, "<{}>", tag);
165    for column in key.columns() {
166        push_indent(out, indent + 1);
167        let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape(column.name()));
168    }
169    push_indent(out, indent);
170    let _ = writeln!(out, "</{}>", tag);
171}
172
173fn write_index(out: &mut String, index: &Key, indent: usize) {
174    push_indent(out, indent);
175    let _ = write!(out, "<index");
176    if index.is_unique() {
177        out.push_str(" unique=\"true\"");
178    }
179    if let Some(include) = index.include() {
180        let _ = write!(out, " include=\"{}\"", xml_escape(include));
181    }
182    out.push_str(">\n");
183    for column in index.columns() {
184        push_indent(out, indent + 1);
185        let _ = writeln!(out, "<column name=\"{}\"/>", xml_escape(column.name()));
186    }
187    push_indent(out, indent);
188    out.push_str("</index>\n");
189}
190
191fn write_relations(out: &mut String, relations: &[Relation], indent: usize) {
192    if relations.is_empty() {
193        return;
194    }
195    push_indent(out, indent);
196    out.push_str("<relations>\n");
197    for relation in relations {
198        push_indent(out, indent + 1);
199        let _ = writeln!(
200            out,
201            "<relation src=\"{}\" table=\"{}\" column=\"{}\" type=\"{}\"/>",
202            xml_escape(relation.from_column_name()),
203            xml_escape(relation.to_table_name()),
204            xml_escape(relation.to_column_name()),
205            relation_type_str(relation.relation_type())
206        );
207    }
208    push_indent(out, indent);
209    out.push_str("</relations>\n");
210}
211
212fn write_constraints(out: &mut String, constraints: &[Constraint], indent: usize) {
213    if constraints.is_empty() {
214        return;
215    }
216    push_indent(out, indent);
217    out.push_str("<constraints>\n");
218    for constraint in constraints {
219        push_indent(out, indent + 1);
220        let _ = writeln!(out, "<constraint name=\"{}\">", xml_escape(constraint.name()));
221        push_indent(out, indent + 2);
222        let _ = writeln!(out, "<![CDATA[{}]]>", constraint.sql());
223        push_indent(out, indent + 1);
224        out.push_str("</constraint>\n");
225    }
226    push_indent(out, indent);
227    out.push_str("</constraints>\n");
228}
229
230fn relation_type_str(relation_type: schema_model::model::types::RelationType) -> &'static str {
231    use schema_model::model::types::RelationType;
232    match relation_type {
233        RelationType::Cascade => "cascade",
234        RelationType::Enforce => "enforce",
235        RelationType::SetNull => "setnull",
236        RelationType::DoNothing => "donothing",
237    }
238}
239
240fn boolean_mode_str(mode: BooleanMode) -> &'static str {
241    match mode {
242        BooleanMode::Native => "native",
243        BooleanMode::YesNo => "yesno",
244        BooleanMode::YN => "yn",
245    }
246}
247
248fn foreign_key_mode_str(mode: ForeignKeyMode) -> &'static str {
249    match mode {
250        ForeignKeyMode::None => "none",
251        ForeignKeyMode::Relations => "relations",
252        ForeignKeyMode::Triggers => "triggers",
253    }
254}
255
256fn push_indent(out: &mut String, indent: usize) {
257    for _ in 0..indent {
258        out.push_str("  ");
259    }
260}
261
262/// XML-escapes attribute and text content consistently (the Java writer inconsistently escaped
263/// index/unique key column names but not primary key column names -- here every column name and
264/// text value goes through the same escaping).
265fn xml_escape(value: &str) -> String {
266    let mut escaped = String::with_capacity(value.len());
267    for ch in value.chars() {
268        match ch {
269            '&' => escaped.push_str("&amp;"),
270            '<' => escaped.push_str("&lt;"),
271            '>' => escaped.push_str("&gt;"),
272            '"' => escaped.push_str("&quot;"),
273            '\'' => escaped.push_str("&apos;"),
274            _ => escaped.push(ch),
275        }
276    }
277    escaped
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use schema_model::builder::{ColumnBuilder, KeyBuilder, SchemaBuilder, TableBuilder};
284    use schema_model::model::column_type::ColumnType;
285    use schema_model::model::enum_type::EnumValue;
286    use schema_model::model::relation::Relation;
287    use schema_model::model::types::{DatabaseType, RelationType};
288
289    #[test]
290    fn writes_table_with_columns_pk_and_relation() {
291        let parent = TableBuilder::new(None::<&str>, "parent")
292            .add_column(ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence).required(true).build())
293            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
294            .build();
295
296        let child = TableBuilder::new(None::<&str>, "child")
297            .add_column(ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence).required(true).build())
298            .add_column(ColumnBuilder::new(None::<&str>, "parent_id", ColumnType::Int).required(true).build())
299            .add_key(KeyBuilder::new(KeyType::Primary).add_column("id").build())
300            .add_relation(Relation::new("parent", "id", "child", "parent_id", RelationType::Cascade, false))
301            .build();
302
303        let schema = SchemaBuilder::new(None::<&str>)
304            .add_table(parent)
305            .add_table(child)
306            .add_enum_type(EnumType::new("mood", vec![EnumValue::new("HAPPY", None::<String>)]))
307            .add_view(View::new(None::<&str>, "v1", "select 1", Some(DatabaseType::Postgresql)))
308            .build();
309
310        let model = DatabaseModel::new(None, BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
311        let xml = write_database_xml(&model);
312
313        assert!(xml.contains("<database xmlns=\"http://stano.com/database\""));
314        assert!(xml.contains("<table name=\"parent\">"));
315        assert!(xml.contains("<column name=\"id\" type=\"sequence\" required=\"true\"/>"));
316        assert!(xml.contains("<relation src=\"parent_id\" table=\"parent\" column=\"id\" type=\"cascade\"/>"));
317        assert!(xml.contains("<enum name=\"mood\">"));
318        assert!(xml.contains("<view name=\"v1\">"));
319    }
320
321    #[test]
322    fn omits_keys_when_no_primary_key_present() {
323        let table = TableBuilder::new(None::<&str>, "t")
324            .add_column(ColumnBuilder::new(None::<&str>, "a", ColumnType::Int).build())
325            .build();
326        let schema = SchemaBuilder::new(None::<&str>).add_table(table).build();
327        let model = DatabaseModel::new(None, BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
328        let xml = write_database_xml(&model);
329        assert!(!xml.contains("<keys>"));
330    }
331}