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..68d95e9 100644 --- a/pgspecial/iocommands.py +++ b/pgspecial/iocommands.py @@ -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] @@ -236,7 +248,7 @@ def execute_named_query(cur, 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..fe457d7 100644 --- a/pgspecial/namedqueries.py +++ b/pgspecial/namedqueries.py @@ -17,6 +17,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..8a238b6 100644 --- a/tests/test_named_queries.py +++ b/tests/test_named_queries.py @@ -5,7 +5,9 @@ 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 @pytest.fixture(scope="module") @@ -43,3 +45,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")