dinoco_engine 1.0.9

Database adapters, query execution, and migration engine components for Dinoco.
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
use crate::{
    AddColumnMigration, AddForeignKeyMigration, AlterColumnMigration, AlterEnumMigration, CountQuery,
    CreateEnumMigration, CreateIndexMigration, CreateTableMigration, DeleteQuery, DinocoSqlCompiler, DinocoValue,
    DropColumnMigration, DropEnumMigration, DropForeignKeyMigration, DropIndexMigration, DropTableMigration,
    FindOrderBy, FindQuery, FindWhere, InsertQuery, MigrationColumn, MigrationColumnType, MigrationDefault,
    MigrationForeignKey, MigrationIndexKind, MySqlAdapter, ReferentialAction, RelationBatchQuery, RelationCountQuery,
    RelationJoinQuery, RenameColumnMigration, UpdateQuery,
};

impl DinocoSqlCompiler for MySqlAdapter {
    fn compile_find_query(&self, query: FindQuery) -> (String, Vec<DinocoValue>) {
        let fields = query.fields.iter().map(|field| sql_identifier(field)).collect::<Vec<_>>().join(", ");
        let mut sql = format!("SELECT {fields} FROM {}", sql_identifier(query.from));
        let params = append_find_tail(&mut sql, query.conditions, query.order_by, query.limit, query.skip, None);

        (sql, params)
    }

    fn compile_insert_query(&self, query: InsertQuery) -> (String, Vec<DinocoValue>) {
        let fields_len = query.fields.len();
        let row_placeholders = format!("({})", vec!["?"; fields_len].join(", "));
        let placeholders = vec![row_placeholders; query.rows.len()].join(", ");
        let params = query.rows.into_iter().flatten().collect::<Vec<_>>();
        let fields = query.fields.iter().map(|field| sql_identifier(field)).collect::<Vec<_>>().join(", ");
        let mut sql = format!("INSERT INTO {} ({fields}) VALUES {placeholders}", sql_identifier(query.table));

        if let Some(returning) = query.returning {
            sql.push_str(" RETURNING ");
            sql.push_str(&returning.iter().map(|field| sql_identifier(field)).collect::<Vec<_>>().join(", "));
        }

        (sql, params)
    }

    fn compile_update_query(&self, query: UpdateQuery) -> (String, Vec<DinocoValue>) {
        let sets = query.sets.iter().filter(|set| set.operation == crate::UpdateOperation::Set).collect::<Vec<_>>();
        let mut params = sets.iter().map(|set| set.value.clone()).collect::<Vec<_>>();
        let set_sql =
            sets.iter().map(|set| format!("{} = ?", sql_identifier(set.field))).collect::<Vec<_>>().join(", ");
        let mut sql = format!("UPDATE {} SET {set_sql}", sql_identifier(query.table));

        params.extend(append_conditions(&mut sql, query.conditions, None));

        if let Some(returning) = query.returning {
            sql.push_str(" RETURNING ");
            sql.push_str(&returning.iter().map(|field| sql_identifier(field)).collect::<Vec<_>>().join(", "));
        }

        (sql, params)
    }

    fn compile_delete_query(&self, query: DeleteQuery) -> (String, Vec<DinocoValue>) {
        let mut sql = format!("DELETE FROM {}", sql_identifier(query.table));
        let params = append_conditions(&mut sql, query.conditions, None);

        if let Some(returning) = query.returning {
            sql.push_str(" RETURNING ");
            sql.push_str(&returning.iter().map(|field| sql_identifier(field)).collect::<Vec<_>>().join(", "));
        }

        (sql, params)
    }

    fn compile_count_query(&self, query: CountQuery) -> (String, Vec<DinocoValue>) {
        let mut sql = format!("SELECT COUNT(*) FROM {}", sql_identifier(query.table));
        let params = append_conditions(&mut sql, query.conditions, None);

        (sql, params)
    }

    fn compile_relation_count_query(&self, query: RelationCountQuery) -> (String, Vec<DinocoValue>) {
        let mut parent_sql = format!("SELECT {} FROM {}", query.parent_field, query.parent_table);
        let mut params = append_conditions(&mut parent_sql, query.parent_conditions, Some(query.parent_table));
        let mut sql =
            format!("SELECT COUNT(*) FROM {} WHERE {} IN ({parent_sql})", query.child_table, query.child_field,);
        collect_conditions_prefixed_with_and(&mut sql, &mut params, query.child_conditions, Some(query.child_table));

        (sql, params)
    }

    fn compile_relation_batch_query(&self, query: RelationBatchQuery) -> (String, Vec<DinocoValue>) {
        let fields =
            query.query.fields.iter().map(|field| qualify_field(field, Some(query.query.from))).collect::<Vec<_>>();
        let mut select_fields = fields.join(", ");
        select_fields.push_str(", ");
        select_fields.push_str(&qualify_field(query.relation_key_field, Some(query.query.from)));
        select_fields.push_str(" AS __dinoco_relation_key");

        if query.query.limit >= 0 || query.query.skip >= 0 {
            return compile_partitioned_relation_batch_query(query, select_fields);
        }

        let table = query.query.from;
        let mut sql = format!("SELECT {select_fields} FROM {table}");
        let params = append_find_tail(
            &mut sql,
            query.query.conditions,
            query.query.order_by,
            query.query.limit,
            query.query.skip,
            Some(table),
        );

        (sql, params)
    }

    fn compile_relation_join_query(&self, query: RelationJoinQuery) -> (String, Vec<DinocoValue>) {
        if query.query.limit >= 0 || query.query.skip >= 0 {
            return compile_partitioned_relation_join_query(query);
        }

        let placeholders = vec!["?"; query.key_count].join(", ");
        let mut sql = format!(
            "SELECT {} FROM {} LEFT JOIN {} ON {}.{} = {}.{}",
            relation_join_fields(&query).join(", "),
            query.parent_table,
            query.child_table,
            query.parent_table,
            query.parent_field,
            query.child_table,
            query.child_field,
        );
        let params = append_join_conditions(
            &mut sql,
            query.parent_table,
            query.parent_field,
            query.child_table,
            placeholders,
            query.query.conditions,
        );
        append_order_by(&mut sql, query.query.order_by, Some(query.child_table));

        (sql, params)
    }

    fn compile_create_migrations_table(&self) -> String {
        "CREATE TABLE IF NOT EXISTS dinoco_migrations (name VARCHAR(255) PRIMARY KEY, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
            .to_string()
    }

    fn compile_insert_migration_record(&self, name: &str) -> String {
        format!("INSERT IGNORE INTO dinoco_migrations (name) VALUES ('{}')", escape_sql(name))
    }

    fn compile_create_table_migration(&self, migration: CreateTableMigration) -> String {
        let if_not_exists = if migration.if_not_exists { " IF NOT EXISTS" } else { "" };
        let primary_key_columns = migration
            .columns
            .iter()
            .filter(|column| column.primary_key)
            .map(|column| sql_identifier(&column.name))
            .collect::<Vec<_>>();
        let inline_primary_key = primary_key_columns.len() <= 1;
        let mut definitions = migration
            .columns
            .iter()
            .map(|column| compile_migration_column(column, inline_primary_key))
            .collect::<Vec<_>>();
        if !inline_primary_key {
            definitions.push(format!("PRIMARY KEY ({})", primary_key_columns.join(", ")));
        }
        definitions.extend(migration.foreign_keys.iter().map(compile_foreign_key));

        format!(
            "CREATE TABLE{if_not_exists} {} (\n    {}\n);",
            sql_identifier(&migration.table),
            definitions.join(",\n    ")
        )
    }

    fn compile_drop_table_migration(&self, migration: DropTableMigration) -> String {
        let if_exists = if migration.if_exists { " IF EXISTS" } else { "" };
        format!("DROP TABLE{if_exists} {};", migration.table)
    }

    fn compile_add_column_migration(&self, migration: AddColumnMigration) -> String {
        format!("ALTER TABLE {} ADD COLUMN {};", migration.table, compile_migration_column(&migration.column, true))
    }

    fn compile_drop_column_migration(&self, migration: DropColumnMigration) -> String {
        format!("ALTER TABLE {} DROP COLUMN {};", migration.table, migration.column)
    }

    fn compile_alter_column_migration(&self, migration: AlterColumnMigration) -> Vec<String> {
        vec![format!(
            "ALTER TABLE {} MODIFY COLUMN {};",
            migration.table,
            compile_migration_column(&migration.desired, true)
        )]
    }

    fn compile_rename_column_migration(&self, migration: RenameColumnMigration) -> Vec<String> {
        vec![format!("ALTER TABLE {} RENAME COLUMN {} TO {};", migration.table, migration.from, migration.to)]
    }

    fn compile_add_foreign_key_migration(&self, migration: AddForeignKeyMigration) -> Vec<String> {
        vec![format!("ALTER TABLE {} ADD {};", migration.table, compile_foreign_key(&migration.foreign_key))]
    }

    fn compile_drop_foreign_key_migration(&self, migration: DropForeignKeyMigration) -> Vec<String> {
        vec![format!("ALTER TABLE {} DROP FOREIGN KEY {};", migration.table, migration.name)]
    }

    fn compile_create_index_migration(&self, migration: CreateIndexMigration) -> String {
        let index_type = match migration.index.kind {
            MigrationIndexKind::Standard => "",
            MigrationIndexKind::Unique => "UNIQUE ",
            MigrationIndexKind::FullText => "FULLTEXT ",
        };
        format!(
            "CREATE {index_type}INDEX {} ON {} ({});",
            sql_identifier(&migration.index.name),
            sql_identifier(&migration.table),
            migration.index.columns.iter().map(|column| sql_identifier(column)).collect::<Vec<_>>().join(", ")
        )
    }

    fn compile_drop_index_migration(&self, migration: DropIndexMigration) -> String {
        format!("DROP INDEX {} ON {};", sql_identifier(&migration.index.name), sql_identifier(&migration.table))
    }

    fn compile_create_enum_migration(&self, _migration: CreateEnumMigration) -> Vec<String> {
        Vec::new()
    }

    fn compile_drop_enum_migration(&self, _migration: DropEnumMigration) -> Vec<String> {
        Vec::new()
    }

    fn compile_alter_enum_migration(&self, _migration: AlterEnumMigration) -> Vec<String> {
        Vec::new()
    }
}

fn compile_migration_column(column: &MigrationColumn, inline_primary_key: bool) -> String {
    let mut parts = vec![sql_identifier(&column.name), migration_type(&column.ty)];

    if column.primary_key && inline_primary_key {
        parts.push("PRIMARY KEY".to_string());
    }

    if column.unique && !column.primary_key {
        parts.push("UNIQUE".to_string());
    }

    if !column.nullable {
        parts.push("NOT NULL".to_string());
    }

    if let Some(default) = &column.default
        && let Some(default) = migration_default(default)
    {
        parts.push(default);
    }

    parts.join(" ")
}

fn compile_foreign_key(foreign_key: &MigrationForeignKey) -> String {
    format!(
        "CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {} ({}) ON UPDATE {} ON DELETE {}",
        foreign_key.name,
        foreign_key.columns.join(", "),
        foreign_key.references_table,
        foreign_key.references_columns.join(", "),
        referential_action(foreign_key.on_update),
        referential_action(foreign_key.on_delete),
    )
}

fn referential_action(action: ReferentialAction) -> &'static str {
    match action {
        ReferentialAction::Cascade => "CASCADE",
        ReferentialAction::Restrict => "RESTRICT",
        ReferentialAction::NoAction => "NO ACTION",
        ReferentialAction::SetNull => "SET NULL",
        ReferentialAction::SetDefault => "SET DEFAULT",
    }
}

fn migration_type(ty: &MigrationColumnType) -> String {
    match ty {
        MigrationColumnType::String | MigrationColumnType::Text => "VARCHAR(255)".to_string(),
        MigrationColumnType::Boolean => "TINYINT(1)".to_string(),
        MigrationColumnType::Integer => "BIGINT".to_string(),
        MigrationColumnType::Float => "DOUBLE PRECISION".to_string(),
        MigrationColumnType::DateTime => "TIMESTAMP".to_string(),
        MigrationColumnType::Date => "DATE".to_string(),
        MigrationColumnType::Json => "JSON".to_string(),
        MigrationColumnType::Enum { values, .. } => {
            let values = values.iter().map(|value| format!("'{}'", escape_sql(value))).collect::<Vec<_>>().join(", ");
            format!("ENUM({values})")
        }
    }
}

fn migration_default(default: &MigrationDefault) -> Option<String> {
    match default {
        MigrationDefault::String(value) => Some(format!("DEFAULT '{}'", escape_sql(value))),
        MigrationDefault::Boolean(value) => Some(format!("DEFAULT {value}")),
        MigrationDefault::Integer(value) => Some(format!("DEFAULT {value}")),
        MigrationDefault::Float(value) => Some(format!("DEFAULT {value}")),
        MigrationDefault::CurrentTimestamp => Some("DEFAULT CURRENT_TIMESTAMP".to_string()),
        MigrationDefault::AutoIncrement => Some("AUTO_INCREMENT".to_string()),
    }
}

fn escape_sql(value: &str) -> String {
    value.replace('\'', "''")
}

fn compile_partitioned_relation_batch_query(
    query: RelationBatchQuery,
    select_fields: String,
) -> (String, Vec<DinocoValue>) {
    let table = query.query.from;
    let partition_field = format!("{table}.{}", query.relation_key_field);
    let order_by = relation_partition_order_by(table, query.query.order_by, &partition_field);
    let mut inner_sql = format!(
        "SELECT {select_fields}, ROW_NUMBER() OVER (PARTITION BY {partition_field} ORDER BY {order_by}) AS __dinoco_row_num FROM {table}",
    );
    let mut params = append_conditions(&mut inner_sql, query.query.conditions, Some(table));

    append_row_window(&mut params, &mut inner_sql, query.query.skip, query.query.limit)
}

fn compile_partitioned_relation_join_query(query: RelationJoinQuery) -> (String, Vec<DinocoValue>) {
    let placeholders = vec!["?"; query.key_count].join(", ");
    let partition_field = format!("{}.{}", query.parent_table, query.parent_field);
    let order_by = relation_partition_order_by(
        query.child_table,
        query.query.order_by.clone(),
        &format!("{}.{}", query.child_table, query.child_field),
    );
    let mut fields = relation_join_fields(&query);
    fields.push(format!("ROW_NUMBER() OVER (PARTITION BY {partition_field} ORDER BY {order_by}) AS __dinoco_row_num"));

    let mut inner_sql = format!(
        "SELECT {} FROM {} LEFT JOIN {} ON {}.{} = {}.{}",
        fields.join(", "),
        query.parent_table,
        query.child_table,
        query.parent_table,
        query.parent_field,
        query.child_table,
        query.child_field,
    );
    let mut params = append_join_conditions(
        &mut inner_sql,
        query.parent_table,
        query.parent_field,
        query.child_table,
        placeholders,
        query.query.conditions,
    );

    append_row_window(&mut params, &mut inner_sql, query.query.skip, query.query.limit)
}

fn append_row_window(
    params: &mut Vec<DinocoValue>,
    inner_sql: &mut str,
    skip: i32,
    limit: i32,
) -> (String, Vec<DinocoValue>) {
    let mut row_conditions = Vec::new();
    let skip = skip.max(0);

    if skip > 0 {
        row_conditions.push("__dinoco_row_num > ?".to_string());
        params.push(DinocoValue::Integer(skip as i64));
    }

    if limit >= 0 {
        row_conditions.push("__dinoco_row_num <= ?".to_string());
        params.push(DinocoValue::Integer((skip + limit) as i64));
    }

    let mut sql = format!("SELECT * FROM ({inner_sql}) AS __dinoco_partitioned");

    if !row_conditions.is_empty() {
        sql.push_str(" WHERE ");
        sql.push_str(&row_conditions.join(" AND "));
    }

    sql.push_str(" ORDER BY __dinoco_relation_key, __dinoco_row_num");

    (sql, std::mem::take(params))
}

fn relation_join_fields(query: &RelationJoinQuery) -> Vec<String> {
    let mut fields =
        query.query.fields.iter().map(|field| qualify_field(field, Some(query.child_table))).collect::<Vec<_>>();

    fields.push(qualify_field(query.child_field, Some(query.child_table)));
    fields.push(format!("{} AS __dinoco_relation_key", qualify_field(query.parent_field, Some(query.parent_table))));

    fields
}

fn append_find_tail(
    sql: &mut String,
    conditions: Vec<FindWhere>,
    order_by: Option<FindOrderBy>,
    limit: i32,
    skip: i32,
    qualifier: Option<&str>,
) -> Vec<DinocoValue> {
    let mut params = append_conditions(sql, conditions, qualifier);

    append_order_by(sql, order_by, qualifier);

    if limit >= 0 {
        sql.push_str(" LIMIT ?");
        params.push(DinocoValue::Integer(limit as i64));
    }

    if skip >= 0 {
        sql.push_str(" OFFSET ?");
        params.push(DinocoValue::Integer(skip as i64));
    }

    params
}

fn append_join_conditions(
    sql: &mut String,
    parent_table: &str,
    parent_field: &str,
    child_table: &str,
    placeholders: String,
    child_conditions: Vec<FindWhere>,
) -> Vec<DinocoValue> {
    let mut conditions = vec![format!("{parent_table}.{parent_field} IN ({placeholders})")];
    let mut params = Vec::new();

    collect_conditions(&mut conditions, &mut params, child_conditions, Some(child_table));

    sql.push_str(" WHERE ");
    sql.push_str(&conditions.join(" AND "));

    params
}

fn append_conditions(sql: &mut String, conditions: Vec<FindWhere>, qualifier: Option<&str>) -> Vec<DinocoValue> {
    let mut params = Vec::new();
    let mut sql_conditions = Vec::new();

    collect_conditions(&mut sql_conditions, &mut params, conditions, qualifier);

    if !sql_conditions.is_empty() {
        sql.push_str(" WHERE ");
        sql.push_str(&sql_conditions.join(" AND "));
    }

    params
}

fn collect_conditions_prefixed_with_and(
    sql: &mut String,
    params: &mut Vec<DinocoValue>,
    conditions: Vec<FindWhere>,
    qualifier: Option<&str>,
) {
    let mut sql_conditions = Vec::new();

    collect_conditions(&mut sql_conditions, params, conditions, qualifier);

    if !sql_conditions.is_empty() {
        sql.push_str(" AND ");
        sql.push_str(&sql_conditions.join(" AND "));
    }
}

fn collect_conditions(
    sql_conditions: &mut Vec<String>,
    params: &mut Vec<DinocoValue>,
    conditions: Vec<FindWhere>,
    qualifier: Option<&str>,
) {
    for condition in conditions {
        match condition {
            FindWhere::Eq(field, value) => {
                sql_conditions.push(format!("{} = ?", qualify_field(field, qualifier)));
                params.push(value);
            }
            FindWhere::Neq(field, value) => {
                sql_conditions.push(format!("{} != ?", qualify_field(field, qualifier)));
                params.push(value);
            }
            FindWhere::Gt(field, value) => {
                sql_conditions.push(format!("{} > ?", qualify_field(field, qualifier)));
                params.push(value);
            }
            FindWhere::Gte(field, value) => {
                sql_conditions.push(format!("{} >= ?", qualify_field(field, qualifier)));
                params.push(value);
            }
            FindWhere::Lt(field, value) => {
                sql_conditions.push(format!("{} < ?", qualify_field(field, qualifier)));
                params.push(value);
            }
            FindWhere::Lte(field, value) => {
                sql_conditions.push(format!("{} <= ?", qualify_field(field, qualifier)));
                params.push(value);
            }
            FindWhere::Like(field, value) => {
                sql_conditions.push(format!("{} LIKE ?", qualify_field(field, qualifier)));
                params.push(value);
            }
            FindWhere::FullText(fields, value) => {
                let fields = fields.iter().map(|field| qualify_field(field, qualifier)).collect::<Vec<_>>().join(", ");
                sql_conditions.push(format!("MATCH ({fields}) AGAINST (? IN NATURAL LANGUAGE MODE)"));
                params.push(value);
            }
            FindWhere::Between(field, start, end) => {
                sql_conditions.push(format!(
                    "{} >= ? AND {} <= ?",
                    qualify_field(field, qualifier),
                    qualify_field(field, qualifier)
                ));
                params.push(start);
                params.push(end);
            }
            FindWhere::Batch(field, values) => {
                if values.is_empty() {
                    sql_conditions.push("1 = 0".to_string());
                } else {
                    let placeholders = vec!["?"; values.len()].join(", ");
                    sql_conditions.push(format!("{} IN ({placeholders})", qualify_field(field, qualifier)));
                    params.extend(values);
                }
            }
            FindWhere::Null(field) => {
                sql_conditions.push(format!("{} IS NULL", qualify_field(field, qualifier)));
            }
            FindWhere::NotNull(field) => {
                sql_conditions.push(format!("{} IS NOT NULL", qualify_field(field, qualifier)));
            }
            FindWhere::And(conditions) => {
                push_condition_group(sql_conditions, params, conditions, qualifier, "AND", "1 = 1");
            }
            FindWhere::Or(conditions) => {
                push_condition_group(sql_conditions, params, conditions, qualifier, "OR", "1 = 0");
            }
            FindWhere::Not(condition) => {
                let mut nested = Vec::new();
                collect_conditions(&mut nested, params, vec![*condition], qualifier);
                let expression = if nested.is_empty() { "1 = 1".to_string() } else { nested.join(" AND ") };
                sql_conditions.push(format!("NOT ({expression})"));
            }
        }
    }
}

fn push_condition_group(
    sql_conditions: &mut Vec<String>,
    params: &mut Vec<DinocoValue>,
    conditions: Vec<FindWhere>,
    qualifier: Option<&str>,
    operator: &str,
    empty_expression: &str,
) {
    let mut nested = Vec::new();
    collect_conditions(&mut nested, params, conditions, qualifier);
    let expression =
        if nested.is_empty() { empty_expression.to_string() } else { nested.join(&format!(" {operator} ")) };
    sql_conditions.push(format!("({expression})"));
}

fn append_order_by(sql: &mut String, order_by: Option<FindOrderBy>, qualifier: Option<&str>) {
    if let Some(order_by) = order_by {
        let (field, direction) = match order_by {
            FindOrderBy::Asc(field) => (field, "ASC"),
            FindOrderBy::Desc(field) => (field, "DESC"),
        };

        sql.push_str(" ORDER BY ");
        sql.push_str(&qualify_field(field, qualifier));
        sql.push(' ');
        sql.push_str(direction);
    }
}

fn relation_partition_order_by(table: &str, order_by: Option<FindOrderBy>, fallback: &str) -> String {
    let Some(order_by) = order_by else {
        return fallback.to_string();
    };

    let (field, direction) = match order_by {
        FindOrderBy::Asc(field) => (field, "ASC"),
        FindOrderBy::Desc(field) => (field, "DESC"),
    };

    format!("{} {direction}", qualify_field(field, Some(table)))
}

fn qualify_field(field: &str, qualifier: Option<&str>) -> String {
    match qualifier {
        Some(qualifier) if !field.contains('.') => {
            format!("{}.{}", sql_identifier(qualifier), sql_identifier(field))
        }
        _ if field.contains('.') => field.split('.').map(sql_identifier).collect::<Vec<_>>().join("."),
        _ => sql_identifier(field),
    }
}

fn sql_identifier(identifier: &str) -> String {
    if is_reserved_identifier(identifier) {
        format!("`{}`", identifier.replace('`', "``"))
    } else {
        identifier.to_string()
    }
}

fn is_reserved_identifier(identifier: &str) -> bool {
    matches!(
        identifier.to_ascii_lowercase().as_str(),
        "group"
            | "order"
            | "select"
            | "table"
            | "where"
            | "from"
            | "limit"
            | "offset"
            | "primary"
            | "references"
            | "constraint"
            | "index"
            | "unique"
            | "default"
            | "check"
    )
}