diff --git a/sqlit/domains/query/completion/completion.py b/sqlit/domains/query/completion/completion.py index ee94d23a..434c14ba 100644 --- a/sqlit/domains/query/completion/completion.py +++ b/sqlit/domains/query/completion/completion.py @@ -38,6 +38,7 @@ 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 @@ -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. @@ -287,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 [] diff --git a/sqlit/domains/query/completion/postgres_identity.py b/sqlit/domains/query/completion/postgres_identity.py new file mode 100644 index 00000000..f38d41d5 --- /dev/null +++ b/sqlit/domains/query/completion/postgres_identity.py @@ -0,0 +1,199 @@ +"""PostgreSQL identity completion for integer column definitions.""" + +import re + +# 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.ASCII, +) +_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+{_INTEGER_TYPE}(?:\s+(?:NOT\s+NULL|PRIMARY\s+KEY|UNIQUE))*" + r"\s+([a-z\s]+)", + 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_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 sql[position - 1] in _SPACE: + position -= 1 + + # 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 + + +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 _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 _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 + position = unmasked_start = 0 + parts: list[str] = [] + 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 + parts.clear() + unmasked_start = position + elif token == "(": + if depth == 0: + outer_open = start + depth += 1 + elif token == ")": + depth -= 1 + 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) + if create and depth == 1 and outer_open == statement_start + create.end() - 1: + 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) + 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 + ] + 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/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/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py b/sqlit/domains/query/ui/mixins/autocomplete_suggestions.py index 126c14f6..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,8 +163,8 @@ def needs_column_load(key: str) -> bool: elif table_key in loading: return ["Loading..."] - # 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,5 +173,3 @@ def needs_column_load(key: str) -> bool: include_keywords=True, include_functions=True, ) - - return results diff --git a/tests/ui/test_query_tab_insert.py b/tests/ui/test_query_tab_insert.py index 88a3183c..0785a679 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,101 @@ 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", + ), + ( + "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", + ");", + "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_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() 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..136f74e4 --- /dev/null +++ b/tests/unit/sql_completion/test_postgres_identity.py @@ -0,0 +1,90 @@ +"""Regression coverage for dialect-specific identity completion.""" + +import pytest + +from sqlit.domains.query.completion import get_completions, 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), [], {} + ) + + +@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, earlier_statement, prefix): + def unexpected_tokenization(_sql): + pytest.fail("SELECT reached the PostgreSQL identity scanner") + + monkeypatch.setattr(postgres_identity, "_scan_context", unexpected_tokenization) + history = "SELECT id, title FROM books WHERE id = 12345;\n" * 250 + 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, {} + ) + + +@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/* 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), + (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 + + +@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