Skip to main content

Query building for the postgresql prepared statements and asyncpg.

Project description

BuildStatus Coverage pypi

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.get_event_loop().run_until_complete(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

|

OR

=

=

!=

!=

<

<

<=

<=

>

>

>=

>=

+

+

-

-

*

*

/

/

%

%

**

^

-

-

~

not(...)

sqrt

|/;

abs

@

contains

@>

contained_by

<@

overlap

&&

like

LIKE

cat

||

in_

in

from_

from

at_time_zone

AT TIME ZONE

matches

@@

for_

for

factorial

!

cast

::

asc

`` ASC``

desc

DESC

comma

, ;

on

ON

as_

AS

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]

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)

|/ <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']

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

buildpg-0.2.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

buildpg-0.2-py36.py37-none-any.whl (11.5 kB view details)

Uploaded Python 3.6Python 3.7

File details

Details for the file buildpg-0.2.tar.gz.

File metadata

  • Download URL: buildpg-0.2.tar.gz
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.3

File hashes

Hashes for buildpg-0.2.tar.gz
Algorithm Hash digest
SHA256 9e9dcf009fd0605e2b2caf1b224f9382652b8b11b366c2e39178e7ee297f83e0
MD5 8c6aabdcdef3258127b6fef3d12a0f02
BLAKE2b-256 a18682b4a25a378d6d4c5722a6bdadaa3ca0fa66804b695e1150a9233f3a8785

See more details on using hashes here.

File details

Details for the file buildpg-0.2-py36.py37-none-any.whl.

File metadata

  • Download URL: buildpg-0.2-py36.py37-none-any.whl
  • Upload date:
  • Size: 11.5 kB
  • Tags: Python 3.6, Python 3.7
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.3

File hashes

Hashes for buildpg-0.2-py36.py37-none-any.whl
Algorithm Hash digest
SHA256 d4e648da5c8dde1336d5a91d0305b214a941206f4ac0458bfadfc11aa227be80
MD5 8d0dd2d3eccf48851e408db0ad3dde5d
BLAKE2b-256 3b1b68dbaf295dd49a4c36e19849e71764df71212e9595bb94c0de43291e9e5f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page