-
-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathsql.rs
More file actions
1357 lines (1277 loc) · 48.1 KB
/
Copy pathsql.rs
File metadata and controls
1357 lines (1277 loc) · 48.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::csv_import::{extract_csv_copy_statement, CsvImport};
use super::sqlpage_functions::functions::SqlPageFunctionName;
use super::syntax_tree::StmtParam;
use super::SupportedDatabase;
use crate::file_cache::AsyncFromStrWithState;
use crate::webserver::database::error_highlighting::quote_source_with_highlight;
use crate::webserver::database::DbInfo;
use crate::{AppState, Database};
use async_trait::async_trait;
use sqlparser::ast::helpers::attached_token::AttachedToken;
use sqlparser::ast::{
CastKind, DataType, Expr, Function, FunctionArg, FunctionArgExpr, FunctionArgumentList,
FunctionArguments, Ident, ObjectName, ObjectNamePart, SelectFlavor, SelectItem, Set, SetExpr,
Spanned, Statement, Value, ValueWithSpan,
};
use sqlparser::dialect::{
Dialect, DuckDbDialect, GenericDialect, MsSqlDialect, MySqlDialect, OracleDialect,
PostgreSqlDialect, SQLiteDialect, SnowflakeDialect,
};
use sqlparser::parser::{Parser, ParserError};
use sqlparser::tokenizer::Token::{self, SemiColon, EOF};
use sqlparser::tokenizer::{Location, Span, TokenWithSpan, Tokenizer};
use sqlx::any::AnyKind;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use std::str::FromStr;
mod parameter_extraction;
use self::parameter_extraction::{
extract_ident_param, validate_function_calls, ParameterExtractor, TEMP_PLACEHOLDER_PREFIX,
};
pub(super) use self::parameter_extraction::{
function_args_to_stmt_params, DbPlaceHolder, ParamExtractContext, SqlPageFunctionError,
DB_PLACEHOLDERS,
};
#[derive(Default)]
pub struct ParsedSqlFile {
pub(super) statements: Vec<ParsedStatement>,
pub source_path: PathBuf,
}
impl ParsedSqlFile {
#[must_use]
pub fn new(db: &Database, sql: &str, source_path: &Path) -> ParsedSqlFile {
let dialect = dialect_for_db(db.info.database_type);
log::debug!(
"Parsing SQL file {} using dialect {:?}",
source_path.display(),
dialect
);
let parsed_statements = match parse_sql(&db.info, dialect.as_ref(), sql) {
Ok(parsed) => parsed,
Err(err) => return Self::from_err(err, source_path),
};
let statements = parsed_statements.collect();
ParsedSqlFile {
statements,
source_path: source_path.to_path_buf(),
}
}
fn from_err(e: impl Into<anyhow::Error>, source_path: &Path) -> Self {
Self {
statements: vec![ParsedStatement::Error(
e.into()
.context(format!("Error parsing file {}", source_path.display())),
)],
source_path: source_path.to_path_buf(),
}
}
}
#[async_trait(? Send)]
impl AsyncFromStrWithState for ParsedSqlFile {
async fn from_str_with_state(
app_state: &AppState,
source: &str,
source_path: &Path,
) -> anyhow::Result<Self> {
Ok(ParsedSqlFile::new(&app_state.db, source, source_path))
}
}
/// A single SQL statement that has been parsed from a SQL file.
#[derive(Debug, PartialEq)]
pub(super) struct StmtWithParams {
/// The SQL query with placeholders for parameters.
pub query: String,
/// The line and column of the first token in the query.
pub query_position: SourceSpan,
/// Parameters that should be bound to the query.
/// They can contain functions that will be called before the query is executed,
/// the result of which will be bound to the query.
pub params: Vec<StmtParam>,
/// Functions that are called on the result set after the query has been executed,
/// and which can be passed the result of the query as an argument.
pub delayed_functions: Vec<DelayedFunctionCall>,
/// Columns that are JSON columns, and which should be converted to JSON objects after the query is executed.
/// Only relevant for databases that do not have a native JSON type, and which return JSON values as text.
pub json_columns: Vec<String>,
}
/// A location in the source code.
#[derive(Debug, PartialEq, Clone, Copy)]
pub(super) struct SourceSpan {
pub start: SourceLocation,
pub end: SourceLocation,
}
/// A location in the source code.
#[derive(Debug, PartialEq, Clone, Copy)]
pub(super) struct SourceLocation {
pub line: usize,
pub column: usize,
}
#[derive(Debug)]
pub(super) enum ParsedStatement {
StmtWithParams(StmtWithParams),
StaticSimpleSelect {
values: Vec<(String, SimpleSelectValue)>,
query_position: SourceSpan,
},
SetVariable {
variable: StmtParam,
value: StmtWithParams,
},
StaticSimpleSet {
variable: StmtParam,
value: SimpleSelectValue,
},
CsvImport(CsvImport),
Error(anyhow::Error),
}
#[derive(Debug, PartialEq)]
pub(super) enum SimpleSelectValue {
Static(serde_json::Value),
Dynamic(StmtParam),
}
fn parse_sql<'a>(
db_info: &'a DbInfo,
dialect: &'a dyn Dialect,
sql: &'a str,
) -> anyhow::Result<impl Iterator<Item = ParsedStatement> + 'a> {
log::trace!("Parsing {} SQL: {sql}", db_info.dbms_name);
let tokens = Tokenizer::new(dialect, sql)
.tokenize_with_location()
.map_err(|err| {
let location = err.location;
anyhow::Error::new(err).context(format!("The SQLPage parser could not understand the SQL file. Tokenization failed. Please check for syntax errors:\n{}", quote_source_with_highlight(sql, location.line, location.column)))
})?;
let mut parser = Parser::new(dialect).with_tokens_with_locations(tokens);
let mut has_error = false;
Ok(std::iter::from_fn(move || {
if has_error {
// Return the first error and ignore the rest
return None;
}
let statement = parse_single_statement(&mut parser, db_info, sql);
log::debug!("Parsed statement: {statement:?}");
if let Some(ParsedStatement::Error(_)) = &statement {
has_error = true;
}
statement
}))
}
fn transform_to_positional_placeholders(stmt: &mut StmtWithParams, kind: AnyKind) {
if let Some((_, DbPlaceHolder::Positional { placeholder })) = DB_PLACEHOLDERS
.iter()
.find(|(placeholder_kind, _)| *placeholder_kind == kind)
{
let mut new_params = Vec::new();
let mut query = stmt.query.clone();
while let Some(pos) = query.find(TEMP_PLACEHOLDER_PREFIX) {
let start_of_number = pos + TEMP_PLACEHOLDER_PREFIX.len();
let end = query[start_of_number..]
.find(|c: char| !c.is_ascii_digit())
.map_or(query.len(), |i| start_of_number + i);
let param_idx = query[start_of_number..end].parse::<usize>().unwrap_or(1) - 1;
query.replace_range(pos..end, placeholder);
new_params.push(stmt.params[param_idx].clone());
}
stmt.query = query;
stmt.params = new_params;
}
}
fn parse_single_statement(
parser: &mut Parser<'_>,
db_info: &DbInfo,
source_sql: &str,
) -> Option<ParsedStatement> {
if parser.peek_token() == EOF {
return None;
}
let mut stmt = match parser.parse_statement() {
Ok(stmt) => stmt,
Err(err) => return Some(syntax_error(err, parser, source_sql)),
};
let mut semicolon = false;
while parser.consume_token(&SemiColon) {
semicolon = true;
}
let mut params = match ParameterExtractor::extract_parameters(&mut stmt, db_info.clone()) {
Ok(p) => p,
Err(err) => return Some(ParsedStatement::Error(err)),
};
let dbms = db_info.database_type;
if let Some(parsed) = extract_set_variable(&mut stmt, &mut params, db_info) {
return Some(parsed);
}
if let Some(csv_import) = extract_csv_copy_statement(&mut stmt) {
return Some(ParsedStatement::CsvImport(csv_import));
}
if let Some(static_statement) = extract_static_simple_select(&stmt, ¶ms) {
log::debug!("Optimised a static simple select to avoid a trivial database query: {stmt} optimized to {static_statement:?}");
return Some(ParsedStatement::StaticSimpleSelect {
values: static_statement,
query_position: extract_query_start(&stmt),
});
}
let delayed_functions = extract_toplevel_functions(&mut stmt);
if let Err(err) = validate_function_calls(&stmt) {
return Some(ParsedStatement::Error(err));
}
let json_columns = extract_json_columns(&stmt, dbms);
let query = format!(
"{stmt}{semicolon}",
semicolon = if semicolon { ";" } else { "" }
);
let mut stmt_with_params = StmtWithParams {
query,
query_position: extract_query_start(&stmt),
params,
delayed_functions,
json_columns,
};
transform_to_positional_placeholders(&mut stmt_with_params, db_info.kind);
log::debug!("Final transformed statement: {}", stmt_with_params.query);
Some(ParsedStatement::StmtWithParams(stmt_with_params))
}
fn extract_query_start(stmt: &impl Spanned) -> SourceSpan {
let location = stmt.span();
SourceSpan {
start: SourceLocation {
line: usize::try_from(location.start.line).unwrap_or(0),
column: usize::try_from(location.start.column).unwrap_or(0),
},
end: SourceLocation {
line: usize::try_from(location.end.line).unwrap_or(0),
column: usize::try_from(location.end.column).unwrap_or(0),
},
}
}
fn syntax_error(err: ParserError, parser: &Parser, sql: &str) -> ParsedStatement {
let Span {
start: Location {
line: start_line,
column: start_column,
},
end: Location { line: end_line, .. },
} = parser.peek_token_no_skip().span;
let mut msg = String::from(
"Parsing failed: SQLPage couldn't understand the SQL file. Please check for syntax errors on ",
);
if start_line == end_line {
write!(&mut msg, "line {start_line}:").unwrap();
} else {
write!(&mut msg, "lines {start_line} to {end_line}:").unwrap();
}
write!(
&mut msg,
"\n{}",
quote_source_with_highlight(sql, start_line, start_column)
)
.unwrap();
ParsedStatement::Error(anyhow::Error::from(err).context(msg))
}
fn dialect_for_db(dbms: SupportedDatabase) -> Box<dyn Dialect> {
match dbms {
SupportedDatabase::Duckdb => Box::new(DuckDbDialect {}),
SupportedDatabase::Oracle => Box::new(OracleDialect {}),
SupportedDatabase::Postgres => Box::new(PostgreSqlDialect {}),
SupportedDatabase::Generic => Box::new(GenericDialect {}),
SupportedDatabase::Mssql => Box::new(MsSqlDialect {}),
SupportedDatabase::MySql => Box::new(MySqlDialect {}),
SupportedDatabase::Sqlite => Box::new(SQLiteDialect {}),
SupportedDatabase::Snowflake => Box::new(SnowflakeDialect {}),
}
}
#[derive(Debug, PartialEq)]
pub struct DelayedFunctionCall {
pub function: SqlPageFunctionName,
pub argument_col_names: Vec<String>,
pub target_col_name: String,
}
/// The execution of top-level functions is delayed until after the query has been executed.
/// For instance, `SELECT sqlpage.fetch(x) FROM t` will be executed as `SELECT x as _sqlpage_f0_a0 FROM t`
/// and the `sqlpage.fetch` function will be called with the value of `_sqlpage_f0_a0` after the query has been executed,
/// on each row of the result set.
fn extract_toplevel_functions(stmt: &mut Statement) -> Vec<DelayedFunctionCall> {
struct SelectItemToAdd {
expr_to_insert: SelectItem,
position: usize,
}
let mut delayed_function_calls: Vec<DelayedFunctionCall> = Vec::new();
let set_expr = match stmt {
Statement::Query(q) => q.body.as_mut(),
_ => return delayed_function_calls,
};
let select_items = match set_expr {
sqlparser::ast::SetExpr::Select(s) => &mut s.projection,
_ => return delayed_function_calls,
};
let mut select_items_to_add: Vec<SelectItemToAdd> = Vec::new();
for (position, select_item) in select_items.iter_mut().enumerate() {
let SelectItem::ExprWithAlias {
expr:
Expr::Function(Function {
name: ObjectName(func_name_parts),
args:
FunctionArguments::List(FunctionArgumentList {
args,
duplicate_treatment: None,
..
}),
..
}),
alias,
} = select_item
else {
continue;
};
let Some(func_name) = extract_sqlpage_function_name(func_name_parts) else {
continue;
};
func_name_parts.clear(); // mark the function for deletion
let mut argument_col_names = Vec::with_capacity(args.len());
for (arg_idx, arg) in args.iter_mut().enumerate() {
match arg {
FunctionArg::Unnamed(FunctionArgExpr::Expr(expr))
| FunctionArg::Named {
arg: FunctionArgExpr::Expr(expr),
..
} => {
let func_idx = delayed_function_calls.len();
let argument_col_name = format!("_sqlpage_f{func_idx}_a{arg_idx}");
argument_col_names.push(argument_col_name.clone());
let expr_to_insert = SelectItem::ExprWithAlias {
expr: std::mem::replace(expr, Expr::value(Value::Null)),
alias: Ident::with_quote('"', argument_col_name),
};
select_items_to_add.push(SelectItemToAdd {
expr_to_insert,
position,
});
}
other => {
log::error!("Unsupported argument to {func_name}: {other}");
}
}
}
delayed_function_calls.push(DelayedFunctionCall {
function: func_name,
argument_col_names,
target_col_name: alias.value.clone(),
});
}
// Insert the new select items (the function arguments) at the positions where the function calls were
let mut it = select_items_to_add.into_iter().peekable();
*select_items = std::mem::take(select_items)
.into_iter()
.enumerate()
.flat_map(|(position, item)| {
let mut items = Vec::with_capacity(1);
while it.peek().is_some_and(|x| x.position == position) {
items.push(it.next().unwrap().expr_to_insert);
}
if items.is_empty() {
items.push(item);
}
items
})
.collect();
delayed_function_calls
}
fn extract_static_simple_select(
stmt: &Statement,
params: &[StmtParam],
) -> Option<Vec<(String, SimpleSelectValue)>> {
let set_expr = match stmt {
Statement::Query(q)
if q.limit_clause.is_none()
&& q.fetch.is_none()
&& q.order_by.is_none()
&& q.with.is_none()
&& q.locks.is_empty() =>
{
q.body.as_ref()
}
_ => return None,
};
let select_items = match set_expr {
sqlparser::ast::SetExpr::Select(s)
if s.cluster_by.is_empty()
&& s.distinct.is_none()
&& s.distribute_by.is_empty()
&& s.from.is_empty()
&& s.group_by == sqlparser::ast::GroupByExpr::Expressions(vec![], vec![])
&& s.having.is_none()
&& s.into.is_none()
&& s.lateral_views.is_empty()
&& s.named_window.is_empty()
&& s.qualify.is_none()
&& s.selection.is_none()
&& s.sort_by.is_empty()
&& s.top.is_none() =>
{
&s.projection
}
_ => return None,
};
let mut items = Vec::with_capacity(select_items.len());
let mut params_iter = params.iter().cloned();
for select_item in select_items {
let sqlparser::ast::SelectItem::ExprWithAlias { expr, alias } = select_item else {
return None;
};
let value = expr_to_simple_select_val(&mut params_iter, expr)?;
let key = alias.value.clone();
items.push((key, value));
}
if let Some(p) = params_iter.next() {
log::error!("static select extraction failed because of extraneous parameter: {p:?}");
return None;
}
Some(items)
}
fn expr_to_simple_select_val(
params_iter: &mut impl Iterator<Item = StmtParam>,
expr: &Expr,
) -> Option<SimpleSelectValue> {
use serde_json::Value::{Bool, Null, Number, String};
use SimpleSelectValue::{Dynamic, Static};
Some(match expr {
Expr::Value(ValueWithSpan {
value: Value::Boolean(b),
..
}) => Static(Bool(*b)),
Expr::Value(ValueWithSpan {
value: Value::Number(n, _),
..
}) => Static(Number(n.parse().ok()?)),
Expr::Value(ValueWithSpan {
value: Value::SingleQuotedString(s),
..
}) => Static(String(s.clone())),
Expr::Value(ValueWithSpan {
value: Value::Null, ..
}) => Static(Null),
e if is_simple_select_placeholder(e) => {
if let Some(p) = params_iter.next() {
Dynamic(p)
} else {
log::error!("Parameter not extracted for placehorder: {expr:?}");
return None;
}
}
other => {
log::trace!("Cancelling simple select optimization because of expr: {other:?}");
return None;
}
})
}
fn is_simple_select_placeholder(e: &Expr) -> bool {
match e {
Expr::Value(ValueWithSpan {
value: Value::Placeholder(_),
..
}) => true,
Expr::Cast {
expr,
data_type: DataType::Text | DataType::Varchar(_) | DataType::Char(_),
format: None,
kind: CastKind::Cast,
..
} if is_simple_select_placeholder(expr) => true,
_ => false,
}
}
fn extract_set_variable(
stmt: &mut Statement,
params: &mut Vec<StmtParam>,
db_info: &DbInfo,
) -> Option<ParsedStatement> {
if let Statement::Set(Set::SingleAssignment {
variable: ObjectName(name),
values,
scope: None,
hivevar: false,
}) = stmt
{
if let ([ObjectNamePart::Identifier(ident)], [value]) =
(name.as_mut_slice(), values.as_mut_slice())
{
let variable = if let Some(variable) = extract_ident_param(ident) {
variable
} else {
StmtParam::PostOrGet(std::mem::take(&mut ident.value))
};
let owned_expr = std::mem::replace(value, Expr::value(Value::Null));
let mut params_iter = params.iter().cloned();
if let Some(value) = expr_to_simple_select_val(&mut params_iter, &owned_expr) {
return Some(ParsedStatement::StaticSimpleSet { variable, value });
}
let mut select_stmt: Statement = expr_to_statement(owned_expr);
let delayed_functions = extract_toplevel_functions(&mut select_stmt);
if let Err(err) = validate_function_calls(&select_stmt) {
return Some(ParsedStatement::Error(err));
}
let json_columns = extract_json_columns(&select_stmt, db_info.database_type);
let mut value = StmtWithParams {
query: select_stmt.to_string(),
query_position: extract_query_start(&select_stmt),
params: std::mem::take(params),
delayed_functions,
json_columns,
};
transform_to_positional_placeholders(&mut value, db_info.kind);
return Some(ParsedStatement::SetVariable { variable, value });
}
}
None
}
const SQLPAGE_FUNCTION_NAMESPACE: &str = "sqlpage";
fn is_sqlpage_func(func_name_parts: &[ObjectNamePart]) -> bool {
if let [ObjectNamePart::Identifier(Ident { value, .. }), ObjectNamePart::Identifier(Ident { .. })] =
func_name_parts
{
value == SQLPAGE_FUNCTION_NAMESPACE
} else {
false
}
}
fn extract_sqlpage_function_name(
func_name_parts: &[ObjectNamePart],
) -> Option<SqlPageFunctionName> {
if let [ObjectNamePart::Identifier(Ident {
value: namespace, ..
}), ObjectNamePart::Identifier(Ident { value, .. })] = func_name_parts
{
if namespace == SQLPAGE_FUNCTION_NAMESPACE {
return SqlPageFunctionName::from_str(value).ok();
}
}
None
}
fn sqlpage_func_name(func_name_parts: &[ObjectNamePart]) -> &str {
if let [ObjectNamePart::Identifier(Ident { .. }), ObjectNamePart::Identifier(Ident { value, .. })] =
func_name_parts
{
value
} else {
debug_assert!(
false,
"sqlpage function name should have been checked by is_sqlpage_func"
);
""
}
}
fn extract_json_columns(stmt: &Statement, dbms: SupportedDatabase) -> Vec<String> {
// Only extract JSON columns for databases without native JSON support
if matches!(dbms, SupportedDatabase::Postgres | SupportedDatabase::Mssql) {
return Vec::new();
}
let mut json_columns = Vec::new();
if let Statement::Query(query) = stmt {
if let SetExpr::Select(select) = query.body.as_ref() {
for item in &select.projection {
if let SelectItem::ExprWithAlias { expr, alias } = item {
if is_json_function(expr) {
json_columns.push(alias.value.clone());
log::trace!("Found JSON column: {alias}");
}
}
}
}
}
json_columns
}
fn is_json_function(expr: &Expr) -> bool {
match expr {
Expr::Function(function) => {
if let [ObjectNamePart::Identifier(Ident { value, .. })] = function.name.0.as_slice() {
[
"json_object",
"json_array",
"json_build_object",
"json_build_array",
"to_json",
"to_jsonb",
"json_agg",
"jsonb_agg",
"json_arrayagg",
"json_objectagg",
"json_group_array",
"json_group_object",
"json",
"jsonb",
]
.iter()
.any(|&func| value.eq_ignore_ascii_case(func))
} else {
false
}
}
Expr::Cast { data_type, .. } => {
if matches!(data_type, DataType::JSON | DataType::JSONB) {
true
} else if let DataType::Custom(ObjectName(parts), _) = data_type {
if let [ObjectNamePart::Identifier(ident)] = parts.as_slice() {
ident.value.eq_ignore_ascii_case("json")
} else {
false
}
} else {
false
}
}
_ => false,
}
}
fn expr_to_statement(expr: Expr) -> Statement {
Statement::Query(Box::new(sqlparser::ast::Query {
with: None,
body: Box::new(sqlparser::ast::SetExpr::Select(Box::new(
sqlparser::ast::Select {
select_token: AttachedToken(TokenWithSpan::new(
Token::make_keyword("SELECT"),
expr.span(),
)),
distinct: None,
top: None,
projection: vec![SelectItem::ExprWithAlias {
expr,
alias: Ident::new("sqlpage_set_expr"),
}],
into: None,
from: vec![],
lateral_views: vec![],
selection: None,
group_by: sqlparser::ast::GroupByExpr::Expressions(vec![], vec![]),
cluster_by: vec![],
distribute_by: vec![],
sort_by: vec![],
having: None,
named_window: vec![],
qualify: None,
top_before_distinct: false,
prewhere: None,
window_before_qualify: false,
value_table_mode: None,
connect_by: Vec::new(),
optimizer_hint: None,
select_modifiers: None,
flavor: SelectFlavor::Standard,
exclude: None,
},
))),
order_by: None,
limit_clause: None,
fetch: None,
locks: vec![],
for_clause: None,
settings: None,
format_clause: None,
pipe_operators: Vec::new(),
}))
}
#[cfg(test)]
mod test {
use super::super::sqlpage_functions::functions::SqlPageFunctionName;
use super::super::syntax_tree::SqlPageFunctionCall;
use super::*;
fn parse_stmt(sql: &str, dialect: &dyn Dialect) -> Statement {
let mut ast = Parser::parse_sql(dialect, sql).unwrap();
assert_eq!(ast.len(), 1);
ast.pop().unwrap()
}
fn parse_postgres_stmt(sql: &str) -> Statement {
parse_stmt(sql, &PostgreSqlDialect {})
}
#[test]
fn test_statement_rewrite() {
let mut ast =
parse_postgres_stmt("select $a from t where $x > $a OR $x = sqlpage.cookie('cookoo')");
let db_info = create_test_db_info(SupportedDatabase::Postgres);
let parameters = ParameterExtractor::extract_parameters(&mut ast, db_info).unwrap();
// $a -> $1
// $x -> $2
// sqlpage.cookie(...) -> $3
assert_eq!(
ast.to_string(),
"SELECT CAST($1 AS TEXT) FROM t WHERE CAST($2 AS TEXT) > CAST($1 AS TEXT) OR CAST($2 AS TEXT) = CAST($3 AS TEXT)"
);
assert_eq!(
parameters,
[
StmtParam::PostOrGet("a".to_string()),
StmtParam::PostOrGet("x".to_string()),
StmtParam::FunctionCall(SqlPageFunctionCall {
function: SqlPageFunctionName::cookie,
arguments: vec![StmtParam::Literal("cookoo".to_string())]
}),
]
);
}
#[test]
fn test_statement_rewrite_sqlite() {
let mut ast = parse_stmt("select $x, :y from t", &SQLiteDialect {});
let db_info = create_test_db_info(SupportedDatabase::Sqlite);
let parameters = ParameterExtractor::extract_parameters(&mut ast, db_info).unwrap();
assert_eq!(
ast.to_string(),
"SELECT CAST(?1 AS TEXT), CAST(?2 AS TEXT) FROM t"
);
assert_eq!(
parameters,
[
StmtParam::PostOrGet("x".to_string()),
StmtParam::Post("y".to_string()),
]
);
}
const ALL_DIALECTS: &[(&dyn Dialect, SupportedDatabase)] = &[
(&PostgreSqlDialect {}, SupportedDatabase::Postgres),
(&MsSqlDialect {}, SupportedDatabase::Mssql),
(&MySqlDialect {}, SupportedDatabase::MySql),
(&SQLiteDialect {}, SupportedDatabase::Sqlite),
];
fn create_test_db_info(database_type: SupportedDatabase) -> DbInfo {
let kind = match database_type {
SupportedDatabase::Postgres => AnyKind::Postgres,
SupportedDatabase::Mssql => AnyKind::Mssql,
SupportedDatabase::MySql => AnyKind::MySql,
SupportedDatabase::Sqlite => AnyKind::Sqlite,
_ => AnyKind::Odbc,
};
DbInfo {
dbms_name: database_type.display_name().to_string(),
database_type,
kind,
}
}
#[test]
fn test_duckdb_odbc_dialect_selection() {
use std::any::Any;
let dbms = SupportedDatabase::from_dbms_name("DuckDB");
assert_eq!(dbms, SupportedDatabase::Duckdb);
let dialect = dialect_for_db(dbms);
assert_eq!(dialect.as_ref().type_id(), (DuckDbDialect {}).type_id());
let sql = "select {'a': 1, 'b': 2} as payload";
let db_info = create_test_db_info(dbms);
let mut parsed = parse_sql(&db_info, dialect.as_ref(), sql).unwrap();
let stmt = parsed.next().expect("expected one statement");
assert!(
!matches!(stmt, ParsedStatement::Error(_)),
"duckdb dictionary literals should parse"
);
let pg_info = create_test_db_info(SupportedDatabase::Postgres);
let mut parsed = parse_sql(&pg_info, &PostgreSqlDialect {}, sql).unwrap();
let stmt = parsed.next().expect("expected one statement");
assert!(
matches!(stmt, ParsedStatement::Error(_)),
"postgres should reject duckdb dictionary literals"
);
}
#[test]
fn test_extract_toplevel_delayed_functions() {
let mut ast = parse_stmt(
"select sqlpage.fetch($x) as x, sqlpage.persist_uploaded_file('a', 'b') as y from t",
&PostgreSqlDialect {},
);
let functions = extract_toplevel_functions(&mut ast);
assert_eq!(
ast.to_string(),
"SELECT $x AS \"_sqlpage_f0_a0\", 'a' AS \"_sqlpage_f1_a0\", 'b' AS \"_sqlpage_f1_a1\" FROM t"
);
assert_eq!(
functions,
vec![
DelayedFunctionCall {
function: SqlPageFunctionName::fetch,
argument_col_names: vec!["_sqlpage_f0_a0".to_string()],
target_col_name: "x".to_string()
},
DelayedFunctionCall {
function: SqlPageFunctionName::persist_uploaded_file,
argument_col_names: vec![
"_sqlpage_f1_a0".to_string(),
"_sqlpage_f1_a1".to_string()
],
target_col_name: "y".to_string()
}
]
);
}
#[test]
fn test_extract_toplevel_delayed_functions_parameter_order() {
// The order of the function arguments should be preserved
// Otherwise the statement parameters will be bound to the wrong arguments
let sql = "select $a as a, sqlpage.exec('xxx', x = $b) as b, $c as c from t";
let mut ast = parse_postgres_stmt(sql);
let delayed_functions = extract_toplevel_functions(&mut ast);
assert_eq!(
ast.to_string(),
"SELECT $a AS a, 'xxx' AS \"_sqlpage_f0_a0\", x = $b AS \"_sqlpage_f0_a1\", $c AS c FROM t"
);
assert_eq!(
delayed_functions,
&[DelayedFunctionCall {
function: SqlPageFunctionName::exec,
argument_col_names: vec![
"_sqlpage_f0_a0".to_string(),
"_sqlpage_f0_a1".to_string()
],
target_col_name: "b".to_string()
}]
);
}
#[test]
fn test_sqlpage_function_with_argument() {
for &(dialect, _kind) in ALL_DIALECTS {
let sql = "select sqlpage.fetch($x)";
let mut ast = parse_stmt(sql, dialect);
let db_info = create_test_db_info(SupportedDatabase::Postgres);
let parameters = ParameterExtractor::extract_parameters(&mut ast, db_info).unwrap();
assert_eq!(
parameters,
[StmtParam::FunctionCall(SqlPageFunctionCall {
function: SqlPageFunctionName::fetch,
arguments: vec![StmtParam::PostOrGet("x".to_string())]
})],
"Failed for dialect {dialect:?}"
);
}
}
#[test]
fn test_parse_sql_unsupported_expr_in_sqlpage_arg() {
let sql = "SELECT sqlpage.link('x', json_build_object('k', c)) FROM (SELECT 1 AS c) t";
let db_info = create_test_db_info(SupportedDatabase::Postgres);
let mut parsed = parse_sql(&db_info, &PostgreSqlDialect {}, sql).unwrap();
let stmt = parsed.next().expect("one statement");
let ParsedStatement::Error(err) = stmt else {
panic!("expected ParsedStatement::Error: {stmt:?}");
};
let err_msg = format!("{err:#}");
assert!(
err_msg.contains("Unsupported sqlpage function argument:"),
"{err_msg}"
);
assert!(err_msg.contains("\"c\" is an sql expression, which cannot be passed as a nested sqlpage function argument."), "{err_msg}");
}
#[test]
fn test_parse_sql_unemulated_function_in_sqlpage_arg() {
let sql = "SELECT sqlpage.link('x', upper('a')) FROM (SELECT 1) t";
let db_info = create_test_db_info(SupportedDatabase::Postgres);
let mut parsed = parse_sql(&db_info, &PostgreSqlDialect {}, sql).unwrap();
let stmt = parsed.next().expect("one statement");
let ParsedStatement::Error(err) = stmt else {
panic!("expected ParsedStatement::Error: {stmt:?}");
};
let err_msg = format!("{err:#}");
assert!(
err_msg.contains("Unsupported sqlpage function argument:"),
"{err_msg}"
);
assert!(
err_msg.contains("\"upper\" is not a supported sqlpage function"),
"{err_msg}"
);
}
#[test]
fn test_set_variable_to_other_variable() {
let sql = "set x = $y";
for &(dialect, dbms) in ALL_DIALECTS {
let mut parser = Parser::new(dialect).try_with_sql(sql).unwrap();
let db_info = create_test_db_info(dbms);
match parse_single_statement(&mut parser, &db_info, sql) {
Some(ParsedStatement::StaticSimpleSet { variable, value }) => {
assert_eq!(
variable,
StmtParam::PostOrGet("x".to_string()),
"{dialect:?}"
);
assert_eq!(
value,
SimpleSelectValue::Dynamic(StmtParam::PostOrGet("y".to_string()))
);
}
other => panic!("Failed for dialect {dialect:?}: {other:#?}"),
}
}
}
#[test]
fn is_own_placeholder() {
assert!(ParameterExtractor {
db_info: create_test_db_info(SupportedDatabase::Postgres),
parameters: vec![],
extract_error: None,
}
.is_own_placeholder("$1"));
assert!(ParameterExtractor {
db_info: create_test_db_info(SupportedDatabase::Postgres),
parameters: vec![StmtParam::Get("x".to_string())],
extract_error: None,
}
.is_own_placeholder("$2"));
assert!(!ParameterExtractor {
db_info: create_test_db_info(SupportedDatabase::Postgres),
parameters: vec![],
extract_error: None,
}
.is_own_placeholder("$2"));
assert!(ParameterExtractor {
db_info: create_test_db_info(SupportedDatabase::Sqlite),
parameters: vec![],
extract_error: None,
}
.is_own_placeholder("?1"));
assert!(!ParameterExtractor {
db_info: create_test_db_info(SupportedDatabase::Sqlite),
parameters: vec![],
extract_error: None,
}
.is_own_placeholder("$1"));
}
#[test]
fn test_mssql_statement_rewrite() {
let mut ast = parse_stmt(
"select '' || $1 from [a schema].[a table]",
&MsSqlDialect {},
);
let db_info = create_test_db_info(SupportedDatabase::Mssql);
let parameters = ParameterExtractor::extract_parameters(&mut ast, db_info).unwrap();
assert_eq!(