diff --git a/AUTHORS b/AUTHORS index d0b4a5cee..0dc08685a 100644 --- a/AUTHORS +++ b/AUTHORS @@ -16,6 +16,7 @@ Core Devs: Contributors: ------------- + * Boulea7 * AC (ac1982) * Wu Shuwen (dajiaohuang) * Brett diff --git a/changelog.rst b/changelog.rst index a1ade6bc2..c24997719 100644 --- a/changelog.rst +++ b/changelog.rst @@ -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 diff --git a/pgcli/main.py b/pgcli/main.py index 972b3c670..3e5ed1363 100644 --- a/pgcli/main.py +++ b/pgcli/main.py @@ -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: diff --git a/pgcli/pgexecute.py b/pgcli/pgexecute.py index 1cac82eb4..c428ba874 100644 --- a/pgcli/pgexecute.py +++ b/pgcli/pgexecute.py @@ -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, @@ -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.") diff --git a/tests/test_main.py b/tests/test_main.py index 57ba8afe8..1894c7851 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -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 @@ -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):