use std::sync::Arc;
use crate::builder::AnyBuilder;
use crate::builder::case::CaseExpression;
use crate::builder::core::{
AfterBuild, Builder, Dialect, ExistsSubquery, ExplainOptions, LateralJoin, SubSelect, WhereInSubquery,
};
use crate::builder::join::JoinBuilder;
use crate::builder::steps::{Arg, Step};
use crate::builder::types::{
CteClause, Executor, JoinType, Statement, UnionClause, UnionType, WindowDefinition, WindowFrame, WindowSelect,
};
use crate::enums::NullsPosition;
use crate::error::{Error, Result};
use crate::hook::Hook;
use crate::method::Method;
use crate::query::{Compiler, Query};
use crate::value::{Array, IntoValues, Value};
fn strings<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Vec<String> {
items.into_iter().map(Into::into).collect()
}
fn is_window_function(function: &str) -> bool {
let text = function.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
let text = text.as_bytes();
let is_space = |b: u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0B' | b'\x0C');
let mut i = 0;
match text.first() {
Some(b) if b.is_ascii_alphabetic() || *b == b'_' => i += 1,
_ => return false,
}
while i < text.len() && (text[i].is_ascii_alphanumeric() || text[i] == b'_') {
i += 1;
}
while i < text.len() && is_space(text[i]) {
i += 1;
}
if text.get(i) != Some(&b'(') || text.last() != Some(&b')') || i == text.len() - 1 {
return false;
}
text[i + 1..text.len() - 1]
.iter()
.all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b',' | b'.' | b'*' | b'"' | b'`') || is_space(b))
}
impl<D: Dialect> Builder<D> {
pub fn from(&mut self, table: impl Into<String>, alias: impl Into<String>) -> &mut Self {
self.scoped_from(table.into(), alias.into())
}
pub fn take_refusal(&mut self) -> Option<crate::Error> {
self.core.deferred.take()
}
pub fn from_none(&mut self) -> &mut Self {
self.from("", "")
}
pub fn from_sub(&mut self, subquery: impl AnyBuilder + 'static, alias: impl Into<String>) -> &mut Self {
self.from_sub_boxed(Box::new(subquery), alias)
}
pub fn from_sub_boxed(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
self.core.from_subquery = Some(SubSelect { subquery, alias: alias.into() });
self.core.table.clear();
self
}
pub fn select_sub(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
self.core.sub_selects.push(SubSelect { subquery, alias: alias.into() });
self
}
pub fn filter_where_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: false });
self
}
pub fn filter_where_not_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: true });
self
}
pub fn filter_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
self.core.exists_subqueries.push(ExistsSubquery { subquery, not: false });
self
}
pub fn filter_not_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
self.core.exists_subqueries.push(ExistsSubquery { subquery, not: true });
self
}
pub fn select<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
self.core.pending.push(Query::select(columns));
self
}
pub fn select_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
self.core
.raw_selects
.push(crate::builder::Condition::new(expression, bindings.into_values().values().cloned().collect()));
self
}
pub fn distinct(&mut self) -> &mut Self {
self.core.pending.push(Query::distinct());
self
}
pub fn filter(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
self.core.pending.extend(queries);
self
}
pub fn queries(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
self.core.pending.extend(queries);
self
}
pub fn sort_asc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
self.core.pending.push(Query::order_asc(attribute, nulls));
self
}
pub fn sort_desc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
self.core.pending.push(Query::order_desc(attribute, nulls));
self
}
pub fn sort_random(&mut self) -> &mut Self {
self.core.pending.push(Query::order_random());
self
}
pub fn limit(&mut self, value: i64) -> &mut Self {
self.core.pending.push(Query::limit(value));
self
}
pub fn offset(&mut self, value: i64) -> &mut Self {
self.core.pending.push(Query::offset(value));
self
}
pub fn fetch(&mut self, count: i64, with_ties: bool) -> &mut Self {
self.core.fetch_count = Some(count);
self.core.fetch_with_ties = with_ties;
self
}
pub fn page(&mut self, page: i64, per_page: i64) -> Result<&mut Self> {
let [limit, offset] = Query::page(page, per_page)?;
self.core.pending.push(limit);
self.core.pending.push(offset);
Ok(self)
}
pub fn cursor_after(&mut self, row: Value) -> &mut Self {
self.core.pending.push(Query::cursor_after(row));
self
}
pub fn cursor_before(&mut self, row: Value) -> &mut Self {
self.core.pending.push(Query::cursor_before(row));
self
}
pub fn when(&mut self, condition: bool, callback: impl FnOnce(&mut Self) -> Result<()>) -> Result<&mut Self> {
if condition {
callback(self)?;
}
Ok(self)
}
pub fn before_build(&mut self, callback: impl Fn(&mut Self) -> Result<()> + Send + Sync + 'static) -> &mut Self {
self.before_build.push(Arc::new(callback));
self
}
pub fn after_build(
&mut self,
callback: impl Fn(Statement) -> Result<Statement> + Send + Sync + 'static,
) -> &mut Self {
self.after_build_owned(move |_, statement| callback(statement))
}
pub fn after_build_owned(
&mut self,
callback: impl Fn(usize, Statement) -> Result<Statement> + Send + Sync + 'static,
) -> &mut Self {
let callback: AfterBuild = Arc::new(callback);
self.core.after_build.push(callback);
self
}
pub fn set_executor(&mut self, executor: Executor) -> &mut Self {
self.core.executor = Some(executor);
self
}
pub fn explain(&mut self, analyze: bool) -> Result<Statement> {
D::explain(self, analyze, &ExplainOptions::default())
}
pub fn explain_with(&mut self, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
D::explain(self, analyze, options)
}
pub fn execute(&mut self) -> Result<Value> {
self.build()?.execute()
}
pub fn to_raw_sql(&mut self) -> Result<String> {
self.raw_sql(false)
}
pub fn to_raw_sql_widened(&mut self) -> Result<String> {
self.raw_sql(true)
}
fn raw_sql(&mut self, widened: bool) -> Result<String> {
let result = self.built()?;
let mut sql = result.query;
let mut offset = 0;
for binding in &result.bindings {
let literal = match binding {
Value::Str(s) if widened => {
D::LITERAL.quote(&s.as_bytes().iter().map(|&b| char::from(b)).collect::<String>())?
}
Value::Str(s) => D::LITERAL.quote(&String::from_utf8_lossy(s.as_bytes()))?,
Value::Int(_) | Value::Float(_) => crate::value::to_php_string(binding),
Value::Bool(b) => if *b { "1" } else { "0" }.to_owned(),
_ => "NULL".to_owned(),
};
if let Some(pos) = sql.get(offset..).and_then(|rest| rest.find('?')).map(|p| p + offset) {
sql.replace_range(pos..=pos, &literal);
offset = pos + literal.len();
}
}
Ok(sql)
}
pub fn binding_list(&self) -> &[crate::builder::Binding] {
&self.core.bindings
}
pub fn set_binding_list(&mut self, bindings: Vec<crate::builder::Binding>) -> &mut Self {
self.core.bindings = bindings;
self
}
pub fn set_pending(&mut self, queries: Vec<Query>) -> &mut Self {
self.core.pending = queries;
self
}
pub fn resolved_attributes(&self) -> impl Iterator<Item = (&str, &str)> {
self.core.resolved.iter().map(|(attribute, resolved)| (attribute.as_str(), resolved.as_str()))
}
pub fn set_resolved_attributes(&mut self, resolved: impl IntoIterator<Item = (String, String)>) -> &mut Self {
self.core.resolved = resolved.into_iter().collect();
self
}
pub fn bindings(&mut self) -> Vec<Value> {
self.binding_values()
}
pub fn reset(&mut self) -> &mut Self {
let core = &mut self.core;
core.pending.clear();
core.bindings.clear();
core.resolved.clear();
core.table.clear();
core.alias.clear();
core.unions.clear();
core.rows.clear();
core.raw_sets.clear();
core.raw_set_bindings.clear();
core.conflict_keys.clear();
core.conflict_update_columns.clear();
core.conflict_raw_sets.clear();
core.conflict_raw_set_bindings.clear();
core.insert_column_expressions.clear();
core.insert_column_expression_bindings.clear();
core.insert_alias.clear();
core.lock_mode = None;
core.lock_of_table = None;
core.insert_select_source = None;
core.insert_select_columns.clear();
core.ctes.clear();
core.raw_selects.clear();
core.window_selects.clear();
core.window_definitions.clear();
core.sample = None;
core.cases.clear();
core.case_sets.clear();
core.where_in_subqueries.clear();
core.sub_selects.clear();
core.from_subquery = None;
core.tableless = false;
core.raw_orders.clear();
core.raw_groups.clear();
core.raw_havings.clear();
core.raw_wheres.clear();
core.column_predicates.clear();
core.joins.clear();
core.exists_subqueries.clear();
core.lateral_joins.clear();
core.after_build.clear();
core.fetch_count = None;
core.fetch_with_ties = false;
core.qualify = false;
core.aggregation_aliases.clear();
self.before_build.clear();
D::reset(self);
self
}
pub fn build(&mut self) -> Result<Statement> {
self.scoped_build()
}
pub fn count(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
self.core.pending.push(Query::count(attribute, alias));
self
}
pub fn count_distinct(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
self.core.pending.push(Query::count_distinct(attribute, alias));
self
}
pub fn sum(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
self.core.pending.push(Query::sum(attribute, alias));
self
}
pub fn avg(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
self.core.pending.push(Query::avg(attribute, alias));
self
}
pub fn min(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
self.core.pending.push(Query::min(attribute, alias));
self
}
pub fn max(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
self.core.pending.push(Query::max(attribute, alias));
self
}
pub fn group_by<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
self.core.pending.push(Query::group_by(columns));
self
}
pub fn group_by_time_bucket(&mut self, attribute: impl Into<String>, interval: &str) -> Result<&mut Self> {
self.core.pending.push(Query::group_by_time_bucket(attribute, interval)?);
Ok(self)
}
pub fn having(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
self.core.pending.push(Query::having(queries));
self
}
fn join_on(
&mut self,
method: Method,
table: String,
left: &str,
right: &str,
operator: &str,
alias: String,
) -> &mut Self {
let on = Query::on(left, right, operator);
self.core.pending.push(Query::new(method, table, crate::value::list([on]), alias));
self
}
pub fn join(
&mut self,
table: impl Into<String>,
left: &str,
right: &str,
operator: &str,
alias: impl Into<String>,
) -> &mut Self {
self.join_on(Method::Join, table.into(), left, right, operator, alias.into())
}
pub fn left_join(
&mut self,
table: impl Into<String>,
left: &str,
right: &str,
operator: &str,
alias: impl Into<String>,
) -> &mut Self {
self.join_on(Method::LeftJoin, table.into(), left, right, operator, alias.into())
}
pub fn right_join(
&mut self,
table: impl Into<String>,
left: &str,
right: &str,
operator: &str,
alias: impl Into<String>,
) -> &mut Self {
self.join_on(Method::RightJoin, table.into(), left, right, operator, alias.into())
}
pub fn join_where(
&mut self,
table: impl Into<String>,
callback: impl FnOnce(&mut JoinBuilder) -> Result<()>,
join_type: JoinType,
alias: impl Into<String>,
) -> Result<&mut Self> {
let mut join = JoinBuilder::new();
callback(&mut join)?;
let method = match join_type {
JoinType::Left => Method::LeftJoin,
JoinType::Right => Method::RightJoin,
JoinType::Cross => Method::CrossJoin,
JoinType::FullOuter => Method::FullOuterJoin,
JoinType::Natural => Method::NaturalJoin,
JoinType::Inner => Method::Join,
};
self.core.pending.push(Query::new(method, table, Array::default(), alias));
let index = self.core.pending.len() - 1;
self.core.joins.insert(index, join);
Ok(self)
}
fn union_with(&mut self, union_type: UnionType, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
let result = other.build()?;
self.core.unions.push(UnionClause::new(union_type, result.query, result.bindings));
Ok(self)
}
pub fn union(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
self.union_with(UnionType::Union, other)
}
pub fn union_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
self.union_with(UnionType::UnionAll, other)
}
pub fn intersect(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
self.union_with(UnionType::Intersect, other)
}
pub fn intersect_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
self.union_with(UnionType::IntersectAll, other)
}
pub fn except(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
self.union_with(UnionType::Except, other)
}
pub fn except_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
self.union_with(UnionType::ExceptAll, other)
}
pub fn with<S: Into<String>>(
&mut self,
name: impl Into<String>,
query: &mut dyn AnyBuilder,
columns: impl IntoIterator<Item = S>,
) -> Result<&mut Self> {
let result = query.build()?;
self.core.ctes.push(CteClause::new(name, result.query, result.bindings, false, strings(columns)));
Ok(self)
}
pub fn with_recursive<S: Into<String>>(
&mut self,
name: impl Into<String>,
query: &mut dyn AnyBuilder,
columns: impl IntoIterator<Item = S>,
) -> Result<&mut Self> {
let result = query.build()?;
self.core.ctes.push(CteClause::new(name, result.query, result.bindings, true, strings(columns)));
Ok(self)
}
pub fn with_recursive_seed_step<S: Into<String>>(
&mut self,
name: impl Into<String>,
seed: &mut dyn AnyBuilder,
step: &mut dyn AnyBuilder,
columns: impl IntoIterator<Item = S>,
) -> Result<&mut Self> {
let seed = seed.build()?;
let step = step.build()?;
let mut bindings = seed.bindings;
bindings.extend(step.bindings);
self.core.ctes.push(CteClause::new(
name,
format!("{} UNION ALL {}", seed.query, step.query),
bindings,
true,
strings(columns),
));
Ok(self)
}
pub fn into(&mut self, table: impl Into<String>) -> &mut Self {
let table = table.into();
self.defer_unbound(&format!("insert into table '{table}'"));
self.core.table = table;
self
}
pub fn insert_as(&mut self, alias: impl Into<String>) -> &mut Self {
self.core.insert_alias = alias.into();
self
}
pub fn set(&mut self, row: Array) -> Result<&mut Self> {
D::set(self, row)?;
Ok(self)
}
pub fn on_conflict<K: Into<String>, U: Into<String>>(
&mut self,
keys: impl IntoIterator<Item = K>,
update_columns: impl IntoIterator<Item = U>,
) -> &mut Self {
self.core.conflict_keys = strings(keys);
self.core.conflict_update_columns = strings(update_columns);
self
}
pub fn from_select<S: Into<String>>(
&mut self,
columns: impl IntoIterator<Item = S>,
source: Box<dyn AnyBuilder>,
) -> &mut Self {
self.core.insert_select_columns = strings(columns);
self.core.insert_select_source = Some(source);
self
}
pub fn insert(&mut self) -> Result<Statement> {
self.check_deferred()?;
D::insert(self)
}
pub fn insert_default_values(&mut self) -> Result<Statement> {
self.check_deferred()?;
D::insert_default_values(self)
}
pub fn insert_select(&mut self) -> Result<Statement> {
self.check_deferred()?;
self.base_insert_select()
}
pub fn update(&mut self) -> Result<Statement> {
self.check_deferred()?;
D::update(self)
}
pub fn delete(&mut self) -> Result<Statement> {
self.check_deferred()?;
D::delete(self)
}
pub fn add_hook(&mut self, hook: impl Into<Hook>) -> Result<&mut Self> {
D::add_hook(self, hook.into())?;
Ok(self)
}
pub fn select_window(
&mut self,
function: impl Into<String>,
alias: impl Into<String>,
partition_by: Option<Vec<String>>,
order_by: Option<Vec<String>>,
window_name: Option<String>,
frame: Option<WindowFrame>,
) -> Result<&mut Self> {
let function = function.into();
if !is_window_function(&function) {
return Err(Error::Validation(format!("Invalid window function: {function}")));
}
self.core.window_selects.push(WindowSelect::new(function, alias, partition_by, order_by, window_name, frame));
Ok(self)
}
pub fn window(
&mut self,
name: impl Into<String>,
partition_by: Option<Vec<String>>,
order_by: Option<Vec<String>>,
frame: Option<WindowFrame>,
) -> &mut Self {
self.core.window_definitions.push(WindowDefinition::new(name, partition_by, order_by, frame));
self
}
pub fn pending(&self) -> &[Query] {
&self.core.pending
}
pub(crate) fn push_case(&mut self, case: CaseExpression) {
self.core.cases.push(case);
}
pub(crate) fn add_lateral(&mut self, subquery: Box<dyn AnyBuilder>, alias: String, join_type: JoinType) {
self.core.lateral_joins.push(LateralJoin { subquery, alias, join_type });
}
}
impl<D: Dialect> Compiler for Builder<D> {
fn compile_filter(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileFilter, &[Arg::Query(query)])
}
fn compile_order(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileOrder, &[Arg::Query(query)])
}
fn compile_limit(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileLimit, &[Arg::Query(query)])
}
fn compile_offset(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileOffset, &[Arg::Query(query)])
}
fn compile_select(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileSelect, &[Arg::Query(query)])
}
fn compile_cursor(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileCursor, &[Arg::Query(query)])
}
fn compile_aggregate(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileAggregate, &[Arg::Query(query)])
}
fn compile_group_by(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileGroupBy, &[Arg::Query(query)])
}
fn compile_join(&mut self, query: &Query) -> Result<String> {
self.step_string(Step::CompileJoin, &[Arg::Query(query)])
}
}
impl<D: Dialect> AnyBuilder for Builder<D> {
fn build(&mut self) -> Result<Statement> {
D::build(self)
}
fn clone_box(&self) -> Box<dyn AnyBuilder> {
Box::new(self.clone())
}
fn php_class(&self) -> &'static str {
D::CLASS
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}