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