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::dialect_config::DialectConfig;
8use super::types::Parameter;
9use crate::errors::{CompilationErrorKind, VlorQLError};
10use crate::schema::{
11    BinaryOperator, ComparisonOperator, DataType, Expression, FromClause,
12    InTarget, JoinType, Predicate, Projection, QueryPlan, SetOperation, SetOperationClause,
13    SqlDialect, WindowFrame, WindowFrameBound, WindowFrameKind, WindowSpec,
14};
15use crate::validate::ValidatedPlan;
16use serde_json::{Value, json};
17use std::borrow::Cow;
18use std::collections::HashMap;
19use std::fmt::Write;
20
21/// Builds SQL while preserving the exact textual order of bind parameters.
22pub struct QueryBuilder<'a> {
23    plan: &'a ValidatedPlan,
24    config: &'a DialectConfig,
25    dialect: SqlDialect,
26    parameters: Vec<Parameter>,
27    /// Stack of alias maps for each query level (outermost first).
28    /// Each map resolves table names (and aliases) to effective aliases.
29    alias_stack: Vec<HashMap<String, String>>,
30    /// Deduplication cache: (value_json_string, data_type) → parameter index (0-based).
31    /// Used so the SAME literal expression always produces the SAME placeholder,
32    /// which PostgreSQL requires for GROUP BY / ORDER BY matching.
33    param_cache: HashMap<(String, DataType), usize>,
34    /// When true, numeric literals are rendered with explicit CAST so that
35    /// PostgreSQL can infer their types (required in recursive CTE contexts
36    /// where parameterized literals are inferred as `text`).
37    in_cte: bool,
38}
39
40impl<'a> QueryBuilder<'a> {
41    /// Creates a builder for one validated plan and dialect config.
42    pub fn new(
43        plan: &'a ValidatedPlan,
44        config: &'a DialectConfig,
45    ) -> Self {
46        let dialect = match config.name.to_lowercase().as_str() {
47            "postgres" | "postgresql" => SqlDialect::Postgres,
48            "sqlite" => SqlDialect::Sqlite,
49            "mysql" | "my_sql" => SqlDialect::MySql,
50            _ => SqlDialect::Postgres,
51        };
52        let mut builder = Self {
53            plan,
54            config,
55            dialect,
56            parameters: Vec::new(),
57            alias_stack: Vec::new(),
58            param_cache: HashMap::new(),
59            in_cte: false,
60        };
61        builder.push_alias_scope(plan.as_plan());
62        builder
63    }
64
65    fn push_alias_scope(&mut self, plan: &QueryPlan) {
66        let mut map = HashMap::new();
67        Self::collect_aliases(&plan.from, &mut map);
68        if let Some(joins) = &plan.joins {
69            for join in joins {
70                Self::collect_aliases(&join.right_table, &mut map);
71            }
72        }
73        self.alias_stack.push(map);
74    }
75
76    fn collect_aliases(from: &FromClause, map: &mut HashMap<String, String>) {
77        let effective = from.alias.clone().unwrap_or_else(|| from.table.clone());
78        // 保留首次注册的表名→别名映射,避免自连接中后注册的 JOIN 覆盖 FROM 的映射
79        map.entry(from.table.clone()).or_insert_with(|| effective.clone());
80        if let Some(ref alias) = from.alias {
81            map.insert(alias.clone(), effective);
82        }
83    }
84
85    fn resolve_alias<'b>(&self, qualifier: &'b str) -> Cow<'b, str> {
86        self.alias_stack
87            .iter()
88            .rev()
89            .find_map(|map| map.get(qualifier))
90            .map(|s| Cow::Owned(s.clone()))
91            .unwrap_or(Cow::Borrowed(qualifier))
92    }
93
94    /// Builds a SQL string and returns its parameters in placeholder order.
95    pub fn build(mut self) -> Result<(String, Vec<Parameter>), VlorQLError> {
96        tracing::event!(tracing::Level::DEBUG, "Building SQL from QueryPlan");
97        let plan = self.plan.as_plan();
98        let mut sql = String::new();
99        self.build_query(plan, &mut sql)?;
100        Ok((sql, self.parameters))
101    }
102
103    /// Renders one expression and appends any literal parameters to this builder.
104    pub fn render_expression(&mut self, expression: &Expression) -> Result<String, VlorQLError> {
105        let mut buf = String::new();
106        self.render_expression_to(expression, &mut buf)?;
107        Ok(buf)
108    }
109
110    /// Renders one expression into `buf`, avoiding intermediate allocations.
111    pub fn render_expression_to(
112        &mut self,
113        expression: &Expression,
114        buf: &mut String,
115    ) -> Result<(), VlorQLError> {
116        match expression {
117            Expression::Literal { value, data_type } => {
118                let placeholder = self.add_parameter(value.clone(), *data_type);
119                // In CTE contexts, PostgreSQL cannot infer the type of
120                // parameterized literals — add explicit CAST so the type
121                // is known (e.g. `CAST($1 AS integer)`).
122                if self.in_cte && self.dialect == SqlDialect::Postgres {
123                    match data_type {
124                        DataType::Int => write!(buf, "CAST({placeholder} AS INTEGER)"),
125                        DataType::Float => write!(buf, "CAST({placeholder} AS DOUBLE PRECISION)"),
126                        DataType::Boolean => write!(buf, "CAST({placeholder} AS BOOLEAN)"),
127                        _ => write!(buf, "{placeholder}"),
128                    }
129                    .map_err(formatting_error)?;
130                } else {
131                    buf.push_str(&placeholder);
132                }
133                Ok(())
134            }
135            Expression::ColumnRef { table, column } => {
136                buf.push_str(&self.render_qualified_identifier(table.as_deref(), column)?);
137                Ok(())
138            }
139            Expression::FunctionCall {
140                name,
141                args,
142                distinct,
143            } => {
144                let function = self.render_function_name(name)?;
145                buf.push_str(&function);
146                buf.push('(');
147                if *distinct {
148                    buf.push_str("DISTINCT ");
149                }
150                for (i, argument) in args.iter().enumerate() {
151                    if i > 0 {
152                        buf.push_str(", ");
153                    }
154                    self.render_expression_to(argument, buf)?;
155                }
156                buf.push(')');
157                Ok(())
158            }
159            Expression::BinaryOp { left, op, right } => {
160                buf.push('(');
161                self.render_expression_to(left, buf)?;
162                write!(buf, " {} ", self.render_binary_operator(*op)).map_err(formatting_error)?;
163                self.render_expression_to(right, buf)?;
164                buf.push(')');
165                Ok(())
166            }
167            Expression::Star => {
168                buf.push('*');
169                Ok(())
170            }
171            Expression::SubQuery { query } => {
172                buf.push('(');
173                self.build_query(query, buf)?;
174                buf.push(')');
175                Ok(())
176            }
177            Expression::Case {
178                operand,
179                when_thens,
180                else_result,
181            } => {
182                buf.push_str("CASE");
183                if let Some(op) = operand {
184                    buf.push(' ');
185                    self.render_expression_to(op, buf)?;
186                }
187                for wt in when_thens {
188                    buf.push_str(" WHEN ");
189                    self.render_expression_to(&wt.when, buf)?;
190                    buf.push_str(" THEN ");
191                    self.render_expression_to(&wt.then, buf)?;
192                }
193                if let Some(el) = else_result {
194                    buf.push_str(" ELSE ");
195                    self.render_expression_to(el, buf)?;
196                }
197                buf.push_str(" END");
198                Ok(())
199            }
200            Expression::WindowFunction {
201                name,
202                args,
203                distinct,
204                over,
205            } => {
206                let function = self.render_function_name(name)?;
207                buf.push_str(&function);
208                buf.push('(');
209                if *distinct {
210                    buf.push_str("DISTINCT ");
211                }
212                for (i, argument) in args.iter().enumerate() {
213                    if i > 0 {
214                        buf.push_str(", ");
215                    }
216                    self.render_expression_to(argument, buf)?;
217                }
218                buf.push(')');
219                self.render_window_spec(over, buf)?;
220                Ok(())
221            }
222        }
223    }
224
225    /// Renders one predicate and appends literal values as bind parameters.
226    pub fn render_predicate(&mut self, predicate: &Predicate) -> Result<String, VlorQLError> {
227        let mut buf = String::new();
228        self.render_predicate_to(predicate, &mut buf)?;
229        Ok(buf)
230    }
231
232    /// Renders one predicate into `buf`, avoiding intermediate allocations.
233    pub fn render_predicate_to(
234        &mut self,
235        predicate: &Predicate,
236        buf: &mut String,
237    ) -> Result<(), VlorQLError> {
238        match predicate {
239            Predicate::Comparison { left, op, right } => {
240                self.render_expression_to(left, buf)?;
241                write!(buf, " {} ", self.render_comparison_operator(*op)?)
242                    .map_err(formatting_error)?;
243                self.render_expression_to(right, buf)
244            }
245            Predicate::And { left, right } => {
246                buf.push('(');
247                self.render_predicate_to(left, buf)?;
248                buf.push_str(") AND (");
249                self.render_predicate_to(right, buf)?;
250                buf.push(')');
251                Ok(())
252            }
253            Predicate::Or { left, right } => {
254                buf.push('(');
255                self.render_predicate_to(left, buf)?;
256                buf.push_str(") OR (");
257                self.render_predicate_to(right, buf)?;
258                buf.push(')');
259                Ok(())
260            }
261            Predicate::Not { child } => {
262                buf.push_str("NOT (");
263                self.render_predicate_to(child, buf)?;
264                buf.push(')');
265                Ok(())
266            }
267            Predicate::Between { expr, low, high } => {
268                self.render_expression_to(expr, buf)?;
269                buf.push_str(" BETWEEN ");
270                self.render_expression_to(low, buf)?;
271                buf.push_str(" AND ");
272                self.render_expression_to(high, buf)
273            }
274            Predicate::In { expr, target } => {
275                self.render_expression_to(expr, buf)?;
276                match target {
277                    InTarget::Values(values) => {
278                        if values.is_empty() {
279                            return Err(compilation_error(
280                                "empty_in_list",
281                                json!({"predicate": "in"}),
282                            ));
283                        }
284                        buf.push_str(" IN (");
285                        for (i, value) in values.iter().enumerate() {
286                            if i > 0 {
287                                buf.push_str(", ");
288                            }
289                            self.render_expression_to(value, buf)?;
290                        }
291                        buf.push(')');
292                        Ok(())
293                    }
294                    InTarget::SubQuery(query) => {
295                        buf.push_str(" IN (");
296                        self.build_query(query, buf)?;
297                        buf.push(')');
298                        Ok(())
299                    }
300                }
301            }
302            Predicate::Exists { query } => {
303                buf.push_str("EXISTS (");
304                self.build_query(query, buf)?;
305                buf.push(')');
306                Ok(())
307            }
308            Predicate::Like { expr, pattern } => {
309                self.render_expression_to(expr, buf)?;
310                let placeholder =
311                    self.add_parameter(Value::String(pattern.clone()), DataType::String);
312                write!(buf, " LIKE {placeholder}").map_err(formatting_error)
313            }
314            Predicate::IsNull { expr } => {
315                self.render_expression_to(expr, buf)?;
316                buf.push_str(" IS NULL");
317                Ok(())
318            }
319        }
320    }
321
322    /// Adds a parameter and returns the placeholder for the selected dialect.
323    /// Deduplicates parameters: the same (value, data_type) pair always produces
324    /// the same placeholder index, which PostgreSQL requires for GROUP BY matching.
325    pub fn add_parameter(&mut self, value: Value, data_type: DataType) -> String {
326        let val_str = serde_json::to_string(&value).unwrap_or_default();
327        let key = (val_str, data_type);
328
329        if let Some(&idx) = self.param_cache.get(&key) {
330            if self.config.placeholder.contains("{index}") {
331                return self.config.placeholder_str(idx + 1);
332            }
333            return self.config.placeholder_str(0);
334        }
335
336        let idx = self.parameters.len();
337        self.parameters.push(Parameter { value, data_type });
338        self.param_cache.insert(key, idx);
339        self.config.placeholder_str(idx + 1)
340    }
341
342    /// Returns the dialect selected for this builder.
343    pub fn dialect(&self) -> SqlDialect {
344        self.dialect
345    }
346
347    fn build_query(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
348        self.push_alias_scope(plan);
349        self.build_with(plan, sql)?;
350        self.build_select(plan, sql)?;
351        self.build_from(plan, sql)?;
352        self.build_where(plan, sql)?;
353        self.build_group_by(plan, sql)?;
354        self.build_having(plan, sql)?;
355        self.alias_stack.pop();
356
357        // Render set operation (UNION / INTERSECT / EXCEPT) AFTER the
358        // primary query but BEFORE ORDER BY / LIMIT / OFFSET, because
359        // PostgreSQL (and most dialects) require ORDER BY to appear
360        // after the set operation, not before it.
361        if let Some(set_op) = &plan.set_operation {
362            self.render_set_operation(set_op, sql)?;
363        }
364
365        self.build_order_by(plan, sql)?;
366        self.build_limit_offset(plan, sql)?;
367
368        Ok(())
369    }
370
371    fn build_with(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
372        let Some(ctes) = plan.ctes.as_ref().filter(|ctes| !ctes.is_empty()) else {
373            return Ok(());
374        };
375
376        if ctes.iter().any(|cte| cte.recursive) {
377            sql.push_str("WITH RECURSIVE ");
378        } else {
379            sql.push_str("WITH ");
380        }
381        for (index, cte) in ctes.iter().enumerate() {
382            if index > 0 {
383                sql.push_str(", ");
384            }
385            let name = self.quote_identifier(&cte.name)?;
386            write!(sql, "{name} AS (").map_err(formatting_error)?;
387            // Enable CTE mode so numeric literals get explicit type casts
388            // (PostgreSQL cannot infer parameter types in recursive CTEs).
389            let saved = self.in_cte;
390            self.in_cte = true;
391            self.build_query(&cte.query, sql)?;
392            self.in_cte = saved;
393            sql.push(')');
394        }
395        sql.push(' ');
396        Ok(())
397    }
398
399    fn build_select(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
400        if plan.select.is_empty() {
401            return Err(compilation_error(
402                "empty_select_list",
403                json!({"clause": "select"}),
404            ));
405        }
406
407        sql.push_str("SELECT ");
408        if plan.distinct {
409            sql.push_str("DISTINCT ");
410            if let Some(on) = &plan.distinct_on {
411                sql.push_str("ON (");
412                for (i, expr) in on.iter().enumerate() {
413                    if i > 0 {
414                        sql.push_str(", ");
415                    }
416                    self.render_expression_to(expr, sql)?;
417                }
418                sql.push_str(") ");
419            }
420        }
421        for (index, projection) in plan.select.iter().enumerate() {
422            if index > 0 {
423                sql.push_str(", ");
424            }
425            match projection {
426                Projection::Star { table: None } => sql.push('*'),
427                Projection::Star { table: Some(table) } => {
428                    let resolved = self.resolve_alias(table);
429                    write!(sql, "{}.*", self.quote_identifier(&resolved)?)
430                        .map_err(formatting_error)?;
431                }
432                Projection::Column {
433                    table,
434                    column,
435                    alias,
436                } => {
437                    sql.push_str(&self.render_qualified_identifier(table.as_deref(), column)?);
438                    if let Some(alias) = alias {
439                        write!(sql, " AS {}", self.quote_identifier(alias)?)
440                            .map_err(formatting_error)?;
441                    }
442                }
443                Projection::Expr { expression, alias } => {
444                    sql.push_str(&self.render_expression(expression)?);
445                    if let Some(alias) = alias {
446                        write!(sql, " AS {}", self.quote_identifier(alias)?)
447                            .map_err(formatting_error)?;
448                    }
449                }
450            }
451        }
452        Ok(())
453    }
454
455    fn build_from(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
456        sql.push_str(" FROM ");
457        sql.push_str(&self.render_from_clause(&plan.from)?);
458
459        if let Some(joins) = &plan.joins {
460            for join in joins {
461                write!(
462                    sql,
463                    " {} {}",
464                    self.render_join_type(join.join_type)?,
465                    self.render_from_clause(&join.right_table)?
466                )
467                .map_err(formatting_error)?;
468                if join.join_type != JoinType::Cross {
469                    let condition = self.render_predicate(&join.on)?;
470                    write!(sql, " ON {condition}").map_err(formatting_error)?;
471                }
472            }
473        }
474        Ok(())
475    }
476
477    fn build_where(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
478        if let Some(predicate) = &plan.r#where {
479            let predicate = self.render_predicate(predicate)?;
480            write!(sql, " WHERE {predicate}").map_err(formatting_error)?;
481        }
482        Ok(())
483    }
484
485    fn build_group_by(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
486        let Some(expressions) = plan
487            .group_by
488            .as_ref()
489            .filter(|expressions| !expressions.is_empty())
490        else {
491            return Ok(());
492        };
493
494        let mut rendered = Vec::with_capacity(expressions.len());
495        for expression in expressions {
496            rendered.push(self.render_expression(expression)?);
497        }
498        write!(sql, " GROUP BY {}", rendered.join(", ")).map_err(formatting_error)
499    }
500
501    fn build_having(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
502        if let Some(predicate) = &plan.having {
503            let predicate = self.render_predicate(predicate)?;
504            write!(sql, " HAVING {predicate}").map_err(formatting_error)?;
505        }
506        Ok(())
507    }
508
509    fn build_order_by(&mut self, plan: &QueryPlan, sql: &mut String) -> Result<(), VlorQLError> {
510        let Some(terms) = plan.order_by.as_ref().filter(|terms| !terms.is_empty()) else {
511            return Ok(());
512        };
513
514        let mut rendered = Vec::with_capacity(terms.len());
515        for term in terms {
516            let expression = self.render_expression(&term.expr)?;
517            let direction = if term.descending { "DESC" } else { "ASC" };
518            rendered.push(format!("{expression} {direction}"));
519        }
520        write!(sql, " ORDER BY {}", rendered.join(", ")).map_err(formatting_error)
521    }
522
523    fn build_limit_offset(
524        &mut self,
525        plan: &QueryPlan,
526        sql: &mut String,
527    ) -> Result<(), VlorQLError> {
528        match (self.dialect, plan.limit, plan.offset) {
529            (SqlDialect::MySql, Some(limit), Some(offset)) => {
530                let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
531                let limit_ph = self.add_parameter(Value::from(limit), DataType::Int);
532                write!(sql, " LIMIT {offset_ph}, {limit_ph}").map_err(formatting_error)
533            }
534            (SqlDialect::MySql, Some(limit), None) => {
535                let limit_ph = self.add_parameter(Value::from(limit), DataType::Int);
536                write!(sql, " LIMIT {limit_ph}").map_err(formatting_error)
537            }
538            (SqlDialect::MySql, None, Some(offset)) => {
539                let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
540                write!(sql, " LIMIT {offset_ph}, {MYSQL_UNLIMITED_LIMIT}")
541                    .map_err(formatting_error)
542            }
543            (SqlDialect::Sqlite, None, Some(offset)) => {
544                let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
545                write!(sql, " LIMIT -1 OFFSET {offset_ph}").map_err(formatting_error)
546            }
547            (_, limit, offset) => {
548                if let Some(limit) = limit {
549                    let limit_ph = self.add_parameter(Value::from(limit), DataType::Int);
550                    write!(sql, " LIMIT {limit_ph}").map_err(formatting_error)?;
551                }
552                if let Some(offset) = offset {
553                    let offset_ph = self.add_parameter(Value::from(offset), DataType::Int);
554                    write!(sql, " OFFSET {offset_ph}").map_err(formatting_error)?;
555                }
556                Ok(())
557            }
558        }
559    }
560
561    fn render_from_clause(&self, from: &FromClause) -> Result<String, VlorQLError> {
562        let table = self.quote_identifier(&from.table)?;
563        match &from.alias {
564            Some(alias) => Ok(format!("{table} AS {}", self.quote_identifier(alias)?)),
565            None => Ok(table),
566        }
567    }
568
569    fn render_qualified_identifier(
570        &self,
571        qualifier: Option<&str>,
572        identifier: &str,
573    ) -> Result<String, VlorQLError> {
574        let identifier = self.quote_identifier(identifier)?;
575        match qualifier {
576            Some(qualifier) => {
577                let resolved = self.resolve_alias(qualifier);
578                Ok(format!(
579                    "{}.{}",
580                    self.quote_identifier(&resolved)?,
581                    identifier
582                ))
583            }
584            None => Ok(identifier),
585        }
586    }
587
588    fn quote_identifier(&self, identifier: &str) -> Result<String, VlorQLError> {
589        if identifier.is_empty() {
590            return Err(compilation_error(
591                "empty_identifier",
592                json!({"identifier": identifier}),
593            ));
594        }
595
596        let style = self.config.identifier_quote.as_str();
597        if style == "never" {
598            validate_unquoted_identifier(identifier)?;
599            Ok(identifier.to_owned())
600        } else {
601            Ok(self.config.quote_identifier(identifier))
602        }
603    }
604
605    fn render_function_name<'b>(&self, function: &'b str) -> Result<Cow<'b, str>, VlorQLError> {
606        if function.is_empty() {
607            return Err(compilation_error(
608                "empty_function_name",
609                json!({"function": function}),
610            ));
611        }
612        for segment in function.split('.') {
613            // Function names follow identifier syntax but are not subject to
614            // reserved-keyword restrictions (e.g. EXISTS, COALESCE, NULLIF).
615            let mut chars = segment.chars();
616            let valid = chars.next().is_some_and(|c| c == '_' || c.is_ascii_alphabetic())
617                && chars.all(|c| c == '_' || c.is_ascii_alphanumeric());
618            if !valid {
619                return Err(compilation_error(
620                    "invalid_function_name",
621                    json!({"function": function}),
622                ));
623            }
624        }
625        Ok(Cow::Borrowed(function))
626    }
627
628    fn render_window_spec(
629        &mut self,
630        spec: &WindowSpec,
631        buf: &mut String,
632    ) -> Result<(), VlorQLError> {
633        buf.push_str(" OVER (");
634        let mut clause_added = false;
635
636        if let Some(partition_by) = &spec.partition_by {
637            clause_added = true;
638            buf.push_str("PARTITION BY ");
639            for (i, expr) in partition_by.iter().enumerate() {
640                if i > 0 {
641                    buf.push_str(", ");
642                }
643                self.render_expression_to(expr, buf)?;
644            }
645        }
646
647        if let Some(order_by) = &spec.order_by {
648            if clause_added {
649                buf.push(' ');
650            }
651            clause_added = true;
652            buf.push_str("ORDER BY ");
653            for (i, term) in order_by.iter().enumerate() {
654                if i > 0 {
655                    buf.push_str(", ");
656                }
657                self.render_expression_to(&term.expr, buf)?;
658                if term.descending {
659                    buf.push_str(" DESC");
660                } else {
661                    buf.push_str(" ASC");
662                }
663            }
664        }
665
666        if let Some(frame) = &spec.frame {
667            if clause_added {
668                buf.push(' ');
669            }
670            self.render_window_frame(frame, buf)?;
671        }
672
673        buf.push(')');
674        Ok(())
675    }
676
677    fn render_window_frame(
678        &mut self,
679        frame: &WindowFrame,
680        buf: &mut String,
681    ) -> Result<(), VlorQLError> {
682        match frame.kind {
683            WindowFrameKind::Rows => buf.push_str("ROWS"),
684            WindowFrameKind::Range => buf.push_str("RANGE"),
685            WindowFrameKind::Groups => buf.push_str("GROUPS"),
686        }
687        buf.push_str(" BETWEEN ");
688        self.render_window_frame_bound(&frame.start, buf)?;
689        buf.push_str(" AND ");
690        match &frame.end {
691            Some(end) => self.render_window_frame_bound(end, buf)?,
692            None => buf.push_str("CURRENT ROW"),
693        }
694        Ok(())
695    }
696
697    fn render_window_frame_bound(
698        &mut self,
699        bound: &WindowFrameBound,
700        buf: &mut String,
701    ) -> Result<(), VlorQLError> {
702        match bound {
703            WindowFrameBound::UnboundedPreceding => buf.push_str("UNBOUNDED PRECEDING"),
704            WindowFrameBound::Preceding(expr) => {
705                self.render_expression_to(expr, buf)?;
706                buf.push_str(" PRECEDING");
707            }
708            WindowFrameBound::CurrentRow => buf.push_str("CURRENT ROW"),
709            WindowFrameBound::Following(expr) => {
710                self.render_expression_to(expr, buf)?;
711                buf.push_str(" FOLLOWING");
712            }
713            WindowFrameBound::UnboundedFollowing => buf.push_str("UNBOUNDED FOLLOWING"),
714        }
715        Ok(())
716    }
717
718    fn render_binary_operator(&self, operator: BinaryOperator) -> Cow<'static, str> {
719        match operator {
720            BinaryOperator::Add => Cow::Borrowed("+"),
721            BinaryOperator::Sub => Cow::Borrowed("-"),
722            BinaryOperator::Mul => Cow::Borrowed("*"),
723            BinaryOperator::Div => Cow::Borrowed("/"),
724            BinaryOperator::Mod => Cow::Borrowed("%"),
725            BinaryOperator::And => Cow::Borrowed("AND"),
726            BinaryOperator::Or => Cow::Borrowed("OR"),
727            BinaryOperator::Eq => Cow::Borrowed("="),
728            BinaryOperator::Neq => Cow::Borrowed("<>"),
729            BinaryOperator::Gt => Cow::Borrowed(">"),
730            BinaryOperator::Lt => Cow::Borrowed("<"),
731            BinaryOperator::Gte => Cow::Borrowed(">="),
732            BinaryOperator::Lte => Cow::Borrowed("<="),
733            BinaryOperator::Like => Cow::Borrowed("LIKE"),
734            BinaryOperator::ILike => {
735                if self.dialect == SqlDialect::Postgres
736                    && !self.config.type_mappings.contains_key("ilike")
737                {
738                    Cow::Borrowed("ILIKE")
739                } else {
740                    Cow::Owned(
741                        self.config
742                            .type_mappings
743                            .get("ilike")
744                            .cloned()
745                            .unwrap_or_else(|| "LIKE".to_owned()),
746                    )
747                }
748            }
749        }
750    }
751
752    fn render_set_operation(
753        &mut self,
754        set_op: &SetOperationClause,
755        sql: &mut String,
756    ) -> Result<(), VlorQLError> {
757        let keyword = match set_op.operation {
758            SetOperation::UnionAll => " UNION ALL ",
759            SetOperation::Union => " UNION ",
760            SetOperation::Intersect => " INTERSECT ",
761            SetOperation::Except => " EXCEPT ",
762        };
763        sql.push_str(keyword);
764        self.build_query(&set_op.right, sql)
765    }
766
767    fn render_comparison_operator(
768        &self,
769        operator: ComparisonOperator,
770    ) -> Result<Cow<'static, str>, VlorQLError> {
771        match operator {
772            ComparisonOperator::Eq => Ok(Cow::Borrowed("=")),
773            ComparisonOperator::Neq => Ok(Cow::Borrowed("<>")),
774            ComparisonOperator::Gt => Ok(Cow::Borrowed(">")),
775            ComparisonOperator::Lt => Ok(Cow::Borrowed("<")),
776            ComparisonOperator::Gte => Ok(Cow::Borrowed(">=")),
777            ComparisonOperator::Lte => Ok(Cow::Borrowed("<=")),
778            ComparisonOperator::Like => Ok(Cow::Borrowed("LIKE")),
779            ComparisonOperator::ILike => {
780                if self.dialect == SqlDialect::Postgres
781                    && !self.config.type_mappings.contains_key("ilike")
782                {
783                    Ok(Cow::Borrowed("ILIKE"))
784                } else {
785                    Ok(Cow::Owned(
786                        self.config
787                            .type_mappings
788                            .get("ilike")
789                            .cloned()
790                            .unwrap_or_else(|| "LIKE".to_owned()),
791                    ))
792                }
793            }
794            ComparisonOperator::In => Err(compilation_error(
795                "comparison_in_requires_in_predicate",
796                json!({"operator": operator}),
797            )),
798            ComparisonOperator::Between => Err(compilation_error(
799                "comparison_between_requires_between_predicate",
800                json!({"operator": operator}),
801            )),
802        }
803    }
804
805    fn render_join_type(&self, join_type: JoinType) -> Result<&'static str, VlorQLError> {
806        let is_mysql = self.dialect == SqlDialect::MySql
807            || self.config.name.to_lowercase().contains("mysql");
808        match join_type {
809            JoinType::Full if is_mysql => Err(compilation_error(
810                "unsupported_full_join",
811                json!({"dialect": self.config.name, "join_type": "full"}),
812            )),
813            JoinType::Inner => Ok("INNER JOIN"),
814            JoinType::Left => Ok("LEFT JOIN"),
815            JoinType::Right => Ok("RIGHT JOIN"),
816            JoinType::Full => Ok("FULL JOIN"),
817            JoinType::Cross => Ok("CROSS JOIN"),
818        }
819    }
820}
821
822fn validate_unquoted_identifier(identifier: &str) -> Result<(), VlorQLError> {
823    let mut characters = identifier.chars();
824    let valid_start = characters
825        .next()
826        .is_some_and(|character| character == '_' || character.is_ascii_alphabetic());
827    let valid_rest =
828        characters.all(|character| character == '_' || character.is_ascii_alphanumeric());
829    if !valid_start || !valid_rest {
830        return Err(compilation_error(
831            "invalid_unquoted_identifier",
832            json!({"identifier": identifier}),
833        ));
834    }
835    if is_reserved_keyword(identifier) {
836        return Err(compilation_error(
837            "reserved_keyword_unquoted",
838            json!({"identifier": identifier}),
839        ));
840    }
841    Ok(())
842}
843
844/// Standard SQL reserved keywords.  Sorted alphabetically for binary search.
845static RESERVED_KEYWORDS: &[&str] = &[
846    "ALL",
847    "AND",
848    "AS",
849    "BETWEEN",
850    "BY",
851    "CASE",
852    "CROSS",
853    "DELETE",
854    "DESC",
855    "DISTINCT",
856    "DROP",
857    "ELSE",
858    "END",
859    "ESCAPE",
860    "EXCEPT",
861    "EXISTS",
862    "FALSE",
863    "FROM",
864    "FULL",
865    "GROUP",
866    "HAVING",
867    "IN",
868    "INDEX",
869    "INNER",
870    "INSERT",
871    "INTERSECT",
872    "INTO",
873    "IS",
874    "JOIN",
875    "LEFT",
876    "LIKE",
877    "LIMIT",
878    "NOT",
879    "NULL",
880    "OFFSET",
881    "ON",
882    "OR",
883    "ORDER",
884    "OUTER",
885    "RIGHT",
886    "SELECT",
887    "SET",
888    "TABLE",
889    "THEN",
890    "TRUE",
891    "UNION",
892    "UNIQUE",
893    "UPDATE",
894    "VALUES",
895    "WHEN",
896    "WHERE",
897    "WITH",
898];
899
900/// Returns `true` when `ident` is a SQL reserved keyword (case-insensitive).
901fn is_reserved_keyword(ident: &str) -> bool {
902    RESERVED_KEYWORDS
903        .binary_search(&ident.to_uppercase().as_str())
904        .is_ok()
905}
906
907fn compilation_error(feature: impl Into<String>, details: Value) -> VlorQLError {
908    VlorQLError::compilation(
909        CompilationErrorKind::UnsupportedDialectFeature {
910            feature: feature.into(),
911        },
912        details,
913    )
914}
915
916fn formatting_error(_error: std::fmt::Error) -> VlorQLError {
917    compilation_error("sql_formatting", json!({"reason": "formatting_failed"}))
918}