Skip to content
Open
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
2 changes: 2 additions & 0 deletions changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Features:

Bug fixes:
----------
* Use the column list declared on a CTE, as in ``WITH t(a, b) AS (...)``,
when suggesting its columns instead of the names from its query.
* Display database errors from ``\ef`` and ``\ev`` without exiting the
interactive session, allowing recovery from an aborted transaction.
* Fix the development setup instructions to activate the ``.venv`` directory
Expand Down
8 changes: 6 additions & 2 deletions pgcli/packages/parseutils/ctes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sqlparse
from sqlparse import parse
from sqlparse.tokens import Keyword, CTE, DML
from sqlparse.sql import Identifier, IdentifierList, Parenthesis
from sqlparse.sql import Function, Identifier, IdentifierList, Parenthesis
from collections import namedtuple
from .meta import TableMetadata, ColumnMetadata

Expand Down Expand Up @@ -108,7 +108,11 @@ def get_cte_from_token(tok, pos0):
cte_len = len(str(parens)) # includes parens
stop_pos = start_pos + cte_len

column_names = extract_column_names(parens)
_, func = tok.token_next_by(i=Function)
if func:
column_names = tuple(t.get_name() for t in func.get_parameters())
else:
column_names = extract_column_names(parens)

return TableExpression(cte_name, column_names, start_pos, stop_pos)

Expand Down
10 changes: 10 additions & 0 deletions tests/parseutils/test_ctes.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,16 @@ def test_simple_cte_extraction():
assert remainder.strip() == "SELECT * FROM a"


def test_cte_extraction_with_column_list():
sql = "WITH a(b, c) AS (SELECT x, y FROM xxx) SELECT * FROM a"
start_pos = len("WITH a(b, c) AS ")
stop_pos = len("WITH a(b, c) AS (SELECT x, y FROM xxx)")
ctes, remainder = extract_ctes(sql)

assert tuple(ctes) == (("a", ("b", "c"), start_pos, stop_pos),)
assert remainder.strip() == "SELECT * FROM a"


def test_cte_extraction_around_comments():
sql = """--blah blah blah
WITH a AS (SELECT abc def FROM x)
Expand Down
Loading