Skip to content

fix: with ordinality #237

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/pglt_statement_splitter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@ values ('insert', new.id, now());",
]);
}

#[test]
fn with_ordinality() {
Tester::from("insert into table (col) select 1 from other t cross join lateral jsonb_array_elements(t.buttons) with ordinality as a(b, nr) where t.buttons is not null;").expect_statements(vec!["insert into table (col) select 1 from other t cross join lateral jsonb_array_elements(t.buttons) with ordinality as a(b, nr) where t.buttons is not null;"]);
}

#[test]
fn unknown() {
Tester::from("random stuff\n\nmore randomness\n\nselect 3").expect_statements(vec![
Expand Down
21 changes: 20 additions & 1 deletion crates/pglt_statement_splitter/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@ impl Parser {

/// Start statement
pub fn start_stmt(&mut self) {
assert!(self.current_stmt_start.is_none());
assert!(
self.current_stmt_start.is_none(),
"cannot start statement within statement at {:?}",
self.tokens.get(self.current_stmt_start.unwrap())
);
self.current_stmt_start = Some(self.next_pos);
}

Expand Down Expand Up @@ -142,6 +146,21 @@ impl Parser {
}
}

/// Look ahead to the next relevant token
fn look_ahead(&self) -> Option<&Token> {
// we need to look ahead to the next relevant token
let mut look_ahead_pos = self.next_pos + 1;
loop {
let token = self.tokens.get(look_ahead_pos)?;

if !is_irrelevant_token(token) {
return Some(token);
}

look_ahead_pos += 1;
}
}

fn look_back(&self) -> Option<&Token> {
// we need to look back to the last relevant token
let mut look_back_pos = self.next_pos - 1;
Expand Down
13 changes: 13 additions & 0 deletions crates/pglt_statement_splitter/src/parser/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,19 @@ pub(crate) fn unknown(p: &mut Parser, exclude: &[SyntaxKind]) {
}
p.advance();
}
Some(SyntaxKind::With) => {
let next = p.look_ahead().map(|t| t.kind);
if [
// WITH ORDINALITY should not start a new statement
SyntaxKind::Ordinality,
]
.iter()
.all(|x| Some(x) != next.as_ref())
{
break;
}
p.advance();
}
Some(_) => {
break;
}
Expand Down