Skip to main content

vlorql_core/compile/
builder.rs

1//! Dialect-aware parameterized SQL construction.
2
3/// MySQL's maximum unsigned bigint value, used as a sentinel to represent
4/// "no limit" when only OFFSET is specified (LIMIT offset, <unlimited>).
5const MYSQL_UNLIMITED_LIMIT: u64 = 18446744073709551615;
6
7use super::types::Parameter;
8use crate::errors::{CompilationErrorKind, VlorQLError};
9use crate::schema::{
10    BinaryOperator, ComparisonOperator, DataType, Expression, FromClause, IdentifierQuoting,
11    InTarget, JoinType, Predicate, Projection, QueryPlan, SqlDialect,
12};
13use crate::validate::ValidatedPlan;
14use serde_json::{json, Value};
15use std::borrow::Cow;
16use std::fmt::Write;
17
18/// Builds SQL while preserving the exact textual order of bind parameters.
19pub struct QueryBuilder<'a> {
20    plan: &'a ValidatedPlan,
21    dialect: SqlDialect,
22    parameters: Vec<Parameter>,
23    quote_style: IdentifierQuoting,
24}
25
26impl<'a> QueryBuilder<'a> {
27    /// Creates a builder for one validated plan and output dialect.
28    pub fn new(
29        plan: &'a ValidatedPlan,
30        dialect: SqlDialect,
31        quote_style: IdentifierQuoting,
32    ) -> Self {
33        Self {
34            plan,
35            dialect,
36            parameters: Vec::new(),
37            quote_style,
38        }
39    }
40
41    /// Builds a SQL string and returns its parameters in placeholder order.
42    pub fn build(mut self) -> Result<(String, Vec<Parameter>), VlorQLError> {
43        tracing::event!(tracing::Level::DEBUG, "Building SQL from QueryPlan");
44        let plan = self.plan.as_plan();
45        let mut sql = String::new();
46        self.build_query(plan, &mut sql)?;
47        Ok((sql, self.parameters))
48    }
49
50    /// Renders one expression and appends any literal parameters to this builder.
51    pub fn render_expression(&mut self, expression: &Expression) -> Result<String, VlorQLError> {
52        let mut buf = String::new();
53        self.render_expression_to(expression, &mut buf)?;
54        Ok(buf)
55    }
56
57    /// Renders one expression into `buf`, avoiding intermediate allocations.
58    pub fn render_expression_to(
59        &mut self,
60        expression: &Expression,
61        buf: &mut String,
62    ) -> Result<(), VlorQLError> {
63        match expression {
64            Expression::Literal { value, data_type } => {
65                buf.push_str(&self.add_parameter(value.clone(), *data_type));
66                Ok(())
67            }
68            Expression::ColumnRef { table, column } => {
69                buf.push_str(&self.render_qualified_identifier(table.as_deref(), column)?);
70                Ok(())
71            }
72            Expression::FunctionCall {
73                name,
74                args,
75                distinct,
76            } => {
77                let function = self.render_function_name(name)?;
78                buf.push_str(&function);
79                buf.push('(');
80                if *distinct {
81                    buf.push_str("DISTINCT ");
82                }
83                for (i, argument) in args.iter().enumerate() {
84                    if i > 0 {
85                        buf.push_str(", ");
86                    }
87                    self.render_expression_to(argument, buf)?;
88                }
89                buf.push(')');
90                Ok(())
91            }
92            Expression::BinaryOp { left, op, right } => {
93                buf.push('(');
94                self.render_expression_to(left, buf)?;
95                write!(buf, " {} ", self.render_binary_operator(*op)).map_err(formatting_error)?;
96                self.render_expression_to(right, buf)?;
97                buf.push(')');
98                Ok(())
99            }
100            Expression::Star => {
101                buf.push('*');
102                Ok(())
103            }
104            Expression::SubQuery { query } => {
105                buf.push('(');
106                self.build_query(query, buf)?;
107                buf.push(')');
108                Ok(())
109            }
110        }
111    }
112
113    /// Renders one predicate and appends literal values as bind parameters.
114    pub fn render_predicate(&mut self, predicate: &Predicate) -> Result<String, VlorQLError> {
115        let mut buf = String::new();
116        self.render_predicate_to(predicate, &mut buf)?;
117        Ok(buf)
118    }
119
120    /// Renders one predicate into `buf`, avoiding intermediate allocations.
121    pub fn render_predicate_to(
122        &mut self,
123        predicate: &Predicate,
124        buf: &mut String,
125    ) -> Result<(), VlorQLError> {
126        match predicate {
127            Predicate::Comparison { left, op, right } => {
128                self.render_expression_to(left, buf)?;
129                write!(buf, " {} ", self.render_comparison_operator(*op)?)
130                    .map_err(formatting_error)?;
131                self.render_expression_to(right, buf)
132            }
133            Predicate::And { left, right } => {
134                buf.push('(');
135                self.render_predicate_to(left, buf)?;
136                buf.push_str(") AND (");
137                self.render_predicate_to(right, buf)?;
138                buf.push(')');
139                Ok(())
140            }
141            Predicate::Or { left, right } => {
142                buf.push('(');
143                self.render_predicate_to(left, buf)?;
144                buf.push_str(") OR (");
145                self.render_predicate_to(right, buf)?;
146                buf.push(')');
147                Ok(())
148            }
149            Predicate::Not { child } => {
150                buf.push_str("NOT (");
151                self.render_predicate_to(child, buf)?;
152                buf.push(')');
153                Ok(())
154            }
155            Predicate::Between { expr, low, high } => {
156                self.render_expression_to(expr, buf)?;
157                buf.push_str(" BETWEEN ");
158                self.render_expression_to(low, buf)?;
159                buf.push_str(" AND ");
160                self.render_expression_to(high, buf)
161            }
162            Predicate::In { expr, target } => {
163                self.render_expression_to(expr, buf)?;
164                match target {
165                    InTarget::Values(values) => {
166                        if values.is_empty() {
167                            return Err(compilation_error(
168                                "empty_in_list",
169                                json!({"predicate": "in"}),
170                            ));
171                        }
172                        buf.push_str(" IN (");
173                        for (i, value) in values.iter().enumerate() {
174                            if i > 0 {
175                                buf.push_str(", ");
176                            }
177                            self.render_expression_to(value, buf)?;
178                        }
179                        buf.push(')');
180                        Ok(())
181                    }
182                    InTarget::SubQuery(query) => {
183                        buf.push_str(" IN (");
184                        self.build_query(query, buf)?;
185                        buf.push(')');
186                        Ok(())
187                    }
188                }
189            }
190            Predicate::Exists { query } => {
191                buf.push_str("EXISTS (");
192                self.build_query(query, buf)?;
193                buf.push(')');
194                Ok(())
195            }
196            Predicate::Like { expr, pattern } => {
197                self.render_expression_to(expr, buf)?;
198                let placeholder =
199                    self.add_parameter(Value::String(pattern.clone()), DataType::String);
200                write!(buf, " LIKE {placeholder}").map_err(formatting_error)
201            }
202            Predicate::IsNull { expr } => {
203                self.render_expression_to(expr, buf)?;
204                buf.push_str(" IS NULL");
205                Ok(())
206            }
207        }
208    }
209
210    /// Adds a parameter and returns the placeholder for the selected dialect.
211    pub fn add_parameter(&mut self, value: Value, data_type: DataType) -> String {
212        self.parameters.push(Parameter { value, data_type });
213        match self.dialect {
214            SqlDialect::Postgres => format!("${}", self.parameters.len()),
215            SqlDialect::Sqlite | SqlDialect::MySql => "?".to_owned(),
216        }
217    }
218
219    /// Returns the dialect selected for this builder.
220    pub fn dialect(&self) -> SqlDialect {
221        self.dialect
222    }
223
224    fn build_query(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
225        self.build_with(plan, sql)?;
226        self.build_select(plan, sql)?;
227        self.build_from(plan, sql)?;
228        self.build_where(plan, sql)?;
229        self.build_group_by(plan, sql)?;
230        self.build_having(plan, sql)?;
231        self.build_order_by(plan, sql)?;
232        self.build_limit_offset(plan, sql)?;
233        Ok(())
234    }
235
236    fn build_with(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
237        let Some(ctes) = plan.ctes.as_ref().filter(|ctes| !ctes.is_empty()) else {
238            return Ok(());
239        };
240
241        sql.push_str("WITH ");
242        for (index, cte) in ctes.iter().enumerate() {
243            if index > 0 {
244                sql.push_str(", ");
245            }
246            let name = self.quote_identifier(&cte.name)?;
247            write!(sql, "{name} AS (").map_err(formatting_error)?;
248            self.build_query(&cte.query, sql)?;
249            sql.push(')');
250        }
251        sql.push(' ');
252        Ok(())
253    }
254
255    fn build_select(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
256        if plan.select.is_empty() {
257            return Err(compilation_error(
258                "empty_select_list",
259                json!({"clause": "select"}),
260            ));
261        }
262
263        sql.push_str("SELECT ");
264        for (index, projection) in plan.select.iter().enumerate() {
265            if index > 0 {
266                sql.push_str(", ");
267            }
268            match projection {
269                Projection::Star { table: None } => sql.push('*'),
270                Projection::Star { table: Some(table) } => {
271                    write!(sql, "{}.*", self.quote_identifier(table)?).map_err(formatting_error)?;
272                }
273                Projection::Column {
274                    table,
275                    column,
276                    alias,
277                } => {
278                    sql.push_str(&self.render_qualified_identifier(table.as_deref(), column)?);
279                    if let Some(alias) = alias {
280                        write!(sql, " AS {}", self.quote_identifier(alias)?)
281                            .map_err(formatting_error)?;
282                    }
283                }
284                Projection::Expr { expression, alias } => {
285                    sql.push_str(&self.render_expression(expression)?);
286                    if let Some(alias) = alias {
287                        write!(sql, " AS {}", self.quote_identifier(alias)?)
288                            .map_err(formatting_error)?;
289                    }
290                }
291            }
292        }
293        Ok(())
294    }
295
296    fn build_from(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
297        sql.push_str(" FROM ");
298        sql.push_str(&self.render_from_clause(&plan.from)?);
299
300        if let Some(joins) = &plan.joins {
301            for join in joins {
302                write!(
303                    sql,
304                    " {} {}",
305                    self.render_join_type(join.join_type)?,
306                    self.render_from_clause(&join.right_table)?
307                )
308                .map_err(formatting_error)?;
309                if join.join_type != JoinType::Cross {
310                    let condition = self.render_predicate(&join.on)?;
311                    write!(sql, " ON {condition}").map_err(formatting_error)?;
312                }
313            }
314        }
315        Ok(())
316    }
317
318    fn build_where(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
319        if let Some(predicate) = &plan.r#where {
320            let predicate = self.render_predicate(predicate)?;
321            write!(sql, " WHERE {predicate}").map_err(formatting_error)?;
322        }
323        Ok(())
324    }
325
326    fn build_group_by(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
327        let Some(expressions) = plan
328            .group_by
329            .as_ref()
330            .filter(|expressions| !expressions.is_empty())
331        else {
332            return Ok(());
333        };
334
335        let mut rendered = Vec::with_capacity(expressions.len());
336        for expression in expressions {
337            rendered.push(self.render_expression(expression)?);
338        }
339        write!(sql, " GROUP BY {}", rendered.join(", ")).map_err(formatting_error)
340    }
341
342    fn build_having(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
343        if let Some(predicate) = &plan.having {
344            let predicate = self.render_predicate(predicate)?;
345            write!(sql, " HAVING {predicate}").map_err(formatting_error)?;
346        }
347        Ok(())
348    }
349
350    fn build_order_by(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
351        let Some(terms) = plan.order_by.as_ref().filter(|terms| !terms.is_empty()) else {
352            return Ok(());
353        };
354
355        let mut rendered = Vec::with_capacity(terms.len());
356        for term in terms {
357            let expression = self.render_expression(&term.expr)?;
358            let direction = if term.descending { "DESC" } else { "ASC" };
359            rendered.push(format!("{expression} {direction}"));
360        }
361        write!(sql, " ORDER BY {}", rendered.join(", ")).map_err(formatting_error)
362    }
363
364    fn build_limit_offset(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
365        match (self.dialect, plan.limit, plan.offset) {
366            (SqlDialect::MySql, Some(limit), Some(offset)) => {
367                let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
368                let limit_ph = self.add_parameter(Value::from(limit), DataType::Int);
369                write!(sql, " LIMIT {offset_ph}, {limit_ph}").map_err(formatting_error)
370            }
371            (SqlDialect::MySql, Some(limit), None) => {
372                let limit_ph = self.add_parameter(Value::from(limit), DataType::Int);
373                write!(sql, " LIMIT {limit_ph}").map_err(formatting_error)
374            }
375            (SqlDialect::MySql, None, Some(offset)) => {
376                let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
377                write!(sql, " LIMIT {offset_ph}, {MYSQL_UNLIMITED_LIMIT}").map_err(formatting_error)
378            }
379            (SqlDialect::Sqlite, None, Some(offset)) => {
380                let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
381                write!(sql, " LIMIT -1 OFFSET {offset_ph}").map_err(formatting_error)
382            }
383            (_, limit, offset) => {
384                if let Some(limit) = limit {
385                    let limit_ph = self.add_parameter(Value::from(limit), DataType::Int);
386                    write!(sql, " LIMIT {limit_ph}").map_err(formatting_error)?;
387                }
388                if let Some(offset) = offset {
389                    let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
390                    write!(sql, " OFFSET {offset_ph}").map_err(formatting_error)?;
391                }
392                Ok(())
393            }
394        }
395    }
396
397    fn render_from_clause(&self, from: &FromClause) -> Result<String, VlorQLError> {
398        let table = self.quote_identifier(&from.table)?;
399        match &from.alias {
400            Some(alias) => Ok(format!("{table} AS {}", self.quote_identifier(alias)?)),
401            None => Ok(table),
402        }
403    }
404
405    fn render_qualified_identifier(
406        &self,
407        qualifier: Option<&str>,
408        identifier: &str,
409    ) -> Result<String, VlorQLError> {
410        let identifier = self.quote_identifier(identifier)?;
411        match qualifier {
412            Some(qualifier) => Ok(format!(
413                "{}.{}",
414                self.quote_identifier(qualifier)?,
415                identifier
416            )),
417            None => Ok(identifier),
418        }
419    }
420
421    fn quote_identifier(&self, identifier: &str) -> Result<String, VlorQLError> {
422        if identifier.is_empty() {
423            return Err(compilation_error(
424                "empty_identifier",
425                json!({"identifier": identifier}),
426            ));
427        }
428
429        match self.effective_quote_style() {
430            IdentifierQuoting::Never => {
431                validate_unquoted_identifier(identifier)?;
432                Ok(identifier.to_owned())
433            }
434            IdentifierQuoting::DoubleQuote => {
435                Ok(format!("\"{}\"", identifier.replace('"', "\"\"")))
436            }
437            IdentifierQuoting::Backtick => Ok(format!("`{}`", identifier.replace('`', "``"))),
438            IdentifierQuoting::Always => Err(compilation_error(
439                "unresolved_quote_style",
440                json!({"identifier": identifier}),
441            )),
442        }
443    }
444
445    fn effective_quote_style(&self) -> IdentifierQuoting {
446        match self.quote_style {
447            IdentifierQuoting::Always => match self.dialect {
448                SqlDialect::MySql => IdentifierQuoting::Backtick,
449                SqlDialect::Postgres | SqlDialect::Sqlite => IdentifierQuoting::DoubleQuote,
450            },
451            quote_style => quote_style,
452        }
453    }
454
455    fn render_function_name<'b>(&self, function: &'b str) -> Result<Cow<'b, str>, VlorQLError> {
456        if function.is_empty() {
457            return Err(compilation_error(
458                "empty_function_name",
459                json!({"function": function}),
460            ));
461        }
462        for segment in function.split('.') {
463            validate_unquoted_identifier(segment)?;
464        }
465        Ok(Cow::Borrowed(function))
466    }
467
468    fn render_binary_operator(&self, operator: BinaryOperator) -> &'static str {
469        match operator {
470            BinaryOperator::Add => "+",
471            BinaryOperator::Sub => "-",
472            BinaryOperator::Mul => "*",
473            BinaryOperator::Div => "/",
474            BinaryOperator::Mod => "%",
475            BinaryOperator::And => "AND",
476            BinaryOperator::Or => "OR",
477            BinaryOperator::Eq => "=",
478            BinaryOperator::Neq => "<>",
479            BinaryOperator::Gt => ">",
480            BinaryOperator::Lt => "<",
481            BinaryOperator::Gte => ">=",
482            BinaryOperator::Lte => "<=",
483            BinaryOperator::Like => "LIKE",
484            BinaryOperator::ILike if self.dialect == SqlDialect::Postgres => "ILIKE",
485            BinaryOperator::ILike => "LIKE",
486        }
487    }
488
489    fn render_comparison_operator(
490        &self,
491        operator: ComparisonOperator,
492    ) -> Result<&'static str, VlorQLError> {
493        match operator {
494            ComparisonOperator::Eq => Ok("="),
495            ComparisonOperator::Neq => Ok("<>"),
496            ComparisonOperator::Gt => Ok(">"),
497            ComparisonOperator::Lt => Ok("<"),
498            ComparisonOperator::Gte => Ok(">="),
499            ComparisonOperator::Lte => Ok("<="),
500            ComparisonOperator::Like => Ok("LIKE"),
501            ComparisonOperator::ILike if self.dialect == SqlDialect::Postgres => Ok("ILIKE"),
502            ComparisonOperator::ILike => Ok("LIKE"),
503            ComparisonOperator::In => Err(compilation_error(
504                "comparison_in_requires_in_predicate",
505                json!({"operator": operator}),
506            )),
507            ComparisonOperator::Between => Err(compilation_error(
508                "comparison_between_requires_between_predicate",
509                json!({"operator": operator}),
510            )),
511        }
512    }
513
514    fn render_join_type(&self, join_type: JoinType) -> Result<&'static str, VlorQLError> {
515        match join_type {
516            JoinType::Full if self.dialect == SqlDialect::MySql => Err(compilation_error(
517                "unsupported_full_join",
518                json!({"dialect": "mysql", "join_type": "full"}),
519            )),
520            JoinType::Inner => Ok("INNER JOIN"),
521            JoinType::Left => Ok("LEFT JOIN"),
522            JoinType::Right => Ok("RIGHT JOIN"),
523            JoinType::Full => Ok("FULL JOIN"),
524            JoinType::Cross => Ok("CROSS JOIN"),
525        }
526    }
527}
528
529fn validate_unquoted_identifier(identifier: &str) -> Result<(), VlorQLError> {
530    let mut characters = identifier.chars();
531    let valid_start = characters
532        .next()
533        .is_some_and(|character| character == '_' || character.is_ascii_alphabetic());
534    let valid_rest =
535        characters.all(|character| character == '_' || character.is_ascii_alphanumeric());
536    if !valid_start || !valid_rest {
537        return Err(compilation_error(
538            "invalid_unquoted_identifier",
539            json!({"identifier": identifier}),
540        ));
541    }
542    if is_reserved_keyword(identifier) {
543        return Err(compilation_error(
544            "reserved_keyword_unquoted",
545            json!({"identifier": identifier}),
546        ));
547    }
548    Ok(())
549}
550
551/// Standard SQL reserved keywords.  Sorted alphabetically for binary search.
552static RESERVED_KEYWORDS: &[&str] = &[
553    "ALL", "AND", "AS", "BETWEEN", "BY", "CASE", "CROSS", "DELETE", "DESC",
554    "DISTINCT", "DROP", "ELSE", "END", "ESCAPE", "EXCEPT", "EXISTS", "FALSE",
555    "FROM", "FULL", "GROUP", "HAVING", "IN", "INDEX", "INNER", "INSERT",
556    "INTERSECT", "INTO", "IS", "JOIN", "LEFT", "LIKE", "LIMIT", "NOT", "NULL",
557    "OFFSET", "ON", "OR", "ORDER", "OUTER", "RIGHT", "SELECT", "SET", "TABLE",
558    "THEN", "TRUE", "UNION", "UNIQUE", "UPDATE", "VALUES", "WHEN", "WHERE",
559    "WITH",
560];
561
562/// Returns `true` when `ident` is a SQL reserved keyword (case-insensitive).
563fn is_reserved_keyword(ident: &str) -> bool {
564    RESERVED_KEYWORDS
565        .binary_search(&ident.to_uppercase().as_str())
566        .is_ok()
567}
568
569fn compilation_error(feature: impl Into<String>, details: Value) -> VlorQLError {
570    VlorQLError::compilation(
571        CompilationErrorKind::UnsupportedDialectFeature {
572            feature: feature.into(),
573        },
574        details,
575    )
576}
577
578fn formatting_error(_error: std::fmt::Error) -> VlorQLError {
579    compilation_error("sql_formatting", json!({"reason": "formatting_failed"}))
580}