1use crate::errors::{ValidationErrorKind, VlorQLError};
4use crate::schema::{
5 DialectProfile, Expression, InTarget, Predicate, Projection, QueryPlan, WindowFrame,
6 WindowFrameBound,
7};
8use serde_json::json;
9
10#[derive(Debug, Clone, Copy, Default)]
12pub struct DialectValidator;
13
14impl DialectValidator {
15 pub fn bind(profile: &DialectProfile) -> BoundDialectValidator<'_> {
17 BoundDialectValidator { profile }
18 }
19
20 pub fn validate(plan: &QueryPlan, profile: &DialectProfile) -> Result<(), Vec<VlorQLError>> {
22 Self::bind(profile).validate(plan)
23 }
24
25 pub fn validate_plan(
27 plan: &QueryPlan,
28 profile: &DialectProfile,
29 ) -> Result<(), Vec<VlorQLError>> {
30 Self::validate(plan, profile)
31 }
32}
33
34#[derive(Debug, Clone, Copy)]
36pub struct BoundDialectValidator<'a> {
37 profile: &'a DialectProfile,
38}
39
40impl BoundDialectValidator<'_> {
41 pub fn validate(&self, plan: &QueryPlan) -> Result<(), Vec<VlorQLError>> {
43 let mut errors = Vec::new();
44 self.validate_inner(plan, &mut errors);
45 if errors.is_empty() {
46 Ok(())
47 } else {
48 Err(errors)
49 }
50 }
51
52 fn validate_inner(&self, plan: &QueryPlan, errors: &mut Vec<VlorQLError>) {
53 if plan.ctes.as_ref().is_some_and(|ctes| !ctes.is_empty()) && !self.profile.supports_cte {
54 errors.push(self.feature_disabled("common_table_expressions"));
55 }
56
57 let join_count = plan.joins.as_ref().map_or(0, Vec::len);
58 if let Some(max) = self.profile.max_joins
59 && join_count > max
60 {
61 errors.push(VlorQLError::validation(
62 ValidationErrorKind::TooManyJoins {
63 actual: join_count,
64 max,
65 },
66 json!({
67 "actual": join_count,
68 "max": max,
69 "dialect": self.profile.dialect,
70 }),
71 ));
72 }
73
74 if let Some(joins) = &plan.joins {
75 for join in joins {
76 if !self.profile.allowed_join_types.is_empty()
77 && !self.profile.allowed_join_types.contains(&join.join_type)
78 {
79 errors.push(self.feature_disabled(format!(
80 "join_type:{}",
81 format!("{:?}", join.join_type).to_ascii_lowercase()
82 )));
83 }
84 self.validate_predicate(&join.on, errors);
85 }
86 }
87
88 if !self.profile.supports_offset && plan.offset.is_some() {
89 errors.push(self.feature_disabled("offset"));
90 }
91
92 if let Some(max) = self.profile.max_group_by_columns {
93 let actual = plan.group_by.as_ref().map_or(0, Vec::len);
94 if actual > max {
95 errors.push(VlorQLError::validation(
96 ValidationErrorKind::AggregationMismatch {
97 message: format!(
98 "query groups by {actual} columns, but the maximum is {max}"
99 ),
100 },
101 json!({"actual": actual, "max": max}),
102 ));
103 }
104 }
105
106 if plan.distinct && !self.profile.allow_select_distinct {
107 errors.push(self.feature_disabled("select_distinct"));
108 }
109
110 self.validate_select_group_by(plan, errors);
111
112 for projection in &plan.select {
113 if let Projection::Expr { expression, .. } = projection {
114 self.validate_expression(expression, errors);
115 }
116 }
117 if let Some(predicate) = &plan.r#where {
118 self.validate_predicate(predicate, errors);
119 }
120 if let Some(expressions) = &plan.group_by {
121 for expression in expressions {
122 self.validate_expression(expression, errors);
123 }
124 }
125 if let Some(predicate) = &plan.having {
126 self.validate_predicate(predicate, errors);
127 }
128 if let Some(terms) = &plan.order_by {
129 for term in terms {
130 self.validate_expression(&term.expr, errors);
131 }
132 }
133 if let Some(ctes) = &plan.ctes {
134 for cte in ctes {
135 self.validate_inner(&cte.query, errors);
136 }
137 }
138 }
139
140 fn validate_select_group_by(&self, plan: &QueryPlan, errors: &mut Vec<VlorQLError>) {
141 let Some(group_by) = plan.group_by.as_ref().filter(|g| !g.is_empty()) else {
142 return;
143 };
144
145 for projection in &plan.select {
146 match projection {
147 Projection::Star { .. } => {
148 errors.push(self.group_by_error(
149 "SELECT * is not allowed with GROUP BY: every column must be explicitly listed in GROUP BY or wrapped in an aggregate function",
150 ));
151 }
152 Projection::Column { table, column, .. } => {
153 if !is_column_in_group_by(group_by, table, column) {
154 errors.push(self.group_by_error(format!(
155 "column `{}.{}` must appear in GROUP BY or be wrapped in an aggregate function",
156 table.as_deref().unwrap_or("?"),
157 column,
158 )));
159 }
160 }
161 Projection::Expr { expression, .. } => {
162 match expression {
163 Expression::ColumnRef { table, column } => {
164 if !is_column_in_group_by(group_by, table, column) {
165 errors.push(self.group_by_error(format!(
166 "column `{}.{}` must appear in GROUP BY or be wrapped in an aggregate function",
167 table.as_deref().unwrap_or("?"),
168 column,
169 )));
170 }
171 }
172 Expression::Star => {
173 errors.push(
174 self.group_by_error(
175 "bare `*` is not allowed in SELECT with GROUP BY",
176 ),
177 );
178 }
179 Expression::FunctionCall { .. } => {}
182 _ => {}
185 }
186 }
187 }
188 }
189 }
190
191 fn group_by_error(&self, message: impl Into<String>) -> VlorQLError {
192 VlorQLError::validation(
193 ValidationErrorKind::AggregationMismatch {
194 message: message.into(),
195 },
196 json!({"type": "select_group_by_mismatch"}),
197 )
198 }
199
200 fn validate_expression(&self, expression: &Expression, errors: &mut Vec<VlorQLError>) {
201 match expression {
202 Expression::Literal { .. } | Expression::ColumnRef { .. } => {}
203 Expression::FunctionCall {
204 name,
205 args,
206 distinct,
207 } => {
208 let denied = self
209 .profile
210 .denied_functions
211 .iter()
212 .any(|function| function.eq_ignore_ascii_case(name));
213 let allowed = self.profile.allowed_functions.is_empty()
214 || self
215 .profile
216 .allowed_functions
217 .iter()
218 .any(|function| function.eq_ignore_ascii_case(name));
219 if denied || !allowed {
220 errors.push(VlorQLError::validation(
221 ValidationErrorKind::InvalidFunction {
222 function: name.clone(),
223 allowed_functions: self.profile.allowed_functions.clone(),
224 },
225 json!({
226 "function": name,
227 "denied": denied,
228 "allowed_functions": self.profile.allowed_functions,
229 }),
230 ));
231 }
232 if *distinct && !self.profile.allow_distinct {
233 errors.push(self.feature_disabled("distinct"));
234 }
235 for argument in args {
236 self.validate_expression(argument, errors);
237 }
238 }
239 Expression::BinaryOp { left, right, .. } => {
240 self.validate_expression(left, errors);
241 self.validate_expression(right, errors);
242 }
243 Expression::Star => {} Expression::SubQuery { query } => {
245 self.validate_inner(query, errors);
246 }
247 Expression::Case {
248 operand,
249 when_thens,
250 else_result,
251 } => {
252 if let Some(op) = operand {
253 self.validate_expression(op, errors);
254 }
255 for wt in when_thens {
256 self.validate_expression(&wt.when, errors);
257 self.validate_expression(&wt.then, errors);
258 }
259 if let Some(el) = else_result {
260 self.validate_expression(el, errors);
261 }
262 }
263 Expression::WindowFunction {
264 name,
265 args,
266 distinct,
267 over,
268 } => {
269 if !self.profile.supports_window_functions {
270 errors.push(self.feature_disabled("window_functions"));
271 }
272 let denied = self
273 .profile
274 .denied_functions
275 .iter()
276 .any(|function| function.eq_ignore_ascii_case(name));
277 let allowed = self.profile.allowed_functions.is_empty()
278 || self
279 .profile
280 .allowed_functions
281 .iter()
282 .any(|function| function.eq_ignore_ascii_case(name));
283 if denied || !allowed {
284 errors.push(VlorQLError::validation(
285 ValidationErrorKind::InvalidFunction {
286 function: name.clone(),
287 allowed_functions: self.profile.allowed_functions.clone(),
288 },
289 json!({
290 "function": name,
291 "denied": denied,
292 "allowed_functions": self.profile.allowed_functions,
293 }),
294 ));
295 }
296 if *distinct && !self.profile.allow_distinct {
297 errors.push(self.feature_disabled("distinct"));
298 }
299 for argument in args {
300 self.validate_expression(argument, errors);
301 }
302 if let Some(partition_by) = &over.partition_by {
304 for expr in partition_by {
305 self.validate_expression(expr, errors);
306 }
307 }
308 if let Some(order_by) = &over.order_by {
309 for term in order_by {
310 self.validate_expression(&term.expr, errors);
311 }
312 }
313 if let Some(frame) = &over.frame {
314 self.validate_window_frame_bounds(frame, errors);
315 }
316 }
317 }
318 }
319
320 fn validate_predicate(&self, predicate: &Predicate, errors: &mut Vec<VlorQLError>) {
321 match predicate {
322 Predicate::Comparison { left, right, .. } => {
323 self.validate_expression(left, errors);
324 self.validate_expression(right, errors);
325 }
326 Predicate::And { left, right } | Predicate::Or { left, right } => {
327 self.validate_predicate(left, errors);
328 self.validate_predicate(right, errors);
329 }
330 Predicate::Not { child } => self.validate_predicate(child, errors),
331 Predicate::Between { expr, low, high } => {
332 self.validate_expression(expr, errors);
333 self.validate_expression(low, errors);
334 self.validate_expression(high, errors);
335 }
336 Predicate::In { expr, target } => {
337 self.validate_expression(expr, errors);
338 match target {
339 InTarget::Values(values) => {
340 for value in values {
341 self.validate_expression(value, errors);
342 }
343 }
344 InTarget::SubQuery(query) => {
345 self.validate_inner(query, errors);
346 }
347 }
348 }
349 Predicate::Exists { query } => {
350 self.validate_inner(query, errors);
351 }
352 Predicate::Like { expr, .. } | Predicate::IsNull { expr } => {
353 self.validate_expression(expr, errors);
354 }
355 }
356 }
357
358 fn feature_disabled(&self, feature: impl Into<String>) -> VlorQLError {
359 let feature = feature.into();
360 VlorQLError::validation(
361 ValidationErrorKind::DialectFeatureDisabled {
362 feature: feature.clone(),
363 },
364 json!({
365 "feature": feature,
366 "dialect": self.profile.dialect,
367 }),
368 )
369 }
370
371 fn validate_window_frame_bounds(
372 &self,
373 frame: &WindowFrame,
374 errors: &mut Vec<VlorQLError>,
375 ) {
376 Self::validate_frame_bound(&frame.start, errors);
378 if let Some(end) = &frame.end {
379 Self::validate_frame_bound(end, errors);
380 }
381 }
382
383 fn validate_frame_bound(bound: &WindowFrameBound, errors: &mut Vec<VlorQLError>) {
384 match bound {
385 WindowFrameBound::Preceding(expr) | WindowFrameBound::Following(expr) => {
386 if matches!(expr.as_ref(), Expression::SubQuery { .. }) {
388 errors.push(VlorQLError::validation(
389 ValidationErrorKind::TypeMismatch {
390 expected: "literal or column".to_owned(),
391 found: "subquery".to_owned(),
392 expr: "window_frame_bound".to_owned(),
393 },
394 json!({
395 "expected": "literal or column",
396 "found": "subquery",
397 "bound": format!("{bound:?}"),
398 }),
399 ));
400 }
401 }
402 _ => {}
403 }
404 }
405}
406
407fn is_column_in_group_by(group_by: &[Expression], table: &Option<String>, column: &str) -> bool {
413 group_by.iter().any(|expr| match expr {
414 Expression::ColumnRef {
415 table: gb_table,
416 column: gb_column,
417 } => match (gb_table, table) {
418 (Some(t1), Some(t2)) => t1 == t2 && gb_column == column,
419 _ => gb_column == column,
420 },
421 _ => false,
422 })
423}