You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Can this support at least one of the param styles in the pep? Preferably pyformat.
Ideally, the parameters could then be passed in as a dictionary instead of a ordered list.
conn.fetch(myquery, {bar='bar', foo='foo'})
Reacted by Brain Morsel, Seth Larson, Benjamin W. Smith, Kostya Leschenko, Bob Colner, Imbolc, Oleg, Alexander Malev, schneefux, Eugene Klimov and 68 more
I'll let this issue stay open for a while to see if a lot of people is interested in this feature. Adding named parameters will require us to tokenize SQL, which is something I don't want to do unless it's absolutely necessary.
@1st1 I'd like to see this implemented as well. It would make maintaining queries easier. With just ordered parameters you have to be very careful when updating queries, and it's easy to get it wrong, especially if you have lots of parameters.
I'd very much like to see named parameters as well - ordered ones have proven error prone to the point where we've made it a code style across the company to use only named parameters unless there's some reason it's impossible.
OK; signing off this thread. Anybody needing the named parameter solution can find it at the git link posted above. It's an add-on class that leverages off of the existing asyncpg codebase.
[As I say on the git: I think named parameters are much safer than positional ones, and in my opinion it should be the rule and not the exception...]
Reacted by Esteban Echeverry and Juan Pablo Tamayo
By the way, Arseny: you were right! The query parsing needed to be decoupled from the statement generation, for reasons of thread efficiency (otherwise, the threads using prepared statements might get bottlenecked on one connection; accomplished that by using two classes...)
[Just wanted to credit Arseny for the good advice in this thread, Sam...]
query="SELECT * FROM user WHERE name = %(name)s, email = %(email)s"named_args= {'name': 'John Cena', 'email': '[email protected]'}
new_query, positional_args=pyformat2psql(query, named_args)
print(new_query) # prints SELECT * FROM user WHERE name = $1, email = $2print(positional_args) # prints ['John Cena', '[email protected]']
Reacted by Vitalii Ponomar, Naim Aryudya Azizi, Alexey Vaganov, gloryknight, Igor Nehoroshev, Eir Nym, Nathaniel Sabanski, Hayssam Soueidan, Dziga Vertov, 4thel00z and 11 more
Reacted by Nathaniel Sabanski, Kintaro Oe, Mikhail Pyrev, Adam Powis, Timur Makarov, Job Seuren, Stas Davydov, James Landon and Ekin Dursun
Thank you @cordalace for the polished solution for developers who want optional named parameters! 👍 Should seriously be considered for inclusion as a core utility function, considering how popular this story is!
Also to be fair many of us do not want to introduce ORM bloat. Named parameters are a highly valuable (for many), yet tiny, feature.
That said, thank you for asyncpg. I'm astounded at the quality of this project! @elprans@1st1
@cordalace built upon your code above for a "many" variant, list of dicts... seems to work, but curious how you would implement!? Thank you for your code too!
Considering Python dictionaries are now ordered and that the format_map method doesn't create a new dictionary on every call, like format does, one could use a Serial dict to solve this problem:
# Serial Dict#############classSerial(dict):
def__getitem__(self, key):
returnf"${list(self.keys()).index(key) +1}"# Tests#######parameters=Serial(foo='FOO', bar='BAR', baz='BAZ')
query="select {foo} from {bar} where baz={baz}".format_map(parameters)
assertquery=="select $1 from $2 where baz=$3"# Ordered Parametersparameters=Serial(baz='BAZ', foo='FOO', bar='BAR')
query="select {foo} from {bar} where baz={baz}".format_map(parameters)
assertquery=="select $2 from $3 where baz=$1"# Unordered Parametersparameters=Serial({'foo': 'FOO', 'baz': 'BAZ'})
query="select {foo} from {foo} where baz={baz}".format_map(parameters)
assertquery=="select $1 from $1 where baz=$2"# Repeated Parameters# Mocking Fetch###############defmock_fetch(query, *args):
assertquery=="select $1 from $1 where baz=$2"assertargs== ('FOO', 'BAZ')
query="select {foo} from {foo} where baz={baz}"parameters=Serial({'foo': 'FOO', 'baz': 'BAZ'})
mock_fetch(query.format_map(parameters), *parameters.values())
NOTE: The examples here are not valid PostgreSQL statements. These were used just to demonstrate the usage of format_map to create serial numeric placeholders based on a dictionary.
SQL function arguments can only be used as data values, not as identifiers.
Wanted to handle auto-removal of arguments not present in the query, instead of throwing an error. Based on @tebanep's snippet.
Enjoy:
# Serial Dictionary.classSerial(dict):
def__getitem__(self, key):
returnf"${list(self.keys()).index(key) +1}"# Pyformat to psql format.defpyformat2psql(query: str, args_dict: Dict[str, Any]) ->Tuple[str, List[Any]]:
# Remove args not present in query.args_list=list(args_dict.keys())
forvalueinargs_list:
iff"{{{value}}}"notinquery:
args_dict.pop(value, None)
# Generate query with serial positions.args=Serial(args_dict)
query_formatted=query.format_map(args)
args_formatted=list(args.values())
returnquery_formatted, args_formatted
Usage
# Will just ignore 'foo' instead of throwing error.query, params=pyformat2psql("SELECT * FROM users where name={baz}", {'foo': 'bob2', 'baz': 'bob'})
result=awaitconn.fetch(query, *params)
Considering Python dictionaries are now ordered and that the format_map method doesn't create a new dictionary on every call, like format does, one could use a Serial dict to solve this problem:
# Serial Dict#############classSerial(dict):
def__getitem__(self, key):
returnf"${list(self.keys()).index(key) +1}"# Tests#######parameters=Serial(foo='FOO', bar='BAR', baz='BAZ')
query="select {foo} from {bar} where baz={baz}".format_map(parameters)
assertquery=="select $1 from $2 where baz=$3"# Ordered Parametersparameters=Serial(baz='BAZ', foo='FOO', bar='BAR')
query="select {foo} from {bar} where baz={baz}".format_map(parameters)
assertquery=="select $2 from $3 where baz=$1"# Unordered Parametersparameters=Serial({'foo': 'FOO', 'baz': 'BAZ'})
query="select {foo} from {foo} where baz={baz}".format_map(parameters)
assertquery=="select $1 from $1 where baz=$2"# Repeated Parameters# Mocking Fetch###############defmock_fetch(query, *args):
assertquery=="select $1 from $1 where baz=$2"assertargs== ('FOO', 'BAZ')
query="select {foo} from {foo} where baz={baz}"parameters=Serial({'foo': 'FOO', 'baz': 'BAZ'})
mock_fetch(query.format_map(parameters), *parameters.values())
NOTE: The examples here are not valid PostgreSQL statements. These were used just to demonstrate the usage of format_map to create serial numeric placeholders based on a dictionary.
SQL function arguments can only be used as data values, not as identifiers.
It is a tiny library with only 2 classes (excluding the tests) so you could copy one or both of them into your project if you don't want to add a dependency.
The idea is that you use an args object in f-strings to build your queries. You then unpack the args object when using asyncpg. It supports executemany and fetchmany too.
Lower level arguments usage:
frompgargsimportArgsargs=Args(name="bilbo", age=111)
query=f"SELECT * FROM table WHERE name = {args.name} AND age = {args.age}"awaitconn.fetch(query, *args)
Higher level columns usage:
frompgargsimportArgs, Colscols=Cols(name="bilbo", age=111)
query=f"INSERT INTO table {cols.names} VALUES {cols.values}"awaitconn.execute(query, *cols.args)
args=Args()
search=Cols(args, name="bilbo", age=111)
changes=Cols(args, adventurous=False, hungry=True)
query=f"UPDATE table SET {changes.assignments} WHERE {search.conditions}"awaitconn.execute(query, *args)
Activity
ludovic-gasc commentedon Jul 26, 2016
+1 for pyformat: we use massively this format for our queries, it's the most explicit, at least to me.
1st1 commentedon Jul 26, 2016
I'll let this issue stay open for a while to see if a lot of people is interested in this feature. Adding named parameters will require us to tokenize SQL, which is something I don't want to do unless it's absolutely necessary.
gigatexal commentedon Aug 4, 2016
Will tokenizing hurt performance? I, too, prefer the dictionary vs ordered list approach.
sethmlarson commentedon Aug 5, 2016
I can say that if this feature were added I would use it over ordered list.
gglanzani commentedon Aug 30, 2016
@1st1 Interested here as well. It makes everything so much easier
treycucco commentedon Sep 13, 2016
@1st1 I'd like to see this implemented as well. It would make maintaining queries easier. With just ordered parameters you have to be very careful when updating queries, and it's easy to get it wrong, especially if you have lots of parameters.
bobcolner commentedon Oct 15, 2016
named keywords have proven more reliable for me as well. On brand with the python-zen 'explicit > implicit' credo as well.
imbolc commentedon Oct 28, 2016
Why don't you just use little wrappers like this?
Daenyth commentedon Sep 12, 2017
I'd very much like to see named parameters as well - ordered ones have proven error prone to the point where we've made it a code style across the company to use only named parameters unless there's some reason it's impossible.
thehesiod commentedon Sep 12, 2017
If tokenizing I'd suggest re-using any available code in libpq/psycopg2
elprans commentedon Sep 12, 2017
psycopg2 is LGPL, we can't reuse any code from there.
thehesiod commentedon Sep 12, 2017
meant as a library :)
*Experimental* support for kwargs.
25 remaining items
bitmodeler commentedon Nov 17, 2019
OK; signing off this thread. Anybody needing the named parameter solution can find it at the git link posted above. It's an add-on class that leverages off of the existing asyncpg codebase.
[As I say on the git: I think named parameters are much safer than positional ones, and in my opinion it should be the rule and not the exception...]
bitmodeler commentedon Nov 17, 2019
PS Thanks for the constructive suggestions, Arseny...
eirnym commentedon Nov 17, 2019
@samuelcolvin thank you for a notification
@bitmodeler Thank you for a discussion
bitmodeler commentedon Nov 18, 2019
By the way, Arseny: you were right! The query parsing needed to be decoupled from the statement generation, for reasons of thread efficiency (otherwise, the threads using prepared statements might get bottlenecked on one connection; accomplished that by using two classes...)
[Just wanted to credit Arseny for the good advice in this thread, Sam...]
cordalace commentedon Mar 18, 2020
pyformat could be simply converted to psql-format using
defaultdict:Example:
sany2k8 commentedon Dec 1, 2020
Is there any sql alchemy core implementation for asyncpg? I don't want to use raw queries
Working code:
But I want sqlalchemy version without raw query and table name.
elprans commentedon Dec 1, 2020
SQLAlchemy 1.4 supports asyncpg natively: https://docs.sqlalchemy.org/en/14/changelog/migration_14.html#asynchronous-io-support-for-core-and-orm
nhumrich commentedon Dec 16, 2020
@sany2k8 there is also asyncpgsa : https://github.com/CanopyTax/asyncpgsa
gnat commentedon Jan 1, 2021
Thank you @cordalace for the polished solution for developers who want optional named parameters! 👍 Should seriously be considered for inclusion as a core utility function, considering how popular this story is!
Also to be fair many of us do not want to introduce ORM bloat. Named parameters are a highly valuable (for many), yet tiny, feature.
That said, thank you for asyncpg. I'm astounded at the quality of this project! @elprans @1st1
singlecheeze commentedon Jun 26, 2021
@cordalace built upon your code above for a "many" variant, list of dicts... seems to work, but curious how you would implement!? Thank you for your code too!
tebanep commentedon Jul 1, 2021
Considering Python dictionaries are now ordered and that the format_map method doesn't create a new dictionary on every call, like format does, one could use a Serial dict to solve this problem:
NOTE: The examples here are not valid PostgreSQL statements. These were used just to demonstrate the usage of format_map to create serial numeric placeholders based on a dictionary.
https://www.postgresql.org/docs/current/xfunc-sql.html
Hope this might be helpful for some of you! :D
gnat commentedon Jul 21, 2021
Wanted to handle auto-removal of arguments not present in the query, instead of throwing an error. Based on @tebanep's snippet.
Enjoy:
Usage
singlecheeze commentedon Jul 30, 2021
This is almost perfect, but what about an .executemany() variant? 😄
svaponi commentedon Jul 27, 2024
Based on the code provided by @cordalace and @tebanep
raymondbutcher commentedon Mar 12, 2025
Here's my approach: pgargs
It is a tiny library with only 2 classes (excluding the tests) so you could copy one or both of them into your project if you don't want to add a dependency.
The idea is that you use an
argsobject in f-strings to build your queries. You then unpack theargsobject when using asyncpg. It supportsexecutemanyandfetchmanytoo.Lower level arguments usage:
Higher level columns usage: