The Wayback Machine - https://web.archive.org/web/20201011071229/https://github.com/MagicStack/asyncpg/issues/579
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Allow named parameters in query #579

Open
RyadIso opened this issue May 29, 2020 · 1 comment
Open

[Feature] Allow named parameters in query #579

RyadIso opened this issue May 29, 2020 · 1 comment

Comments

@RyadIso
Copy link

@RyadIso RyadIso commented May 29, 2020

I'm currently switching over from psycopg2 to asyncpg. Many things are solved pretty well/consistent with asyncpg but there is one thing I'm really missing: Named parameters to a query. Here is how I typically make my queries with psycopg2:

query = "SELECT * FROM mytable WHERE foo=%(foo)s"
vars = {"foo": "something"}
if filter_for_bar is not None
    query += " AND bar=%(bar)s"
    vars["bar"] = filter_for_bar
if myint_min_val is not None:
    query += " AND myint >= %(myint_min_val)s"
    vars["myint_min_val"] = myint_min_val
# [Many more parameters/filters in real queries]
cur.execute(query, vars)

This syntax with named parameters makes the code a lot easier to read (and less likely to contain errors).

As of now, asyncpg only supports an args array with a number of parameters, which are referenced as $1, $2, ... in the query. I'm sometimes writing really complex queries with 5-10 joins and dozens of different query parameters (some of them added at runtime depending on user input). It is really easy to mess up some parameter numbers with that. So it would be really great if you could add a way to use named parameters as an alternative to numbers. This could be done with something like $foo instead of $1 in the sql and then passing a dictionary instead of the args list.

@lsabi
Copy link

@lsabi lsabi commented Jun 16, 2020

This issue was already addressed in:

#9
#64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
2 participants
You can’t perform that action at this time.