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