Skip to main content

buildpg

CI Coverage pypi versions license

Query building for the postgresql prepared statements and asyncpg.

Lots of more powerful features, including full clause construction, multiple values, logic functions, query pretty-printing and different variable substitution - below is just a very quick summary. Please check the code and tests for examples.

Building Queries

Simple variable substitution:

from buildpg import render

render('select * from mytable where x=:foo and y=:bar', foo=123, bar='whatever')
>> 'select * from mytable where x=$1 and y=$2', [123, 'whatever']

Use of V to substitute constants:

from buildpg import V, render

render('select * from mytable where :col=:foo', col=V('x'), foo=456)
>> 'select * from mytable where x=$1', [456]

Complex logic:

from buildpg import V, funcs, render

where_logic = V('foo.bar') == 123
if spam_value:
   where_logic &= V('foo.spam') <= spam_value

if exclude_cake:
   where_logic &= funcs.not_(V('foo.cake').in_([1, 2, 3]))

render('select * from foo :where', where=where_logic)
>> 'select * from foo foo.bar = $1 AND foo.spam <= $2 AND not(foo.cake in $3)', [123, 123, ['x', 'y']]

Values usage:

from buildpg import Values, render

render('insert into the_table (:values__names) values :values', values=Values(a=123, b=456, c='hello'))
>> 'insert into the_table (a, b, c) values ($1, $2, $3)', [123, 456, 'hello']

With asyncpg

As a wrapper around asyncpg:

import asyncio
from buildpg import asyncpg

async def main():
   async with asyncpg.create_pool_b('postgres://postgres@localhost:5432/db') as pool:
       await pool.fetchval_b('select spam from mytable where x=:foo and y=:bar', foo=123, bar='whatever')
       >> 42

asyncio.run(main())

Both the pool and connections have *_b variants of all common query methods:

  • execute_b
  • executemany_b
  • fetch_b
  • fetchval_b
  • fetchrow_b
  • cursor_b

Operators

Python operator/function SQL operator
& AND
` `
= =
!= !=
< <
<= <=
> >
>= >=
+ +
- -
* *
/ /
% %
** ^
- -
~ not(...)
sqrt `
abs @
contains @>
contained_by <@
overlap &&
like LIKE
ilike ILIKE
cat `
in_ in
from_ from
at_time_zone AT TIME ZONE
matches @@
is_ is
is_not is not
for_ for
factorial !
cast ::
asc ASC
desc DESC
comma ,
on ON
as_ AS
nulls_first NULLS FIRST
nulls_last NULLS LAST

Usage:

from buildpg import V, S, render

def show(component):
   sql, params = render(':c', c=component)
   print(f'sql="{sql}" params={params}')

show(V('foobar').contains([1, 2, 3]))
#> sql="foobar @> $1" params=[[1, 2, 3]]
show(V('foobar') == 4)
#> sql="foobar = $1" params=[4]
show(~V('foobar'))
#> sql="not(foobar)" params=[]
show(S(625).sqrt())
#> sql="|/ $1" params=[625]
show(V('foo').is_not('true'))
#> sql="foo is not true" params=[]

Functions

Python function SQL function
AND(*args) <arg1> and <arg2> ...
OR(*args) <arg1> or <arg2> ...
NOT(arg) not(<arg>)
comma_sep(*args) <arg1>, <arg2>, ...
count(expr) count(expr)
any(arg) any(<arg1>)
now() now()
cast(v, cast_type) <v>::<cast_type>
upper(string) upper(<string>)
lower(string) lower(<string>)
length(string) length(<string>)
left(string, n) left(<string>, <n>)
right(string, n) right(<string>, <n>)
extract(expr) extract(<expr>)
sqrt(n) `
abs(n) @<n>
factorial(n) !<n>
position(substring, string) position(<substring> in <st...
substring(string, pattern, escape-None) substring(<string> from <pa...
to_tsvector(arg1, document-None) to_tsvector(<arg1>)
to_tsquery(arg1, text-None) to_tsquery(<arg1>)

Usage:

from buildpg import V, render, funcs

def show(component):
  sql, params = render(':c', c=component)
  print(f'sql="{sql}" params={params}')

show(funcs.AND(V('x') == 4, V('y') > 6))
#> sql="x = $1 AND y > $2" params=[4, 6]
show(funcs.position('foo', 'this has foo in it'))
#> sql="position($1 in $2)" params=['foo', 'this has foo in it']

Metadata

Release files for buildpg 0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for buildpg 0.4
File Size Uploaded Provenance
buildpg-0.4.tar.gz 12.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for buildpg 0.4
File Interpreter ABI Platform
buildpg-0.4-py3-none-any.whl Python 3 none any Details

Total release size: 24.2 kB

Release files / buildpg-0.4.tar.gz

Download URL buildpg-0.4.tar.gz
Size 12.5 kB
Tags Source
SHA-256 checksum
How to use checksums
3a6c1f40fb6c826caa819d84727e36a1372f7013ba696637b492e5935916d479
BLAKE2b-256 checksum
How to use checksums
48f2ff0e51a3c2390538da6eb4f85e30d87aafbcc6d057c6c9bb9fa222c8f2fc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.8.12

Release files / buildpg-0.4-py3-none-any.whl

Download URL buildpg-0.4-py3-none-any.whl
Size 11.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
20d539976c81ea6f5529d3930016b0482ed0ff06def3d6da79d0fc0a3bbaeeb1
BLAKE2b-256 checksum
How to use checksums
315ac5ecd08a0c9b4dfece3b41aeefc3770968b4a2da1784941c9c8dd1c65347
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.8.12

Security for buildpg 0.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page