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
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Core Devs:

Contributors:
-------------
* Boulea7
* AC (ac1982)
* Wu Shuwen (dajiaohuang)
* Brett
Expand Down
2 changes: 2 additions & 0 deletions changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Bug fixes:
----------
* Display database errors from ``\ef`` and ``\ev`` without exiting the
interactive session, allowing recovery from an aborted transaction.
* Let ``\ef`` select overloaded functions by argument types, for example
``\ef foo(integer, text)``.
* Fix the development setup instructions to activate the ``.venv`` directory
created by ``uv venv``.
* Read ``alias_map_file`` as UTF-8 (with or without a BOM) instead of the
Expand Down
6 changes: 4 additions & 2 deletions pgcli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,10 +926,12 @@ def handle_editor_command(self, text):
query = special.get_editor_query(text) or self.get_last_query()
else: # \ev or \ef
filename = None
spec = text.split()[1]
if editor_command == "\\ev":
query = self.pgexecute.view_definition(spec)
query = self.pgexecute.view_definition(text.split()[1])
elif editor_command == "\\ef":
spec = text.strip().split(maxsplit=1)[1]
# The optional editor line number is not part of the function signature.
spec = re.sub(r"\s+[0-9]+$", "", spec)
query = self.pgexecute.function_definition(spec)
sql, message = special.open_external_editor(filename, sql=query, editor=get_editor())
if message:
Expand Down
11 changes: 5 additions & 6 deletions pgcli/pgexecute.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,7 @@ class PGExecute:
LEFT JOIN pg_catalog.pg_namespace n ON (c.relnamespace = n.oid)
JOIN v ON (c.oid = v.v_oid)"""

function_definition_query = """
WITH f AS
(SELECT %s::pg_catalog.regproc::pg_catalog.oid AS f_oid)
SELECT pg_catalog.pg_get_functiondef(f.f_oid)
FROM f"""
function_definition_query = psycopg.sql.SQL("SELECT pg_catalog.pg_get_functiondef(%s::pg_catalog.{}::pg_catalog.oid)")

def __init__(
self,
Expand Down Expand Up @@ -531,13 +527,16 @@ def view_definition(self, spec):
def function_definition(self, spec):
"""Returns the SQL defining functions described by `spec`"""

lookup_type = "regprocedure" if spec.rstrip().endswith(")") else "regproc"
sql = self.function_definition_query.format(psycopg.sql.Identifier(lookup_type))
with self.conn.cursor() as cur:
sql = self.function_definition_query
_logger.debug("Function Definition Query. sql: %r\nspec: %r", sql, spec)
try:
cur.execute(sql, (spec,))
result = cur.fetchone()
return result[0]
except psycopg.errors.AmbiguousFunction:
raise
except psycopg.ProgrammingError:
raise RuntimeError(f"Function {spec} does not exist.")

Expand Down
37 changes: 37 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
)
from pgcli.pgexecute import PGExecute
from psycopg.conninfo import conninfo_to_dict
from psycopg.errors import AmbiguousFunction
from psycopg.pq import TransactionStatus
from pgspecial.main import PAGER_OFF, PAGER_LONG_OUTPUT, PAGER_ALWAYS
from utils import dbtest, run
Expand Down Expand Up @@ -657,6 +658,42 @@ def test_file_mode_runs_statements(tmpdir):
mock_exec.assert_called_once_with("select 1;\nselect 2;")


@dbtest
def test_edit_function_by_signature(executor, tmpdir):
executor.conn.execute("""
CREATE FUNCTION example(integer) RETURNS text
LANGUAGE sql AS $$ SELECT 'integer overload'::text $$;
CREATE FUNCTION example(text, double precision) RETURNS text
LANGUAGE sql AS $$ SELECT 'text overload'::text $$;
CREATE FUNCTION example_unique() RETURNS text
LANGUAGE sql AS $$ SELECT 'unique function'::text $$;
CREATE FUNCTION "example (quoted)"() RETURNS text
LANGUAGE sql AS $$ SELECT 'quoted function'::text $$;
""")
cli = PGCli(pgexecute=executor, pgclirc_file=str(tmpdir.join("rcfile")))
cli.prompt_app = mock.Mock()
cli.prompt_app.prompt.return_value = "SELECT 1"

with mock.patch("pgcli.main.special.open_external_editor", return_value=("", None)) as editor:
for spec, body in (
("example(integer)", "integer overload"),
("public.example(text, double precision)", "text overload"),
("example(integer) 3", "integer overload"),
("example_unique()", "unique function"),
("example_unique", "unique function"),
('"example (quoted)"', "quoted function"),
):
assert cli.handle_editor_command(r"\ef " + spec) == "SELECT 1"
assert body in editor.call_args.kwargs["sql"]

editor.reset_mock()
with pytest.raises(AmbiguousFunction, match="more than one function named"):
cli.handle_editor_command(r"\ef example")
with pytest.raises(RuntimeError, match="does not exist"):
cli.handle_editor_command(r"\ef example(uuid)")
editor.assert_not_called()


@dbtest
@pytest.mark.parametrize("editor_command", [r"\ef example", r"\ev example"])
def test_editor_in_failed_transaction(executor, tmpdir, capsys, editor_command):
Expand Down