Skip to content
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
12 changes: 11 additions & 1 deletion src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14459,7 +14459,7 @@ impl<'a> Parser<'a> {

let order_by = self.parse_optional_order_by()?;

let limit_clause = self.parse_optional_limit_clause()?;
let mut limit_clause = self.parse_optional_limit_clause()?;

let settings = self.parse_settings()?;

Expand All @@ -14479,6 +14479,16 @@ impl<'a> Parser<'a> {
locks.push(self.parse_lock()?);
}
}

// Some databases (e.g. PostgreSQL) accept `LIMIT`/`OFFSET` after the
// row-locking clause (`... FOR UPDATE SKIP LOCKED LIMIT 5`) as well
// as before it. The locking clause above is parsed for every
// dialect, so accept a trailing limit here too rather than gating it
// behind a dialect flag.
if limit_clause.is_none() {
limit_clause = self.parse_optional_limit_clause()?;
}

let format_clause =
if self.dialect.supports_select_format() && self.parse_keyword(Keyword::FORMAT) {
if self.parse_keyword(Keyword::NULL) {
Expand Down
17 changes: 17 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9486,3 +9486,20 @@ fn exclude_as_column_name() {
}
}
}

#[test]
fn parse_limit_after_locking_clause() {
// PostgreSQL accepts `LIMIT`/`OFFSET` after the row-locking clause as well
// as before it; both orderings are semantically identical. The AST renders
// the limit in its canonical position (before the locking clause).
pg().one_statement_parses_to(
"SELECT * FROM t ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 5",
"SELECT * FROM t ORDER BY id LIMIT 5 FOR UPDATE SKIP LOCKED",
);
pg().one_statement_parses_to(
"SELECT * FROM t FOR UPDATE LIMIT 5",
"SELECT * FROM t LIMIT 5 FOR UPDATE",
);
// The pre-existing ordering keeps round-tripping unchanged.
pg().verified_stmt("SELECT * FROM t ORDER BY id LIMIT 5 FOR UPDATE SKIP LOCKED");
}
Loading