Skip to content
Merged
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
8 changes: 8 additions & 0 deletions sqlit/domains/query/completion/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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 []
Expand Down
199 changes: 199 additions & 0 deletions sqlit/domains/query/completion/postgres_identity.py
Original file line number Diff line number Diff line change
@@ -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"(?<![{_NAME_CONTINUE}.])(?:pg_catalog\.)?[a-z]+[248]?\Z",
re.IGNORECASE | re.ASCII,
)
_MAX_TAIL_WORD = len("pg_catalog.smallint")
_SPACE = " \t\n\r\f\v"
_LINE_END = re.compile(r"[\r\n]")
_BLOCK_DELIMITER = re.compile(r"/\*|\*/")
_STRING = re.compile(r"'(?:[^']|'')*'(?!')")
_ESCAPE_STRING = re.compile(r"'(?:[^'\\]|''|\\[\s\S])*'(?!')")
_ESCAPE_CONTINUATION = re.compile(r"(?:[ \t\f\v]*(?:--[^\r\n]*)?[\r\n])+[ \t\f\v]*'")
_QUOTED_IDENTIFIER = re.compile(r'"(?:[^"]|"")*"(?!")')
_CONTEXT_TOKEN = re.compile(
r"(?P<comment>/\*|--)|(?P<quote>[Ee]'|['\"])"
rf"|(?P<dollar>\$(?:[{_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<punct>[();,])"
)


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
5 changes: 4 additions & 1 deletion sqlit/domains/query/ui/mixins/autocomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 9 additions & 4 deletions sqlit/domains/query/ui/mixins/autocomplete_suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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", {})
Expand Down Expand Up @@ -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,
Expand All @@ -166,5 +173,3 @@ def needs_column_load(key: str) -> bool:
include_keywords=True,
include_functions=True,
)

return results
96 changes: 96 additions & 0 deletions tests/ui/test_query_tab_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
Loading
Loading