From cffd58e5be41486b5a24503d4b896ae964f8f4a6 Mon Sep 17 00:00:00 2001 From: leo7martins <219400372+leo7martins@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:37:11 +0000 Subject: [PATCH 1/2] feat: optional parameters for named queries, written $?N (#143) Named queries gain optional placeholders $?1, $?2, ...: an argument supplied at that position is substituted the same way as a regular $N parameter, while a missing one is replaced by null. This lets one saved query serve both filtered and unfiltered runs, e.g.: \ns opt select * from abc where ($?1 is null or a like '%$?1%') - the gate in execute_named_query now also fires when the query only contains optional placeholders (a literal '$1' is no longer required to reach the substitution step) - unknown-argument error now mentions both the $N and $?N forms - unit tests for the substitution function (supplied, missing, mixed mandatory/optional, extra-argument error) plus an end-to-end dbtest running a saved query with and without its optional argument - changelog entry and usage example Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- changelog.rst | 8 +++++ pgspecial/iocommands.py | 58 ++++++++++++++++++++------------- pgspecial/namedqueries.py | 8 +++-- tests/test_named_queries.py | 64 +++++++++++++++++++++++++++++++++++-- 4 files changed, 110 insertions(+), 28 deletions(-) diff --git a/changelog.rst b/changelog.rst index 249b8ff..50a2fa2 100644 --- a/changelog.rst +++ b/changelog.rst @@ -1,4 +1,12 @@ +Unreleased +========== + +Features: +--------- +* Named queries: support optional parameters written ``$?1``, ``$?2``, ...: a supplied argument is substituted like a regular parameter, while a missing one is replaced by ``null``, so one saved query can serve both filtered and unfiltered runs (#143). + + 2.3.0 (2026-09-14) ================== diff --git a/pgspecial/iocommands.py b/pgspecial/iocommands.py index 46607d3..d63cf82 100644 --- a/pgspecial/iocommands.py +++ b/pgspecial/iocommands.py @@ -1,16 +1,16 @@ -from __future__ import unicode_literals +import logging +from os.path import expanduser import re +import shlex import sys -import logging + import click -import io -import shlex -import sqlparse import psycopg -from os.path import expanduser -from .namedqueries import NamedQueries +import sqlparse + from . import export from .main import show_extra_help_command, special_command +from .namedqueries import NamedQueries NAMED_QUERY_PLACEHOLDERS = frozenset({"$1", "$*", "$@"}) @@ -93,7 +93,7 @@ def open_external_editor(filename=None, sql=None, editor=None): # Populate the editor buffer with the partial sql (if available) and a # placeholder comment. query = click.edit( - "{sql}\n\n{marker}".format(sql=sql, marker=MARKER), + f"{sql}\n\n{MARKER}", filename=filename, extension=".sql", editor=editor, @@ -102,7 +102,7 @@ def open_external_editor(filename=None, sql=None, editor=None): if filename: try: query = read_from_file(filename) - except IOError: + except OSError: message = "Error reading file: %s." % filename if query is not None: @@ -116,7 +116,7 @@ def open_external_editor(filename=None, sql=None, editor=None): def read_from_file(path): - with io.open(expanduser(path), encoding="utf-8") as f: + with open(expanduser(path), encoding="utf-8") as f: contents = f.read() return contents @@ -150,7 +150,7 @@ def copy(cur, pattern, verbose): query = f"{before_file_name} {replacement_file_name} {after_file_name}" open_mode = "r" if direction == "FROM" else "wb" if file_name.startswith("'") and file_name.endswith("'"): - file = io.open(expanduser(file_name.strip("'")), mode=open_mode) + file = open(expanduser(file_name.strip("'")), mode=open_mode) elif "stdin" in file_name.lower(): file = sys.stdin.buffer elif "stdout" in file_name.lower(): @@ -178,7 +178,12 @@ def copy(cur, pattern, verbose): def subst_favorite_query_args(query, args): - """replace positional parameters ($1,$2,...$n) in query.""" + """replace positional parameters in query. + + Regular parameters ($1, $2, ... $n) must be given an argument. + Optional parameters ($?1, $?2, ...) are replaced by an argument + when it is supplied, and by null when it is not. + """ is_query_with_aggregation = ("$*" in query) or ("$@" in query) # In case of arguments aggregation we replace all positional arguments until the @@ -186,18 +191,22 @@ def subst_favorite_query_args(query, args): # replace the placeholder with them. for idx, val in enumerate(args, start=1): subst_var = "$" + str(idx) - if subst_var not in query: - if is_query_with_aggregation: - # remove consumed arguments ( - 1 to include current value) - args = args[idx - 1 :] - break - + optional_subst_var = "$?" + str(idx) + if subst_var in query: + query = query.replace(subst_var, val) + elif optional_subst_var in query: + # Optional parameter ($?N) with an argument supplied for it. + query = query.replace(optional_subst_var, val) + elif is_query_with_aggregation: + # remove consumed arguments ( - 1 to include current value) + args = args[idx - 1 :] + break + else: return [ None, - "query does not have substitution parameter " + subst_var + ":\n " + query, + "query does not have substitution parameter " + subst_var + " or " + optional_subst_var + ":\n " + query, ] - query = query.replace(subst_var, val) # we consumed all arguments else: args = [] @@ -217,6 +226,9 @@ def subst_favorite_query_args(query, args): "missing substitution for " + match.group(0) + " in query:\n " + query, ] + # Optional parameters the caller did not supply become null. + query = re.sub(r"\$\?\d+", "null", query) + return [query, None] @@ -230,13 +242,13 @@ def execute_named_query(cur, pattern, **_): pattern = params.pop(0) query = NamedQueries.instance.get(pattern) - title = "> {}".format(query) + title = f"> {query}" if query is None: - message = "No named query: {}".format(pattern) + message = f"No named query: {pattern}" return [(None, None, None, message)] try: - if any(p in query for p in NAMED_QUERY_PLACEHOLDERS): + if any(p in query for p in NAMED_QUERY_PLACEHOLDERS) or "$?" in query: query, params = subst_favorite_query_args(query, params) if query is None: raise Exception("Bad arguments\n" + params) diff --git a/pgspecial/namedqueries.py b/pgspecial/namedqueries.py index ef46617..a66916c 100644 --- a/pgspecial/namedqueries.py +++ b/pgspecial/namedqueries.py @@ -1,5 +1,4 @@ -# -*- coding: utf-8 -*- -class NamedQueries(object): +class NamedQueries: section_name = "named queries" usage = """Named Queries are a way to save frequently used queries @@ -17,6 +16,11 @@ class NamedQueries(object): | simple | SELECT * FROM xyzb where a is not null | +--------+----------------------------------------+ + # Save a named query with optional parameters ($?1, ...). Missing + # arguments are substituted by null, so this query lists everything + # when it is run without arguments: + > \\ns opt select * from abc where ($?1 is null or a like %\\'$?1%\\'); + # Run a named query. > \\n simple +-----+ diff --git a/tests/test_named_queries.py b/tests/test_named_queries.py index 040cfbd..338a749 100644 --- a/tests/test_named_queries.py +++ b/tests/test_named_queries.py @@ -1,11 +1,14 @@ """Tests for named queries.""" -import pytest import tempfile -from pgspecial.namedqueries import NamedQueries -from pgspecial.main import PGSpecial from configobj import ConfigObj +from dbutils import dbtest +import pytest + +from pgspecial.iocommands import subst_favorite_query_args +from pgspecial.main import PGSpecial +from pgspecial.namedqueries import NamedQueries @pytest.fixture(scope="module") @@ -43,3 +46,58 @@ def test_print_named_queries(named_query): None, None, ) + + +def test_favorite_query_with_optional_parameter_supplied(): + query = "select * from abc where ($?1 is null or name like '%$?1%')" + result = subst_favorite_query_args(query, ["foo"]) + assert result == [ + "select * from abc where (foo is null or name like '%foo%')", + None, + ] + + +def test_favorite_query_with_optional_parameter_missing_becomes_null(): + query = "select * from abc where ($?1 is null or name like '%$?1%')" + result = subst_favorite_query_args(query, []) + assert result == [ + "select * from abc where (null is null or name like '%null%')", + None, + ] + + +def test_favorite_query_optional_and_mandatory_parameters(): + query = "select * from t where a > $1 and ($?2 is null or b like '%$?2%')" + assert subst_favorite_query_args(query, ["5"])[0] == ("select * from t where a > 5 and (null is null or b like '%null%')") + assert subst_favorite_query_args(query, ["5", "x"])[0] == ("select * from t where a > 5 and (x is null or b like '%x%')") + + +def test_favorite_query_extra_argument_beyond_placeholders_errors(): + query = "select * from t where a > $1 and b like '%$?2%'" + result = subst_favorite_query_args(query, ["5", "x", "y"]) + assert result[0] is None + assert "$3" in result[1] and "$?3" in result[1] + + +@dbtest +def test_run_named_query_with_only_optional_param(named_query, connection): + # A saved query with only optional parameters must still reach the + # substitution step; the old gate only fired on a literal $1. + cur = connection.cursor() + + cur.execute("DROP TABLE IF EXISTS nq_optional_test") + cur.execute("CREATE TABLE nq_optional_test (i int)") + cur.execute("INSERT INTO nq_optional_test VALUES (1), (10)") + + save = r"\ns nq_opt select * from nq_optional_test where ($?1 is null or i > $?1)" + PGSpecial().execute(cur, save) + + list(PGSpecial().execute(cur, r"\n nq_opt")) + rows = cur.fetchall() + assert sorted(r[0] for r in rows) == [1, 10] + + list(PGSpecial().execute(cur, r"\n nq_opt 5")) + rows = cur.fetchall() + assert [r[0] for r in rows] == [10] + + cur.execute("DROP TABLE IF EXISTS nq_optional_test") From b2c92e55f5809740a3118522fc16cec8e935e112 Mon Sep 17 00:00:00 2001 From: leo7martins <219400372+leo7martins@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:52:50 +0000 Subject: [PATCH 2/2] Keep named query optional parameters diff focused --- pgspecial/iocommands.py | 26 +++++++++++++------------- pgspecial/namedqueries.py | 3 ++- tests/test_named_queries.py | 9 ++++----- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/pgspecial/iocommands.py b/pgspecial/iocommands.py index d63cf82..68d95e9 100644 --- a/pgspecial/iocommands.py +++ b/pgspecial/iocommands.py @@ -1,16 +1,16 @@ -import logging -from os.path import expanduser +from __future__ import unicode_literals import re -import shlex import sys - +import logging import click -import psycopg +import io +import shlex import sqlparse - +import psycopg +from os.path import expanduser +from .namedqueries import NamedQueries from . import export from .main import show_extra_help_command, special_command -from .namedqueries import NamedQueries NAMED_QUERY_PLACEHOLDERS = frozenset({"$1", "$*", "$@"}) @@ -93,7 +93,7 @@ def open_external_editor(filename=None, sql=None, editor=None): # Populate the editor buffer with the partial sql (if available) and a # placeholder comment. query = click.edit( - f"{sql}\n\n{MARKER}", + "{sql}\n\n{marker}".format(sql=sql, marker=MARKER), filename=filename, extension=".sql", editor=editor, @@ -102,7 +102,7 @@ def open_external_editor(filename=None, sql=None, editor=None): if filename: try: query = read_from_file(filename) - except OSError: + except IOError: message = "Error reading file: %s." % filename if query is not None: @@ -116,7 +116,7 @@ def open_external_editor(filename=None, sql=None, editor=None): def read_from_file(path): - with open(expanduser(path), encoding="utf-8") as f: + with io.open(expanduser(path), encoding="utf-8") as f: contents = f.read() return contents @@ -150,7 +150,7 @@ def copy(cur, pattern, verbose): query = f"{before_file_name} {replacement_file_name} {after_file_name}" open_mode = "r" if direction == "FROM" else "wb" if file_name.startswith("'") and file_name.endswith("'"): - file = open(expanduser(file_name.strip("'")), mode=open_mode) + file = io.open(expanduser(file_name.strip("'")), mode=open_mode) elif "stdin" in file_name.lower(): file = sys.stdin.buffer elif "stdout" in file_name.lower(): @@ -242,9 +242,9 @@ def execute_named_query(cur, pattern, **_): pattern = params.pop(0) query = NamedQueries.instance.get(pattern) - title = f"> {query}" + title = "> {}".format(query) if query is None: - message = f"No named query: {pattern}" + message = "No named query: {}".format(pattern) return [(None, None, None, message)] try: diff --git a/pgspecial/namedqueries.py b/pgspecial/namedqueries.py index a66916c..fe457d7 100644 --- a/pgspecial/namedqueries.py +++ b/pgspecial/namedqueries.py @@ -1,4 +1,5 @@ -class NamedQueries: +# -*- coding: utf-8 -*- +class NamedQueries(object): section_name = "named queries" usage = """Named Queries are a way to save frequently used queries diff --git a/tests/test_named_queries.py b/tests/test_named_queries.py index 338a749..8a238b6 100644 --- a/tests/test_named_queries.py +++ b/tests/test_named_queries.py @@ -1,14 +1,13 @@ """Tests for named queries.""" +import pytest import tempfile +from pgspecial.namedqueries import NamedQueries +from pgspecial.main import PGSpecial +from pgspecial.iocommands import subst_favorite_query_args from configobj import ConfigObj from dbutils import dbtest -import pytest - -from pgspecial.iocommands import subst_favorite_query_args -from pgspecial.main import PGSpecial -from pgspecial.namedqueries import NamedQueries @pytest.fixture(scope="module")