Skip to content

Commit bc58deb

Browse files
committed
Use the declared column list of a CTE for completion
1 parent 8b3b281 commit bc58deb

3 files changed

Lines changed: 18 additions & 2 deletions

File tree

‎changelog.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ Features:
1010

1111
Bug fixes:
1212
----------
13+
* Use the column list declared on a CTE, as in ``WITH t(a, b) AS (...)``,
14+
when suggesting its columns instead of the names from its query.
1315
* Display database errors from ``\ef`` and ``\ev`` without exiting the
1416
interactive session, allowing recovery from an aborted transaction.
1517
* Fix the development setup instructions to activate the ``.venv`` directory

‎pgcli/packages/parseutils/ctes.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import sqlparse
22
from sqlparse import parse
33
from sqlparse.tokens import Keyword, CTE, DML
4-
from sqlparse.sql import Identifier, IdentifierList, Parenthesis
4+
from sqlparse.sql import Function, Identifier, IdentifierList, Parenthesis
55
from collections import namedtuple
66
from .meta import TableMetadata, ColumnMetadata
77

@@ -108,7 +108,11 @@ def get_cte_from_token(tok, pos0):
108108
cte_len = len(str(parens)) # includes parens
109109
stop_pos = start_pos + cte_len
110110

111-
column_names = extract_column_names(parens)
111+
_, func = tok.token_next_by(i=Function)
112+
if func:
113+
column_names = tuple(t.get_name() for t in func.get_parameters())
114+
else:
115+
column_names = extract_column_names(parens)
112116

113117
return TableExpression(cte_name, column_names, start_pos, stop_pos)
114118

‎tests/parseutils/test_ctes.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,16 @@ def test_simple_cte_extraction():
8484
assert remainder.strip() == "SELECT * FROM a"
8585

8686

87+
def test_cte_extraction_with_column_list():
88+
sql = "WITH a(b, c) AS (SELECT x, y FROM xxx) SELECT * FROM a"
89+
start_pos = len("WITH a(b, c) AS ")
90+
stop_pos = len("WITH a(b, c) AS (SELECT x, y FROM xxx)")
91+
ctes, remainder = extract_ctes(sql)
92+
93+
assert tuple(ctes) == (("a", ("b", "c"), start_pos, stop_pos),)
94+
assert remainder.strip() == "SELECT * FROM a"
95+
96+
8797
def test_cte_extraction_around_comments():
8898
sql = """--blah blah blah
8999
WITH a AS (SELECT abc def FROM x)

0 commit comments

Comments
 (0)