use std::marker::PhantomData;
use crate::{
ColumnRef, ColumnType, CompareOp, CreateTableAst, DatabaseValue, DeleteAst, Expr, InsertAst,
JoinType, OrderDirection, QueryAst, SelectAst, TableSchema, UpdateAst,
};
pub trait SqlDialect {
fn placeholder(output: &mut String, index: usize);
fn column_type(column_type: ColumnType, output: &mut String);
fn identity_primary_key(output: &mut String);
fn timestamp_default(output: &mut String);
}
pub struct PostgresDialect;
impl SqlDialect for PostgresDialect {
fn placeholder(output: &mut String, index: usize) {
output.push('$');
output.push_str(&index.to_string());
}
fn column_type(column_type: ColumnType, output: &mut String) {
output.push_str(match column_type {
ColumnType::Integer => "BIGINT",
ColumnType::Text => "TEXT",
ColumnType::Binary => "BYTEA",
ColumnType::Boolean => "BOOLEAN",
ColumnType::DateTime => "TIMESTAMPTZ",
});
}
fn identity_primary_key(output: &mut String) {
output.push_str(" GENERATED BY DEFAULT AS IDENTITY");
}
fn timestamp_default(output: &mut String) {
output.push_str("CURRENT_TIMESTAMP");
}
}
pub struct SqliteDialect;
impl SqlDialect for SqliteDialect {
fn placeholder(output: &mut String, _index: usize) {
output.push('?');
}
fn column_type(column_type: ColumnType, output: &mut String) {
output.push_str(match column_type {
ColumnType::Integer => "INTEGER",
ColumnType::Text => "TEXT",
ColumnType::Binary => "BLOB",
ColumnType::Boolean => "INTEGER",
ColumnType::DateTime => "TEXT",
});
}
fn identity_primary_key(_output: &mut String) {}
fn timestamp_default(output: &mut String) {
output.push_str("(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))");
}
}
#[cfg(all(feature = "postgres", not(feature = "sqlite")))]
pub type CurrentDialect = PostgresDialect;
#[cfg(all(feature = "sqlite", not(feature = "postgres")))]
pub type CurrentDialect = SqliteDialect;
#[derive(Debug)]
pub struct CompiledQuery {
pub sql: String,
pub params: Vec<DatabaseValue>,
}
#[derive(Debug)]
pub struct CompiledSchema {
pub table: String,
pub indexes: Vec<String>,
}
pub struct SqlCompiler<D> {
sql: String,
params: Vec<DatabaseValue>,
_dialect: PhantomData<D>,
}
pub type Compiler = SqlCompiler<CurrentDialect>;
impl<D: SqlDialect> SqlCompiler<D> {
pub fn compile_schema(schema: &TableSchema) -> CompiledSchema {
let table_ast = CreateTableAst {
schema: schema.clone(),
};
let table = Self::compile(&QueryAst::CreateTable(table_ast)).sql;
let indexes = schema
.indexes
.iter()
.enumerate()
.map(|(index, columns)| {
let mut sql = String::new();
sql.push_str("CREATE INDEX ");
sql.push_str(schema.name);
sql.push_str("_idx_");
sql.push_str(&index.to_string());
sql.push_str(" ON ");
sql.push_str(schema.name);
sql.push_str(" (");
for (column_index, column) in columns.iter().enumerate() {
if column_index != 0 {
sql.push_str(", ");
}
sql.push_str(column);
}
sql.push(')');
sql
})
.collect();
CompiledSchema { table, indexes }
}
pub fn compile(ast: &QueryAst) -> CompiledQuery {
let mut compiler = Self {
sql: String::new(),
params: Vec::new(),
_dialect: PhantomData,
};
match ast {
QueryAst::Select(query) => compiler.compile_select(query),
QueryAst::Insert(query) => compiler.compile_insert(query),
QueryAst::Update(query) => compiler.compile_update(query),
QueryAst::Delete(query) => compiler.compile_delete(query),
QueryAst::CreateTable(query) => compiler.compile_create_table(query),
}
CompiledQuery {
sql: compiler.sql,
params: compiler.params,
}
}
fn push_identifier(&mut self, identifier: &str) {
self.sql.push_str(identifier);
}
fn push_column(&mut self, column: &ColumnRef) {
self.push_identifier(column.table);
self.sql.push('.');
self.push_identifier(column.name);
}
fn push_value(&mut self, value: &DatabaseValue) {
self.params.push(value.clone());
D::placeholder(&mut self.sql, self.params.len());
}
fn compile_expr(&mut self, expr: &Expr) {
match expr {
Expr::Column(column) => self.push_column(column),
Expr::Value(value) => self.push_value(value),
Expr::Compare { left, op, right } => {
self.sql.push('(');
self.compile_expr(left);
self.sql.push(' ');
self.sql.push_str(match op {
CompareOp::Eq => "=",
CompareOp::Ne => "<>",
CompareOp::Gt => ">",
CompareOp::Gte => ">=",
CompareOp::Lt => "<",
CompareOp::Lte => "<=",
});
self.sql.push(' ');
self.compile_expr(right);
self.sql.push(')');
}
Expr::Like { left, pattern } => {
self.sql.push('(');
self.compile_expr(left);
self.sql.push_str(" LIKE ");
self.compile_expr(pattern);
self.sql.push(')');
}
Expr::In { left, values } => {
if values.is_empty() {
self.sql.push_str("(1 = 0)");
} else {
self.sql.push('(');
self.compile_expr(left);
self.sql.push_str(" IN (");
for (index, value) in values.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_value(value);
}
self.sql.push_str("))");
}
}
Expr::And { left, right } => self.compile_binary(left, right, " AND "),
Expr::Or { left, right } => self.compile_binary(left, right, " OR "),
Expr::Not(expr) => {
self.sql.push_str("NOT (");
self.compile_expr(expr);
self.sql.push(')');
}
Expr::IsNull(expr) => {
self.sql.push('(');
self.compile_expr(expr);
self.sql.push_str(" IS NULL)");
}
Expr::IsNotNull(expr) => {
self.sql.push('(');
self.compile_expr(expr);
self.sql.push_str(" IS NOT NULL)");
}
}
}
fn compile_binary(&mut self, left: &Expr, right: &Expr, operator: &str) {
self.sql.push('(');
self.compile_expr(left);
self.sql.push_str(operator);
self.compile_expr(right);
self.sql.push(')');
}
fn compile_select(&mut self, query: &SelectAst) {
self.sql.push_str("SELECT ");
for (index, column) in query.columns.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_column(column);
}
self.sql.push_str(" FROM ");
self.push_identifier(query.table.name);
for join in &query.joins {
self.sql.push(' ');
self.sql.push_str(match join.kind {
JoinType::Inner => "INNER JOIN ",
JoinType::Left => "LEFT JOIN ",
});
self.push_identifier(join.table.name);
self.sql.push_str(" AS ");
self.push_identifier(join.alias);
self.sql.push_str(" ON ");
self.compile_expr(&join.on);
}
if let Some(filter) = &query.filter {
self.sql.push_str(" WHERE ");
self.compile_expr(filter);
}
if !query.order_by.is_empty() {
self.sql.push_str(" ORDER BY ");
for (index, order) in query.order_by.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_column(&order.column);
self.sql.push_str(match order.direction {
OrderDirection::Asc => " ASC",
OrderDirection::Desc => " DESC",
});
}
}
if let Some(limit) = query.limit {
self.sql.push_str(" LIMIT ");
self.sql.push_str(&limit.to_string());
}
if let Some(offset) = query.offset {
self.sql.push_str(" OFFSET ");
self.sql.push_str(&offset.to_string());
}
}
fn compile_insert(&mut self, query: &InsertAst) {
self.sql.push_str("INSERT INTO ");
self.push_identifier(query.table.name);
if query.values.is_empty() {
self.sql.push_str(" DEFAULT VALUES");
self.compile_returning(&query.returning);
return;
}
self.sql.push_str(" (");
for (index, value) in query.values.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_identifier(value.column.name);
}
self.sql.push_str(") VALUES (");
for (index, value) in query.values.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_value(&value.value);
}
self.sql.push(')');
self.compile_returning(&query.returning);
}
fn compile_update(&mut self, query: &UpdateAst) {
self.sql.push_str("UPDATE ");
self.push_identifier(query.table.name);
self.sql.push_str(" SET ");
for (index, assignment) in query.assignments.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_identifier(assignment.column.name);
self.sql.push_str(" = ");
self.push_value(&assignment.value);
}
if let Some(filter) = &query.filter {
self.sql.push_str(" WHERE ");
self.compile_expr(filter);
}
self.compile_returning(&query.returning);
}
fn compile_delete(&mut self, query: &DeleteAst) {
self.sql.push_str("DELETE FROM ");
self.push_identifier(query.table.name);
if let Some(filter) = &query.filter {
self.sql.push_str(" WHERE ");
self.compile_expr(filter);
}
}
fn compile_create_table(&mut self, query: &CreateTableAst) {
let schema = &query.schema;
self.sql.push_str("CREATE TABLE ");
self.push_identifier(schema.name);
self.sql.push_str(" (");
for (index, column) in schema.columns.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_identifier(column.name);
self.sql.push(' ');
D::column_type(column.column_type, &mut self.sql);
if column.primary_key && column.column_type == ColumnType::Integer {
D::identity_primary_key(&mut self.sql);
}
if column.primary_key {
self.sql.push_str(" PRIMARY KEY");
}
if !column.nullable && !column.primary_key {
self.sql.push_str(" NOT NULL");
}
if column.unique {
self.sql.push_str(" UNIQUE");
}
if (column.auto_now_add || column.auto_now) && column.default.is_none() {
self.sql.push_str(" DEFAULT ");
D::timestamp_default(&mut self.sql);
}
if let Some(default) = column.default {
self.sql.push_str(" DEFAULT ");
self.sql.push_str(default);
}
if let Some(check) = column.check {
self.sql.push_str(" CHECK (");
self.sql.push_str(check);
self.sql.push(')');
}
if let Some(choices) = &column.choices {
self.sql.push_str(" CHECK (");
self.push_identifier(column.name);
self.sql.push_str(" IN (");
for (choice_index, choice) in choices.iter().enumerate() {
if choice_index != 0 {
self.sql.push_str(", ");
}
self.sql.push('\'');
self.sql.push_str(&choice.replace('\'', "''"));
self.sql.push('\'');
}
self.sql.push_str("))");
}
if let Some(reference) = &column.references {
self.sql.push_str(" REFERENCES ");
self.sql.push_str(reference.target());
if let Some(on_delete) = reference.on_delete() {
self.sql.push_str(" ON DELETE ");
self.sql.push_str(&on_delete.to_uppercase());
}
}
}
for columns in &schema.unique_constraints {
self.sql.push_str(", UNIQUE (");
self.push_column_names(columns);
self.sql.push(')');
}
self.sql.push(')');
}
fn push_column_names(&mut self, columns: &[&'static str]) {
for (index, column) in columns.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_identifier(column);
}
}
fn compile_returning(&mut self, columns: &[ColumnRef]) {
if columns.is_empty() {
return;
}
self.sql.push_str(" RETURNING ");
for (index, column) in columns.iter().enumerate() {
if index != 0 {
self.sql.push_str(", ");
}
self.push_identifier(column.name);
}
}
}