Skip to main content

schema_parser/parser/
roxml_parser.rs

1use crate::parser::nodes::*;
2use roxmltree::{Document, Node};
3
4const NS: &str = "http://stano.com/database";
5
6pub fn parse_database_roxml(xml: &str) -> Result<DatabaseXml, String> {
7    let doc = Document::parse(xml).map_err(|e| format!("XML parse error: {e}"))?;
8    let root = doc
9        .descendants()
10        .find(|n| n.has_tag_name((NS, "database")))
11        .ok_or_else(|| "No <database> root element found".to_string())?;
12
13    parse_database_node(root)
14}
15
16fn parse_database_node(node: Node) -> Result<DatabaseXml, String> {
17    let foreign_key_mode = attr_string(node, "foreignKeyMode");
18    let boolean_mode = attr_string(node, "booleanMode");
19    let case_sensitive_text = attr_bool(node, "caseSensitiveText")?;
20
21    let mut tables = Vec::new();
22    let mut enums = Vec::new();
23    let mut views = Vec::new();
24    let mut functions = Vec::new();
25    let mut procedures = Vec::new();
26    let mut other_sql = Vec::new();
27    let mut schemas = Vec::new();
28
29    for child in node.children().filter(|n| n.is_element()) {
30        match child.tag_name().name() {
31            "table" if child.has_tag_name((NS, "table")) => tables.push(parse_table_node(child)?),
32            "enum" if child.has_tag_name((NS, "enum")) => enums.push(parse_enum_node(child)?),
33            "view" if child.has_tag_name((NS, "view")) => views.push(parse_view_node(child)?),
34            "function" if child.has_tag_name((NS, "function")) => functions.push(parse_function_node(child)?),
35            "procedure" if child.has_tag_name((NS, "procedure")) => procedures.push(parse_procedure_node(child)?),
36            "otherSql" if child.has_tag_name((NS, "otherSql")) => other_sql.push(parse_other_sql_node(child)?),
37            "schema" if child.has_tag_name((NS, "schema")) => schemas.push(parse_schema_node(child)?),
38            _ => {}
39        }
40    }
41
42    Ok(DatabaseXml {
43        foreign_key_mode,
44        boolean_mode,
45        case_sensitive_text,
46        tables,
47        enums,
48        views,
49        functions,
50        procedures,
51        other_sql,
52        schemas,
53    })
54}
55
56fn parse_schema_node(node: Node) -> Result<SchemaXml, String> {
57    let name = attr_string_required(node, "name")?;
58    let case_sensitive_text = attr_bool(node, "caseSensitiveText")?;
59
60    let mut tables = Vec::new();
61    let mut enums = Vec::new();
62    let mut views = Vec::new();
63    let mut functions = Vec::new();
64    let mut procedures = Vec::new();
65    let mut other_sql = Vec::new();
66
67    for child in node.children().filter(|n| n.is_element()) {
68        match child.tag_name().name() {
69            "table" if child.has_tag_name((NS, "table")) => tables.push(parse_table_node(child)?),
70            "enum" if child.has_tag_name((NS, "enum")) => enums.push(parse_enum_node(child)?),
71            "view" if child.has_tag_name((NS, "view")) => views.push(parse_view_node(child)?),
72            "function" if child.has_tag_name((NS, "function")) => functions.push(parse_function_node(child)?),
73            "procedure" if child.has_tag_name((NS, "procedure")) => procedures.push(parse_procedure_node(child)?),
74            "otherSql" if child.has_tag_name((NS, "otherSql")) => other_sql.push(parse_other_sql_node(child)?),
75            _ => {}
76        }
77    }
78
79    Ok(SchemaXml { name, case_sensitive_text, tables, enums, views, functions, procedures, other_sql })
80}
81
82fn parse_table_node(node: Node) -> Result<TableXml, String> {
83    let name = attr_string_required(node, "name")?;
84    let data_opt = attr_bool(node, "data")?;
85    let no_export = attr_bool(node, "noExport")?;
86    let export_data_column = attr_string(node, "exportDataColumn");
87    let compress = attr_bool(node, "compress")?;
88    let lock_escalation = attr_string(node, "lockEscalation");
89
90    let mut columns: Option<ColumnsXml> = None;
91    let mut keys: Option<KeysXml> = None;
92    let mut relations: Option<RelationsXml> = None;
93    let mut triggers: Option<TriggersXml> = None;
94    let mut constraints: Option<ConstraintsXml> = None;
95    let mut aggregations: Option<AggregationsXml> = None;
96    let mut initial_data: Option<InitialDataXml> = None;
97
98    for child in node.children().filter(|n| n.is_element()) {
99        if child.has_tag_name((NS, "columns")) {
100            columns = Some(parse_columns_node(child)?);
101        } else if child.has_tag_name((NS, "keys")) {
102            keys = Some(parse_keys_node(child)?);
103        } else if child.has_tag_name((NS, "relations")) {
104            relations = Some(parse_relations_node(child)?);
105        } else if child.has_tag_name((NS, "triggers")) {
106            triggers = Some(parse_triggers_node(child)?);
107        } else if child.has_tag_name((NS, "constraints")) {
108            constraints = Some(parse_constraints_node(child)?);
109        } else if child.has_tag_name((NS, "aggregations")) {
110            aggregations = Some(parse_aggregations_node(child)?);
111        } else if child.has_tag_name((NS, "initialData")) {
112            initial_data = Some(parse_initial_data_node(child));
113        }
114    }
115
116    Ok(TableXml {
117        name,
118        data_opt,
119        no_export,
120        export_data_column,
121        compress,
122        lock_escalation,
123        columns,
124        keys,
125        relations,
126        triggers,
127        constraints,
128        aggregations,
129        initial_data,
130    })
131}
132
133fn parse_columns_node(node: Node) -> Result<ColumnsXml, String> {
134    let mut cols = Vec::new();
135    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
136        cols.push(parse_column_node(c)?);
137    }
138    Ok(ColumnsXml { column: cols })
139}
140
141fn parse_column_node(node: Node) -> Result<ColumnXml, String> {
142    Ok(ColumnXml {
143        name: attr_string_required(node, "name")?,
144        r#type: attr_string_required(node, "type")?,
145        length: attr_i32(node, "length")?,
146        scale: attr_i32(node, "scale")?,
147        required: attr_bool(node, "required")?,
148        default_value: attr_string(node, "default"),
149        generated: attr_string(node, "generated"),
150        enum_type: attr_string(node, "enumType"),
151        element_type: attr_string(node, "elementType"),
152        min_value: attr_f64(node, "minValue")?,
153        max_value: attr_f64(node, "maxValue")?,
154        check: node
155            .children()
156            .find(|n| n.has_tag_name((NS, "check")))
157            .map(parse_check_node),
158    })
159}
160
161fn parse_check_node(node: Node) -> CheckXml {
162    let text = node.text().map(|s| s.trim()).filter(|s| !s.is_empty());
163    CheckXml { value: text.map(|s| s.to_string()) }
164}
165
166fn parse_keys_node(node: Node) -> Result<KeysXml, String> {
167    let mut primary: Option<KeyColumnsXml> = None;
168    let mut uniques: Vec<KeyColumnsXml> = Vec::new();
169    let mut indexes: Vec<IndexXml> = Vec::new();
170
171    for c in node.children().filter(|n| n.is_element()) {
172        if c.has_tag_name((NS, "primary")) {
173            primary = Some(parse_key_columns_node(c)?);
174        } else if c.has_tag_name((NS, "unique")) {
175            uniques.push(parse_key_columns_node(c)?);
176        } else if c.has_tag_name((NS, "index")) {
177            indexes.push(parse_index_node(c)?);
178        }
179    }
180
181    Ok(KeysXml { primary, uniques, indexes })
182}
183
184fn parse_key_columns_node(node: Node) -> Result<KeyColumnsXml, String> {
185    let mut columns = Vec::new();
186    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
187        columns.push(KeyColumnXml {
188            name: attr_string_required(c, "name")?,
189        });
190    }
191    let cluster = attr_bool(node, "cluster")?;
192    let where_clause = attr_string(node, "where");
193    Ok(KeyColumnsXml { columns, cluster, where_clause })
194}
195
196fn parse_index_node(node: Node) -> Result<IndexXml, String> {
197    let mut columns = Vec::new();
198    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
199        columns.push(KeyColumnXml { name: attr_string_required(c, "name")? });
200    }
201    Ok(IndexXml {
202        columns,
203        include: attr_string(node, "include"),
204        compress: attr_bool(node, "compress")?,
205        unique: attr_bool(node, "unique")?,
206        where_clause: attr_string(node, "where"),
207    })
208}
209
210fn parse_relations_node(node: Node) -> Result<RelationsXml, String> {
211    let mut rels = Vec::new();
212    let mut composite_rels = Vec::new();
213    for r in node.children().filter(|n| n.is_element()) {
214        if r.has_tag_name((NS, "relation")) {
215            rels.push(RelationXml {
216                src: attr_string_required(r, "src")?,
217                table: attr_string_required(r, "table")?,
218                column: attr_string_required(r, "column")?,
219                r#type: attr_string_required(r, "type")?,
220                disable_usage_checking: attr_bool(r, "disableUsageChecking")?,
221            });
222        } else if r.has_tag_name((NS, "compositeRelation")) {
223            composite_rels.push(parse_composite_relation_node(r)?);
224        }
225    }
226    Ok(RelationsXml { relation: rels, composite_relation: composite_rels })
227}
228
229fn parse_composite_relation_node(node: Node) -> Result<CompositeRelationXml, String> {
230    let mut columns = Vec::new();
231    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
232        columns.push(CompositeRelationColumnXml {
233            src: attr_string_required(c, "src")?,
234            name: attr_string_required(c, "name")?,
235        });
236    }
237    Ok(CompositeRelationXml {
238        table: attr_string_required(node, "table")?,
239        r#type: attr_string_required(node, "type")?,
240        disable_usage_checking: attr_bool(node, "disableUsageChecking")?,
241        column: columns,
242    })
243}
244
245fn parse_view_node(node: Node) -> Result<ViewXml, String> {
246    Ok(ViewXml {
247        name: attr_string_required(node, "name")?,
248        database_type: attr_string(node, "databaseType"),
249        sql: collect_text(node),
250    })
251}
252
253fn parse_function_node(node: Node) -> Result<FunctionXml, String> {
254    let name = attr_string_required(node, "name")?;
255    let mut sql = Vec::new();
256    for s in node.children().filter(|n| n.has_tag_name((NS, "sql"))) {
257        sql.push(VendorSqlXml {
258            database_type: attr_string_required(s, "databaseType")?,
259            sql: collect_text(s),
260        });
261    }
262    Ok(FunctionXml { name, sql })
263}
264
265fn parse_procedure_node(node: Node) -> Result<ProcedureXml, String> {
266    let name = attr_string_required(node, "name")?;
267    let mut sql = Vec::new();
268    for s in node.children().filter(|n| n.has_tag_name((NS, "sql"))) {
269        sql.push(VendorSqlXml {
270            database_type: attr_string_required(s, "databaseType")?,
271            sql: collect_text(s),
272        });
273    }
274    Ok(ProcedureXml { name, sql })
275}
276
277fn parse_other_sql_node(node: Node) -> Result<OtherSqlXml, String> {
278    let database_type = attr_string_required(node, "databaseType")?;
279    let order_text = attr_string_required(node, "order")?;
280    let order = match order_text.to_ascii_lowercase().as_str() {
281        "top" => OtherSqlOrderXml::Top,
282        "bottom" => OtherSqlOrderXml::Bottom,
283        other => {
284            return Err(format!(
285                "<otherSql> element has an unrecognized order '{}' (expected top or bottom)",
286                other
287            ));
288        }
289    };
290    Ok(OtherSqlXml { database_type, order, sql: collect_text(node) })
291}
292
293fn parse_enum_node(node: Node) -> Result<EnumXml, String> {
294    let name = attr_string_required(node, "name")?;
295    let mut value = Vec::new();
296    for v in node.children().filter(|n| n.has_tag_name((NS, "value"))) {
297        value.push(EnumValueXml { name: attr_string_required(v, "name")?, code: attr_string(v, "code") });
298    }
299    Ok(EnumXml { name, value })
300}
301
302fn parse_triggers_node(node: Node) -> Result<TriggersXml, String> {
303    let mut update = Vec::new();
304    let mut delete = Vec::new();
305    for c in node.children().filter(|n| n.is_element()) {
306        if c.has_tag_name((NS, "update")) {
307            update.push(TriggerXml { database_type: attr_string_required(c, "databaseType")?, sql: collect_text(c) });
308        } else if c.has_tag_name((NS, "delete")) {
309            delete.push(TriggerXml { database_type: attr_string_required(c, "databaseType")?, sql: collect_text(c) });
310        }
311    }
312    Ok(TriggersXml { update, delete })
313}
314
315fn parse_constraints_node(node: Node) -> Result<ConstraintsXml, String> {
316    let mut constraint = Vec::new();
317    for c in node.children().filter(|n| n.has_tag_name((NS, "constraint"))) {
318        constraint.push(ConstraintXml {
319            name: attr_string_required(c, "name")?,
320            database_type: attr_string(c, "databaseType"),
321            sql: collect_text(c),
322        });
323    }
324    Ok(ConstraintsXml { constraint })
325}
326
327fn parse_aggregations_node(node: Node) -> Result<AggregationsXml, String> {
328    let mut aggregate = Vec::new();
329    for a in node.children().filter(|n| n.has_tag_name((NS, "aggregate"))) {
330        aggregate.push(parse_aggregate_node(a)?);
331    }
332    Ok(AggregationsXml { aggregate })
333}
334
335fn parse_aggregate_node(node: Node) -> Result<AggregateXml, String> {
336    let mut sum = Vec::new();
337    let mut count = Vec::new();
338    let mut group: Option<GroupXml> = None;
339
340    for c in node.children().filter(|n| n.is_element()) {
341        if c.has_tag_name((NS, "sum")) {
342            sum.push(SumXml {
343                source_column: attr_string_required(c, "sourceColumn")?,
344                destination_column: attr_string_required(c, "destinationColumn")?,
345            });
346        } else if c.has_tag_name((NS, "count")) {
347            count.push(CountXml { destination_column: attr_string_required(c, "destinationColumn")? });
348        } else if c.has_tag_name((NS, "group")) {
349            group = Some(parse_group_node(c)?);
350        }
351    }
352
353    Ok(AggregateXml {
354        sum,
355        count,
356        group: group.unwrap_or_else(|| GroupXml { column: Vec::new() }),
357        destination_table: attr_string_required(node, "destinationTable")?,
358        date_column: attr_string_required(node, "dateColumn")?,
359        timestamp_column: attr_string_required(node, "timestampColumn")?,
360        frequency: attr_string_required(node, "frequency")?,
361        criteria: attr_string(node, "criteria"),
362    })
363}
364
365fn parse_group_node(node: Node) -> Result<GroupXml, String> {
366    let mut column = Vec::new();
367    for c in node.children().filter(|n| n.has_tag_name((NS, "column"))) {
368        column.push(GroupColumnXml {
369            source: attr_string_required(c, "source")?,
370            destination: attr_string_required(c, "destination")?,
371            source_derived_from: attr_string(c, "sourceDerivedFrom"),
372        });
373    }
374    Ok(GroupXml { column })
375}
376
377fn parse_initial_data_node(node: Node) -> InitialDataXml {
378    let mut sql = Vec::new();
379    for s in node.children().filter(|n| n.has_tag_name((NS, "sql"))) {
380        sql.push(InitialSqlXml {
381            database_type: attr_string(s, "databaseType"),
382            sql: collect_text(s),
383        });
384    }
385    InitialDataXml { sql }
386}
387
388// -------- Utils --------
389fn attr_string(node: Node, name: &str) -> Option<String> {
390    node.attribute(name).map(|s| s.to_string())
391}
392
393/// Reads a required attribute. Returns an error (naming the element and attribute)
394/// rather than silently defaulting to `""` when it's absent - a missing `name`/`type`/
395/// `table`/`column`/etc. attribute is a malformed schema definition, and nothing
396/// downstream validates against an empty name, so a silent default would otherwise let
397/// it through as a real (if oddly-named) table/column/relation.
398fn attr_string_required(node: Node, name: &str) -> Result<String, String> {
399    node.attribute(name).map(|s| s.to_string()).ok_or_else(|| {
400        format!(
401            "<{}> element is missing required attribute '{}'",
402            node.tag_name().name(),
403            name
404        )
405    })
406}
407
408/// Reads an optional boolean attribute. Unlike a missing attribute (which is a legitimate
409/// "not specified"), a *present but unparseable* value (`required="yep"`) is a malformed
410/// schema definition - silently falling back to `None`/`false` would hide a typo instead of
411/// reporting it, so this errors instead.
412fn attr_bool(node: Node, name: &str) -> Result<Option<bool>, String> {
413    match node.attribute(name) {
414        None => Ok(None),
415        Some(v) => match v.to_ascii_lowercase().as_str() {
416            "true" | "1" | "yes" | "on" => Ok(Some(true)),
417            "false" | "0" | "no" | "off" => Ok(Some(false)),
418            _ => Err(format!(
419                "<{}> attribute '{}' has invalid boolean value '{}' (expected true/false, 1/0, yes/no, or on/off)",
420                node.tag_name().name(),
421                name,
422                v
423            )),
424        },
425    }
426}
427
428/// Reads an optional integer attribute, erroring (rather than silently defaulting to `None`)
429/// when the attribute is present but not a valid `i32` - a typo like `length="1O0"` or an
430/// overflowing value like `length="99999999999"` should be reported, not turned into 0.
431fn attr_i32(node: Node, name: &str) -> Result<Option<i32>, String> {
432    match node.attribute(name) {
433        None => Ok(None),
434        Some(v) => v.parse::<i32>().map(Some).map_err(|_| {
435            format!(
436                "<{}> attribute '{}' has invalid integer value '{}'",
437                node.tag_name().name(),
438                name,
439                v
440            )
441        }),
442    }
443}
444
445/// Reads an optional numeric attribute, erroring (rather than silently defaulting to `None`)
446/// when the attribute is present but not a finite `f64` - this covers unparseable typos like
447/// `minValue="1o"` as well as `inf`/`nan`, which `f64::parse` otherwise accepts silently.
448fn attr_f64(node: Node, name: &str) -> Result<Option<f64>, String> {
449    match node.attribute(name) {
450        None => Ok(None),
451        Some(v) => match v.parse::<f64>() {
452            Ok(n) if n.is_finite() => Ok(Some(n)),
453            _ => Err(format!(
454                "<{}> attribute '{}' has invalid numeric value '{}'",
455                node.tag_name().name(),
456                name,
457                v
458            )),
459        },
460    }
461}
462
463fn collect_text(node: Node) -> String {
464    let mut out = String::new();
465    for n in node.children() {
466        if n.is_text() {
467            out.push_str(n.text().unwrap_or(""));
468        }
469    }
470    out.trim().to_string()
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use std::fs;
477
478    #[test]
479    fn parse_with_roxmltree_sample() {
480        let xml = fs::read_to_string("tests/resources/schema-parser-test-schema.xml").expect("resource present");
481        let db = parse_database_roxml(&xml).expect("parsed");
482        assert!(!db.tables.is_empty());
483        assert!(db.schemas.is_empty() || !db.schemas[0].tables.is_empty());
484    }
485
486    #[test]
487    fn attr_bool_is_case_insensitive() {
488        let doc = Document::parse(
489            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="TRUE" cluster="No"/>"#,
490        )
491        .unwrap();
492        let node = doc.root_element();
493
494        assert_eq!(attr_bool(node, "required"), Ok(Some(true)));
495        assert_eq!(attr_bool(node, "cluster"), Ok(Some(false)));
496    }
497
498    #[test]
499    fn attr_bool_errors_on_unrecognized_value() {
500        let doc = Document::parse(
501            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="yep"/>"#,
502        )
503        .unwrap();
504        let node = doc.root_element();
505
506        let err = attr_bool(node, "required").unwrap_err();
507        assert!(err.contains("required"));
508        assert!(err.contains("yep"));
509    }
510
511    #[test]
512    fn attr_i32_errors_on_unparseable_value() {
513        let doc = Document::parse(
514            r#"<column xmlns="http://stano.com/database" name="x" type="varchar" length="1O0"/>"#,
515        )
516        .unwrap();
517        let node = doc.root_element();
518
519        let err = attr_i32(node, "length").unwrap_err();
520        assert!(err.contains("length"));
521        assert!(err.contains("1O0"));
522    }
523
524    #[test]
525    fn attr_f64_errors_on_unparseable_value() {
526        let doc = Document::parse(
527            r#"<column xmlns="http://stano.com/database" name="x" type="int" minValue="1o"/>"#,
528        )
529        .unwrap();
530        let node = doc.root_element();
531
532        let err = attr_f64(node, "minValue").unwrap_err();
533        assert!(err.contains("minValue"));
534        assert!(err.contains("1o"));
535    }
536
537    #[test]
538    fn attr_f64_errors_on_infinite_value() {
539        let doc = Document::parse(
540            r#"<column xmlns="http://stano.com/database" name="x" type="int" maxValue="inf"/>"#,
541        )
542        .unwrap();
543        let node = doc.root_element();
544
545        let err = attr_f64(node, "maxValue").unwrap_err();
546        assert!(err.contains("maxValue"));
547        assert!(err.contains("inf"));
548    }
549
550    #[test]
551    fn parse_column_node_honors_uppercase_required_attribute() {
552        let doc = Document::parse(
553            r#"<column xmlns="http://stano.com/database" name="x" type="int" required="TRUE"/>"#,
554        )
555        .unwrap();
556        let node = doc.root_element();
557
558        let column = parse_column_node(node).expect("parse ok");
559
560        assert_eq!(column.required, Some(true));
561    }
562
563    #[test]
564    fn missing_required_attribute_returns_error_instead_of_defaulting_to_empty_string() {
565        let doc = Document::parse(r#"<column xmlns="http://stano.com/database" type="int"/>"#).unwrap();
566        let node = doc.root_element();
567
568        let err = parse_column_node(node).unwrap_err();
569        assert!(err.contains("column"));
570        assert!(err.contains("name"));
571    }
572}