From 15b2468e753be5e89e9ae65db1e9ab7d150b6c11 Mon Sep 17 00:00:00 2001 From: Maxteabag Date: Fri, 27 Nov 2026 15:29:35 +0000 Subject: [PATCH 1/5] feat(completion): suggest PostgreSQL identity clauses Closes #344 --- sqlit/domains/query/completion/completion.py | 8 ++ .../query/completion/postgres_identity.py | 79 +++++++++++++++++++ .../ui/mixins/autocomplete_suggestions.py | 2 + 3 files changed, 89 insertions(+) create mode 100644 sqlit/domains/query/completion/postgres_identity.py diff --git a/sqlit/domains/query/completion/completion.py b/sqlit/domains/query/completion/completion.py index ee94d23a..06e20ab3 100644 --- a/sqlit/domains/query/completion/completion.py +++ b/sqlit/domains/query/completion/completion.py @@ -34,6 +34,7 @@ ) from .create_index import get_create_index_completions from .create_table import get_create_table_completions +from .postgres_identity import get_postgres_identity_completions from .create_view import get_create_view_completions from .delete import extract_delete_table_refs, get_delete_context from .drop import get_drop_completions @@ -198,6 +199,8 @@ def get_completions( procedures: list[str] | None = None, include_keywords: bool = True, include_functions: bool = True, + *, + dialect: str | None = None, ) -> list[str]: """Get completion suggestions for the given SQL and cursor position. @@ -295,6 +298,11 @@ def scoped_routine_names( if not before_cursor.strip(): return [] + if dialect == "postgresql": + identity = get_postgres_identity_completions(before_cursor) + if identity is not None: + return identity + # Try DDL-specific handlers first (they return completions directly) for ddl_handler in [ get_create_table_completions, diff --git a/sqlit/domains/query/completion/postgres_identity.py b/sqlit/domains/query/completion/postgres_identity.py new file mode 100644 index 00000000..62d722f6 --- /dev/null +++ b/sqlit/domains/query/completion/postgres_identity.py @@ -0,0 +1,79 @@ +"""PostgreSQL identity completion for integer column definitions.""" + +import re + +from sqlparse import tokens +from sqlparse.lexer import tokenize + +_IDENTIFIER = r'(?:"(?:[^"]|"")+"|[a-z_][\w$]*)' +_TABLE = rf"{_IDENTIFIER}(?:\s*\.\s*{_IDENTIFIER})?" +_CREATE = re.compile( + rf"\s*CREATE\s+(?:(?:TEMP(?:ORARY)?|UNLOGGED)\s+)?TABLE\s+" + rf"(?:IF\s+NOT\s+EXISTS\s+)?{_TABLE}\s*\(", + re.IGNORECASE, +) +_ALTER = re.compile(rf"\s*ALTER\s+TABLE\s+{_TABLE}\s+", re.IGNORECASE) +_ADD = re.compile(r"\s*ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?", re.IGNORECASE) +_COLUMN = re.compile( + rf"\s*{_IDENTIFIER}\s+(?:pg_catalog\.)?" + r"(?:smallint|integer|bigint|int[248]?)(?:\s+(?:NOT\s+NULL|PRIMARY\s+KEY|UNIQUE))*" + r"\s+([a-z\s]+)", + re.IGNORECASE, +) +_CLAUSES = ("GENERATED ALWAYS AS IDENTITY", "GENERATED BY DEFAULT AS IDENTITY") + + +def get_postgres_identity_completions(before_cursor: str) -> list[str] | None: + statement_start = item_start = depth = 0 + outer_open = -1 + alter_item_start = 0 + position = 0 + for kind, value in tokenize(before_cursor): + if kind in tokens.Punctuation: + if value == ";": + statement_start = item_start = alter_item_start = position + 1 + depth = 0 + elif value == "(": + if depth == 0: + outer_open = position + depth += 1 + elif value == ")": + depth -= 1 + elif value == ",": + if depth == 1: + item_start = position + 1 + elif depth == 0: + alter_item_start = position + 1 + position += len(value) + + statement = before_cursor[statement_start:] + create = _CREATE.match(statement) + alter = _ALTER.match(statement) + if create and depth == 1 and outer_open == statement_start + create.end() - 1: + column = before_cursor[max(statement_start + create.end(), item_start):] + elif alter and depth == 0: + action = before_cursor[max(statement_start + alter.end(), alter_item_start):] + add = _ADD.match(action) + if not add: + return None + column = action[add.end():] + else: + return None + + match = _COLUMN.fullmatch(column) + if not match: + return None + + typed = match[1].upper() + words = typed.split() + if not words: + return None + # The editor replaces only the current word when accepting a suggestion. + completed_words = len(words) - int(not typed[-1].isspace()) + prefix = " ".join(words) + (" " if typed[-1].isspace() else "") + matches = [ + " ".join(clause.split()[completed_words:]) + for clause in _CLAUSES + if clause.startswith(prefix) and clause != prefix + ] + return matches or None diff --git a/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py b/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py index 126c14f6..74628887 100644 --- a/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py +++ b/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py @@ -156,6 +156,7 @@ def needs_column_load(key: str) -> bool: elif table_key in loading: return ["Loading..."] + provider = getattr(self, "current_provider", None) # Now call get_completions with all available data results = get_completions( text, @@ -165,6 +166,7 @@ def needs_column_load(key: str) -> bool: procedures, include_keywords=True, include_functions=True, + dialect=provider.metadata.db_type if provider else None, ) return results From e4fe9ebc06992dff8d6d06bd16fdbf941bf96f0c Mon Sep 17 00:00:00 2001 From: Maxteabag Date: Fri, 27 Nov 2026 15:30:33 +0000 Subject: [PATCH 2/5] fix(completion): skip identity lexing without a candidate prefix --- .../query/completion/postgres_identity.py | 25 +++++++++++++++ .../sql_completion/test_postgres_identity.py | 32 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 tests/unit/sql_completion/test_postgres_identity.py diff --git a/sqlit/domains/query/completion/postgres_identity.py b/sqlit/domains/query/completion/postgres_identity.py index 62d722f6..ee352aa3 100644 --- a/sqlit/domains/query/completion/postgres_identity.py +++ b/sqlit/domains/query/completion/postgres_identity.py @@ -23,7 +23,32 @@ _CLAUSES = ("GENERATED ALWAYS AS IDENTITY", "GENERATED BY DEFAULT AS IDENTITY") +def _has_identity_prefix(before_cursor: str) -> bool: + # Read at most the five words of a clause, starting at the cursor. + # The full lexer still validates the DDL context. + position = len(before_cursor) + prefix = " " if before_cursor and before_cursor[-1].isspace() else "" + for _ in range(5): + while position and before_cursor[position - 1].isspace(): + position -= 1 + end = position + while position and not before_cursor[position - 1].isspace(): + position -= 1 + if end - position > len("GENERATED"): + return False + if end == position: + return False + word = before_cursor[position:end].upper() + prefix = word + (" " if prefix and prefix != " " else "") + prefix + if any(clause.startswith(prefix) and clause != prefix for clause in _CLAUSES): + return True + return False + + def get_postgres_identity_completions(before_cursor: str) -> list[str] | None: + if not _has_identity_prefix(before_cursor): + return None + statement_start = item_start = depth = 0 outer_open = -1 alter_item_start = 0 diff --git a/tests/unit/sql_completion/test_postgres_identity.py b/tests/unit/sql_completion/test_postgres_identity.py new file mode 100644 index 00000000..3f219c0d --- /dev/null +++ b/tests/unit/sql_completion/test_postgres_identity.py @@ -0,0 +1,32 @@ +"""Regression coverage for dialect-specific identity completion.""" + +import pytest + +from sqlit.domains.query.completion import get_completions +from sqlit.domains.query.completion import postgres_identity + + +@pytest.mark.parametrize( + ("sql", "expected"), + [ + ("CREATE TABLE books (id BIGINT GEN", "GENERATED ALWAYS AS IDENTITY"), + ("ALTER TABLE books ADD COLUMN id INT GENERATED ", "ALWAYS AS IDENTITY"), + ("CREATE TABLE books (id BIGINT GENERATED\nBY DEFAULT AS I", "IDENTITY"), + ], +) +def test_identity_completion_is_postgresql_only(sql, expected): + assert expected in get_completions(sql, len(sql), [], {}, dialect="postgresql") + assert get_completions(sql, len(sql), [], {}, dialect="sqlite") == get_completions( + sql, len(sql), [], {} + ) + + +def test_ordinary_postgres_select_skips_identity_tokenization(monkeypatch): + def unexpected_tokenization(_sql): + pytest.fail("SELECT without an identity prefix reached the identity lexer") + + monkeypatch.setattr(postgres_identity, "tokenize", unexpected_tokenization) + sql = "SELECT * FROM books WHERE title = " + assert get_completions(sql, len(sql), [], {}, dialect="postgresql") == get_completions( + sql, len(sql), [], {} + ) From c4d6a0692d9c22a074e379b393b77b4452e9f903 Mon Sep 17 00:00:00 2001 From: Maxteabag Date: Fri, 27 Nov 2026 15:40:34 +0000 Subject: [PATCH 3/5] fix(completion): preserve PostgreSQL generated column choices --- sqlit/domains/query/completion/completion.py | 12 +-- .../query/completion/postgres_identity.py | 95 +++++++++++++++++-- tests/ui/test_query_tab_insert.py | 61 ++++++++++++ .../sql_completion/test_postgres_identity.py | 41 +++++++- 4 files changed, 189 insertions(+), 20 deletions(-) diff --git a/sqlit/domains/query/completion/completion.py b/sqlit/domains/query/completion/completion.py index 06e20ab3..434c14ba 100644 --- a/sqlit/domains/query/completion/completion.py +++ b/sqlit/domains/query/completion/completion.py @@ -34,11 +34,11 @@ ) from .create_index import get_create_index_completions from .create_table import get_create_table_completions -from .postgres_identity import get_postgres_identity_completions from .create_view import get_create_view_completions from .delete import extract_delete_table_refs, get_delete_context from .drop import get_drop_completions from .insert import get_insert_context +from .postgres_identity import get_postgres_identity_completions from .truncate import get_truncate_completions from .update import get_update_context @@ -290,6 +290,11 @@ def scoped_routine_names( ] table_function_names = [routine_display_name(routine) for routine in table_function_routines] + if dialect == "postgresql": + identity = get_postgres_identity_completions(before_cursor) + if identity is not None: + return identity + # Don't suggest if inside string literal if is_inside_string(before_cursor): return [] @@ -298,11 +303,6 @@ def scoped_routine_names( if not before_cursor.strip(): return [] - if dialect == "postgresql": - identity = get_postgres_identity_completions(before_cursor) - if identity is not None: - return identity - # Try DDL-specific handlers first (they return completions directly) for ddl_handler in [ get_create_table_completions, diff --git a/sqlit/domains/query/completion/postgres_identity.py b/sqlit/domains/query/completion/postgres_identity.py index ee352aa3..b36d92b6 100644 --- a/sqlit/domains/query/completion/postgres_identity.py +++ b/sqlit/domains/query/completion/postgres_identity.py @@ -20,6 +20,14 @@ r"\s+([a-z\s]+)", re.IGNORECASE, ) +# A necessary condition only. The lexer decides whether the keyword is +# outside comments and literals and starts the statement at the cursor. +_DDL_KEYWORD = re.compile(r"\b(?:CREATE|ALTER)\b", re.IGNORECASE) +_BLOCK_DELIMITER = re.compile(r"/\*|\*/") +_STRING = re.compile(r"'(?:[^']|'')*'(?!')") +_ESCAPE_STRING = re.compile(r"[Ee]'(?:[^'\\]|''|\\[\s\S])*'(?!')") +_QUOTED_IDENTIFIER = re.compile(r'"(?:[^"]|"")*"(?!")') +_DOLLAR_QUOTE = re.compile(r"(? bool: return False +def _block_comment_end(sql: str, start: int) -> int | None: + depth = 1 + for delimiter in _BLOCK_DELIMITER.finditer(sql, start + 2): + depth += 1 if delimiter[0] == "/*" else -1 + if depth == 0: + return delimiter.end() + return None + + +def _postgres_span(sql: str, position: int, value: str) -> tuple[int, bool] | None: + """Return the token's end and whether it is a PostgreSQL comment.""" + end = position + len(value) + if sql.startswith("/*", position): + # PostgreSQL nests block comments. sqlparse closes at the first */. + comment_end = _block_comment_end(sql, position) + return (comment_end, True) if comment_end is not None else None + if value.startswith("--"): + if end == len(sql) and not value.endswith(("\r", "\n")): + return None + return end, True + + # sqlparse can split escape strings or unfinished literals into SQL tokens. + quoted = None + if value[0] == "'": + quoted = _STRING + elif value[0] == '"': + quoted = _QUOTED_IDENTIFIER + elif sql[position:position + 2].lower() == "e'": + quoted = _ESCAPE_STRING + if quoted is not None: + match = quoted.match(sql, position) + return (match.end(), False) if match else None + + if value.startswith("$") and (tag := _DOLLAR_QUOTE.match(sql, position)): + close = sql.find(tag[0], tag.end()) + return (close + len(tag[0]), False) if close != -1 else None + return end, False + + def get_postgres_identity_completions(before_cursor: str) -> list[str] | None: - if not _has_identity_prefix(before_cursor): + if not _has_identity_prefix(before_cursor) or not _DDL_KEYWORD.search(before_cursor): return None statement_start = item_start = depth = 0 outer_open = -1 alter_item_start = 0 - position = 0 - for kind, value in tokenize(before_cursor): - if kind in tokens.Punctuation: + position = unmasked_start = 0 + parts: list[str] = [] + lexer = tokenize(before_cursor) + while position < len(before_cursor): + kind, value = next(lexer) + lexer_end = position + len(value) + span = _postgres_span(before_cursor, position, value) + if span is None: + return None + end, is_comment = span + if is_comment: + # Preserve offsets used for the statement and column boundaries. + parts.extend((before_cursor[unmasked_start:position], " " * (end - position))) + unmasked_start = end + elif kind in tokens.Punctuation: if value == ";": statement_start = item_start = alter_item_start = position + 1 depth = 0 @@ -69,15 +128,24 @@ def get_postgres_identity_completions(before_cursor: str) -> list[str] | None: item_start = position + 1 elif depth == 0: alter_item_start = position + 1 - position += len(value) - statement = before_cursor[statement_start:] + # Skip any extra lexer tokens inside a PostgreSQL literal or comment. + while lexer_end < end: + _, skipped = next(lexer) + lexer_end += len(skipped) + if lexer_end != end: + # A token crossed the end of the span. Start again at its boundary. + lexer = tokenize(before_cursor[end:]) + position = end + + clean = "".join([*parts, before_cursor[unmasked_start:]]) if parts else before_cursor + statement = clean[statement_start:] create = _CREATE.match(statement) alter = _ALTER.match(statement) if create and depth == 1 and outer_open == statement_start + create.end() - 1: - column = before_cursor[max(statement_start + create.end(), item_start):] + column = clean[max(statement_start + create.end(), item_start):] elif alter and depth == 0: - action = before_cursor[max(statement_start + alter.end(), alter_item_start):] + action = clean[max(statement_start + alter.end(), alter_item_start):] add = _ADD.match(action) if not add: return None @@ -101,4 +169,13 @@ def get_postgres_identity_completions(before_cursor: str) -> list[str] | None: for clause in _CLAUSES if clause.startswith(prefix) and clause != prefix ] - return matches or None + if not matches: + return None + + # Keep the single keyword first when the same prefix can continue a + # computed column. The dropdown selects the first match for plain Tab. + if completed_words == 0: + matches.insert(0, "GENERATED") + elif words[:-1] in (["GENERATED"], ["GENERATED", "ALWAYS"]) and prefix.endswith((" A", " AS")): + matches.insert(0, "AS") + return matches diff --git a/tests/ui/test_query_tab_insert.py b/tests/ui/test_query_tab_insert.py index 88a3183c..d77dbd87 100644 --- a/tests/ui/test_query_tab_insert.py +++ b/tests/ui/test_query_tab_insert.py @@ -7,6 +7,7 @@ from sqlit.core.keymap import ActionKeyDef, DefaultKeymapProvider, reset_keymap, set_keymap from sqlit.core.vim import VimMode +from sqlit.domains.connections.providers.catalog import get_provider from sqlit.domains.shell.app.keymap_manager import FileBasedKeymapProvider from sqlit.domains.shell.app.main import SSMSTUI from sqlit.shared.ui.widgets_autocomplete import AutocompleteItem @@ -74,6 +75,66 @@ async def test_tab_accepts_autocomplete_suggestion(self) -> None: assert app._autocomplete_visible is False assert app.query_input.text == "select" + @pytest.mark.parametrize( + ("before", "after", "key", "accept", "expected"), + [ + ("CREATE TABLE t (id INT GE", ");", "n", ("tab",), "CREATE TABLE t (id INT GENERATED"), + ("CREATE TABLE t (id INT GENERATED ", ");", "a", ("tab",), "CREATE TABLE t (id INT GENERATED AS"), + ( + "CREATE TABLE t (source INT, result INT GENERATED ALWAYS ", + " (source + 1) STORED);", + "a", + ("tab",), + "CREATE TABLE t (source INT, result INT GENERATED ALWAYS AS", + ), + ( + "CREATE TABLE books (id BIGINT GE", + ", title text)", + "n", + ("down", "tab"), + "CREATE TABLE books (id BIGINT GENERATED ALWAYS AS IDENTITY", + ), + ( + "ALTER TABLE altered ADD COLUMN id INTEGER GENERATED", + "", + "space", + ("tab",), + "ALTER TABLE altered ADD COLUMN id INTEGER GENERATED ALWAYS AS IDENTITY", + ), + ( + "/* publisher's schema */ CREATE TABLE t (source INT, -- publisher's id\n id INT GE", + ");", + "n", + ("down", "tab"), + "/* publisher's schema */ CREATE TABLE t (source INT, -- publisher's id\n id INT GENERATED ALWAYS AS IDENTITY", + ), + ], + ) + @pytest.mark.asyncio + async def test_postgres_generated_completions_accept_through_editor(self, before, after, key, accept, expected) -> None: + app = _make_app() + + async with app.run_test(size=(120, 40)) as pilot: + app.current_provider = get_provider("postgresql") + app.current_connection = object() + try: + app.action_focus_query() + await pilot.press("i") + app.query_input.text = before + after + app.query_input.cursor_location = (before.count("\n"), len(before.rsplit("\n", 1)[-1])) + + await pilot.press(key) + await pilot.pause(0.15) + typed = " " if key == "space" else key + assert app.query_input.text == before + typed + after + assert app._autocomplete_visible + await pilot.press(*accept) + await pilot.pause() + + assert app.query_input.text == expected + after + finally: + app.current_connection = None + @pytest.mark.asyncio async def test_enter_inserts_newline_with_default_tab_accept_binding(self) -> None: app = _make_app() diff --git a/tests/unit/sql_completion/test_postgres_identity.py b/tests/unit/sql_completion/test_postgres_identity.py index 3f219c0d..5fdf8855 100644 --- a/tests/unit/sql_completion/test_postgres_identity.py +++ b/tests/unit/sql_completion/test_postgres_identity.py @@ -2,8 +2,7 @@ import pytest -from sqlit.domains.query.completion import get_completions -from sqlit.domains.query.completion import postgres_identity +from sqlit.domains.query.completion import get_completions, postgres_identity @pytest.mark.parametrize( @@ -21,12 +20,44 @@ def test_identity_completion_is_postgresql_only(sql, expected): ) -def test_ordinary_postgres_select_skips_identity_tokenization(monkeypatch): +@pytest.mark.parametrize("prefix", ["g", "ge", "gen", "q"]) +def test_ordinary_postgres_select_skips_identity_tokenization(monkeypatch, prefix): def unexpected_tokenization(_sql): - pytest.fail("SELECT without an identity prefix reached the identity lexer") + pytest.fail("SELECT reached the PostgreSQL identity lexer") monkeypatch.setattr(postgres_identity, "tokenize", unexpected_tokenization) - sql = "SELECT * FROM books WHERE title = " + history = "SELECT id, title FROM books WHERE id = 12345;\n" * 250 + sql = history + f"SELECT * FROM {prefix}" assert get_completions(sql, len(sql), [], {}, dialect="postgresql") == get_completions( sql, len(sql), [], {} ) + + +@pytest.mark.parametrize( + ("query", "identity"), + [ + ("SELECT 1; -- publisher's schema ; (\nCREATE TABLE t (id INT GE|);", True), + ("/* publisher's schema ; ( */ CREATE TABLE t (id INT GEN|);", True), + ("CREATE TABLE t (x TEXT, -- publisher's id ; (\n id INT GEN|);", True), + ("CREATE TABLE t (x TEXT,/* outer /* inner */ ; ' ( */ id INT GEN|);", True), + ("ALTER TABLE t ADD x TEXT, /* publisher's id ; ( */ ADD id INT GEN|;", True), + ('CREATE TABLE "/*t*/" ("--id" INT GEN|);', True), + ("CREATE TABLE t (x TEXT DEFAULT '/* ; (, */ -- ''', id INT GEN|);", True), + ("CREATE TABLE t (x TEXT DEFAULT $body$/* '; (, --$body$, id INT GEN|);", True), + (r"CREATE TABLE t (x TEXT DEFAULT E'a\'; /*', id INT GEN|);", True), + ("SELECT '/*'; CREATE TABLE t (id INT GEN|);", True), + ("-- ; CREATE TABLE t (id INT GEN|\n", False), + ("/* outer /* inner */ ; CREATE TABLE t (id INT GEN|); */", False), + ("SELECT 'text ; CREATE TABLE t (id INT GEN|);';", False), + ("SELECT $body$ ; CREATE TABLE t (id INT GEN|); $body$;", False), + (r"SELECT E'a\'; CREATE TABLE t (id INT GEN|);';", False), + ("CREATE TABLE t (id INT CHECK (id BIGINT GEN|));", False), + ("CREATE TABLE t (id TEXT GEN|);", False), + ("CREATE TABLE t (id INT); SELECT * FROM gen|", False), + ("SELECT 1 GEN|; CREATE TABLE t (id INT);", False), + ], +) +def test_identity_completion_uses_sql_context_before_cursor(query, identity): + before, after = query.split("|") + suggestions = get_completions(before + after, len(before), [], {}, dialect="postgresql") + assert ("GENERATED ALWAYS AS IDENTITY" in suggestions) is identity From dc4c0000db87001492fd291ae38fab6828d145c6 Mon Sep 17 00:00:00 2001 From: Maxteabag Date: Fri, 27 Nov 2026 15:47:14 +0000 Subject: [PATCH 4/5] fix(completion): scope PostgreSQL identity lexing to column candidates --- .../query/completion/postgres_identity.py | 238 ++++++++++-------- sqlit/domains/query/ui/mixins/autocomplete.py | 5 +- tests/ui/test_query_tab_insert.py | 7 + .../sql_completion/test_postgres_identity.py | 41 ++- 4 files changed, 173 insertions(+), 118 deletions(-) diff --git a/sqlit/domains/query/completion/postgres_identity.py b/sqlit/domains/query/completion/postgres_identity.py index b36d92b6..f38d41d5 100644 --- a/sqlit/domains/query/completion/postgres_identity.py +++ b/sqlit/domains/query/completion/postgres_identity.py @@ -2,54 +2,84 @@ import re -from sqlparse import tokens -from sqlparse.lexer import tokenize - -_IDENTIFIER = r'(?:"(?:[^"]|"")+"|[a-z_][\w$]*)' +# PostgreSQL accepts any high byte in identifiers and dollar tags. Dollar +# signs can continue an identifier, but they cannot occur inside the tag. +_NAME_START = r"a-zA-Z_\x80-\U0010ffff" +_TAG_CONTINUE = _NAME_START + "0-9" +_NAME_CONTINUE = _TAG_CONTINUE + "$" +_IDENTIFIER = rf'(?:"(?:[^"]|"")+"|[{_NAME_START}][{_NAME_CONTINUE}]*)' _TABLE = rf"{_IDENTIFIER}(?:\s*\.\s*{_IDENTIFIER})?" _CREATE = re.compile( rf"\s*CREATE\s+(?:(?:TEMP(?:ORARY)?|UNLOGGED)\s+)?TABLE\s+" rf"(?:IF\s+NOT\s+EXISTS\s+)?{_TABLE}\s*\(", - re.IGNORECASE, + re.IGNORECASE | re.ASCII, ) -_ALTER = re.compile(rf"\s*ALTER\s+TABLE\s+{_TABLE}\s+", re.IGNORECASE) -_ADD = re.compile(r"\s*ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?", re.IGNORECASE) +_ALTER = re.compile(rf"\s*ALTER\s+TABLE\s+{_TABLE}\s+", re.IGNORECASE | re.ASCII) +_ADD = re.compile(r"\s*ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?", re.IGNORECASE | re.ASCII) +_INTEGER_TYPE = r"(?:pg_catalog\.)?(?:smallint|integer|bigint|int[248]?)" _COLUMN = re.compile( - rf"\s*{_IDENTIFIER}\s+(?:pg_catalog\.)?" - r"(?:smallint|integer|bigint|int[248]?)(?:\s+(?:NOT\s+NULL|PRIMARY\s+KEY|UNIQUE))*" + rf"\s*{_IDENTIFIER}\s+{_INTEGER_TYPE}(?:\s+(?:NOT\s+NULL|PRIMARY\s+KEY|UNIQUE))*" r"\s+([a-z\s]+)", - re.IGNORECASE, + re.IGNORECASE | re.ASCII, +) +_CLAUSES = ("GENERATED ALWAYS AS IDENTITY", "GENERATED BY DEFAULT AS IDENTITY") +_CLAUSE_WORDS = {word for clause in _CLAUSES for word in clause.split()} +_CLAUSE_PREFIXES = {word[:end] for word in _CLAUSE_WORDS for end in range(1, len(word) + 1)} +_COLUMN_TAIL_WORDS = _CLAUSE_WORDS | {"NOT", "NULL", "PRIMARY", "KEY", "UNIQUE"} +_TAIL_WORD = re.compile( + rf"(?/\*|--)|(?P[Ee]'|['\"])" + rf"|(?P\$(?:[{_NAME_START}][{_TAG_CONTINUE}]*)?\$)" + # Consume complete unquoted identifiers so their interior dollar signs + # and any trailing E cannot be mistaken for literal openers. + rf"|[{_NAME_START}][{_NAME_CONTINUE}]*|(?P[();,])" +) -def _has_identity_prefix(before_cursor: str) -> bool: - # Read at most the five words of a clause, starting at the cursor. - # The full lexer still validates the DDL context. - position = len(before_cursor) - prefix = " " if before_cursor and before_cursor[-1].isspace() else "" - for _ in range(5): - while position and before_cursor[position - 1].isspace(): - position -= 1 +def _has_identity_candidate(sql: str) -> bool: + """Reject ordinary completion requests using only the suffix at the cursor.""" + position = len(sql) + at_cursor = True + while position: end = position - while position and not before_cursor[position - 1].isspace(): + while position and sql[position - 1] in _SPACE: position -= 1 - if end - position > len("GENERATED"): - return False - if end == position: - return False - word = before_cursor[position:end].upper() - prefix = word + (" " if prefix and prefix != " " else "") + prefix - if any(clause.startswith(prefix) and clause != prefix for clause in _CLAUSES): + + # A comment can stand in for whitespace anywhere in the column + # definition. Let the forward scanner resolve ambiguous boundaries. + if sql.endswith("*/", 0, position): return True + if _LINE_END.search(sql, position, end): + line = position + while line and sql[line - 1] not in "\r\n": + line -= 1 + if sql.find("--", line, position) != -1: + return True + + word = _TAIL_WORD.search(sql, max(0, position - _MAX_TAIL_WORD), position) + if not word: + return False + if not at_cursor and re.fullmatch( + _INTEGER_TYPE, word[0], re.IGNORECASE | re.ASCII + ): + return word.start() > 0 and ( + sql[word.start() - 1] in _SPACE or sql.endswith("*/", 0, word.start()) + ) + if word[0].upper() not in (_CLAUSE_PREFIXES if at_cursor else _COLUMN_TAIL_WORDS): + return False + at_cursor = False + position = word.start() return False @@ -62,95 +92,83 @@ def _block_comment_end(sql: str, start: int) -> int | None: return None -def _postgres_span(sql: str, position: int, value: str) -> tuple[int, bool] | None: - """Return the token's end and whether it is a PostgreSQL comment.""" - end = position + len(value) - if sql.startswith("/*", position): - # PostgreSQL nests block comments. sqlparse closes at the first */. - comment_end = _block_comment_end(sql, position) - return (comment_end, True) if comment_end is not None else None - if value.startswith("--"): - if end == len(sql) and not value.endswith(("\r", "\n")): - return None - return end, True - - # sqlparse can split escape strings or unfinished literals into SQL tokens. - quoted = None - if value[0] == "'": - quoted = _STRING - elif value[0] == '"': - quoted = _QUOTED_IDENTIFIER - elif sql[position:position + 2].lower() == "e'": - quoted = _ESCAPE_STRING - if quoted is not None: - match = quoted.match(sql, position) - return (match.end(), False) if match else None - - if value.startswith("$") and (tag := _DOLLAR_QUOTE.match(sql, position)): - close = sql.find(tag[0], tag.end()) - return (close + len(tag[0]), False) if close != -1 else None - return end, False +def _quoted_end(sql: str, start: int, token: str) -> int | None: + if token == '"': + match = _QUOTED_IDENTIFIER.match(sql, start) + elif token == "'": + match = _STRING.match(sql, start) + else: + match = _ESCAPE_STRING.match(sql, start + 1) + while match and (continued := _ESCAPE_CONTINUATION.match(sql, match.end())): + match = _ESCAPE_STRING.match(sql, continued.end() - 1) + return match.end() if match else None -def get_postgres_identity_completions(before_cursor: str) -> list[str] | None: - if not _has_identity_prefix(before_cursor) or not _DDL_KEYWORD.search(before_cursor): - return None - - statement_start = item_start = depth = 0 +def _scan_context(sql: str) -> str | None: + """Locate the active column definition, with comments replaced by spaces.""" + statement_start = item_start = alter_item_start = depth = 0 outer_open = -1 - alter_item_start = 0 position = unmasked_start = 0 parts: list[str] = [] - lexer = tokenize(before_cursor) - while position < len(before_cursor): - kind, value = next(lexer) - lexer_end = position + len(value) - span = _postgres_span(before_cursor, position, value) - if span is None: - return None - end, is_comment = span - if is_comment: - # Preserve offsets used for the statement and column boundaries. - parts.extend((before_cursor[unmasked_start:position], " " * (end - position))) - unmasked_start = end - elif kind in tokens.Punctuation: - if value == ";": - statement_start = item_start = alter_item_start = position + 1 + while match := _CONTEXT_TOKEN.search(sql, position): + start, position = match.span() + token = match[0] + if match.lastgroup == "comment": + if token == "/*": + end = _block_comment_end(sql, start) + else: + newline = _LINE_END.search(sql, position) + end = newline.start() if newline else None + if end is None: + return None + parts.extend((sql[unmasked_start:start], " " * (end - start))) + position = unmasked_start = end + elif match.lastgroup == "quote": + end = _quoted_end(sql, start, token) + if end is None: + return None + position = end + elif match.lastgroup == "dollar": + close = sql.find(token, position) + if close == -1: + return None + position = close + len(token) + elif match.lastgroup == "punct": + if token == ";": + statement_start = item_start = alter_item_start = position depth = 0 - elif value == "(": + parts.clear() + unmasked_start = position + elif token == "(": if depth == 0: - outer_open = position + outer_open = start depth += 1 - elif value == ")": + elif token == ")": depth -= 1 - elif value == ",": - if depth == 1: - item_start = position + 1 - elif depth == 0: - alter_item_start = position + 1 - - # Skip any extra lexer tokens inside a PostgreSQL literal or comment. - while lexer_end < end: - _, skipped = next(lexer) - lexer_end += len(skipped) - if lexer_end != end: - # A token crossed the end of the span. Start again at its boundary. - lexer = tokenize(before_cursor[end:]) - position = end - - clean = "".join([*parts, before_cursor[unmasked_start:]]) if parts else before_cursor - statement = clean[statement_start:] + elif depth == 1: + item_start = position + elif depth == 0: + alter_item_start = position + + statement = "".join([*parts, sql[unmasked_start:]]) if parts else sql[statement_start:] create = _CREATE.match(statement) - alter = _ALTER.match(statement) if create and depth == 1 and outer_open == statement_start + create.end() - 1: - column = clean[max(statement_start + create.end(), item_start):] - elif alter and depth == 0: - action = clean[max(statement_start + alter.end(), alter_item_start):] - add = _ADD.match(action) - if not add: - return None - column = action[add.end():] - else: + return statement[max(create.end(), item_start - statement_start):] + + alter = _ALTER.match(statement) + if alter and depth == 0: + action = statement[max(alter.end(), alter_item_start - statement_start):] + if add := _ADD.match(action): + return action[add.end():] + return None + + +def get_postgres_identity_completions(before_cursor: str) -> list[str] | None: + if not _has_identity_candidate(before_cursor): + return None + + column = _scan_context(before_cursor) + if column is None: return None match = _COLUMN.fullmatch(column) diff --git a/sqlit/domains/query/ui/mixins/autocomplete.py b/sqlit/domains/query/ui/mixins/autocomplete.py index 72d642ba..2e73b43d 100644 --- a/sqlit/domains/query/ui/mixins/autocomplete.py +++ b/sqlit/domains/query/ui/mixins/autocomplete.py @@ -68,10 +68,13 @@ def _apply_autocomplete(self: AutocompleteMixinHost) -> None: cursor_loc = self.query_input.cursor_location cursor_pos = self._location_to_offset(text, cursor_loc) + provider = getattr(self, "current_provider", None) + postgres = provider is not None and provider.metadata.db_type == "postgresql" word_start = cursor_pos while word_start > 0: previous = text[word_start - 1] - if previous in " \t\r\n,()[].": + # A PostgreSQL block comment separates tokens even without whitespace. + if previous in " \t\r\n,()[]." or (postgres and text.endswith("*/", 0, word_start)): break word_start -= 1 diff --git a/tests/ui/test_query_tab_insert.py b/tests/ui/test_query_tab_insert.py index d77dbd87..8a0d65fd 100644 --- a/tests/ui/test_query_tab_insert.py +++ b/tests/ui/test_query_tab_insert.py @@ -101,6 +101,13 @@ async def test_tab_accepts_autocomplete_suggestion(self) -> None: ("tab",), "ALTER TABLE altered ADD COLUMN id INTEGER GENERATED ALWAYS AS IDENTITY", ), + ( + "SELECT 2 # 1; CREATE TABLE t (id INT/* explanation */GE", + ");", + "n", + ("down", "tab"), + "SELECT 2 # 1; CREATE TABLE t (id INT/* explanation */GENERATED ALWAYS AS IDENTITY", + ), ( "/* publisher's schema */ CREATE TABLE t (source INT, -- publisher's id\n id INT GE", ");", diff --git a/tests/unit/sql_completion/test_postgres_identity.py b/tests/unit/sql_completion/test_postgres_identity.py index 5fdf8855..136f74e4 100644 --- a/tests/unit/sql_completion/test_postgres_identity.py +++ b/tests/unit/sql_completion/test_postgres_identity.py @@ -20,16 +20,21 @@ def test_identity_completion_is_postgresql_only(sql, expected): ) +@pytest.mark.parametrize( + "earlier_statement", + ["", "CREATE TABLE genres (id INT);\n", "ALTER TABLE genres ADD id INT;\n", "-- CREATE\n"], +) @pytest.mark.parametrize("prefix", ["g", "ge", "gen", "q"]) -def test_ordinary_postgres_select_skips_identity_tokenization(monkeypatch, prefix): +def test_ordinary_postgres_select_skips_identity_tokenization(monkeypatch, earlier_statement, prefix): def unexpected_tokenization(_sql): - pytest.fail("SELECT reached the PostgreSQL identity lexer") + pytest.fail("SELECT reached the PostgreSQL identity scanner") - monkeypatch.setattr(postgres_identity, "tokenize", unexpected_tokenization) + monkeypatch.setattr(postgres_identity, "_scan_context", unexpected_tokenization) history = "SELECT id, title FROM books WHERE id = 12345;\n" * 250 - sql = history + f"SELECT * FROM {prefix}" - assert get_completions(sql, len(sql), [], {}, dialect="postgresql") == get_completions( - sql, len(sql), [], {} + sql = earlier_statement + history + f"SELECT * FROM {prefix}" + tables = ["gadgets", "geographies", "genres", "quotes", "books"] + assert get_completions(sql, len(sql), tables, {}, dialect="postgresql") == get_completions( + sql, len(sql), tables, {} ) @@ -46,10 +51,17 @@ def unexpected_tokenization(_sql): ("CREATE TABLE t (x TEXT DEFAULT $body$/* '; (, --$body$, id INT GEN|);", True), (r"CREATE TABLE t (x TEXT DEFAULT E'a\'; /*', id INT GEN|);", True), ("SELECT '/*'; CREATE TABLE t (id INT GEN|);", True), + ("CREATE TABLE t (id INT/* explanation */GEN|);", True), + ("CREATE TABLE t (id INT-- explanation\r\nGEN|);", True), + ("CREATE TABLE t (id pg_catalog.int8 NOT NULL UNIQUE GEN|);", True), + ("SELECT 2 # 1; CREATE TABLE t (id INT GEN|);", True), + ("SELECT '$💡$'; CREATE TABLE t (id INT GEN|);", True), + ("SELECT value$💡$; CREATE TABLE t (id INT GEN|);", True), + ("SELECT E'a'\n'\\'; hidden'; CREATE TABLE t (id INT GEN|);", True), + ("SELECT E'a'\n'\\'; CREATE TABLE t (id INT GEN|);';", False), ("-- ; CREATE TABLE t (id INT GEN|\n", False), ("/* outer /* inner */ ; CREATE TABLE t (id INT GEN|); */", False), ("SELECT 'text ; CREATE TABLE t (id INT GEN|);';", False), - ("SELECT $body$ ; CREATE TABLE t (id INT GEN|); $body$;", False), (r"SELECT E'a\'; CREATE TABLE t (id INT GEN|);';", False), ("CREATE TABLE t (id INT CHECK (id BIGINT GEN|));", False), ("CREATE TABLE t (id TEXT GEN|);", False), @@ -61,3 +73,18 @@ def test_identity_completion_uses_sql_context_before_cursor(query, identity): before, after = query.split("|") suggestions = get_completions(before + after, len(before), [], {}, dialect="postgresql") assert ("GENERATED ALWAYS AS IDENTITY" in suggestions) is identity + + +@pytest.mark.parametrize("tag", ["", "body", "💡", "a\u0301"]) +@pytest.mark.parametrize("closed", [False, True]) +def test_identity_completion_respects_dollar_quote_boundaries(tag, closed): + delimiter = f"${tag}$" + ddl = "CREATE TABLE t (id INT GEN" + sql = f"SELECT {delimiter}; {ddl}" + if closed: + sql += f"); {delimiter}; {ddl}" + after = ");" + else: + after = f"); {delimiter};" + completion = get_completions(sql + after, len(sql), [], {}, dialect="postgresql") + assert ("GENERATED ALWAYS AS IDENTITY" in completion) is closed From 1f4a0f3f1aaafb983680ec133a32eadf434c6880 Mon Sep 17 00:00:00 2001 From: Maxteabag Date: Fri, 27 Nov 2026 15:50:45 +0000 Subject: [PATCH 5/5] fix(completion): prioritize PostgreSQL identity over metadata loading --- .../ui/mixins/autocomplete_suggestions.py | 15 ++++++---- tests/ui/test_query_tab_insert.py | 28 +++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py b/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py index 74628887..8829bb04 100644 --- a/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py +++ b/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py @@ -11,6 +11,7 @@ get_completions, get_context, ) +from sqlit.domains.query.completion.postgres_identity import get_postgres_identity_completions from sqlit.shared.ui.protocols import AutocompleteMixinHost @@ -104,6 +105,12 @@ def is_known(name: str) -> bool: def _get_autocomplete_suggestions(self: AutocompleteMixinHost, text: str, cursor_pos: int) -> list[str]: """Get autocomplete suggestions using the SQL completion engine.""" + provider = getattr(self, "current_provider", None) + if provider and provider.metadata.db_type == "postgresql": + identity = get_postgres_identity_completions(text[:cursor_pos]) + if identity is not None: + return identity + # Build schema data for get_completions raw_tables = self._schema_cache.get("tables", []) + self._schema_cache.get("views", []) raw_columns = self._schema_cache.get("columns", {}) @@ -156,9 +163,8 @@ def needs_column_load(key: str) -> bool: elif table_key in loading: return ["Loading..."] - provider = getattr(self, "current_provider", None) - # Now call get_completions with all available data - results = get_completions( + # Dialect-specific identity completion was checked before metadata loading. + return get_completions( text, cursor_pos, tables, @@ -166,7 +172,4 @@ def needs_column_load(key: str) -> bool: procedures, include_keywords=True, include_functions=True, - dialect=provider.metadata.db_type if provider else None, ) - - return results diff --git a/tests/ui/test_query_tab_insert.py b/tests/ui/test_query_tab_insert.py index 8a0d65fd..0785a679 100644 --- a/tests/ui/test_query_tab_insert.py +++ b/tests/ui/test_query_tab_insert.py @@ -142,6 +142,34 @@ async def test_postgres_generated_completions_accept_through_editor(self, before finally: app.current_connection = None + @pytest.mark.asyncio + async def test_postgres_identity_accepts_tab_while_earlier_select_columns_load(self) -> None: + app = _make_app() + before = "SELECT * FROM books;\nCREATE TABLE t (id INT GENERATED BY" + after = ");" + + async with app.run_test(size=(120, 40)) as pilot: + app.current_provider = get_provider("postgresql") + app.current_connection = object() + try: + app._schema_cache["tables"] = ["books"] + app._table_metadata["books"] = ("public", "books", "") + app._columns_loading.add("books") + + app.action_focus_query() + await pilot.press("i") + app.query_input.text = before + after + app.query_input.cursor_location = (1, len(before.splitlines()[-1])) + + await pilot.press("space") + await pilot.pause(0.15) + await pilot.press("tab") + await pilot.pause() + + assert app.query_input.text == before + " DEFAULT AS IDENTITY" + after + finally: + app.current_connection = None + @pytest.mark.asyncio async def test_enter_inserts_newline_with_default_tab_accept_binding(self) -> None: app = _make_app()