Skip to content

Commit 2182e7c

Browse files
aj-fuentesKangOl
andcommitted
[IMP] util/pg: add a query format utility
We want to move away of manual formatting. Part-of: #20 Co-authored-by: Christophe Simonis <[email protected]>
1 parent 3869719 commit 2182e7c

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/base/tests/test_util.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,3 +924,56 @@ def test_expand_braces(self, value, expected):
924924
def test_expand_braces_failure(self, value):
925925
with self.assertRaises(ValueError):
926926
util.expand_braces(value)
927+
928+
929+
class TestQueryFormat(UnitTestCase):
930+
@parametrize(
931+
[
932+
(
933+
"SELECT id FROM {table}",
934+
[],
935+
{"table": "res_users"},
936+
'SELECT id FROM "res_users"',
937+
),
938+
(
939+
"SELECT id FROM {1} WHERE {0} > 2",
940+
["id", "res_users"],
941+
{},
942+
'SELECT id FROM "res_users" WHERE "id" > 2',
943+
),
944+
(
945+
"SELECT id FROM {} WHERE {{parallel_filter}}",
946+
["res_users"],
947+
{},
948+
'SELECT id FROM "res_users" WHERE {parallel_filter}',
949+
),
950+
(
951+
"SELECT {col} FROM {table}",
952+
[],
953+
{"table": "res_users", "col": "id"},
954+
'SELECT "id" FROM "res_users"',
955+
),
956+
("{col} = 1", [], {"col": "X; fd"}, '"X; fd" = 1'),
957+
(
958+
"{col1} = {col2}",
959+
[],
960+
{"col2": "X; fd", "col1": "xxx"},
961+
'"xxx" = "X; fd"',
962+
),
963+
(
964+
"WITH {cte} AS (SELECT 1) SELECT 2",
965+
[],
966+
{"cte": "some info"},
967+
'WITH "some info" AS (SELECT 1) SELECT 2',
968+
),
969+
(
970+
"UPDATE res_users SET id = 2 WHERE {col} = %s",
971+
[],
972+
{"col": "Ab"},
973+
'UPDATE res_users SET id = 2 WHERE "Ab" = %s',
974+
),
975+
]
976+
)
977+
def test_format(self, query, args, kwargs, expected):
978+
cr = self.env.cr
979+
self.assertEqual(util.format_query(cr, query, *args, **kwargs), expected)

src/util/pg.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,20 @@ def execute(query):
114114
)
115115

116116

117+
def format_query(cr, query, *args, **kwargs):
118+
"""
119+
Format the `query` replacing arguments as SQL indentifiers
120+
Example:
121+
```
122+
>>> util.format_query(cr, "SELECT {0} FROM {table}", "id", table="res_users")
123+
SELECT "id" FROM "res_users"
124+
```
125+
"""
126+
args = tuple(a if isinstance(a, sql.Composable) else sql.Identifier(a) for a in args)
127+
kwargs = {k: v if isinstance(v, sql.Composable) else sql.Identifier(v) for k, v in kwargs.items()}
128+
return sql.SQL(query).format(*args, **kwargs).as_string(cr._cnx)
129+
130+
117131
def explode_query(cr, query, alias=None, num_buckets=8, prefix=None):
118132
"""
119133
Explode a query to multiple queries that can be executed in parallel

0 commit comments

Comments
 (0)