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