Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active September 23, 2020 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/f49f2adc90a915b363e1a42e6c498a60 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/f49f2adc90a915b363e1a42e6c498a60 to your computer and use it in GitHub Desktop.
Dynamic Binding for PostgreSQL with AsyncPG #python #postgresql #asyncpg
from collections import OrderdDict
from typings import Hashable, List
class SQLParams:
def __init__(self):
self.__values = OrderedDict()
self.__count = 1
def bind(self, value: Hashable):
index = self.__values.get(value)
if index is None:
index = self.__count
self.__values[value] = index
self.__count += 1
return f"${index}"
def bindings(self) -> List[Hashable]:
return list(self.__values.keys())
@CMCDragonkai
Copy link
Author

Use it like conn.fetchrow(query, *params.bindings()).

Useful when constructing queries with dynamic number of parameters.

Avoid sql interpolation or concatenation with user provided parameters. Always try to do binding!!!

But this won't work for table names... etc. In those cases you have to do a direct conversion to a string enum!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment