Skip to content

Commit 02b6db1

Browse files
committed
refactor(syntax): split CREATE FUNCTION parsing and meet the layout rules
Move CREATE FUNCTION parsing out of the commands module, return a user credential action's existence flags instead of mutating a parameter, read a procedure's EXECUTE AS in its own helper, keep the template operand switch with the other grammar constants, and parametrize the derived limit test.
1 parent 7754eb4 commit 02b6db1

12 files changed

Lines changed: 654 additions & 613 deletions

File tree

‎crates/sqlquack-syntax-snowflake/src/parser/_helpers/ddl/commands.rs‎

Lines changed: 0 additions & 565 deletions
Large diffs are not rendered by default.

‎crates/sqlquack-syntax-snowflake/src/parser/_helpers/ddl/create_function.rs‎

Lines changed: 574 additions & 0 deletions
Large diffs are not rendered by default.

‎crates/sqlquack-syntax-snowflake/src/parser/_helpers/ddl/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
pub(crate) mod alter;
44
pub(crate) mod commands;
55
pub(crate) mod constraints;
6+
pub(crate) mod create_function;
67
pub(crate) mod create_table;
78
pub(crate) mod create_table_forms;
89
pub(crate) mod explain;

‎crates/sqlquack-syntax-snowflake/src/parser/_helpers/ddl/snowflake_alter_tables.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,6 @@ impl Parser {
195195
let mut properties: Vec<ObjectProperty> = Vec::new();
196196
if self.match_identifier("MAX_SIZE") {
197197
self.expect_token(TokenType::Eq)?;
198-
// Snowflake parses a string here and rejects it only semantically.
199198
let size = if self.check(TokenType::String) {
200199
self.parse_primary()?
201200
} else {

‎crates/sqlquack-syntax-snowflake/src/parser/_helpers/ddl/snowflake_alter_user.rs‎

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,15 @@ impl Parser {
7575
if unnamed && named_only {
7676
return Err(self.parse_error(format!("Expected a user name before {action}")));
7777
}
78-
let mut existence = (false, false);
79-
let (action, parts): Action = match action.as_str() {
80-
"RENAME TO" => (action, (vec![self.parse_user_operand()?], vec![])),
81-
"ADD" | "MODIFY" | "REMOVE" | "ROTATE" => {
82-
self.parse_user_credential_action(action, &mut existence)?
83-
}
84-
"SET" | "UNSET" => self.parse_user_set(action)?,
85-
_ => (action, (vec![], vec![])),
78+
let no_existence = (false, false);
79+
let ((action, parts), existence): (Action, (bool, bool)) = match action.as_str() {
80+
"RENAME TO" => (
81+
(action, (vec![self.parse_user_operand()?], vec![])),
82+
no_existence,
83+
),
84+
"ADD" | "MODIFY" | "REMOVE" | "ROTATE" => self.parse_user_credential_action(action)?,
85+
"SET" | "UNSET" => (self.parse_user_set(action)?, no_existence),
86+
_ => ((action, (vec![], vec![])), no_existence),
8687
};
8788
let Expression::AlterObject(mut alter) =
8889
alter_object("USER", (TableRef::new(""), if_exists), action, parts)
@@ -94,21 +95,21 @@ impl Parser {
9495
Ok(Expression::AlterObject(alter))
9596
}
9697

97-
/// The object of ADD, MODIFY, REMOVE or ROTATE: a credential, an MFA method or a delegated authorization; a token's IF [NOT] EXISTS goes to `existence`.
98+
/// The object of ADD, MODIFY, REMOVE or ROTATE: a credential, an MFA method or a delegated authorization, with a token's IF EXISTS and IF NOT EXISTS.
9899
fn parse_user_credential_action(
99100
&mut self,
100101
mut action: String,
101-
existence: &mut (bool, bool),
102-
) -> Result<Action> {
102+
) -> Result<(Action, (bool, bool))> {
103103
let verb = action.clone();
104+
let mut existence = (false, false);
104105
if self.match_text_seq(&["MFA", "METHOD"]) {
105106
action.push_str(" MFA METHOD");
106-
return self.parse_user_mfa_method(&verb, action);
107+
return Ok((self.parse_user_mfa_method(&verb, action)?, existence));
107108
}
108109
if self.check_identifier("DELEGATED") && matches!(verb.as_str(), "ADD" | "REMOVE") {
109110
self.skip();
110111
action.push_str(" DELEGATED");
111-
return self.parse_user_delegation(&verb, action);
112+
return Ok((self.parse_user_delegation(&verb, action)?, existence));
112113
}
113114
let kind = self.expect_alter_words(CREDENTIALS)?;
114115
let kind = match kind.as_str() {
@@ -138,13 +139,13 @@ impl Parser {
138139
"SET" => (operands, self.parse_user_properties()?),
139140
_ => (operands, self.parse_user_unset_names()?),
140141
};
141-
return Ok((action, parts));
142+
return Ok(((action, parts), existence));
142143
}
143144
"REMOVE" => vec![],
144145
_ if self.is_statement_end_at(0) => vec![],
145146
_ => self.parse_user_properties()?,
146147
};
147-
Ok((action, (operands, properties)))
148+
Ok(((action, (operands, properties)), existence))
148149
}
149150

150151
/// ADD MFA METHOD OTP [ COUNT = n ], REMOVE MFA METHOD <m> or MODIFY MFA METHOD <m> SET COMMENT = '<string>'.

‎crates/sqlquack-syntax-snowflake/src/parser/_helpers/ddl/snowflake_opaque.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ impl Parser {
6060
return checked;
6161
}
6262
let project = matches!(second.as_str(), "PROJECT") && after_name > kind_at + 2;
63-
let project_or_bundle = project || kind == "CODE";
6463
let checked = match kind.as_str() {
6564
"EXTERNAL" if matches!(second.as_str(), "AGENT") => self.check_external_agent_tail(),
6665
"VARIABLE" => self.check_variable_tail(),
@@ -71,7 +70,10 @@ impl Parser {
7170
"NOTEBOOK" if project && !self.check(TokenType::From) => {
7271
Err(self.parse_error("Expected FROM"))
7372
}
74-
"CODE" | "NOTEBOOK" if project_or_bundle && !self.check_next(TokenType::String) => {
73+
"CODE" if !self.check_next(TokenType::String) => {
74+
Err(self.parse_error("Expected a quoted location after FROM"))
75+
}
76+
"NOTEBOOK" if project && !self.check_next(TokenType::String) => {
7577
Err(self.parse_error("Expected a quoted location after FROM"))
7678
}
7779
"PIPE" => self.check_pipe_body(),

‎crates/sqlquack-syntax-snowflake/src/parser/_helpers/expressions/operators.rs‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use sqlquack_syntax::expressions::schema_objects::models::DropType;
2626
use sqlquack_syntax::expressions::schema_objects::models::FunctionBody;
2727
use sqlquack_syntax::expressions::schema_objects::models::FunctionParameter;
2828
use sqlquack_syntax::expressions::schema_objects::models::FunctionSecurity;
29+
use sqlquack_syntax::expressions::schema_objects::models::ObjectProperty;
2930
use sqlquack_syntax::expressions::schema_objects::models::ParameterMode;
3031
use sqlquack_syntax::expressions::schema_objects::models::SeqPropKind;
3132
use sqlquack_syntax::expressions::schema_objects::models::SequenceBound;
@@ -315,6 +316,25 @@ impl Parser {
315316
}
316317
}
317318

319+
/// Reads `AS { CALLER | OWNER | SELF | RESTRICTED CALLER }` after a procedure's EXECUTE; None without AS or an unknown principal outside Snowflake.
320+
fn parse_procedure_execute_as(&mut self) -> Result<Option<String>> {
321+
if !self.match_token(TokenType::As) {
322+
return Ok(None);
323+
}
324+
if self.match_text_seq(&["RESTRICTED", "CALLER"]) {
325+
return Ok(Some("RESTRICTED CALLER".to_string()));
326+
}
327+
for principal in ["CALLER", "OWNER", "SELF"] {
328+
if self.match_identifier(principal) {
329+
return Ok(Some(principal.to_string()));
330+
}
331+
}
332+
match self.is_snowflake() {
333+
true => Err(self.parse_error("Expected OWNER, CALLER or RESTRICTED CALLER")),
334+
false => Ok(None),
335+
}
336+
}
337+
318338
/// Parse CREATE PROCEDURE statement
319339
pub(crate) fn parse_create_procedure(
320340
&mut self,
@@ -346,7 +366,7 @@ impl Parser {
346366
let mut return_type = None;
347367
let mut execute_as = None;
348368
let mut with_options: Vec<String> = Vec::new();
349-
let mut snowflake_properties = Vec::new();
369+
let mut snowflake_properties: Vec<ObjectProperty> = Vec::new();
350370
let mut null_or_volatility = false;
351371

352372
while !self.is_at_end() && !self.check(TokenType::Semicolon) {
@@ -374,18 +394,8 @@ impl Parser {
374394
}
375395
}
376396
} else if self.match_identifier("EXECUTE") || self.match_token(TokenType::Execute) {
377-
if self.match_token(TokenType::As) {
378-
if self.match_identifier("CALLER") {
379-
execute_as = Some("CALLER".to_string());
380-
} else if self.match_identifier("OWNER") {
381-
execute_as = Some("OWNER".to_string());
382-
} else if self.match_identifier("SELF") {
383-
execute_as = Some("SELF".to_string());
384-
} else if self.match_text_seq(&["RESTRICTED", "CALLER"]) {
385-
execute_as = Some("RESTRICTED CALLER".to_string());
386-
} else if self.is_snowflake() {
387-
return Err(self.parse_error("Expected OWNER, CALLER or RESTRICTED CALLER"));
388-
}
397+
if let Some(principal) = self.parse_procedure_execute_as()? {
398+
execute_as = Some(principal);
389399
}
390400
} else if self.match_token(TokenType::Language) {
391401
language = Some(self.expect_identifier_or_keyword()?);

‎scripts/grammar_obligations/_helpers/grammar.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
OPEN_OPTIONAL,
2121
PLACEHOLDER_IN_LITERAL,
2222
QUOTED_PLACEHOLDER,
23+
TEMPLATE_OPERANDS,
2324
TOKEN,
2425
TOKEN_BRACKET,
2526
TOKEN_ELISION,
@@ -31,10 +32,6 @@
3132
)
3233
from scripts.grammar_obligations.models import Node
3334

34-
TEMPLATE_OPERANDS: bool = False
35-
"""Whether a quoted value built from placeholders is a string operand; a dialect's install sets
36-
it."""
37-
3835

3936
def tokens(production: str) -> list[tuple[str, str]]:
4037
"""(kind, text) pairs of a production; a definition's `<name> ::=` head is dropped."""
@@ -169,8 +166,7 @@ def placeholder_name(node: Node) -> str:
169166

170167

171168
def template_name(node: Node) -> str:
172-
"""A quoted value built from placeholders, such as `'<num> MINUTE'`, lower-cased without its
173-
quotes when TEMPLATE_OPERANDS is set; empty for anything else, a lone `'<name>'` included."""
169+
"""Lower-cased unquoted text of a placeholder-built value like `'<num> MINUTE'`; else empty."""
174170
if not TEMPLATE_OPERANDS or node.kind != NODE_TOKEN or node.token_kind != TOKEN_LITERAL:
175171
return ""
176172
if QUOTED_PLACEHOLDER.fullmatch(node.text) or not PLACEHOLDER_IN_LITERAL.search(node.text):

‎scripts/grammar_obligations/constants.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,11 +248,11 @@
248248
)
249249

250250
COMMAND_FAMILIES: frozenset[str] = frozenset({"classes"})
251-
"""Expression-argument families of commands and methods: a leading instance name and a LIKE pattern
252-
are operands there, not call arguments, and a TAG list is a clause, not a call."""
253251

254252
COMMAND_NON_CALL_KEYWORDS: frozenset[str] = frozenset({"TAG"})
255253

254+
TEMPLATE_OPERANDS: bool = False
255+
256256
PLACEHOLDER_IN_LITERAL: re.Pattern[str] = re.compile(r"<[^<>]+>")
257257

258258
STATEMENT_TERMINATOR: str = ";"

‎scripts/syntax_obligations_snowflake/_helpers/rules.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@
1818

1919

2020
def install() -> None:
21-
"""Classify the pages' object and word operands first, then widen the shared integer rule; a
22-
quoted value built from placeholders is a string operand."""
21+
"""Classify object and word operands, widen the integer rule, and read quoted templates."""
2322
grammar.TEMPLATE_OPERANDS = True
2423
grammar.CLASS_RULES = (
2524
(re.compile(IDENTIFIER_NAMES), IDENTIFIER_CLASS),

0 commit comments

Comments
 (0)