Skip to content

Unwrap leading parenthesis in Statement.get_type() (fixes #727) - #877

Open
ChrisJr404 wants to merge 1 commit into
andialbrecht:masterfrom
ChrisJr404:fix/get-type-parenthesized-issue727
Open

Unwrap leading parenthesis in Statement.get_type() (fixes #727)#877
ChrisJr404 wants to merge 1 commit into
andialbrecht:masterfrom
ChrisJr404:fix/get-type-parenthesized-issue727

Conversation

@ChrisJr404

Copy link
Copy Markdown

Fixes #727.

Statement.get_type() only looked at the first significant token. When a
statement is wrapped in parentheses, that token is the whole Parenthesis
group rather than a DML/DDL keyword, so the type came back as UNKNOWN:

>>> import sqlparse
>>> sqlparse.parse('(select 1 as "a") UNION (select 2 as "a")')[0].get_type()
'UNKNOWN'
>>> sqlparse.parse('select 1 as "a" UNION select 2 as "a"')[0].get_type()
'SELECT'

Parenthesized sub-selects like this (e.g. the sides of a compound UNION)
are common, so it is surprising that only the un-parenthesized form is
recognized.

Change

get_type() now unwraps a leading parenthesis before matching the keyword.
The loop handles nested parentheses (((select 1))) and skips the opening
punctuation together with any whitespace/comments inside. The existing CTE
handling now runs against the unwrapped container, so a WITH wrapped in
parentheses resolves too. Empty parentheses still report UNKNOWN.

>>> sqlparse.parse('(select 1) UNION (select 2)')[0].get_type()
'SELECT'
>>> sqlparse.parse('(INSERT INTO foo VALUES (1))')[0].get_type()
'INSERT'
>>> sqlparse.parse('()')[0].get_type()
'UNKNOWN'

Tests

Added test_gettype_parenthesized_statement_issue727 covering the reported
case plus nesting, a non-SELECT keyword, a leading comment, a parenthesized
CTE, and the empty-parentheses guard. The full suite passes (pytest), and
ruff check is clean on the changed module.

A parenthesized statement, such as one side of a compound query like
(SELECT ...) UNION (SELECT ...), previously reported its type as
UNKNOWN because get_type() only inspected the outer Parenthesis token.

Unwrap a leading parenthesis (including nested ones) before matching the
DML/DDL/CTE keyword, so the keyword inside the parentheses determines the
statement type. Empty parentheses still report UNKNOWN.

Fixes andialbrecht#727
@ChrisJr404
ChrisJr404 force-pushed the fix/get-type-parenthesized-issue727 branch from 3a8f362 to 880d2d6 Compare August 18, 2026 20:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

get_type returns UNKNOWN if first token is Parenthesis

1 participant