schema-parser 0.6.8

A set of tools to manage relational database schemas
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use super::nodes::*;
use crate::parser::table_parser::parse_table;
use schema_model::builder::SchemaBuilder;
use schema_model::model::database_model::DatabaseModel;
use schema_model::model::relation::Relation;
use schema_model::model::schema::Schema;
use schema_model::model::types::{
    BooleanMode, DatabaseType, ForeignKeyMode, OtherSqlOrder,
};
use schema_model::model::view::View;
use schema_model::model::{
    aggregation::AggregationFrequency,
    enum_type::{EnumType, EnumValue},
    function::Function,
    other_sql::OtherSql,
    procedure::Procedure,
};

pub fn convert_database(database_xml: DatabaseXml) -> Result<DatabaseModel, String> {
    let mut schemas: Vec<Schema> = Vec::new();

    if let Some(default_schema) = default_schema(&database_xml)? {
        schemas.push(default_schema);
    }

    for schema_xml in database_xml.schemas.into_iter() {
        schemas.push(sub_schema(&schema_xml)?);
    }

    let boolean_mode = database_xml
        .boolean_mode
        .as_deref()
        .map(|s| s.parse::<BooleanMode>())
        .unwrap_or(Ok(BooleanMode::Native))?;
    let foreign_key_mode = database_xml
        .foreign_key_mode
        .as_deref()
        .map(|s| s.parse::<ForeignKeyMode>())
        .unwrap_or(Ok(ForeignKeyMode::Relations))?;

    let mut database_model = DatabaseModel::new(boolean_mode, foreign_key_mode, schemas);

    database_model.sort_tables_by_name();
    reverse_relations(&mut database_model)?;

    Ok(database_model)
}

fn default_schema(database: &DatabaseXml) -> Result<Option<Schema>, String> {
    let mut schema_builder = SchemaBuilder::new(None::<&str>);

    if let Some(cst) = database.case_sensitive_text {
        schema_builder = schema_builder.case_sensitive_text(cst);
    }

    for table_xml in database.tables.iter() {
        let table = parse_table(table_xml, None)?;
        schema_builder = schema_builder.add_table(table);
    }

    for view_xml in database.views.iter() {
        let database_type = optional_database_type(
            view_xml.database_type.as_deref(),
            &format!("view '{}'", view_xml.name),
        )?;
        schema_builder = schema_builder.add_view(View::new(
            None,
            &view_xml.name,
            &view_xml.sql,
            database_type,
        ));
    }

    for enum_xml in database.enums.iter() {
        let evs: Vec<EnumValue> = enum_xml
            .value
            .iter()
            .map(|v| EnumValue::new(&v.name, v.code.clone()))
            .collect();
        schema_builder = schema_builder.add_enum_type(EnumType::new(&enum_xml.name, evs));
    }

    for function_xml in database.functions.iter() {
        let mut functions: Vec<Function> = Vec::new();
        for vendor_sql_xml in function_xml.sql.iter() {
            let database_type = required_database_type(
                Some(&vendor_sql_xml.database_type),
                &format!("function '{}'", function_xml.name),
            )?;
            functions.push(Function::new(
                None,
                &function_xml.name,
                database_type,
                &vendor_sql_xml.sql,
            ));
        }
        if !functions.is_empty() {
            schema_builder = schema_builder.add_functions(functions);
        }
    }

    for procedure_xml in database.procedures.iter() {
        let mut procedures: Vec<Procedure> = Vec::new();
        for vendor_sql_xml in procedure_xml.sql.iter() {
            let database_type = required_database_type(
                Some(&vendor_sql_xml.database_type),
                &format!("procedure '{}'", procedure_xml.name),
            )?;
            procedures.push(Procedure::new(
                None,
                &procedure_xml.name,
                database_type,
                &vendor_sql_xml.sql,
            ));
        }
        if !procedures.is_empty() {
            schema_builder = schema_builder.add_procedures(procedures);
        }
    }

    for other_sql_xml in database.other_sql.iter() {
        let database_type = required_database_type(Some(&other_sql_xml.database_type), "otherSql")?;
        if let Some(order) = other_sql_order(&other_sql_xml.order) {
            schema_builder = schema_builder.add_other_sql(OtherSql::new(
                database_type,
                order,
                &other_sql_xml.sql,
            ));
        }
    }

    let root_schema = schema_builder.build();
    if !root_schema.tables().is_empty()
        || !database.views.is_empty()
        || !database.enums.is_empty()
        || !database.functions.is_empty()
        || !database.procedures.is_empty()
        || !database.other_sql.is_empty()
    {
        return Ok(Some(root_schema));
    }

    Ok(None)
}

fn sub_schema(schema_xml: &SchemaXml) -> Result<Schema, String> {
    let mut schema_builder = SchemaBuilder::new(Some(&schema_xml.name));

    if let Some(cst) = schema_xml.case_sensitive_text {
        schema_builder = schema_builder.case_sensitive_text(cst);
    }

    for table_xml in schema_xml.tables.iter() {
        schema_builder = schema_builder.add_table(parse_table(table_xml, Some(&schema_xml.name))?);
    }

    for view_xml in schema_xml.views.iter() {
        let database_type = optional_database_type(
            view_xml.database_type.as_deref(),
            &format!("view '{}.{}'", schema_xml.name, view_xml.name),
        )?;
        schema_builder = schema_builder.add_view(View::new(
            Some(&schema_xml.name),
            &view_xml.name,
            &view_xml.sql,
            database_type,
        ));
    }

    for enum_xml in schema_xml.enums.iter() {
        let enum_values: Vec<EnumValue> = enum_xml
            .value
            .iter()
            .map(|v| EnumValue::new(&v.name, v.code.clone()))
            .collect();
        schema_builder = schema_builder.add_enum_type(EnumType::new(&enum_xml.name, enum_values));
    }

    for function_xml in schema_xml.functions.iter() {
        let mut functions: Vec<Function> = Vec::new();
        for vendor_sql_xml in function_xml.sql.iter() {
            let database_type = required_database_type(
                Some(&vendor_sql_xml.database_type),
                &format!("function '{}.{}'", schema_xml.name, function_xml.name),
            )?;
            functions.push(Function::new(
                Some(schema_xml.name.as_str()),
                &function_xml.name,
                database_type,
                &vendor_sql_xml.sql,
            ));
        }
        if !functions.is_empty() {
            schema_builder = schema_builder.add_functions(functions);
        }
    }

    for procedure_xml in schema_xml.procedures.iter() {
        let mut procedures: Vec<Procedure> = Vec::new();
        for vendor_sql_xml in procedure_xml.sql.iter() {
            let database_type = required_database_type(
                Some(&vendor_sql_xml.database_type),
                &format!("procedure '{}.{}'", schema_xml.name, procedure_xml.name),
            )?;
            procedures.push(Procedure::new(
                Some(schema_xml.name.as_str()),
                &procedure_xml.name,
                database_type,
                &vendor_sql_xml.sql,
            ));
        }
        if !procedures.is_empty() {
            schema_builder = schema_builder.add_procedures(procedures);
        }
    }

    for other_sql_xml in schema_xml.other_sql.iter() {
        let database_type = required_database_type(
            Some(&other_sql_xml.database_type),
            &format!("otherSql in schema '{}'", schema_xml.name),
        )?;
        if let Some(order) = other_sql_order(&other_sql_xml.order) {
            schema_builder = schema_builder.add_other_sql(OtherSql::new(
                database_type,
                order,
                &other_sql_xml.sql,
            ));
        }
    }

    Ok(schema_builder.build())
}

pub(crate) fn str_to_database_type(s: Option<&str>) -> Option<DatabaseType> {
    s.and_then(|v| match v.to_ascii_lowercase().as_str() {
        "postgresql" => Some(DatabaseType::Postgresql),
        "sqlite" => Some(DatabaseType::Sqlite),
        "sqlserver" | "mssql" => Some(DatabaseType::SqlServer),
        _ => None,
    })
}

/// Parses a `databaseType` attribute that's required for the element to mean anything
/// (functions/procedures/otherSql/triggers/constraints all need one specific target
/// database - none of them can represent "applies to every database"). Returns an error
/// rather than silently discarding the element when the attribute is missing or doesn't
/// match a known database type; a typo here used to make the whole element vanish from
/// the parsed model with no warning.
pub(crate) fn required_database_type(value: Option<&str>, context: &str) -> Result<DatabaseType, String> {
    let value = value.ok_or_else(|| format!("{context}: missing required databaseType attribute"))?;
    str_to_database_type(Some(value)).ok_or_else(|| format!("{context}: unrecognized databaseType '{value}'"))
}

/// Parses an optional `databaseType` attribute where absence has a real meaning: "applies
/// to every database type" (mirrors `View`/`InitialData`'s `Option<DatabaseType>`). An
/// attribute that IS present but unrecognized is still always an error, so a typo never
/// silently broadens an element's scope to every database instead of the one intended.
pub(crate) fn optional_database_type(value: Option<&str>, context: &str) -> Result<Option<DatabaseType>, String> {
    match value {
        None => Ok(None),
        Some(v) => str_to_database_type(Some(v))
            .map(Some)
            .ok_or_else(|| format!("{context}: unrecognized databaseType '{v}'")),
    }
}

fn other_sql_order(o: &OtherSqlOrderXml) -> Option<OtherSqlOrder> {
    match o {
        OtherSqlOrderXml::Top => Some(OtherSqlOrder::Top),
        OtherSqlOrderXml::Bottom => Some(OtherSqlOrder::Bottom),
    }
}

pub(crate) fn agg_frequency_from_str(s: &str) -> Result<AggregationFrequency, String> {
    match s.to_ascii_lowercase().as_str() {
        "daily" => Ok(AggregationFrequency::Daily),
        "weekly" => Ok(AggregationFrequency::Weekly),
        "monthly" => Ok(AggregationFrequency::Monthly),
        "yearly" => Ok(AggregationFrequency::Yearly),
        other => Err(format!(
            "unrecognized frequency '{other}' (expected daily, weekly, monthly, or yearly)"
        )),
    }
}

fn reverse_relations(database_model: &mut DatabaseModel) -> Result<(), String> {
    // First pass: collect all reverse relation updates
    let mut updates = Vec::new();

    for table in database_model.all_tables() {
        for relation in table.relations() {
            let parent_table_name = relation.to_table_name();
            let parent_table_parts = split_schema_table(parent_table_name);

            // `relation.from_table_name()` is just `table`'s own bare name (see
            // `parse_relations` in table_parser.rs, which has no schema context) -
            // schema-qualify it here using `table`'s own schema, the same way
            // `to_table_name` is already schema-qualified by the XML author, so the
            // reverse relation stored on the parent can resolve the child table
            // correctly (via `find_table_by_qualified_name`) even when the child
            // lives in a non-default schema.
            let qualified_from_table_name = qualify_table_name(table.schema_name(), relation.from_table_name());

            updates.push((
                parent_table_parts.0,
                parent_table_parts.1.to_string(),
                qualified_from_table_name.clone(),
                Relation::new(
                    relation.to_table_name(),
                    relation.to_column_name(),
                    qualified_from_table_name.as_str(),
                    relation.from_column_name(),
                    relation.relation_type(),
                    false,
                ),
            ));
        }
    }

    // Second pass: apply updates using mutable borrows. A relation whose target table
    // doesn't exist (typo'd name, or a schema that was never declared) is a malformed
    // schema definition, not a bug in this code, so it's surfaced as an `Err` rather
    // than panicking the whole parse.
    for (schema, table_name, from_table_name, reverse_relation) in updates {
        let parent_table = database_model
            .find_table_mut_checked(schema.as_deref(), &table_name)
            .ok_or_else(|| {
                format!(
                    "table '{}' has a relation to '{}' which does not exist",
                    from_table_name,
                    schema
                        .as_deref()
                        .map(|s| format!("{}.{}", s, table_name))
                        .unwrap_or_else(|| table_name.clone())
                )
            })?;
        parent_table.add_reverse_relation(reverse_relation);
    }

    Ok(())
}

/// Renders `table_name` as `schema.table_name` when `schema_name` is present, or bare
/// `table_name` otherwise - matching the format `find_table_by_qualified_name` expects
/// (an unqualified name resolves to the default schema).
fn qualify_table_name(schema_name: Option<&str>, table_name: &str) -> String {
    match schema_name {
        Some(schema) => format!("{}.{}", schema, table_name),
        None => table_name.to_string(),
    }
}

fn split_schema_table(table_name: &str) -> (Option<String>, String) {
    if let Some(pos) = table_name.find('.') {
        let schema = table_name[..pos].to_string();
        let table = table_name[pos + 1..].to_string();
        (Some(schema), table)
    } else {
        (None, table_name.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn empty_database_xml() -> DatabaseXml {
        DatabaseXml {
            foreign_key_mode: None,
            boolean_mode: None,
            case_sensitive_text: None,
            tables: Vec::new(),
            enums: Vec::new(),
            views: Vec::new(),
            functions: Vec::new(),
            procedures: Vec::new(),
            other_sql: Vec::new(),
            schemas: Vec::new(),
        }
    }

    /// H5: a typo'd `booleanMode` attribute must return an `Err`, not panic via `.unwrap()`.
    #[test]
    fn invalid_boolean_mode_returns_err_instead_of_panicking() {
        let mut database_xml = empty_database_xml();
        database_xml.boolean_mode = Some("yes_no".to_string());

        let result = convert_database(database_xml);

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Unknown boolean mode"));
    }

    /// H5: a typo'd `foreignKeyMode` attribute must return an `Err`, not panic via `.unwrap()`.
    #[test]
    fn invalid_foreign_key_mode_returns_err_instead_of_panicking() {
        let mut database_xml = empty_database_xml();
        database_xml.foreign_key_mode = Some("relation".to_string());

        let result = convert_database(database_xml);

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Unknown foreign key mode"));
    }

    #[test]
    fn valid_modes_still_parse_successfully() {
        let mut database_xml = empty_database_xml();
        database_xml.boolean_mode = Some("YesNo".to_string());
        database_xml.foreign_key_mode = Some("triggers".to_string());

        let model = convert_database(database_xml).unwrap();

        assert_eq!(model.boolean_mode(), BooleanMode::YesNo);
        assert_eq!(model.foreign_key_mode(), ForeignKeyMode::Triggers);
    }

    #[test]
    fn missing_modes_default_to_native_and_relations() {
        let model = convert_database(empty_database_xml()).unwrap();

        assert_eq!(model.boolean_mode(), BooleanMode::Native);
        assert_eq!(model.foreign_key_mode(), ForeignKeyMode::Relations);
    }
}