Skip to content

Support pyformat and keyword args #9

Closed

Description

@nhumrich

It looks like for prepared statements, statements have to be in the form
'select $1 from $2 where baz=$3 with the arguments ('foo', 'bar', 'baz')

It is common in python database api's to support the pyformat int PEP 249. http://legacy.python.org/dev/peps/pep-0249/#paramstyle

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'})

Activity

  1. ludovic-gasc commented on Jul 26, 2016

    @ludovic-gasc

    +1 for pyformat: we use massively this format for our queries, it's the most explicit, at least to me.

  2. 1st1 commented on Jul 26, 2016

    @1st1
    Member

    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.

  3. gigatexal commented on Aug 4, 2016

    @gigatexal

    Will tokenizing hurt performance? I, too, prefer the dictionary vs ordered list approach.

  4. sethmlarson commented on Aug 5, 2016

    @sethmlarson

    I can say that if this feature were added I would use it over ordered list.

  5. gglanzani commented on Aug 30, 2016

    @gglanzani

    @1st1 Interested here as well. It makes everything so much easier

  6. treycucco commented on Sep 13, 2016

    @treycucco

    @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.

  7. bobcolner commented on Oct 15, 2016

    @bobcolner

    named keywords have proven more reliable for me as well. On brand with the python-zen 'explicit > implicit' credo as well.

  8. imbolc commented on Oct 28, 2016

    @imbolc

    Why don't you just use little wrappers like this?

    def insert(conn, table, fields=None, **kwargs):                                                                               
        fields = fields or {}                                                                                                     
        fields.update(kwargs)                                                                                                     
        items = list(fields.items())                                                                                              
        keys, values = [x[0] for x in items], [x[1] for x in items]                                                               
        placeholders = ['${}'.format(i) for i, _ in enumerate(values, 1)]                                                         
        query = 'INSERT INTO {} ({}) VALUES ({}) RETURNING id'.format(                                                            
            table, ', '.join(keys), ', '.join(placeholders))                                                                      
        return conn.fetchval(query, *values)
    
    id = await insert(conn, 'users', {'email': '[email protected]', 'name': 'foo'})                                               
    id = await insert(conn, 'users', email='[email protected]', name='bar') 
    
  9. Daenyth commented on Sep 12, 2017

    @Daenyth

    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.

  10. thehesiod commented on Sep 12, 2017

    @thehesiod

    If tokenizing I'd suggest re-using any available code in libpq/psycopg2

  11. elprans commented on Sep 12, 2017

    @elprans
    Member

    If tokenizing I'd suggest re-using any available code in libpq/psycopg2

    psycopg2 is LGPL, we can't reuse any code from there.

  12. thehesiod commented on Sep 12, 2017

    @thehesiod

    meant as a library :)

  13. added a commit that references this issue on Sep 15, 2017
  14. 25 remaining items

  15. bitmodeler commented on Nov 17, 2019

    @bitmodeler

    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...]

  16. bitmodeler commented on Nov 17, 2019

    @bitmodeler

    PS Thanks for the constructive suggestions, Arseny...

  17. eirnym commented on Nov 17, 2019

    @eirnym

    @samuelcolvin thank you for a notification

    @bitmodeler Thank you for a discussion

  18. bitmodeler commented on Nov 18, 2019

    @bitmodeler

    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...]

  19. cordalace commented on Mar 18, 2020

    @cordalace

    pyformat could be simply converted to psql-format using defaultdict:

    import collections
    import itertools
    from typing import Any, Dict, Tuple, List
    
    
    def pyformat2psql(query: str, named_args: Dict[str, Any]) -> Tuple[str, List[Any]]:
        positional_generator = itertools.count(1)
        positional_map = collections.defaultdict(lambda: '${}'.format(next(positional_generator)))
        formatted_query = query % positional_map
        positional_items = sorted(
            positional_map.items(),
            key=lambda item: int(item[1].replace('$', '')),
        )
        positional_args = [named_args[named_arg] for named_arg, _ in positional_items]
        return formatted_query, positional_args

    Example:

    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 = $2
    print(positional_args)  # prints ['John Cena', '[email protected]']
  20. sany2k8 commented on Dec 1, 2020

    @sany2k8

    Is there any sql alchemy core implementation for asyncpg? I don't want to use raw queries

    statement = (
                    insert(table_obj).
                        values(named_args)
                )
    

    Working code:

    async def insert_named_parameter(self, table, fields=None, **kwargs):
         fields = fields or {}
         fields.update(kwargs)
         items = list(fields.items())
         keys, values = [x[0] for x in items], [x[1] for x in items]
         placeholders = ['${}'.format(i) for i, _ in enumerate(values, 1)]
         query = 'INSERT INTO {} ({}) VALUES ({})'.format(table, ', '.join(keys), ', '.join(placeholders))
         return await self.connection.execute(query, *values)
    
     async def insert_keyword(self, keyword_data):
    
         if keyword_data:
             keyword_data['update_timestamp'] = datetime.datetime.now()
             row = await self.insert_named_parameter('keywords', keyword_data)
             return row
         else:
             return None
    

    But I want sqlalchemy version without raw query and table name.

  21. elprans commented on Dec 1, 2020

    @elprans
    Member
  22. nhumrich commented on Dec 16, 2020

    @nhumrich
    Author
  23. gnat commented on Jan 1, 2021

    @gnat

    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

  24. singlecheeze commented on Jun 26, 2021

    @singlecheeze

    @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!

    def pyformat2psql_many(query: str, named_args: List[Dict[str, Any]]) -> Tuple[str, List[Any]]:
        arg_items = []
        positional_generator = itertools.count(1)
        positional_map = collections.defaultdict(lambda: '${}'.format(next(positional_generator)))
        formatted_query = query % positional_map
    
        for arg_item in named_args:
            positional_items = sorted(
                positional_map.items(),
                key=lambda item: int(item[1].replace('$', '')),
            )
            positional_args = [arg_item[named_arg] for named_arg, _ in positional_items]
            arg_items.append(positional_args)
    
        return formatted_query, arg_items
  25. tebanep commented on Jul 1, 2021

    @tebanep

    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
    #############
    
    class Serial(dict):
        def __getitem__(self, key):
            return f"${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)
    assert query == "select $1 from $2 where baz=$3"  # Ordered Parameters
    
    
    parameters = Serial(baz='BAZ', foo='FOO', bar='BAR')
    query = "select {foo} from {bar} where baz={baz}".format_map(parameters)
    assert query == "select $2 from $3 where baz=$1"  # Unordered Parameters
    
    
    parameters = Serial({'foo': 'FOO', 'baz': 'BAZ'})
    query = "select {foo} from {foo} where baz={baz}".format_map(parameters)
    assert query == "select $1 from $1 where baz=$2"  # Repeated Parameters
    
    
    # Mocking Fetch
    ###############
    
    def mock_fetch(query, *args):
        assert query == "select $1 from $1 where baz=$2"
        assert args == ('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.
    

    https://www.postgresql.org/docs/current/xfunc-sql.html

    Hope this might be helpful for some of you! :D

  26. gnat commented on Jul 21, 2021

    @gnat

    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.
    class Serial(dict):
        def __getitem__(self, key):
            return f"${list(self.keys()).index(key) + 1}"
    
    # Pyformat to psql format.
    def pyformat2psql(query: str, args_dict: Dict[str, Any]) -> Tuple[str, List[Any]]:
        # Remove args not present in query.
        args_list = list(args_dict.keys())
        for value in args_list:
            if f"{{{value}}}" not in query:
                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())
        return query_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 = await conn.fetch(query, *params)
  27. singlecheeze commented on Jul 30, 2021

    @singlecheeze

    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
    #############
    
    class Serial(dict):
        def __getitem__(self, key):
            return f"${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)
    assert query == "select $1 from $2 where baz=$3"  # Ordered Parameters
    
    
    parameters = Serial(baz='BAZ', foo='FOO', bar='BAR')
    query = "select {foo} from {bar} where baz={baz}".format_map(parameters)
    assert query == "select $2 from $3 where baz=$1"  # Unordered Parameters
    
    
    parameters = Serial({'foo': 'FOO', 'baz': 'BAZ'})
    query = "select {foo} from {foo} where baz={baz}".format_map(parameters)
    assert query == "select $1 from $1 where baz=$2"  # Repeated Parameters
    
    
    # Mocking Fetch
    ###############
    
    def mock_fetch(query, *args):
        assert query == "select $1 from $1 where baz=$2"
        assert args == ('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.
    

    https://www.postgresql.org/docs/current/xfunc-sql.html

    Hope this might be helpful for some of you! :D

    This is almost perfect, but what about an .executemany() variant? 😄

  28. svaponi commented on Jul 27, 2024

    @svaponi

    Based on the code provided by @cordalace and @tebanep

    import collections
    import itertools
    import typing
    
    
    def pyformat2psql(
        query: str,
        named_args: dict[str, typing.Any] = None,
        /,
        **kwargs,
    ) -> (str, list[typing.Any]):
        named_args = named_args or {}
        named_args.update(kwargs)
        positional_generator = itertools.count(1)
        positional_map = collections.defaultdict(
            lambda: "${}".format(next(positional_generator))
        )
        formatted_query = query % positional_map
        positional_items = sorted(
            positional_map.items(),
            key=lambda item: int(item[1].replace("$", "")),
        )
        positional_args = [named_args[named_arg] for named_arg, _ in positional_items]
        return formatted_query, positional_args
    
    
    class _Serial(dict):
        def __getitem__(self, key):
            return f"${list(self.keys()).index(key) + 1}"
    
    
    def format2psql(
        query: str,
        named_args: dict[str, typing.Any] = None,
        /,
        **kwargs,
    ) -> (str, list[typing.Any]):
        named_args = named_args or {}
        named_args.update(kwargs)
        parameters = _Serial(named_args)
        return query.format_map(parameters), list(parameters.values())
    
    
    def test_pyformat2psql():
        query, positional_args = pyformat2psql(
            "SELECT * FROM user WHERE foo = %(foo)s AND name = %(name)s AND email = %(email)s",
            {"name": "John Cena", "email": "[email protected]"},
            foo="FOO",
        )
        assert query == "SELECT * FROM user WHERE foo = $1 AND name = $2 AND email = $3"
        assert positional_args == ["FOO", "John Cena", "[email protected]"]
    
    
    def test_format2psql():
        query, positional_args = format2psql(
            "SELECT * FROM user WHERE foo = {foo} AND name = {name} AND email = {email}",
            {"name": "John Cena", "email": "[email protected]"},
            foo="FOO",
        )
        assert query == "SELECT * FROM user WHERE foo = $3 AND name = $1 AND email = $2"
        assert positional_args == ["John Cena", "[email protected]", "FOO"]
    
        query, positional_args = format2psql(
            "select {foo} from {bar} where baz={baz}", foo="FOO", bar="BAR", baz="BAZ"
        )
        assert query == "select $1 from $2 where baz=$3"
        assert positional_args == ["FOO", "BAR", "BAZ"]
    
        query, positional_args = format2psql(
            "select {foo} from {bar} where baz={baz}", baz="BAZ", foo="FOO", bar="BAR"
        )
        assert query == "select $2 from $3 where baz=$1"
        assert positional_args == ["BAZ", "FOO", "BAR"]
    
  29. raymondbutcher commented on Mar 12, 2025

    @raymondbutcher

    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 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:

    from pgargs import Args
    
    args = Args(name="bilbo", age=111)
    query = f"SELECT * FROM table WHERE name = {args.name} AND age = {args.age}"
    await conn.fetch(query, *args)

    Higher level columns usage:

    from pgargs import Args, Cols
    
    cols = Cols(name="bilbo", age=111)
    query = f"INSERT INTO table {cols.names} VALUES {cols.values}"
    await conn.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}"
    await conn.execute(query, *args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions