Skip to content

Commit

Permalink
Merge pull request #4 from sojidotai/feat/dollar-query-params
Browse files Browse the repository at this point in the history
feat: Add an asyncpg compatible query params implementation
  • Loading branch information
baverman committed Mar 15, 2024
2 parents e74b795 + 78b1953 commit 2f1c0a4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
18 changes: 18 additions & 0 deletions sqlbind/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,14 @@ def compile(self, expr: str, params: t.Sequence[t.Any]) -> str:
return expr.format(*(f'%({it})s' for it in names))


class DollarQueryParams(ListQueryParams):
"""QueryParams implementation for format ($1, $2, ...) parameter style"""

def compile(self, expr: str, params: t.Sequence[t.Any]) -> str:
start = self.add(params) + 1
return expr.format(*(f"${i}" for i, _ in enumerate(params, start)))


class BaseDialect:
"""Dialect compatible with most of backends"""

Expand Down Expand Up @@ -797,6 +805,16 @@ def default_format() -> QueryParams:
"""
return FormatQueryParams(BaseDialect)

@staticmethod
def default_dollar() -> QueryParams:
"""Uses dollar params ($1, $2, ...) as placeholders.
Backend examples: asyncpg
>>> q = Dialect.default_dollar()
>>> f'field = {q/20}'
'field = $1'
"""
return DollarQueryParams(BaseDialect)

@staticmethod
def sqlite() -> QueryParams:
"""Uses sqlite dialect and renders binds with qmark (?) placeholders"""
Expand Down
7 changes: 7 additions & 0 deletions tests/test_sqlbind.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ def test_pyformat():
assert q == {'p0': 10, 'p1': 20}


def test_dollar():
q = s.Dialect.default_dollar()
assert q("field1 = {}", 10) == "field1 = $1"
assert q("field2 = {}", 20) == "field2 = $2"
assert q == [10, 20]


def test_conditions():
q = s.Dialect.default()

Expand Down

0 comments on commit 2f1c0a4

Please sign in to comment.