Skip to content

Commit 58b3331

Browse files
committed
Merge remote-tracking branch 'github/main' into fix/parser-gaps-g
2 parents b196cbd + 0f90ecc commit 58b3331

12 files changed

Lines changed: 172 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,15 @@ Converted SQL is proven only where both sessions run in UTC: Snowflake's `TIMEZO
3434
```console
3535
$ cargo run --release -p sqlquack -- check query.sql
3636
$ echo "SELECT 1 QUALIFY TRUE" | cargo run --release -p sqlquack -- check --json
37+
$ cargo run --release -p sqlquack -- explain SQ0203
3738
```
3839

3940
`check` parses Snowflake SQL and reports what Snowflake would reject, without a schema or a
4041
conversion. It prints coded diagnostics on standard error, and `--json` prints
4142
`{"ok": …, "diagnostics": [...]}`. It exits 0 when it finds nothing, 1 when it finds a problem and
42-
2 for input without SQL.
43+
2 for input without SQL. `explain` prints a diagnostic code's meaning, help and an example that
44+
draws it; it takes the code, its name or a guard's former `E_GUARD_*` name, and exits 2 for an
45+
unknown one.
4346

4447
## Convert
4548

@@ -78,10 +81,11 @@ error[SQ0004]: a name does not resolve
7881
With `--json`, each refusal also carries the same diagnostic: `code`, `name`, `alias` (a parser
7982
guard's former `E_GUARD_*` name), `message`, `span` (character `start` and `end`, one-based `line`,
8083
`column`, `end_line` and `end_column`), `label`, `notes` and `help`. Codes are `SQ` and four digits,
81-
listed with an explanation each in `crates/sqlquack-core/src/diagnostics/constants.rs`; a code is
82-
never reused or renumbered. SQL that Snowflake parses but then rejects, such as `INTERSECT ALL`,
83-
`FOR UPDATE WAIT`, `QUALIFY` without a window function, or a `* ILIKE` `REPLACE` or `RENAME` of
84-
a column the pattern removes, is refused with its own `SQ02xx` code instead of being converted.
84+
listed with an explanation each in `crates/sqlquack-core/src/diagnostics/constants.rs`, which
85+
`sqlquack explain <code>` prints; a code is never reused or renumbered. SQL that Snowflake parses
86+
but then rejects, such as `INTERSECT ALL`, `FOR UPDATE WAIT`, `QUALIFY` without a window function,
87+
or a `* ILIKE` `REPLACE` or `RENAME` of a column the pattern removes, is refused with its own
88+
`SQ02xx` code instead of being converted.
8589
A `VALUES` list of more than 1,000 rows is refused for now.
8690
`--session NAME=VALUE` passes the caller's Snowflake session parameters
8791
(`function` takes it too):

‎crates/sqlquack-core/src/diagnostics/constants.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ pub const CODES: &[CodeEntry] = &[
5959
parser's message. Check the SQL at that point against Snowflake's grammar; if \
6060
Snowflake accepts the statement, SQLQuack's parser is missing the syntax and the \
6161
statement should be reported with the label.",
62+
example: r#"echo "SELECT a, FROM orders WHERE (b = 1" | sqlquack check"#,
6263
},
6364
CodeEntry {
6465
code: MISSING_RULE,
@@ -71,6 +72,7 @@ pub const CODES: &[CodeEntry] = &[
7172
the statement is refused rather than converted to SQL that might mean something \
7273
else in DuckDB. Rewrite the statement without the construct, or wait for a rule; \
7374
`sqlquack census` shows which constructs a body of SQL needs.",
75+
example: r#"echo "SELECT WEEKISO(CURRENT_DATE()) AS w" | sqlquack convert --builtin-policy"#,
7476
},
7577
CodeEntry {
7678
code: TYPE_CONDITION,
@@ -85,6 +87,7 @@ pub const CODES: &[CodeEntry] = &[
8587
determine. Declaring the relation's columns and types in the schema often lets the \
8688
types resolve; an explicit cast to a covered type also works when it keeps the \
8789
statement's meaning.",
90+
example: r#"echo "SELECT FLOOR('abc') AS f" | sqlquack convert --builtin-policy"#,
8891
},
8992
CodeEntry {
9093
code: UNRESOLVED_NAME,
@@ -98,6 +101,7 @@ pub const CODES: &[CodeEntry] = &[
98101
name refers to and what type it has. The name at the span is unknown, or resolves to \
99102
more than one column. Add the relation and its columns to the schema file, or \
100103
qualify an ambiguous column with its relation.",
104+
example: r#"echo "SELECT a FROM orders" | sqlquack convert --builtin-policy"#,
101105
},
102106
CodeEntry {
103107
code: NOT_EXPRESSIBLE,
@@ -108,6 +112,7 @@ pub const CODES: &[CodeEntry] = &[
108112
explanation: "The construct at the span has a Snowflake meaning DuckDB has no way to \
109113
reproduce, for the reason in the label. No future rule will convert it as written. \
110114
Rewrite the statement so it does not depend on that behaviour.",
115+
example: "no construct is declared inexpressible yet; one would be refused with the reason as its label",
111116
},
112117
CodeEntry {
113118
code: CONVERSION_BUDGET,
@@ -119,6 +124,7 @@ pub const CODES: &[CodeEntry] = &[
119124
the conversion budget allows. The budget keeps a pathological input from stalling a \
120125
caller. Splitting the statement, for example into common table expressions or \
121126
separate statements, usually brings it under the budget.",
127+
example: "a statement whose conversion runs past the time budget or emits more DuckDB SQL than it allows",
122128
},
123129
CodeEntry {
124130
code: SESSION_PARAMETERS,
@@ -130,6 +136,7 @@ pub const CODES: &[CodeEntry] = &[
130136
session parameters given match none of them, so no conversion is proven for that \
131137
session. The label names the parameters; unset parameters take Snowflake's \
132138
documented defaults.",
139+
example: r#"echo "SELECT 1 AS one" | sqlquack convert --builtin-policy --session WEEK_START=1"#,
133140
},
134141
CodeEntry {
135142
code: DIVERGENCE_REFUSED,
@@ -147,6 +154,7 @@ pub const CODES: &[CodeEntry] = &[
147154
the statement is refused. Allow it in the policy file, use a mode that allows it, \
148155
or confirm the assumption it rests on; otherwise rewrite the statement without the \
149156
construct.",
157+
example: r#"echo "SELECT HASH(1) AS h" | sqlquack convert --builtin-policy"#,
150158
},
151159
CodeEntry {
152160
code: "SQ0101",
@@ -156,6 +164,7 @@ pub const CODES: &[CodeEntry] = &[
156164
help: Some("split the input into smaller files"),
157165
explanation: "The parser refuses inputs beyond a fixed size so that one input cannot \
158166
exhaust memory. Split the SQL into several inputs and convert each.",
167+
example: r#"python3 -c "print('SELECT 1;' * 2000000)" | sqlquack check"#,
159168
},
160169
CodeEntry {
161170
code: "SQ0102",
@@ -165,6 +174,7 @@ pub const CODES: &[CodeEntry] = &[
165174
help: Some("split the input into smaller statements or files"),
166175
explanation: "The parser refuses inputs with more tokens than its budget so that \
167176
parsing time stays bounded. Split the SQL into several statements or inputs.",
177+
example: r#"python3 -c "print('SELECT 1;' * 400000)" | sqlquack check"#,
168178
},
169179
CodeEntry {
170180
code: "SQ0103",
@@ -178,6 +188,7 @@ pub const CODES: &[CodeEntry] = &[
178188
parser's limit. The limit keeps parsing from exhausting the stack. Redundant \
179189
parentheses can be removed; deeply nested subqueries can usually become common \
180190
table expressions.",
191+
example: r#"python3 -c "print('SELECT ' + '(' * 600 + '1' + ')' * 600)" | sqlquack check"#,
181192
},
182193
CodeEntry {
183194
code: "SQ0104",
@@ -188,6 +199,7 @@ pub const CODES: &[CodeEntry] = &[
188199
explanation: "The parser's recursion reached its depth limit at the span. The limit \
189200
keeps parsing from exhausting the stack. Restructure the deepest part of the \
190201
statement, for example with common table expressions.",
202+
example: r#"python3 -c "print('SELECT ' + 'NOT ' * 2000 + 'TRUE')" | sqlquack check"#,
191203
},
192204
CodeEntry {
193205
code: "SQ0105",
@@ -198,6 +210,7 @@ pub const CODES: &[CodeEntry] = &[
198210
explanation: "The statement parsed, but its tree nests deeper than the limit SQLQuack \
199211
places on later analysis, which keeps conversion from exhausting the stack. \
200212
Restructure the deepest part of the statement.",
213+
example: r#"python3 -c "print('SELECT ' + 'CASE WHEN TRUE THEN ' * 600 + '1' + ' END' * 600)" | sqlquack check"#,
201214
},
202215
CodeEntry {
203216
code: "SQ0106",
@@ -207,6 +220,7 @@ pub const CODES: &[CodeEntry] = &[
207220
help: Some("split the statement into smaller statements"),
208221
explanation: "The statement parsed into more tree nodes than SQLQuack's budget, which \
209222
keeps conversion time and memory bounded. Split it into smaller statements.",
223+
example: "a statement that parses into more than a million tree nodes",
210224
},
211225
CodeEntry {
212226
code: "SQ0107",
@@ -217,6 +231,7 @@ pub const CODES: &[CodeEntry] = &[
217231
explanation: "Function calls nest inside each other deeper than SQLQuack's limit at \
218232
the span. Compute the innermost calls in a common table expression or a subquery \
219233
and refer to their results.",
234+
example: r#"python3 -c "print('SELECT ' + 'ABS(' * 300 + '1' + ')' * 300)" | sqlquack check"#,
220235
},
221236
CodeEntry {
222237
code: "SQ0201",
@@ -229,6 +244,7 @@ pub const CODES: &[CodeEntry] = &[
229244
no Snowflake meaning to convert. Without ALL the \
230245
operators compare distinct rows; keeping duplicates needs a rewrite, for example \
231246
numbering each row with ROW_NUMBER() over all columns and comparing those pairs.",
247+
example: r#"echo "SELECT id FROM orders INTERSECT ALL SELECT id FROM returns" | sqlquack check"#,
232248
},
233249
CodeEntry {
234250
code: "SQ0202",
@@ -239,6 +255,7 @@ pub const CODES: &[CodeEntry] = &[
239255
explanation: "FOR UPDATE WAIT n parses, but Snowflake rejects it as an unsupported \
240256
feature, so the statement never runs there. Remove the WAIT clause; Snowflake's \
241257
lock timeout comes from the LOCK_TIMEOUT session parameter instead.",
258+
example: r#"echo "SELECT order_id FROM orders FOR UPDATE WAIT 7" | sqlquack check"#,
242259
},
243260
CodeEntry {
244261
code: "SQ0203",
@@ -253,6 +270,7 @@ pub const CODES: &[CodeEntry] = &[
253270
function (Snowflake error 992). A window function the QUALIFY condition reaches \
254271
through a SELECT-list alias counts. A condition on plain columns belongs in WHERE, \
255272
and one on aggregates in HAVING.",
273+
example: r#"echo "SELECT 1 QUALIFY TRUE" | sqlquack check"#,
256274
},
257275
CodeEntry {
258276
code: "SQ0204",
@@ -264,5 +282,6 @@ pub const CODES: &[CodeEntry] = &[
264282
the pattern first, ignoring case, and rejects a REPLACE or RENAME of a column the \
265283
pattern did not keep (Snowflake error 1431). A name that fails the pattern ignoring \
266284
case fails it whatever the table holds, so no schema is needed to see it.",
285+
example: r#"echo "SELECT * ILIKE '%_id' REPLACE (price * 2 AS price) FROM orders" | sqlquack check"#,
267286
},
268287
];
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
//! `explain_code`: a registered code's title, explanation, help and example, as text.
2+
3+
use crate::diagnostics::_helpers::code_entry::code_entry;
4+
5+
/// The explanation of the code whose code, name or alias is `key`, ignoring case; `None` when none is.
6+
pub fn explain_code(key: &str) -> Option<String> {
7+
let entry = code_entry(key)?;
8+
let alias = match entry.alias {
9+
Some(alias) => format!(" (formerly {alias})"),
10+
None => String::new(),
11+
};
12+
let help = match entry.help {
13+
Some(help) => format!("help: {help}\n\n"),
14+
None => String::new(),
15+
};
16+
Some(format!(
17+
"{code} {name}{alias}: {title}\n\n{explanation}\n\n{help}example:\n {example}\n",
18+
code = entry.code,
19+
name = entry.name,
20+
title = entry.title,
21+
explanation = entry.explanation,
22+
example = entry.example,
23+
))
24+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
pub mod diagnose;
2+
pub mod explain_code;
23
pub mod render_diagnostics;
34
pub mod unplaced_diagnostic;

‎crates/sqlquack-core/src/diagnostics/models.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ pub struct CodeEntry {
3434
pub help: Option<&'static str>,
3535
/// One paragraph explaining what the code means and what to do.
3636
pub explanation: &'static str,
37+
/// A command that draws the code, or what input does when no short command can.
38+
pub example: &'static str,
3739
}
3840

3941
/// Where a diagnostic points, in characters of the source; lines and columns are one-based.

‎crates/sqlquack-core/src/diagnostics/tests/helpers.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ pub(crate) fn registry_mismatches(lock: &str, whole_registry: bool) -> Vec<Strin
7373
|| !entry.code[2..].chars().all(|digit| digit.is_ascii_digit())
7474
|| entry.title.trim().is_empty()
7575
|| entry.explanation.trim().is_empty()
76+
|| entry.example.trim().is_empty()
7677
})
7778
.map(|entry| format!("registry {} {}", entry.code, entry.name));
7879
let keys: Vec<String> = CODES

‎crates/sqlquack/src/cli/_helpers/convert_command.rs‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
//! `sqlquack convert` and `sqlquack check`: Snowflake SQL as DuckDB SQL, or what is wrong with it.
1+
//! `sqlquack convert`, `check` and `explain`: Snowflake SQL as DuckDB SQL, what is wrong with it, and what each code means.
22
33
use std::io::{Read, Write};
44
use std::path::Path;
55
use std::process::ExitCode;
66

77
use sqlquack_core::diagnostics::constants::SESSION_PARAMETERS;
88
use sqlquack_core::diagnostics::main::diagnose::diagnose;
9+
use sqlquack_core::diagnostics::main::explain_code::explain_code;
910
use sqlquack_core::diagnostics::main::render_diagnostics::render_diagnostics;
1011
use sqlquack_core::diagnostics::main::unplaced_diagnostic::unplaced_diagnostic;
1112
use sqlquack_core::diagnostics::models::Diagnostic;
@@ -26,7 +27,8 @@ use crate::analysis::main::with_overrides::with_overrides;
2627
use crate::analysis::models::Analysis;
2728
use crate::cli::_helpers::evidence::caller_choices;
2829
use crate::cli::models::{
29-
CheckArguments, CheckReport, ConvertArguments, ConvertRefusal, ConvertReport, OverrideListing,
30+
CheckArguments, CheckReport, ConvertArguments, ConvertRefusal, ConvertReport, ExplainArguments,
31+
OverrideListing,
3032
};
3133

3234
use crate::cli::main::convert_report::convert_report;
@@ -143,6 +145,27 @@ fn source_name(path: Option<&Path>) -> String {
143145
}
144146

145147
/// `sqlquack check`: exit 0 when the SQL holds no problem, 1 with diagnostics, 2 without SQL.
148+
pub(crate) fn explain_command(
149+
arguments: &ExplainArguments,
150+
stdout: &mut dyn Write,
151+
stderr: &mut dyn Write,
152+
) -> ExitCode {
153+
match explain_code(&arguments.code) {
154+
Some(text) => {
155+
let _ = write!(stdout, "{text}");
156+
ExitCode::SUCCESS
157+
}
158+
None => {
159+
let _ = writeln!(
160+
stderr,
161+
"sqlquack explain: no diagnostic code, name or former name is `{}`",
162+
arguments.code
163+
);
164+
ExitCode::from(2)
165+
}
166+
}
167+
}
168+
146169
pub(crate) fn check_command(
147170
arguments: &CheckArguments,
148171
stdout: &mut dyn Write,

‎crates/sqlquack/src/cli/main/run_cli.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::cli::_helpers::audit_command::{
88
audit_compare_command, audit_errors_command, audit_sample_command,
99
};
1010
use crate::cli::_helpers::census_command::census_command;
11-
use crate::cli::_helpers::convert_command::{check_command, convert_command};
11+
use crate::cli::_helpers::convert_command::{check_command, convert_command, explain_command};
1212
use crate::cli::_helpers::function_command::function_command;
1313
use crate::cli::_helpers::index_command::index_command;
1414
use crate::cli::_helpers::pending_command::pending_command;
@@ -41,6 +41,7 @@ pub fn run_cli() -> ExitCode {
4141
Command::Convert(arguments) => convert_command(arguments, &mut stdout, &mut stderr),
4242
Command::Check(arguments) => check_command(arguments, &mut stdout, &mut stderr),
4343
Command::Compare(arguments) => compare_command(arguments, &mut stdout, &mut stderr),
44+
Command::Explain(arguments) => explain_command(arguments, &mut stdout, &mut stderr),
4445
Command::Audit(arguments) => match (&arguments.sample, arguments.errors) {
4546
(Some(sample), _) => audit_sample_command(arguments, sample, &mut stderr),
4647
(None, true) => audit_errors_command(arguments, &mut stderr),

‎crates/sqlquack/src/cli/models.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ pub enum Command {
5151
Check(CheckArguments),
5252
/// Replay converted SQL over a DuckDB inputs database and compare with recorded results.
5353
Compare(CompareArguments),
54+
/// Explain a diagnostic code, such as `SQ0203`, with its help and an example.
55+
Explain(ExplainArguments),
56+
}
57+
58+
/// Arguments of `sqlquack explain`.
59+
#[derive(Debug, Args)]
60+
pub struct ExplainArguments {
61+
/// The code, its snake_case name, or a guard's former `E_GUARD_*` name.
62+
pub code: String,
5463
}
5564

5665
/// Arguments of `sqlquack compare`.

‎crates/sqlquack/tests/cli.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ mod test_divergence;
1414
mod test_error_check;
1515
#[path = "cli/test_evidence_commands.rs"]
1616
mod test_evidence_commands;
17+
#[path = "cli/test_explain.rs"]
18+
mod test_explain;
1719
#[path = "cli/test_function.rs"]
1820
mod test_function;
1921
#[path = "cli/test_review.rs"]

0 commit comments

Comments
 (0)