GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — PostgreSQL: Add support for DO statement by devtechedge · Pull Request #2618 · apache/datafusion-sqlparser-rs

Conversation

@devtechedge

@devtechedge devtechedge commented Oct 7, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

DO blocks like DO $$BEGIN RAISE NOTICE 'hi'; END$$ currently fail with "Expected: an SQL statement, found: DO".

This adds Statement::Do(DoStatement) for PostgreSQL's DO statement, gated behind a new Dialect::supports_do_statement() that is enabled for PostgreSQL.

DoStatement keeps the items of dostmt_opt_list in source order as a Vec<DoOption>, so every accepted form prints back as written. An item is a code block or LANGUAGE followed by an identifier or a string literal, and the missing code and duplicate checks are left to the server, matching PostgreSQL's grammar.

Code blocks may be single-quoted, dollar-quoted, E'' or U&''. LANGUAGE N'...' is read as the language nchar and a code block, because PostgreSQL's scanner splits it that way.

Tests in tests/sqlparser_common.rs and tests/sqlparser_postgres.rs cover the accepted forms, the round trip, the error cases and dialects without support. Five seeds under fuzz/fuzz_seeds/ cover the same syntax for the fuzzer.

The implementation and tests were drafted with an AI coding assistant (Grok 4.7 effort: xHigh), and I reviewed the diff, ran the test suite and the fuzzer, and stand by the change.

Fixes #2609

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@github-actions github-actions Bot added the PostgreSQL label Oct 7, 2026
@LucaCappelletti94

LucaCappelletti94 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Please add examples of this syntax to the fuzzer corpus

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LucaCappelletti94 LucaCappelletti94 added enhancement New feature or request waiting on reviewer PR needs to be reviewed waiting on contributor The review needs further refinements by its author and removed waiting on reviewer PR needs to be reviewed labels Oct 12, 2026
@codecov-commenter

codecov-commenter commented Oct 12, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.55224% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.11%. Comparing base (1071d75) to head (006a559).

Files with missing lines Patch % Lines
src/ast/mod.rs 76.92% 3 Missing ⚠️
src/ast/spans.rs 91.30% 1 Missing and 1 partial ⚠️
src/parser/mod.rs 92.00% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2618      +/-   ##
==========================================
+ Coverage   83.09%   83.11%   +0.02%     
==========================================
  Files          42       42              
  Lines       36261    36328      +67     
  Branches    36261    36328      +67     
==========================================
+ Hits        30130    30194      +64     
  Misses       2636     2636              
- Partials     3495     3498       +3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@devtechedge
devtechedge force-pushed the postgres-do-statement branch from bad1741 to 0198d07 Compare October 12, 2026 16:52
@devtechedge

devtechedge commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

@LucaCappelletti94 Good call, the fuzzer should know about this syntax too.

I added five seeds under fuzz/fuzz_seeds/: postgres_do.sql, postgres_do_language_before.sql, postgres_do_language_after.sql, postgres_do_tagged_dollar_quote.sql and postgres_do_single_quoted.sql.

Together they cover a plain $$ body, LANGUAGE plpgsql on either side of the body, a tagged dollar quote with a nested $$ inside, and a single-quoted body.

fmt, clippy and the full test suite pass with them added.

Happy to add or reshape any of them if you had other cases in mind 🙂

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

LucaCappelletti94
LucaCappelletti94 requested changes Oct 12, 2026
View reviewed changes
Comment thread src/ast/mod.rs Outdated
Comment on lines +4937 to +4942
Do {
/// Optional procedural language name.
language: Option<Ident>,
/// The anonymous code block, a string literal.
code: ValueWithSpan,
},

@LucaCappelletti94 LucaCappelletti94 Oct 12, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor this to a named struct, as every new statement variant does. I will do another review round after this refactoring as I expect most of the code will change.

Suggested change
Do {
/// Optional procedural language name.
language: Option<Ident>,
/// The anonymous code block, a string literal.
code: ValueWithSpan,
},
Do(DoStatement),

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@devtechedge devtechedge Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @LucaCappelletti94!

I refactored it into a named DoStatement struct (Statement::Do(DoStatement)), with its own Display and From<DoStatement> for Statement, following the pattern of the other statement structs.

I also gave it a Spanned impl covering the language and code block, with a small span test.

Parsing behavior and existing tests are unchanged, and fmt, clippy and the full test suite pass.

Ready for another look whenever you have time.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@devtechedge
devtechedge force-pushed the postgres-do-statement branch from f58b626 to adc68d1 Compare October 14, 2026 04:29
LucaCappelletti94
LucaCappelletti94 requested changes Oct 14, 2026
View reviewed changes
Comment thread src/parser/mod.rs Outdated
match &self.peek_token_ref().token {
Token::SingleQuotedString(_)
| Token::DollarQuotedString(_)
| Token::EscapedStringLiteral(_) => {}

@LucaCappelletti94 LucaCappelletti94 Oct 14, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should accept the Unicode escape string as a code block too. PostgreSQL 18 runs DO U&'BEGIN NULL; END', and the PostgreSQL dialect tokenizes it as Token::UnicodeStringLiteral, so this match rejects it with Expected: string literal, found: U&'BEGIN NULL; END'.

Suggested change
| Token::EscapedStringLiteral(_) => {}
| Token::EscapedStringLiteral(_)
| Token::UnicodeStringLiteral(_) => {}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread tests/sqlparser_common.rs
_ => unreachable!(),
}

dialects.verified_stmt("DO 'BEGIN NULL; END'");

@LucaCappelletti94 LucaCappelletti94 Oct 14, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And its red test.

Suggested change
dialects.verified_stmt("DO 'BEGIN NULL; END'");
dialects.verified_stmt("DO 'BEGIN NULL; END'");
dialects.verified_stmt("DO U&'BEGIN NULL; END'");

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@devtechedge

devtechedge commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @LucaCappelletti94.

I've applied both suggestions: parse_do now accepts Unicode escape strings (U&'...') as the code block, and I added DO U&'BEGIN NULL; END' to parse_do_statement.

fmt and the full test suite pass locally.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

LucaCappelletti94
LucaCappelletti94 requested changes Oct 15, 2026
View reviewed changes
Comment thread src/parser/mod.rs
Comment on lines +1517 to +1539
pub fn parse_do(&mut self) -> Result<Statement, ParserError> {
let mut language = self.parse_do_language()?;
match &self.peek_token_ref().token {
Token::SingleQuotedString(_)
| Token::DollarQuotedString(_)
| Token::EscapedStringLiteral(_)
| Token::UnicodeStringLiteral(_) => {}
_ => return self.expected_ref("string literal", self.peek_token_ref()),
}
let code = self.parse_value()?;
if language.is_none() {
language = self.parse_do_language()?;
}
Ok(Statement::Do(DoStatement { language, code }))
}

fn parse_do_language(&mut self) -> Result<Option<Ident>, ParserError> {
if self.parse_keyword(Keyword::LANGUAGE) {
Ok(Some(self.parse_identifier()?))
} else {
Ok(None)
}
}

@LucaCappelletti94 LucaCappelletti94 Oct 15, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should parse DO the way PostgreSQL's dostmt_opt_list does. That means any run of code blocks and LANGUAGE items, with the name either an identifier or any string literal, and the missing-code and duplicate checks left to the server. The repo's fuzz_postgres_accepts target panics on DO LANGUAGE plpgsql, DO $$a$$ $$b$$, a repeated LANGUAGE and DO LANGUAGE $$plpgsql$$ $$a$$, all of which PostgreSQL's grammar accepts, and fuzzing from this PR's seeds reaches one within seconds.

Please use the fuzzer locally before the next review round to catch these things.

Suggested change
pub fn parse_do(&mut self) -> Result<Statement, ParserError> {
let mut language = self.parse_do_language()?;
match &self.peek_token_ref().token {
Token::SingleQuotedString(_)
| Token::DollarQuotedString(_)
| Token::EscapedStringLiteral(_)
| Token::UnicodeStringLiteral(_) => {}
_ => return self.expected_ref("string literal", self.peek_token_ref()),
}
let code = self.parse_value()?;
if language.is_none() {
language = self.parse_do_language()?;
}
Ok(Statement::Do(DoStatement { language, code }))
}
fn parse_do_language(&mut self) -> Result<Option<Ident>, ParserError> {
if self.parse_keyword(Keyword::LANGUAGE) {
Ok(Some(self.parse_identifier()?))
} else {
Ok(None)
}
}
pub fn parse_do(&mut self) -> Result<Statement, ParserError> {
let mut options = Vec::new();
loop {
let language = self.parse_keyword(Keyword::LANGUAGE);
let string_literal = matches!(
self.peek_token_ref().token,
Token::SingleQuotedString(_)
| Token::DollarQuotedString(_)
| Token::EscapedStringLiteral(_)
| Token::UnicodeStringLiteral(_)
);
let option = match (language, string_literal) {
(true, true) => DoOption::LanguageLiteral(self.parse_value()?),
(true, false) => DoOption::Language(self.parse_identifier()?),
(false, true) => DoOption::Code(self.parse_value()?),
(false, false) if options.is_empty() => {
return self.expected_ref("string literal", self.peek_token_ref());
}
(false, false) => break,
};
options.push(option);
}
Ok(Statement::Do(DoStatement { options }))
}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/ast/mod.rs
Comment on lines +11609 to +11624
pub struct DoStatement {
/// Optional procedural language name.
pub language: Option<Ident>,
/// The anonymous code block, a string literal.
pub code: ValueWithSpan,
}

impl fmt::Display for DoStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DO ")?;
if let Some(language) = &self.language {
write!(f, "LANGUAGE {language} ")?;
}
write!(f, "{}", self.code)
}
}

@LucaCappelletti94 LucaCappelletti94 Oct 15, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should store the items in source order, so every accepted form prints back as written.

Suggested change
pub struct DoStatement {
/// Optional procedural language name.
pub language: Option<Ident>,
/// The anonymous code block, a string literal.
pub code: ValueWithSpan,
}
impl fmt::Display for DoStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DO ")?;
if let Some(language) = &self.language {
write!(f, "LANGUAGE {language} ")?;
}
write!(f, "{}", self.code)
}
}
pub struct DoStatement {
/// The code blocks and `LANGUAGE` options, in source order.
pub options: Vec<DoOption>,
}
impl fmt::Display for DoStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DO {}", display_separated(&self.options, " "))
}
}
/// An item of a [`DoStatement`].
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum DoOption {
/// `LANGUAGE lang_name`
Language(Ident),
/// `LANGUAGE` followed by the name as a string literal.
LanguageLiteral(ValueWithSpan),
/// The anonymous code block, a string literal.
Code(ValueWithSpan),
}
impl fmt::Display for DoOption {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
DoOption::Language(language) => write!(f, "LANGUAGE {language}"),
DoOption::LanguageLiteral(language) => write!(f, "LANGUAGE {language}"),
DoOption::Code(code) => write!(f, "{code}"),
}
}
}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
LucaCappelletti94
LucaCappelletti94 requested changes Oct 15, 2026
View reviewed changes
Comment thread src/ast/spans.rs Outdated
Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, LimitClause,
MatchRecognizePattern, Measure, Merge, MergeAction, MergeClause, MergeInsertExpr,
MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, NamedParenthesizedList,
CreateTableOptions, Cte, Delete, DoStatement, DoUpdate, ExceptSelectItem,

@LucaCappelletti94 LucaCappelletti94 Oct 15, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should import the new DoOption.

Suggested change
CreateTableOptions, Cte, Delete, DoStatement, DoUpdate, ExceptSelectItem,
CreateTableOptions, Cte, Delete, DoOption, DoStatement, DoUpdate, ExceptSelectItem,

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/ast/spans.rs
Comment on lines +2636 to +2646
impl Spanned for DoStatement {
fn span(&self) -> Span {
let DoStatement { language, code } = self;
union_spans(
language
.iter()
.map(|l| l.span)
.chain(core::iter::once(code.span)),
)
}
}

@LucaCappelletti94 LucaCappelletti94 Oct 15, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should span the option list, each item by its name or literal.

Suggested change
impl Spanned for DoStatement {
fn span(&self) -> Span {
let DoStatement { language, code } = self;
union_spans(
language
.iter()
.map(|l| l.span)
.chain(core::iter::once(code.span)),
)
}
}
impl Spanned for DoStatement {
fn span(&self) -> Span {
union_spans(self.options.iter().map(|option| option.span()))
}
}
impl Spanned for DoOption {
fn span(&self) -> Span {
match self {
DoOption::Language(language) => language.span,
DoOption::LanguageLiteral(value) | DoOption::Code(value) => value.span,
}
}
}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread tests/sqlparser_common.rs Outdated
Comment on lines +20519 to +20551
match dialects.verified_stmt("DO $$BEGIN RAISE NOTICE 'hi'; END$$") {
Statement::Do(DoStatement { language, code }) => {
assert_eq!(language, None);
assert_eq!(
code.value,
Value::DollarQuotedString(DollarQuotedString {
value: "BEGIN RAISE NOTICE 'hi'; END".to_string(),
tag: None,
})
);
}
_ => unreachable!(),
}

match dialects.verified_stmt("DO LANGUAGE plpgsql $body$BEGIN NULL; END$body$") {
Statement::Do(DoStatement { language, .. }) => {
assert_eq!(language, Some(Ident::new("plpgsql")));
}
_ => unreachable!(),
}

dialects.verified_stmt("DO 'BEGIN NULL; END'");
dialects.verified_stmt("DO U&'BEGIN NULL; END'");
dialects.one_statement_parses_to(
"DO $$BEGIN NULL; END$$ LANGUAGE plpgsql",
"DO LANGUAGE plpgsql $$BEGIN NULL; END$$",
);
assert_eq!(
dialects
.parse_sql_statements("DO LANGUAGE plpgsql $$BEGIN NULL; END$$ LANGUAGE sql")
.unwrap_err(),
ParserError::ParserError("Expected: end of statement, found: LANGUAGE".to_string())
);

@LucaCappelletti94 LucaCappelletti94 Oct 15, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More red tests.

Suggested change
match dialects.verified_stmt("DO $$BEGIN RAISE NOTICE 'hi'; END$$") {
Statement::Do(DoStatement { language, code }) => {
assert_eq!(language, None);
assert_eq!(
code.value,
Value::DollarQuotedString(DollarQuotedString {
value: "BEGIN RAISE NOTICE 'hi'; END".to_string(),
tag: None,
})
);
}
_ => unreachable!(),
}
match dialects.verified_stmt("DO LANGUAGE plpgsql $body$BEGIN NULL; END$body$") {
Statement::Do(DoStatement { language, .. }) => {
assert_eq!(language, Some(Ident::new("plpgsql")));
}
_ => unreachable!(),
}
dialects.verified_stmt("DO 'BEGIN NULL; END'");
dialects.verified_stmt("DO U&'BEGIN NULL; END'");
dialects.one_statement_parses_to(
"DO $$BEGIN NULL; END$$ LANGUAGE plpgsql",
"DO LANGUAGE plpgsql $$BEGIN NULL; END$$",
);
assert_eq!(
dialects
.parse_sql_statements("DO LANGUAGE plpgsql $$BEGIN NULL; END$$ LANGUAGE sql")
.unwrap_err(),
ParserError::ParserError("Expected: end of statement, found: LANGUAGE".to_string())
);
match dialects.verified_stmt("DO $$BEGIN RAISE NOTICE 'hi'; END$$") {
Statement::Do(DoStatement { options }) => assert_eq!(
options,
vec![DoOption::Code(
Value::DollarQuotedString(DollarQuotedString {
value: "BEGIN RAISE NOTICE 'hi'; END".to_string(),
tag: None,
})
.with_empty_span()
)]
),
_ => unreachable!(),
}
match dialects.verified_stmt("DO LANGUAGE plpgsql $body$BEGIN NULL; END$body$") {
Statement::Do(DoStatement { options }) => {
assert_eq!(options[0], DoOption::Language(Ident::new("plpgsql")));
}
_ => unreachable!(),
}
dialects.verified_stmt("DO 'BEGIN NULL; END'");
dialects.verified_stmt("DO U&'BEGIN NULL; END'");
dialects.verified_stmt("DO $$BEGIN NULL; END$$ LANGUAGE plpgsql");
dialects.verified_stmt("DO LANGUAGE 'plpgsql' $$BEGIN NULL; END$$");
dialects.verified_stmt("DO LANGUAGE $$plpgsql$$ $$BEGIN NULL; END$$");
dialects.verified_stmt("DO $$BEGIN NULL; END$$ LANGUAGE E'plpgsql'");
dialects.verified_stmt("DO LANGUAGE plpgsql");
dialects.verified_stmt("DO $$BEGIN NULL; END$$ $$BEGIN NULL; END$$");
dialects.verified_stmt("DO LANGUAGE plpgsql LANGUAGE sql $$BEGIN NULL; END$$");

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@devtechedge

devtechedge commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, both reviews are addressed in 4e846e6.

parse_do now follows dostmt_opt_list using your suggestion: any run of code blocks and LANGUAGE items, with the language as an identifier or any string literal, kept in source order as Vec<DoOption> so every form round-trips.

I added all your test cases.

I ran fuzz_postgres_accepts from the DO seeds for 8 minutes (about 4.4M execs) and nothing came from DO parsing.

What it did turn up are older issues elsewhere:

  • odd operator expressions in UPDATE … SET (e.g. ! + 0)
  • non-ASCII dollar-quote tags failing in the tokenizer, which also breaks SELECT

Happy to look at those in separate PRs.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@devtechedge
devtechedge force-pushed the postgres-do-statement branch from 4e846e6 to 3ce05be Compare October 15, 2026 22:25
LucaCappelletti94
LucaCappelletti94 requested changes Oct 17, 2026
View reviewed changes

@LucaCappelletti94 LucaCappelletti94 left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also add this red test in the postgres test suite. Please do check whether I missed any other DO related syntaxes, I am not omniscient.

    dialects.verified_stmt("DO LANGUAGE plpgsql LANGUAGE sql $$BEGIN NULL; END$$");
    dialects.one_statement_parses_to(
        "DO LANGUAGE N'BEGIN NULL; END'",
        "DO LANGUAGE nchar 'BEGIN NULL; END'",
    );

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/parser/mod.rs Outdated
);
let option = match (language, string_literal) {
(true, true) => DoOption::LanguageLiteral(self.parse_value()?),
(true, false) => DoOption::Language(self.parse_identifier()?),

@LucaCappelletti94 LucaCappelletti94 Oct 17, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should read LANGUAGE N'...' the way PostgreSQL does, as the language nchar followed by a code block. PostgreSQL's scanner splits N'...' into the keyword NCHAR and a string, and NCHAR is a non-reserved word, so DO LANGUAGE N'BEGIN NULL; END' passes pg_query. fuzz_postgres_accepts panics on it with Expected: identifier, found: N'BEGIN NULL; END', reached from this PR's seeds in about two minutes.

Suggested change
(true, false) => DoOption::Language(self.parse_identifier()?),
(true, false) => match &self.peek_token_ref().token {
// PostgreSQL lexes `N'...'` as the keyword `NCHAR` followed by a string
Token::NationalStringLiteral(code) => {
let code = Value::SingleQuotedString(code.clone());
let span = self.next_token().span;
options.push(DoOption::Language(Ident::with_span(span, "nchar")));
DoOption::Code(code.with_span(span))
}
_ => DoOption::Language(self.parse_identifier()?),
},

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@devtechedge

devtechedge commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the detailed review and for the suggested fix, I really appreciate it.

I will add the test in the Postgres suite and implement the N'...' handling as you described.

I will also check for any other DO forms I may have missed.

So I can plan my time well, could you please give me a rough idea of how many more rounds of changes you expect for this PR?

I am very happy to keep iterating until you are satisfied with it, and a rough sense of the remaining scope will simply help me plan and make sure I cover everything carefully.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LucaCappelletti94

LucaCappelletti94 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

So I can plan my time well, could you please give me a rough idea of how many more rounds of changes you expect for this PR?

Absolutely no idea, until we can't find any fault in it anymore I guess.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@devtechedge

devtechedge commented Oct 18, 2026

Copy link
Copy Markdown
Contributor Author

@LucaCappelletti94, I've pushed the 5th round of changes for this PR.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@devtechedge
devtechedge force-pushed the postgres-do-statement branch from b205a41 to 84477aa Compare October 22, 2026 14:35
@devtechedge

devtechedge commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

Hi @LucaCappelletti94, I've rebased this onto the latest main and resolved the conflicts. The round-5 changes from your last review are in, and fmt, clippy and tests all pass. Whenever you have a moment, could you take another look? Thanks!

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@alamb alamb added the Prolific Author author opened PRs or issues in more than 20 repositories in the last 30 days label Oct 22, 2026
@devtechedge
devtechedge force-pushed the postgres-do-statement branch 2 times, most recently from 36210f5 to bbf088f Compare October 26, 2026 10:49
LucaCappelletti94
LucaCappelletti94 requested changes Nov 2, 2026
View reviewed changes
Comment thread src/parser/mod.rs Outdated
Comment on lines +1539 to +1553
(true, false)
if matches!(self.peek_token_ref().token, Token::NationalStringLiteral(_)) =>
{
// PostgreSQL lexes `N'...'` as the `NCHAR` keyword followed
// by a string literal, so `LANGUAGE N'...'` is the language
// name `nchar` followed by the code block.
let next_token = self.next_token();
let span = next_token.span;
let Token::NationalStringLiteral(code) = next_token.token else {
return self.expected("national string literal", next_token);
};
options.push(DoOption::Language(Ident::with_span(span, "nchar")));
DoOption::Code(Value::SingleQuotedString(code).with_span(span))
}
(true, false) => DoOption::Language(self.parse_identifier()?),

@LucaCappelletti94 LucaCappelletti94 Nov 2, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could take the token once and step back when it is not N'...'. The guard already proved the token is a NationalStringLiteral, so the else arm returning expected("national string literal", ...) can never run.

Suggested change
(true, false)
if matches!(self.peek_token_ref().token, Token::NationalStringLiteral(_)) =>
{
// PostgreSQL lexes `N'...'` as the `NCHAR` keyword followed
// by a string literal, so `LANGUAGE N'...'` is the language
// name `nchar` followed by the code block.
let next_token = self.next_token();
let span = next_token.span;
let Token::NationalStringLiteral(code) = next_token.token else {
return self.expected("national string literal", next_token);
};
options.push(DoOption::Language(Ident::with_span(span, "nchar")));
DoOption::Code(Value::SingleQuotedString(code).with_span(span))
}
(true, false) => DoOption::Language(self.parse_identifier()?),
(true, false) => match self.next_token() {
// PostgreSQL lexes `N'...'` as the `NCHAR` keyword followed
// by a string literal, so `LANGUAGE N'...'` is the language
// name `nchar` followed by the code block.
TokenWithSpan {
token: Token::NationalStringLiteral(code),
span,
} => {
options.push(DoOption::Language(Ident::with_span(span, "nchar")));
DoOption::Code(Value::SingleQuotedString(code).with_span(span))
}
_ => {
self.prev_token();
DoOption::Language(self.parse_identifier()?)
}
},

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/ast/spans.rs
match self {
CreateTableOptions::None => Span::empty(),
CreateTableOptions::With(vec) => union_spans(vec.iter().map(|i| i.span())),
CreateTableOptions::Options(vec) => {

@LucaCappelletti94 LucaCappelletti94 Nov 2, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a clippy code smell or what is its reason?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread tests/sqlparser_common.rs Outdated
);

for i in 0..EXPECTED_PROJ_QTY {
for proj in select.projection.iter().take(EXPECTED_PROJ_QTY) {

@LucaCappelletti94 LucaCappelletti94 Nov 2, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this another clippy code smell?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
devtechedge added 3 commits November 3, 2026 11:30
@devtechedge
PostgreSQL: Add support for DO statement
77d9277
@devtechedge
PostgreSQL: Add DO statement fuzz seeds
635cdef
@devtechedge
PostgreSQL: Make DO statement a named struct
eb06302
devtechedge added 4 commits November 3, 2026 11:30
@devtechedge
Accept Unicode escape string as DO code block
34d4014
@devtechedge
PostgreSQL: Parse DO options like dostmt_opt_list
ada06b4
Accept any run of code blocks and LANGUAGE items, with the language
name as an identifier or any string literal, and keep them in source
order so every accepted form round-trips. Missing-code and duplicate
checks are left to the server, matching PostgreSQL's grammar.
@devtechedge
PostgreSQL: Parse LANGUAGE N string in DO statement
c51190d
@devtechedge
PostgreSQL: Avoid unreachable in DO LANGUAGE parsing
bb6e1aa
@devtechedge
devtechedge force-pushed the postgres-do-statement branch from bbf088f to bb6e1aa Compare November 3, 2026 06:01
@devtechedge
PostgreSQL: Cover more DO statement forms
b4518cf
Add the forms that PostgreSQL also accepts for a Unicode escape string around a LANGUAGE clause and for a LANGUAGE name given as a string literal.
@devtechedge

devtechedge commented Nov 3, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

Thanks for the careful pass, and for catching the dead arm before another round.

The parser point was a real defect, so I took the token once and stepped back when it is not N'...', and the plain (true, false) arm is gone with it.

The other two comments were my own scope creep, not code: a local clippy run had rewritten a redundant as_slice() in CreateTableOptions and a needless_range_loop in parse_window_functions, and I removed both so the diff touches the DO files only.

I rebased onto main as well, since the branch had conflicts.

I also compared thirty DO forms against libpg_query, including every form from your earlier reviews, and the accept and reject results agree.

cargo fmt, clippy and the full test suite pass.

If you would prefer the two clippy lines handled in a separate PR, tell me and I will move them out. 🙂

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

LucaCappelletti94
LucaCappelletti94 requested changes Nov 3, 2026
View reviewed changes
Comment thread src/parser/mod.rs Outdated
Comment on lines +1572 to +1573
options.push(DoOption::Language(Ident::with_span(span, "nchar")));
DoOption::Code(Value::SingleQuotedString(code).with_span(span))

@LucaCappelletti94 LucaCappelletti94 Nov 3, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should split the N'...' token's span between the two items it produces. Both currently get the whole token's span, so get_source on the nchar language returns N'BEGIN NULL; END' instead of N. N is always a single character on the token's first line, so the quote starts one column later.

Suggested change
options.push(DoOption::Language(Ident::with_span(span, "nchar")));
DoOption::Code(Value::SingleQuotedString(code).with_span(span))
let quote = Location::new(span.start.line, span.start.column + 1);
let language = Ident::with_span(Span::new(span.start, quote), "nchar");
options.push(DoOption::Language(language));
let code = Value::SingleQuotedString(code);
DoOption::Code(code.with_span(Span::new(quote, span.end)))

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/ast/spans.rs
Comment on lines +3620 to +3621
assert_eq!(test.get_source(r[0].span()), "plpgsql $$BEGIN NULL; END$$");
}

@LucaCappelletti94 LucaCappelletti94 Nov 3, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should cover the split, since this test fails on the current head because the language's span covers the whole literal.

Suggested change
assert_eq!(test.get_source(r[0].span()), "plpgsql $$BEGIN NULL; END$$");
}
assert_eq!(test.get_source(r[0].span()), "plpgsql $$BEGIN NULL; END$$");
let sql = "DO LANGUAGE N'BEGIN NULL; END'";
let test = SpanTest::new(dialect, sql);
let options = match Parser::parse_sql(dialect, sql).unwrap().remove(0) {
Statement::Do(DoStatement { options }) => options,
stmt => panic!("expected DO, got {stmt:?}"),
};
assert_eq!(test.get_source(options[0].span()), "N");
assert_eq!(test.get_source(options[1].span()), "'BEGIN NULL; END'");
}

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@devtechedge
PostgreSQL: Split the N string span in DO statement
006a559
Share the token span between the nchar language name and the code block it produces, so get_source returns N and the literal separately. Cover the split in the DO span test.
@devtechedge

devtechedge commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

You were right about the span, and I appreciate you taking the time to point at the exact columns. 👍

Both points are addressed in commit 006a559.

The span point is a real bug, and the test point is the coverage that should have come with it.

The language name now runs from the start of the token to the opening quote, so get_source returns N, and the code block picks up at the quote.

The span test covers both halves, with one assertion for N and one for the literal.

I checked the new assertion against the previous commit first, and it fails there, so the test pins the split rather than only passing with the fix.

The formatting check, clippy with -D warnings, and the full test suite all pass on the commit.

I am happy to reshape the offset or the test if you had something else in mind.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

LucaCappelletti94
LucaCappelletti94 approved these changes Nov 4, 2026
View reviewed changes
@LucaCappelletti94

LucaCappelletti94 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Thank you for refining the PR @devtechedge, I will be merging this now.

cc @alamb

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LucaCappelletti94
LucaCappelletti94 added this pull request to the merge queue Nov 4, 2026
Merged via the queue into apache:main with commit ebb8b04 Nov 4, 2026
10 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@LucaCappelletti94 LucaCappelletti94 mentioned this pull request Nov 4, 2026
Move to rusqlite 0.41 and sqlitegis 0.3.2 connetto-rs/pg2sqlite#238
Merged
@devtechedge

devtechedge commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Hi Luca, thanks for guiding this PR through so many detailed review rounds.

Matching PostgreSQL's dostmt_opt_list more closely made the parser truer to what people actually write inside DO blocks, and splitting the N string token span was a sharp catch 🔧.

I also appreciated the habit of running the fuzz harness before each round, which caught issues well before they mattered.

Thanks again for the merge.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LucaCappelletti94 LucaCappelletti94 mentioned this pull request Nov 5, 2026
Refuse a PostgreSQL DO block instead of modelling it as though it had not run connetto-rs/sql-traits#294
Merged
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@LucaCappelletti94 LucaCappelletti94 LucaCappelletti94 approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

enhancement New feature or request PostgreSQL Prolific Author author opened PRs or issues in more than 20 repositories in the last 30 days waiting on contributor The review needs further refinements by its author

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

PostgreSQL DO statement

Uh oh!

There was an error while loading. Please reload this page.

4 participants

@devtechedge @LucaCappelletti94 @codecov-commenter @alamb
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.