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

PostgreSQL: Add support for DO statement #2618

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.

Sign up for GitHub

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
LucaCappelletti94 merged 9 commits into apache:main from devtechedge:postgres-do-statement
Nov 4, 2026

Uh oh!

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

Merged

PostgreSQL: Add support for DO statement #2618

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
9 commits
Select commit Hold shift + click to select a range
77d9277
PostgreSQL: Add support for DO statement
devtechedge Oct 13, 2026
635cdef
PostgreSQL: Add DO statement fuzz seeds
devtechedge Oct 13, 2026
eb06302
PostgreSQL: Make DO statement a named struct
devtechedge Oct 13, 2026
34d4014
Accept Unicode escape string as DO code block
devtechedge Oct 14, 2026
ada06b4
PostgreSQL: Parse DO options like dostmt_opt_list
devtechedge Oct 15, 2026
c51190d
PostgreSQL: Parse LANGUAGE N string in DO statement
devtechedge Oct 17, 2026
bb6e1aa
PostgreSQL: Avoid unreachable in DO LANGUAGE parsing
devtechedge Oct 18, 2026
b4518cf
PostgreSQL: Cover more DO statement forms
devtechedge Nov 3, 2026
006a559
PostgreSQL: Split the N string span in DO statement
devtechedge Nov 4, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

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

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

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

Diff view
Diff view

Some comments aren't visible on the classic Files Changed page.

There are no files selected for viewing

1 change: 1 addition & 0 deletions 1 fuzz/fuzz_seeds/postgres_do.sql
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DO $$BEGIN RAISE NOTICE 'hello'; END$$
1 change: 1 addition & 0 deletions 1 fuzz/fuzz_seeds/postgres_do_language_after.sql
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DO $$BEGIN UPDATE t SET a = a + 1 WHERE b > 0; END$$ LANGUAGE plpgsql
1 change: 1 addition & 0 deletions 1 fuzz/fuzz_seeds/postgres_do_language_before.sql
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DO LANGUAGE plpgsql $$DECLARE n int; BEGIN SELECT count(*) INTO n FROM t; END$$
1 change: 1 addition & 0 deletions 1 fuzz/fuzz_seeds/postgres_do_single_quoted.sql
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DO 'BEGIN RAISE NOTICE ''hi''; END'
1 change: 1 addition & 0 deletions 1 fuzz/fuzz_seeds/postgres_do_tagged_dollar_quote.sql
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DO $body$BEGIN PERFORM $$nested$$; END$body$
57 changes: 57 additions & 0 deletions 57 src/ast/mod.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5003,6 +5003,12 @@ pub enum Statement {
channel: Ident,
},
/// ```sql
/// DO { code | LANGUAGE lang_name } [ ... ]
/// ```
///
/// See Postgres <https://www.postgresql.org/docs/current/sql-do.html>
Do(DoStatement),
/// ```sql
/// NOTIFY channel [ , payload ]
/// ```
/// send a notification event together with an optional "payload" string to channel
Expand Down Expand Up @@ -6573,6 +6579,7 @@ impl fmt::Display for Statement {
write!(f, "UNLISTEN {channel}")?;
Ok(())
}
Statement::Do(s) => write!(f, "{s}"),
Statement::NOTIFY { channel, payload } => {
write!(f, "NOTIFY {channel}")?;
if let Some(payload) = payload {
Expand Down Expand Up @@ -11734,6 +11741,50 @@ impl fmt::Display for WaitForStatement {
}
}

/// PostgreSQL `DO` statement, executing an anonymous code block.
///
/// ```sql
/// DO { code | LANGUAGE lang_name } [ ... ]
/// ```
///
/// See <https://www.postgresql.org/docs/current/sql-do.html>
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
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}"),
}
}
}
Comment thread
Comment on lines +11754 to +11786

@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

/// Represents a `Return` statement.
///
/// [MsSql triggers](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql)
Expand Down Expand Up @@ -12617,6 +12668,12 @@ impl From<ThrowStatement> for Statement {
}
}

impl From<DoStatement> for Statement {
fn from(d: DoStatement) -> Self {
Self::Do(d)
}
}

impl From<Function> for Statement {
fn from(f: Function) -> Self {
Self::Call(f)
Expand Down
66 changes: 50 additions & 16 deletions 66 src/ast/spans.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,22 @@ use super::{
ClusteredIndex, ColumnDef, ColumnOption, ColumnOptionDef, ConditionalStatementBlock,
ConditionalStatements, ConflictTarget, ConnectByKind, ConstraintCharacteristics, CopySource,
CreateIndex, CreateRule, CreateRuleAction, CreateTable, CreateTableOptions, CreateUserMapping,
Cte, Delete, DoUpdate, DropRule, ExceptSelectItem, ExcludeConstraintElement, ExcludeSelectItem,
Expr, ExprWithAlias, Fetch, ForValues, FromTable, Function, FunctionArg, FunctionArgExpr,
FunctionArgumentClause, FunctionArgumentList, FunctionArguments, GroupByExpr, HavingBound,
IfStatement, IlikeSelectItem, InTarget, IndexColumn, Insert, Interpolate, InterpolateExpr,
Join, JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, LimitClause,
MatchRecognizePattern, Measure, Merge, MergeAction, MergeClause, MergeInsertExpr,
MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, NamedParenthesizedList,
NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, OnConflictAction,
OnInsert, OpenStatement, OperateFunctionArg, OrderBy, OrderByExpr, OrderByKind, OutputClause,
Parens, Partition, PartitionBoundValue, PivotValueSource, ProjectionSelect, Query,
RaiseStatement, RaiseStatementValue, ReferentialAction, RefreshMaterializedView,
RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select, SelectInto, SelectItem,
SetExpr, Setting, SqlOption, Statement, Subscript, SymbolDefinition, TableAlias,
TableAliasColumnDef, TableConstraint, TableFactor, TableObject, TableOptionsClustered,
TableWithJoins, Update, UpdateTableFromKind, Use, UserMappingUser, Values, ViewColumnDef,
WhileStatement, WildcardAdditionalOptions, With, WithFill,
Cte, Delete, DoOption, DoStatement, DoUpdate, DropRule, ExceptSelectItem,
ExcludeConstraintElement, ExcludeSelectItem, Expr, ExprWithAlias, Fetch, ForValues, FromTable,
Function, FunctionArg, FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList,
FunctionArguments, GroupByExpr, HavingBound, IfStatement, IlikeSelectItem, InTarget,
IndexColumn, Insert, Interpolate, InterpolateExpr, Join, JoinConstraint, JoinOperator,
JsonPath, JsonPathElem, LateralView, LimitClause, MatchRecognizePattern, Measure, Merge,
MergeAction, MergeClause, MergeInsertExpr, MergeInsertKind, MergeUpdateExpr, MergeUpdateKind,
NamedParenthesizedList, NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict,
OnConflictAction, OnInsert, OpenStatement, OperateFunctionArg, OrderBy, OrderByExpr,
OrderByKind, OutputClause, Parens, Partition, PartitionBoundValue, PivotValueSource,
ProjectionSelect, Query, RaiseStatement, RaiseStatementValue, ReferentialAction,
RefreshMaterializedView, RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select,
SelectInto, SelectItem, SetExpr, Setting, SqlOption, Statement, Subscript, SymbolDefinition,
TableAlias, TableAliasColumnDef, TableConstraint, TableFactor, TableObject,
TableOptionsClustered, TableWithJoins, Update, UpdateTableFromKind, Use, UserMappingUser,
Values, ViewColumnDef, WhileStatement, WildcardAdditionalOptions, With, WithFill,
};

/// Given an iterator of spans, return the [Span::union] of all spans.
Expand Down Expand Up @@ -501,6 +501,7 @@ impl Spanned for Statement {
Statement::ShowObjects { .. } => Span::empty(),
Statement::ShowViews { .. } => Span::empty(),
Statement::LISTEN { .. } => Span::empty(),
Statement::Do(s) => s.span(),
Statement::NOTIFY { .. } => Span::empty(),
Statement::LoadData { .. } => Span::empty(),
Statement::UNLISTEN { .. } => Span::empty(),
Expand Down Expand Up @@ -2868,6 +2869,21 @@ impl Spanned for CreateUserMapping {
}
}

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,
}
}
}
Comment thread
Comment on lines +2872 to +2885

@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

#[cfg(test)]
pub mod tests {
use crate::ast::Value;
Expand Down Expand Up @@ -3594,4 +3610,22 @@ SETTINGS update_parallel_mode = 'auto'"#;
assert_eq!(test.get_source(stmt.span()), expected, "{sql}");
}
}

#[test]
fn test_do_statement_span() {
let dialect = &crate::dialect::PostgreSqlDialect {};
let sql = "DO LANGUAGE plpgsql $$BEGIN NULL; END$$";
let test = SpanTest::new(dialect, sql);
let r = Parser::parse_sql(dialect, sql).unwrap();
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'");
}
Comment thread
Comment on lines +3620 to +3630

@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
}
5 changes: 5 additions & 0 deletions 5 src/dialect/mod.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1505,6 +1505,11 @@ pub trait Dialect: Debug + Any {
false
}

/// Returns true if the dialect supports the `DO` statement
fn supports_do_statement(&self) -> bool {
false
}

/// Returns true if the dialect supports the `LISTEN`, `UNLISTEN` and `NOTIFY` statements
fn supports_listen_notify(&self) -> bool {
false
Expand Down
4 changes: 4 additions & 0 deletions 4 src/dialect/postgresql.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,10 @@ impl Dialect for PostgreSqlDialect {
true
}

fn supports_do_statement(&self) -> bool {
true
}

/// see <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-EXCLUDE>
fn supports_exclude_constraint(&self) -> bool {
true
Expand Down
45 changes: 45 additions & 0 deletions 45 src/parser/mod.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,7 @@ impl<'a> Parser<'a> {
Keyword::LISTEN if self.dialect.supports_listen_notify() => self.parse_listen(),
Keyword::UNLISTEN if self.dialect.supports_listen_notify() => self.parse_unlisten(),
Keyword::NOTIFY if self.dialect.supports_listen_notify() => self.parse_notify(),
Keyword::DO if self.dialect.supports_do_statement() => self.parse_do(),
// `PRAGMA` is sqlite specific https://www.sqlite.org/pragma.html
Keyword::PRAGMA => self.parse_pragma(),
Keyword::UNLOAD => {
Expand Down Expand Up @@ -1546,6 +1547,50 @@ impl<'a> Parser<'a> {
Ok(Statement::UNLISTEN { channel })
}

/// Parse `DO` statement.
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) => 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,
} => {
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)))
}
_ => {
self.prev_token();
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 }))
}
Comment thread
Comment on lines +1551 to +1592

@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

/// Parse `NOTIFY` statement.
pub fn parse_notify(&mut self) -> Result<Statement, ParserError> {
let channel = self.parse_identifier()?;
Expand Down
56 changes: 56 additions & 0 deletions 56 tests/sqlparser_common.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -23414,3 +23414,59 @@ fn display_create_procedure_begin_atomic_propagates_write_errors() {
assert_eq!(write!(writer, "{stmt}"), Err(fmt::Error), "{rejected:?}");
}
}

#[test]
fn parse_do_statement() {
let dialects = all_dialects_where(|d| d.supports_do_statement());

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'");
Comment thread

@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
dialects.verified_stmt("DO U&'BEGIN NULL; END'");
dialects.verified_stmt("DO U&'BEGIN NULL; END' LANGUAGE plpgsql");
dialects.verified_stmt("DO LANGUAGE 'plpgsql'");
dialects.verified_stmt("DO LANGUAGE plpgsql 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$$");

assert_eq!(
dialects.parse_sql_statements("DO 1").unwrap_err(),
ParserError::ParserError("Expected: string literal, found: 1".to_string())
);
assert_eq!(
dialects.parse_sql_statements("DO LANGUAGE").unwrap_err(),
ParserError::ParserError("Expected: identifier, found: EOF".to_string())
);

let dialects = all_dialects_where(|d| !d.supports_do_statement());
assert_eq!(
dialects
.parse_sql_statements("DO $$BEGIN NULL; END$$")
.unwrap_err(),
ParserError::ParserError("Expected: an SQL statement, found: DO".to_string())
);
}
10 changes: 10 additions & 0 deletions 10 tests/sqlparser_postgres.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4553,6 +4553,16 @@ fn parse_xml_typed_string() {
}
}

#[test]
fn parse_do_statement() {
let dialects = pg();
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'",
);
}

fn pg() -> TestedDialects {
TestedDialects::new(vec![Box::new(PostgreSqlDialect {})])
}
Expand Down
Loading
Oops, something went wrong.

Uh oh!

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

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.