Skip to main content

che_orm/
sql.rs

1use std::marker::PhantomData;
2
3use crate::{
4    ColumnRef, ColumnType, CompareOp, CreateTableAst, DatabaseValue, DeleteAst, Expr, InsertAst,
5    JoinType, OrderDirection, QueryAst, SelectAst, TableSchema, UpdateAst,
6};
7
8pub trait SqlDialect {
9    fn identifier(identifier: &str, output: &mut String) {
10        output.push_str(identifier);
11    }
12    fn constraint_name(_table: &str, _kind: &str, _columns: &[&str]) -> Option<String> {
13        None
14    }
15    fn index_name(table: &str, position: usize) -> String {
16        format!("{table}_idx_{position}")
17    }
18    fn placeholder(output: &mut String, index: usize);
19    fn column_type(column_type: ColumnType, output: &mut String);
20    fn identity_primary_key(output: &mut String);
21    fn timestamp_default(output: &mut String);
22    fn datetime_collation(_output: &mut String) {}
23    fn offset_without_limit(_output: &mut String) {}
24}
25
26pub struct PostgresDialect;
27impl SqlDialect for PostgresDialect {
28    fn identifier(identifier: &str, output: &mut String) {
29        output.push('"');
30        output.push_str(&identifier.replace('"', "\"\""));
31        output.push('"');
32    }
33    fn constraint_name(table: &str, kind: &str, columns: &[&str]) -> Option<String> {
34        Some(crate::schema::schema_object_name(table, kind, columns))
35    }
36    fn index_name(table: &str, position: usize) -> String {
37        crate::schema::schema_object_name(table, "idx", &[&position.to_string()])
38    }
39    fn placeholder(output: &mut String, index: usize) {
40        output.push('$');
41        output.push_str(&index.to_string());
42    }
43
44    fn column_type(column_type: ColumnType, output: &mut String) {
45        output.push_str(match column_type {
46            ColumnType::Integer => "BIGINT",
47            ColumnType::Real => "DOUBLE PRECISION",
48            ColumnType::Text => "TEXT",
49            ColumnType::Binary => "BYTEA",
50            ColumnType::Boolean => "BOOLEAN",
51            ColumnType::DateTime => "TIMESTAMPTZ",
52            ColumnType::Uuid => "UUID",
53        });
54    }
55
56    fn identity_primary_key(output: &mut String) {
57        output.push_str(" GENERATED BY DEFAULT AS IDENTITY");
58    }
59
60    fn timestamp_default(output: &mut String) {
61        output.push_str("CURRENT_TIMESTAMP");
62    }
63}
64
65pub struct SqliteDialect;
66impl SqlDialect for SqliteDialect {
67    fn offset_without_limit(output: &mut String) {
68        output.push_str(" LIMIT -1");
69    }
70    fn placeholder(output: &mut String, _index: usize) {
71        output.push('?');
72    }
73
74    fn column_type(column_type: ColumnType, output: &mut String) {
75        output.push_str(match column_type {
76            ColumnType::Integer => "INTEGER",
77            ColumnType::Real => "REAL",
78            ColumnType::Text => "TEXT",
79            ColumnType::Binary => "BLOB",
80            ColumnType::Boolean => "INTEGER",
81            ColumnType::DateTime => "TEXT",
82            ColumnType::Uuid => "BLOB",
83        });
84    }
85
86    fn identity_primary_key(_output: &mut String) {}
87
88    fn timestamp_default(output: &mut String) {
89        output.push_str(crate::datetime::SQLITE_DATETIME_DEFAULT);
90    }
91}
92
93#[cfg(all(feature = "postgres", not(feature = "sqlite")))]
94pub type CurrentDialect = PostgresDialect;
95
96#[cfg(feature = "sqlite")]
97pub type CurrentDialect = SqliteDialect;
98
99#[derive(Debug)]
100/// SQL text and ordered bound parameters.
101pub struct CompiledQuery {
102    pub sql: String,
103    pub params: Vec<DatabaseValue>,
104}
105
106#[derive(Debug)]
107/// Table DDL plus separately executable indexes.
108pub struct CompiledSchema {
109    pub table: String,
110    pub indexes: Vec<String>,
111}
112
113pub struct SqlCompiler<D> {
114    sql: String,
115    params: Vec<DatabaseValue>,
116    _dialect: PhantomData<D>,
117}
118
119#[cfg(any(feature = "sqlite", feature = "postgres"))]
120pub type Compiler = SqlCompiler<CurrentDialect>;
121
122impl<D: SqlDialect> SqlCompiler<D> {
123    /// Compiles a model schema, including indexes.
124    pub fn compile_schema(schema: &TableSchema) -> CompiledSchema {
125        Self::compile_table_state(&crate::TableState::from(schema))
126    }
127
128    /// Compiles owned schema metadata with the same dialect as model schemas.
129    pub fn compile_table_state(schema: &crate::TableState) -> CompiledSchema {
130        let mut compiler = Self {
131            sql: String::new(),
132            params: Vec::new(),
133            _dialect: PhantomData,
134        };
135        compiler.compile_owned_table(schema);
136        let table = compiler.sql;
137        let indexes = schema
138            .indexes
139            .iter()
140            .enumerate()
141            .map(|(index, columns)| {
142                let mut sql = String::new();
143                sql.push_str("CREATE INDEX ");
144                D::identifier(&D::index_name(&schema.name, index), &mut sql);
145                sql.push_str(" ON ");
146                D::identifier(&schema.name, &mut sql);
147                sql.push_str(" (");
148                for (column_index, column) in columns.iter().enumerate() {
149                    if column_index != 0 {
150                        sql.push_str(", ");
151                    }
152                    D::identifier(column, &mut sql);
153                }
154                sql.push(')');
155                sql
156            })
157            .collect();
158        CompiledSchema { table, indexes }
159    }
160
161    /// Compiles a query AST using dialect `D`.
162    pub fn compile(ast: &QueryAst) -> CompiledQuery {
163        let mut compiler = Self {
164            sql: String::new(),
165            params: Vec::new(),
166            _dialect: PhantomData,
167        };
168        match ast {
169            QueryAst::Select(query) => compiler.compile_select(query),
170            QueryAst::Insert(query) => compiler.compile_insert(query),
171            QueryAst::Update(query) => compiler.compile_update(query),
172            QueryAst::Delete(query) => compiler.compile_delete(query),
173            QueryAst::CreateTable(query) => compiler.compile_create_table(query),
174        }
175        CompiledQuery {
176            sql: compiler.sql,
177            params: compiler.params,
178        }
179    }
180
181    fn push_identifier(&mut self, identifier: &str) {
182        D::identifier(identifier, &mut self.sql);
183    }
184    fn push_column(&mut self, column: &ColumnRef) {
185        self.push_identifier(column.table);
186        self.sql.push('.');
187        self.push_identifier(column.name);
188    }
189    fn push_value(&mut self, value: &DatabaseValue) {
190        self.params.push(value.clone());
191        D::placeholder(&mut self.sql, self.params.len());
192    }
193
194    fn push_comparable_column(&mut self, column: &ColumnRef) {
195        self.push_column(column);
196        if column.datetime {
197            D::datetime_collation(&mut self.sql);
198        }
199    }
200
201    fn compile_expr(&mut self, expr: &Expr) {
202        match expr {
203            Expr::Column(column) => self.push_comparable_column(column),
204            Expr::Value(value) => self.push_value(value),
205            Expr::Compare { left, op, right } => {
206                self.sql.push('(');
207                self.compile_expr(left);
208                self.sql.push(' ');
209                self.sql.push_str(match op {
210                    CompareOp::Eq => "=",
211                    CompareOp::Ne => "<>",
212                    CompareOp::Gt => ">",
213                    CompareOp::Gte => ">=",
214                    CompareOp::Lt => "<",
215                    CompareOp::Lte => "<=",
216                });
217                self.sql.push(' ');
218                self.compile_expr(right);
219                self.sql.push(')');
220            }
221            Expr::Like { left, pattern } => {
222                self.sql.push('(');
223                self.compile_expr(left);
224                self.sql.push_str(" LIKE ");
225                self.compile_expr(pattern);
226                self.sql.push(')');
227            }
228            Expr::InQuery { left, query } => {
229                self.sql.push('(');
230                self.compile_expr(left);
231                self.sql.push_str(" IN (");
232                self.compile_select(query);
233                self.sql.push_str("))");
234            }
235            Expr::In { left, values } => {
236                if values.is_empty() {
237                    self.sql.push_str("(1 = 0)");
238                } else {
239                    self.sql.push('(');
240                    self.compile_expr(left);
241                    self.sql.push_str(" IN (");
242                    for (index, value) in values.iter().enumerate() {
243                        if index != 0 {
244                            self.sql.push_str(", ");
245                        }
246                        self.push_value(value);
247                    }
248                    self.sql.push_str("))");
249                }
250            }
251            Expr::And { left, right } => self.compile_binary(left, right, " AND "),
252            Expr::Or { left, right } => self.compile_binary(left, right, " OR "),
253            Expr::Not(expr) => {
254                self.sql.push_str("NOT (");
255                self.compile_expr(expr);
256                self.sql.push(')');
257            }
258            Expr::IsNull(expr) => {
259                self.sql.push('(');
260                self.compile_expr(expr);
261                self.sql.push_str(" IS NULL)");
262            }
263            Expr::IsNotNull(expr) => {
264                self.sql.push('(');
265                self.compile_expr(expr);
266                self.sql.push_str(" IS NOT NULL)");
267            }
268        }
269    }
270
271    fn compile_binary(&mut self, left: &Expr, right: &Expr, operator: &str) {
272        self.sql.push('(');
273        self.compile_expr(left);
274        self.sql.push_str(operator);
275        self.compile_expr(right);
276        self.sql.push(')');
277    }
278
279    fn compile_select(&mut self, query: &SelectAst) {
280        self.sql.push_str("SELECT ");
281        for (index, column) in query.columns.iter().enumerate() {
282            if index != 0 {
283                self.sql.push_str(", ");
284            }
285            self.push_column(column);
286        }
287        self.sql.push_str(" FROM ");
288        self.push_identifier(query.table.name);
289        for join in &query.joins {
290            self.sql.push(' ');
291            self.sql.push_str(match join.kind {
292                JoinType::Inner => "INNER JOIN ",
293                JoinType::Left => "LEFT JOIN ",
294            });
295            self.push_identifier(join.table.name);
296            self.sql.push_str(" AS ");
297            self.push_identifier(join.alias);
298            self.sql.push_str(" ON ");
299            self.compile_expr(&join.on);
300        }
301        if let Some(filter) = &query.filter {
302            self.sql.push_str(" WHERE ");
303            self.compile_expr(filter);
304        }
305        if !query.order_by.is_empty() {
306            self.sql.push_str(" ORDER BY ");
307            for (index, order) in query.order_by.iter().enumerate() {
308                if index != 0 {
309                    self.sql.push_str(", ");
310                }
311                self.push_comparable_column(&order.column);
312                self.sql.push_str(match order.direction {
313                    OrderDirection::Asc => " ASC",
314                    OrderDirection::Desc => " DESC",
315                });
316            }
317        }
318        if let Some(limit) = query.limit {
319            self.sql.push_str(" LIMIT ");
320            self.sql.push_str(&limit.to_string());
321        }
322        if let Some(offset) = query.offset {
323            if query.limit.is_none() {
324                D::offset_without_limit(&mut self.sql);
325            }
326            self.sql.push_str(" OFFSET ");
327            self.sql.push_str(&offset.to_string());
328        }
329    }
330
331    fn compile_insert(&mut self, query: &InsertAst) {
332        self.sql.push_str("INSERT INTO ");
333        self.push_identifier(query.table.name);
334        if query.values.is_empty() {
335            self.sql.push_str(" DEFAULT VALUES");
336            self.compile_returning(&query.returning);
337            return;
338        }
339        self.sql.push_str(" (");
340        for (index, value) in query.values.iter().enumerate() {
341            if index != 0 {
342                self.sql.push_str(", ");
343            }
344            self.push_identifier(value.column.name);
345        }
346        self.sql.push_str(") VALUES (");
347        for (index, value) in query.values.iter().enumerate() {
348            if index != 0 {
349                self.sql.push_str(", ");
350            }
351            self.push_value(&value.value);
352        }
353        self.sql.push(')');
354        self.compile_returning(&query.returning);
355    }
356
357    fn compile_update(&mut self, query: &UpdateAst) {
358        self.sql.push_str("UPDATE ");
359        self.push_identifier(query.table.name);
360        self.sql.push_str(" SET ");
361        for (index, assignment) in query.assignments.iter().enumerate() {
362            if index != 0 {
363                self.sql.push_str(", ");
364            }
365            self.push_identifier(assignment.column.name);
366            self.sql.push_str(" = ");
367            self.push_value(&assignment.value);
368        }
369        if let Some(filter) = &query.filter {
370            self.sql.push_str(" WHERE ");
371            self.compile_expr(filter);
372        }
373        self.compile_returning(&query.returning);
374    }
375
376    fn compile_delete(&mut self, query: &DeleteAst) {
377        self.sql.push_str("DELETE FROM ");
378        self.push_identifier(query.table.name);
379        if let Some(filter) = &query.filter {
380            self.sql.push_str(" WHERE ");
381            self.compile_expr(filter);
382        }
383    }
384
385    fn compile_create_table(&mut self, query: &CreateTableAst) {
386        self.compile_owned_table(&crate::TableState::from(&query.schema));
387    }
388
389    fn compile_owned_table(&mut self, schema: &crate::TableState) {
390        self.sql.push_str("CREATE TABLE ");
391        self.push_identifier(&schema.name);
392        self.sql.push_str(" (");
393
394        for (index, column) in schema.columns.iter().enumerate() {
395            if index != 0 {
396                self.sql.push_str(", ");
397            }
398            self.push_identifier(&column.name);
399            self.sql.push(' ');
400            D::column_type(column.column_type, &mut self.sql);
401
402            if column.primary_key && column.column_type == ColumnType::Integer {
403                D::identity_primary_key(&mut self.sql);
404            }
405            if column.primary_key {
406                self.push_constraint(&schema.name, "pk", &[&column.name]);
407                self.sql.push_str(" PRIMARY KEY");
408            }
409            if !column.nullable && (!column.primary_key || column.column_type == ColumnType::Uuid) {
410                self.sql.push_str(" NOT NULL");
411            }
412            if column.unique {
413                self.push_constraint(&schema.name, "field_unique", &[&column.name]);
414                self.sql.push_str(" UNIQUE");
415            }
416            if (column.auto_now_add || column.auto_now) && column.default.is_none() {
417                self.sql.push_str(" DEFAULT ");
418                D::timestamp_default(&mut self.sql);
419            }
420            if let Some(default) = &column.default {
421                self.sql.push_str(" DEFAULT ");
422                self.sql.push_str(default);
423            }
424            if let Some(check) = &column.check {
425                self.push_constraint(&schema.name, "check", &[&column.name]);
426                self.sql.push_str(" CHECK (");
427                self.sql.push_str(check);
428                self.sql.push(')');
429            }
430            if let Some(choices) = &column.choices {
431                self.push_constraint(&schema.name, "choices", &[&column.name]);
432                self.sql.push_str(" CHECK (");
433                self.push_identifier(&column.name);
434                self.sql.push_str(" IN (");
435                for (choice_index, choice) in choices.iter().enumerate() {
436                    if choice_index != 0 {
437                        self.sql.push_str(", ");
438                    }
439                    self.sql.push('\'');
440                    self.sql.push_str(&choice.replace('\'', "''"));
441                    self.sql.push('\'');
442                }
443                self.sql.push_str("))");
444            }
445            if let Some(reference) = &column.references {
446                self.push_constraint(&schema.name, "fk", &[&column.name]);
447                self.sql.push_str(" REFERENCES ");
448                let (table, column) = reference.target_parts().expect("validated foreign key");
449                self.push_identifier(table);
450                self.sql.push('(');
451                self.push_identifier(column);
452                self.sql.push(')');
453                if let Some(on_delete) = &reference.on_delete {
454                    self.sql.push_str(" ON DELETE ");
455                    self.sql.push_str(&on_delete.to_uppercase());
456                }
457            }
458        }
459
460        for columns in &schema.unique_constraints {
461            let columns = columns.iter().map(String::as_str).collect::<Vec<_>>();
462            self.sql.push(',');
463            self.push_constraint(&schema.name, "unique", &columns);
464            self.sql.push_str(" UNIQUE (");
465            self.push_column_names(&columns);
466            self.sql.push(')');
467        }
468        self.sql.push(')');
469    }
470
471    fn push_constraint(&mut self, table: &str, kind: &str, columns: &[&str]) {
472        if let Some(name) = D::constraint_name(table, kind, columns) {
473            self.sql.push_str(" CONSTRAINT ");
474            self.push_identifier(&name);
475        }
476    }
477
478    fn push_column_names(&mut self, columns: &[&str]) {
479        for (index, column) in columns.iter().enumerate() {
480            if index != 0 {
481                self.sql.push_str(", ");
482            }
483            self.push_identifier(column);
484        }
485    }
486
487    fn compile_returning(&mut self, columns: &[ColumnRef]) {
488        if columns.is_empty() {
489            return;
490        }
491        self.sql.push_str(" RETURNING ");
492        for (index, column) in columns.iter().enumerate() {
493            if index != 0 {
494                self.sql.push_str(", ");
495            }
496            self.push_identifier(column.name);
497        }
498    }
499}