vlorql_core/compile/builder/
mod.rs1use super::dialect_config::{DialectConfig, dialect_from_name};
4use super::types::Parameter;
5use crate::errors::{CompilationErrorKind, VlorQLError};
6use crate::schema::{DataType, Expression, FromClause, Predicate, QueryPlan, SqlDialect};
7use crate::validate::ValidatedPlan;
8use serde_json::{Value, json};
9use std::borrow::Cow;
10use std::collections::HashMap;
11
12pub(crate) mod clause;
13pub(crate) mod expr;
14
15const MYSQL_UNLIMITED_LIMIT: u64 = 18_446_744_073_709_551_615;
18
19pub struct QueryBuilder<'a> {
21 plan: &'a ValidatedPlan,
22 config: &'a DialectConfig,
23 dialect: SqlDialect,
24 parameters: Vec<Parameter>,
25 alias_stack: Vec<HashMap<String, String>>,
26 param_cache: HashMap<(String, DataType), usize>,
27 in_cte: bool,
28}
29
30impl<'a> QueryBuilder<'a> {
31 pub fn new(plan: &'a ValidatedPlan, config: &'a DialectConfig) -> Result<Self, VlorQLError> {
38 let dialect = dialect_from_name(&config.name).ok_or_else(|| {
39 VlorQLError::compilation(
40 CompilationErrorKind::UnsupportedDialectFeature {
41 feature: format!("unknown dialect '{}'", config.name),
42 },
43 json!({"name": &config.name}),
44 )
45 })?;
46 let mut builder = Self {
47 plan,
48 config,
49 dialect,
50 parameters: Vec::new(),
51 alias_stack: Vec::new(),
52 param_cache: HashMap::new(),
53 in_cte: false,
54 };
55 builder.push_alias_scope(plan.as_plan());
56 Ok(builder)
57 }
58
59 fn push_alias_scope(&mut self, plan: &QueryPlan) {
60 let mut map = HashMap::new();
61 Self::collect_aliases(&plan.from, &mut map);
62 if let Some(joins) = &plan.joins {
63 for join in joins {
64 Self::collect_aliases(&join.right_table, &mut map);
65 }
66 }
67 self.alias_stack.push(map);
68 }
69
70 fn collect_aliases(from: &FromClause, map: &mut HashMap<String, String>) {
71 match from {
72 FromClause::Table { table, alias } => {
73 let effective = alias.clone().unwrap_or_else(|| table.clone());
74 map.entry(table.clone())
75 .or_insert_with(|| effective.clone());
76 if let Some(alias) = alias {
77 map.insert(alias.clone(), effective);
78 }
79 }
80 FromClause::Subquery { alias, .. } => {
81 if let Some(alias) = alias {
82 map.insert(alias.clone(), alias.clone());
83 }
84 }
85 }
86 }
87
88 fn resolve_alias<'b>(&self, qualifier: &'b str, max_depth: Option<usize>) -> Cow<'b, str> {
89 self.alias_stack
90 .iter()
91 .rev()
92 .enumerate()
93 .take_while(|(i, _)| max_depth.is_none_or(|d| *i < d))
94 .find_map(|(_, map)| map.get(qualifier))
95 .map(|s| Cow::Owned(s.clone()))
96 .unwrap_or(Cow::Borrowed(qualifier))
97 }
98
99 pub fn build(mut self) -> Result<(String, Vec<Parameter>), VlorQLError> {
101 if dialect_from_name(&self.config.name).is_none() {
102 return Err(compilation_error(
103 "unknown_dialect",
104 json!({"dialect": self.config.name, "accepted": ["postgres", "sqlite", "mysql"]}),
105 ));
106 }
107 tracing::event!(tracing::Level::DEBUG, "Building SQL from QueryPlan");
108 let plan = self.plan.as_plan();
109 let mut sql = String::new();
110 self.build_query(plan, &mut sql)?;
111 Ok((sql, self.parameters))
112 }
113
114 pub fn render_expression(&mut self, expression: &Expression) -> Result<String, VlorQLError> {
116 let mut buf = String::new();
117 self.render_expression_to(expression, &mut buf)?;
118 Ok(buf)
119 }
120
121 pub fn render_predicate(&mut self, predicate: &Predicate) -> Result<String, VlorQLError> {
123 let mut buf = String::new();
124 self.render_predicate_to(predicate, &mut buf)?;
125 Ok(buf)
126 }
127
128 pub fn add_parameter(&mut self, value: Value, data_type: DataType) -> String {
130 let val_str = serde_json::to_string(&value).unwrap_or_default();
131 let key = (val_str, data_type);
132
133 if let Some(&idx) = self.param_cache.get(&key) {
134 if self.config.placeholder.contains("{index}") {
135 return self.config.placeholder_str(idx + 1);
136 }
137 return self.config.placeholder_str(0);
138 }
139
140 let idx = self.parameters.len();
141 self.parameters.push(Parameter { value, data_type });
142 self.param_cache.insert(key, idx);
143 self.config.placeholder_str(idx + 1)
144 }
145
146 pub fn dialect(&self) -> SqlDialect {
148 self.dialect
149 }
150}
151
152fn compilation_error(feature: impl Into<String>, details: Value) -> VlorQLError {
153 VlorQLError::compilation(
154 CompilationErrorKind::UnsupportedDialectFeature {
155 feature: feature.into(),
156 },
157 details,
158 )
159}
160
161fn formatting_error(_error: std::fmt::Error) -> VlorQLError {
162 compilation_error("sql_formatting", json!({"reason": "formatting_failed"}))
163}