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