1use std::sync::Arc;
5
6use crate::builder::AnyBuilder;
7use crate::builder::case::CaseExpression;
8use crate::builder::core::{
9 AfterBuild, Builder, Dialect, ExistsSubquery, ExplainOptions, LateralJoin, SubSelect, WhereInSubquery,
10};
11use crate::builder::join::JoinBuilder;
12use crate::builder::steps::{Arg, Step};
13use crate::builder::types::{
14 CteClause, Executor, JoinType, Statement, UnionClause, UnionType, WindowDefinition, WindowFrame, WindowSelect,
15};
16use crate::enums::NullsPosition;
17use crate::error::{Error, Result};
18use crate::hook::Hook;
19use crate::method::Method;
20use crate::query::{Compiler, Query};
21use crate::value::{Array, IntoValues, Value};
22
23fn strings<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Vec<String> {
24 items.into_iter().map(Into::into).collect()
25}
26
27fn is_window_function(function: &str) -> bool {
30 let text = function.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
31 let text = text.as_bytes();
32 let is_space = |b: u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0B' | b'\x0C');
33 let mut i = 0;
34 match text.first() {
35 Some(b) if b.is_ascii_alphabetic() || *b == b'_' => i += 1,
36 _ => return false,
37 }
38 while i < text.len() && (text[i].is_ascii_alphanumeric() || text[i] == b'_') {
39 i += 1;
40 }
41 while i < text.len() && is_space(text[i]) {
42 i += 1;
43 }
44 if text.get(i) != Some(&b'(') || text.last() != Some(&b')') || i == text.len() - 1 {
45 return false;
46 }
47 text[i + 1..text.len() - 1]
48 .iter()
49 .all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b',' | b'.' | b'*' | b'"' | b'`') || is_space(b))
50}
51
52impl<D: Dialect> Builder<D> {
53 pub fn from(&mut self, table: impl Into<String>, alias: impl Into<String>) -> &mut Self {
62 self.scoped_from(table.into(), alias.into())
63 }
64
65 pub fn take_refusal(&mut self) -> Option<crate::Error> {
72 self.core.deferred.take()
73 }
74
75 pub fn from_none(&mut self) -> &mut Self {
79 self.from("", "")
80 }
81
82 pub fn from_sub(&mut self, subquery: impl AnyBuilder + 'static, alias: impl Into<String>) -> &mut Self {
86 self.from_sub_boxed(Box::new(subquery), alias)
87 }
88
89 pub fn from_sub_boxed(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
91 self.core.from_subquery = Some(SubSelect { subquery, alias: alias.into() });
92 self.core.table.clear();
93 self
94 }
95
96 pub fn select_sub(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
100 self.core.sub_selects.push(SubSelect { subquery, alias: alias.into() });
101 self
102 }
103
104 pub fn filter_where_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
108 self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: false });
109 self
110 }
111
112 pub fn filter_where_not_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
116 self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: true });
117 self
118 }
119
120 pub fn filter_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
124 self.core.exists_subqueries.push(ExistsSubquery { subquery, not: false });
125 self
126 }
127
128 pub fn filter_not_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
132 self.core.exists_subqueries.push(ExistsSubquery { subquery, not: true });
133 self
134 }
135
136 pub fn select<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
140 self.core.pending.push(Query::select(columns));
141 self
142 }
143
144 pub fn select_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
148 self.core
149 .raw_selects
150 .push(crate::builder::Condition::new(expression, bindings.into_values().values().cloned().collect()));
151 self
152 }
153
154 pub fn distinct(&mut self) -> &mut Self {
158 self.core.pending.push(Query::distinct());
159 self
160 }
161
162 pub fn filter(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
166 self.core.pending.extend(queries);
167 self
168 }
169
170 pub fn queries(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
174 self.core.pending.extend(queries);
175 self
176 }
177
178 pub fn sort_asc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
182 self.core.pending.push(Query::order_asc(attribute, nulls));
183 self
184 }
185
186 pub fn sort_desc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
190 self.core.pending.push(Query::order_desc(attribute, nulls));
191 self
192 }
193
194 pub fn sort_random(&mut self) -> &mut Self {
198 self.core.pending.push(Query::order_random());
199 self
200 }
201
202 pub fn limit(&mut self, value: i64) -> &mut Self {
206 self.core.pending.push(Query::limit(value));
207 self
208 }
209
210 pub fn offset(&mut self, value: i64) -> &mut Self {
214 self.core.pending.push(Query::offset(value));
215 self
216 }
217
218 pub fn fetch(&mut self, count: i64, with_ties: bool) -> &mut Self {
222 self.core.fetch_count = Some(count);
223 self.core.fetch_with_ties = with_ties;
224 self
225 }
226
227 pub fn page(&mut self, page: i64, per_page: i64) -> Result<&mut Self> {
231 let [limit, offset] = Query::page(page, per_page)?;
232 self.core.pending.push(limit);
233 self.core.pending.push(offset);
234 Ok(self)
235 }
236
237 pub fn cursor_after(&mut self, row: Value) -> &mut Self {
241 self.core.pending.push(Query::cursor_after(row));
242 self
243 }
244
245 pub fn cursor_before(&mut self, row: Value) -> &mut Self {
249 self.core.pending.push(Query::cursor_before(row));
250 self
251 }
252
253 pub fn when(&mut self, condition: bool, callback: impl FnOnce(&mut Self) -> Result<()>) -> Result<&mut Self> {
257 if condition {
258 callback(self)?;
259 }
260 Ok(self)
261 }
262
263 pub fn before_build(&mut self, callback: impl Fn(&mut Self) -> Result<()> + Send + Sync + 'static) -> &mut Self {
267 self.before_build.push(Arc::new(callback));
268 self
269 }
270
271 pub fn after_build(
275 &mut self,
276 callback: impl Fn(Statement) -> Result<Statement> + Send + Sync + 'static,
277 ) -> &mut Self {
278 self.after_build_owned(move |_, statement| callback(statement))
279 }
280
281 pub fn after_build_owned(
283 &mut self,
284 callback: impl Fn(usize, Statement) -> Result<Statement> + Send + Sync + 'static,
285 ) -> &mut Self {
286 let callback: AfterBuild = Arc::new(callback);
287 self.core.after_build.push(callback);
288 self
289 }
290
291 pub fn set_executor(&mut self, executor: Executor) -> &mut Self {
295 self.core.executor = Some(executor);
296 self
297 }
298
299 pub fn explain(&mut self, analyze: bool) -> Result<Statement> {
303 D::explain(self, analyze, &ExplainOptions::default())
304 }
305
306 pub fn explain_with(&mut self, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
310 D::explain(self, analyze, options)
311 }
312
313 pub fn execute(&mut self) -> Result<Value> {
317 self.build()?.execute()
318 }
319
320 pub fn to_raw_sql(&mut self) -> Result<String> {
327 self.raw_sql(false)
328 }
329
330 pub fn to_raw_sql_widened(&mut self) -> Result<String> {
334 self.raw_sql(true)
335 }
336
337 fn raw_sql(&mut self, widened: bool) -> Result<String> {
338 let result = self.built()?;
339 let mut sql = result.query;
340 let mut offset = 0;
341 for binding in &result.bindings {
342 let literal = match binding {
343 Value::Str(s) if widened => {
344 D::LITERAL.quote(&s.as_bytes().iter().map(|&b| char::from(b)).collect::<String>())?
345 }
346 Value::Str(s) => D::LITERAL.quote(&String::from_utf8_lossy(s.as_bytes()))?,
347 Value::Int(_) | Value::Float(_) => crate::value::to_php_string(binding),
348 Value::Bool(b) => if *b { "1" } else { "0" }.to_owned(),
349 _ => "NULL".to_owned(),
350 };
351 if let Some(pos) = sql.get(offset..).and_then(|rest| rest.find('?')).map(|p| p + offset) {
352 sql.replace_range(pos..=pos, &literal);
353 offset = pos + literal.len();
354 }
355 }
356 Ok(sql)
357 }
358
359 pub fn binding_list(&self) -> &[crate::builder::Binding] {
363 &self.core.bindings
364 }
365
366 pub fn set_binding_list(&mut self, bindings: Vec<crate::builder::Binding>) -> &mut Self {
368 self.core.bindings = bindings;
369 self
370 }
371
372 pub fn set_pending(&mut self, queries: Vec<Query>) -> &mut Self {
376 self.core.pending = queries;
377 self
378 }
379
380 pub fn resolved_attributes(&self) -> impl Iterator<Item = (&str, &str)> {
384 self.core.resolved.iter().map(|(attribute, resolved)| (attribute.as_str(), resolved.as_str()))
385 }
386
387 pub fn set_resolved_attributes(&mut self, resolved: impl IntoIterator<Item = (String, String)>) -> &mut Self {
389 self.core.resolved = resolved.into_iter().collect();
390 self
391 }
392
393 pub fn bindings(&mut self) -> Vec<Value> {
397 self.binding_values()
398 }
399
400 pub fn reset(&mut self) -> &mut Self {
404 let core = &mut self.core;
405 core.pending.clear();
406 core.bindings.clear();
407 core.resolved.clear();
408 core.table.clear();
409 core.alias.clear();
410 core.unions.clear();
411 core.rows.clear();
412 core.raw_sets.clear();
413 core.raw_set_bindings.clear();
414 core.conflict_keys.clear();
415 core.conflict_update_columns.clear();
416 core.conflict_raw_sets.clear();
417 core.conflict_raw_set_bindings.clear();
418 core.insert_column_expressions.clear();
419 core.insert_column_expression_bindings.clear();
420 core.insert_alias.clear();
421 core.lock_mode = None;
422 core.lock_of_table = None;
423 core.insert_select_source = None;
424 core.insert_select_columns.clear();
425 core.ctes.clear();
426 core.raw_selects.clear();
427 core.window_selects.clear();
428 core.window_definitions.clear();
429 core.sample = None;
430 core.cases.clear();
431 core.case_sets.clear();
432 core.where_in_subqueries.clear();
433 core.sub_selects.clear();
434 core.from_subquery = None;
435 core.tableless = false;
436 core.raw_orders.clear();
437 core.raw_groups.clear();
438 core.raw_havings.clear();
439 core.raw_wheres.clear();
440 core.column_predicates.clear();
441 core.joins.clear();
442 core.exists_subqueries.clear();
443 core.lateral_joins.clear();
444 core.after_build.clear();
445 core.fetch_count = None;
446 core.fetch_with_ties = false;
447 core.qualify = false;
448 core.aggregation_aliases.clear();
449 self.before_build.clear();
450 D::reset(self);
451 self
452 }
453
454 pub fn build(&mut self) -> Result<Statement> {
458 self.scoped_build()
459 }
460
461 pub fn count(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
465 self.core.pending.push(Query::count(attribute, alias));
466 self
467 }
468
469 pub fn count_distinct(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
473 self.core.pending.push(Query::count_distinct(attribute, alias));
474 self
475 }
476
477 pub fn sum(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
481 self.core.pending.push(Query::sum(attribute, alias));
482 self
483 }
484
485 pub fn avg(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
489 self.core.pending.push(Query::avg(attribute, alias));
490 self
491 }
492
493 pub fn min(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
497 self.core.pending.push(Query::min(attribute, alias));
498 self
499 }
500
501 pub fn max(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
505 self.core.pending.push(Query::max(attribute, alias));
506 self
507 }
508
509 pub fn group_by<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
513 self.core.pending.push(Query::group_by(columns));
514 self
515 }
516
517 pub fn group_by_time_bucket(&mut self, attribute: impl Into<String>, interval: &str) -> Result<&mut Self> {
521 self.core.pending.push(Query::group_by_time_bucket(attribute, interval)?);
522 Ok(self)
523 }
524
525 pub fn having(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
529 self.core.pending.push(Query::having(queries));
530 self
531 }
532
533 fn join_on(
534 &mut self,
535 method: Method,
536 table: String,
537 left: &str,
538 right: &str,
539 operator: &str,
540 alias: String,
541 ) -> &mut Self {
542 let on = Query::on(left, right, operator);
543 self.core.pending.push(Query::new(method, table, crate::value::list([on]), alias));
544 self
545 }
546
547 pub fn join(
551 &mut self,
552 table: impl Into<String>,
553 left: &str,
554 right: &str,
555 operator: &str,
556 alias: impl Into<String>,
557 ) -> &mut Self {
558 self.join_on(Method::Join, table.into(), left, right, operator, alias.into())
559 }
560
561 pub fn left_join(
565 &mut self,
566 table: impl Into<String>,
567 left: &str,
568 right: &str,
569 operator: &str,
570 alias: impl Into<String>,
571 ) -> &mut Self {
572 self.join_on(Method::LeftJoin, table.into(), left, right, operator, alias.into())
573 }
574
575 pub fn right_join(
579 &mut self,
580 table: impl Into<String>,
581 left: &str,
582 right: &str,
583 operator: &str,
584 alias: impl Into<String>,
585 ) -> &mut Self {
586 self.join_on(Method::RightJoin, table.into(), left, right, operator, alias.into())
587 }
588
589 pub fn join_where(
593 &mut self,
594 table: impl Into<String>,
595 callback: impl FnOnce(&mut JoinBuilder) -> Result<()>,
596 join_type: JoinType,
597 alias: impl Into<String>,
598 ) -> Result<&mut Self> {
599 let mut join = JoinBuilder::new();
600 callback(&mut join)?;
601 let method = match join_type {
602 JoinType::Left => Method::LeftJoin,
603 JoinType::Right => Method::RightJoin,
604 JoinType::Cross => Method::CrossJoin,
605 JoinType::FullOuter => Method::FullOuterJoin,
606 JoinType::Natural => Method::NaturalJoin,
607 JoinType::Inner => Method::Join,
608 };
609 self.core.pending.push(Query::new(method, table, Array::default(), alias));
610 let index = self.core.pending.len() - 1;
611 self.core.joins.insert(index, join);
612 Ok(self)
613 }
614
615 fn union_with(&mut self, union_type: UnionType, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
616 let result = other.build()?;
617 self.core.unions.push(UnionClause::new(union_type, result.query, result.bindings));
618 Ok(self)
619 }
620
621 pub fn union(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
625 self.union_with(UnionType::Union, other)
626 }
627
628 pub fn union_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
632 self.union_with(UnionType::UnionAll, other)
633 }
634
635 pub fn intersect(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
639 self.union_with(UnionType::Intersect, other)
640 }
641
642 pub fn intersect_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
646 self.union_with(UnionType::IntersectAll, other)
647 }
648
649 pub fn except(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
653 self.union_with(UnionType::Except, other)
654 }
655
656 pub fn except_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
660 self.union_with(UnionType::ExceptAll, other)
661 }
662
663 pub fn with<S: Into<String>>(
667 &mut self,
668 name: impl Into<String>,
669 query: &mut dyn AnyBuilder,
670 columns: impl IntoIterator<Item = S>,
671 ) -> Result<&mut Self> {
672 let result = query.build()?;
673 self.core.ctes.push(CteClause::new(name, result.query, result.bindings, false, strings(columns)));
674 Ok(self)
675 }
676
677 pub fn with_recursive<S: Into<String>>(
681 &mut self,
682 name: impl Into<String>,
683 query: &mut dyn AnyBuilder,
684 columns: impl IntoIterator<Item = S>,
685 ) -> Result<&mut Self> {
686 let result = query.build()?;
687 self.core.ctes.push(CteClause::new(name, result.query, result.bindings, true, strings(columns)));
688 Ok(self)
689 }
690
691 pub fn with_recursive_seed_step<S: Into<String>>(
695 &mut self,
696 name: impl Into<String>,
697 seed: &mut dyn AnyBuilder,
698 step: &mut dyn AnyBuilder,
699 columns: impl IntoIterator<Item = S>,
700 ) -> Result<&mut Self> {
701 let seed = seed.build()?;
702 let step = step.build()?;
703 let mut bindings = seed.bindings;
704 bindings.extend(step.bindings);
705 self.core.ctes.push(CteClause::new(
706 name,
707 format!("{} UNION ALL {}", seed.query, step.query),
708 bindings,
709 true,
710 strings(columns),
711 ));
712 Ok(self)
713 }
714
715 pub fn into(&mut self, table: impl Into<String>) -> &mut Self {
719 let table = table.into();
720 self.defer_unbound(&format!("insert into table '{table}'"));
721 self.core.table = table;
722 self
723 }
724
725 pub fn insert_as(&mut self, alias: impl Into<String>) -> &mut Self {
729 self.core.insert_alias = alias.into();
730 self
731 }
732
733 pub fn set(&mut self, row: Array) -> Result<&mut Self> {
737 D::set(self, row)?;
738 Ok(self)
739 }
740
741 pub fn on_conflict<K: Into<String>, U: Into<String>>(
745 &mut self,
746 keys: impl IntoIterator<Item = K>,
747 update_columns: impl IntoIterator<Item = U>,
748 ) -> &mut Self {
749 self.core.conflict_keys = strings(keys);
750 self.core.conflict_update_columns = strings(update_columns);
751 self
752 }
753
754 pub fn from_select<S: Into<String>>(
758 &mut self,
759 columns: impl IntoIterator<Item = S>,
760 source: Box<dyn AnyBuilder>,
761 ) -> &mut Self {
762 self.core.insert_select_columns = strings(columns);
763 self.core.insert_select_source = Some(source);
764 self
765 }
766
767 pub fn insert(&mut self) -> Result<Statement> {
771 self.check_deferred()?;
772 D::insert(self)
773 }
774
775 pub fn insert_default_values(&mut self) -> Result<Statement> {
779 self.check_deferred()?;
780 D::insert_default_values(self)
781 }
782
783 pub fn insert_select(&mut self) -> Result<Statement> {
787 self.check_deferred()?;
788 self.base_insert_select()
789 }
790
791 pub fn update(&mut self) -> Result<Statement> {
795 self.check_deferred()?;
796 D::update(self)
797 }
798
799 pub fn delete(&mut self) -> Result<Statement> {
803 self.check_deferred()?;
804 D::delete(self)
805 }
806
807 pub fn add_hook(&mut self, hook: impl Into<Hook>) -> Result<&mut Self> {
811 D::add_hook(self, hook.into())?;
812 Ok(self)
813 }
814
815 pub fn select_window(
820 &mut self,
821 function: impl Into<String>,
822 alias: impl Into<String>,
823 partition_by: Option<Vec<String>>,
824 order_by: Option<Vec<String>>,
825 window_name: Option<String>,
826 frame: Option<WindowFrame>,
827 ) -> Result<&mut Self> {
828 let function = function.into();
829 if !is_window_function(&function) {
830 return Err(Error::Validation(format!("Invalid window function: {function}")));
831 }
832 self.core.window_selects.push(WindowSelect::new(function, alias, partition_by, order_by, window_name, frame));
833 Ok(self)
834 }
835
836 pub fn window(
840 &mut self,
841 name: impl Into<String>,
842 partition_by: Option<Vec<String>>,
843 order_by: Option<Vec<String>>,
844 frame: Option<WindowFrame>,
845 ) -> &mut Self {
846 self.core.window_definitions.push(WindowDefinition::new(name, partition_by, order_by, frame));
847 self
848 }
849
850 pub fn pending(&self) -> &[Query] {
852 &self.core.pending
853 }
854
855 pub(crate) fn push_case(&mut self, case: CaseExpression) {
856 self.core.cases.push(case);
857 }
858
859 pub(crate) fn add_lateral(&mut self, subquery: Box<dyn AnyBuilder>, alias: String, join_type: JoinType) {
860 self.core.lateral_joins.push(LateralJoin { subquery, alias, join_type });
861 }
862}
863
864impl<D: Dialect> Compiler for Builder<D> {
865 fn compile_filter(&mut self, query: &Query) -> Result<String> {
866 self.step_string(Step::CompileFilter, &[Arg::Query(query)])
867 }
868
869 fn compile_order(&mut self, query: &Query) -> Result<String> {
870 self.step_string(Step::CompileOrder, &[Arg::Query(query)])
871 }
872
873 fn compile_limit(&mut self, query: &Query) -> Result<String> {
874 self.step_string(Step::CompileLimit, &[Arg::Query(query)])
875 }
876
877 fn compile_offset(&mut self, query: &Query) -> Result<String> {
878 self.step_string(Step::CompileOffset, &[Arg::Query(query)])
879 }
880
881 fn compile_select(&mut self, query: &Query) -> Result<String> {
882 self.step_string(Step::CompileSelect, &[Arg::Query(query)])
883 }
884
885 fn compile_cursor(&mut self, query: &Query) -> Result<String> {
886 self.step_string(Step::CompileCursor, &[Arg::Query(query)])
887 }
888
889 fn compile_aggregate(&mut self, query: &Query) -> Result<String> {
890 self.step_string(Step::CompileAggregate, &[Arg::Query(query)])
891 }
892
893 fn compile_group_by(&mut self, query: &Query) -> Result<String> {
894 self.step_string(Step::CompileGroupBy, &[Arg::Query(query)])
895 }
896
897 fn compile_join(&mut self, query: &Query) -> Result<String> {
898 self.step_string(Step::CompileJoin, &[Arg::Query(query)])
899 }
900}
901
902impl<D: Dialect> AnyBuilder for Builder<D> {
903 fn build(&mut self) -> Result<Statement> {
904 D::build(self)
905 }
906
907 fn clone_box(&self) -> Box<dyn AnyBuilder> {
908 Box::new(self.clone())
909 }
910
911 fn php_class(&self) -> &'static str {
912 D::CLASS
913 }
914
915 fn as_any(&self) -> &dyn std::any::Any {
916 self
917 }
918}