Last active
September 23, 2020 05:11
-
-
Save CMCDragonkai/f49f2adc90a915b363e1a42e6c498a60 to your computer and use it in GitHub Desktop.
Dynamic Binding for PostgreSQL with AsyncPG #python #postgresql #asyncpg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!