Skip to main content

Organize app queries in an annotated SQL file.

Project description

https://travis-ci.org/solidsnack/query-selector.svg?branch=master

Query selector allows one treat a file full of SQL queries as a record, with one attribute for each annotated query. This makes working with long, ad-hoc SQL queries more hygienic, and has the benefit of making it easy to find the queries.

The QuerySelector constructor accepts a string, file handle or (<package>, <resource) pair and parses the SQL into groups annotated with --@ <name> <mode>. The <name> is any Python compatible name; it will become an attribute of the object. The <mode> is merely metadata, and can be omitted; it describes whether a query should have one, none or many results.

For example, a file like this:

--@ t one
SELECT now();

becomes an object with a single attribute t:

>>> q.t
Query(args=[], mode=u'one', readonly=False, text=u'SELECT * FROM now();')

Modes

Modes can be one of none, one, one? and many. When not specified, default is many. A mode string can also be followed with the single word ro as a clue that the query is read-only.

Realistically, SELECT now() is a read-only query. We can annotate it as such, the resulting query datastructure records this:

>>> QuerySelector("""
...   --@ t one ro
...   SELECT now();
... """).t
Query(args=[], mode=u'one', readonly=True, text=u'SELECT * FROM now();')

Parameters

query-selector recognizes the %(...)s style parameter references defined in Python DBI 2.0. Say that we’d like to pass a timezone when selecting the server time. We can do so by adding AT TIME ZONE %(tz)s to our query. The presence of this parameter is stored in the args field of the parsed result. (The parameters in .args are listed in the order of their first appearance in the query.)

>>> QuerySelector("""
...     --@ t one ro
...     SELECT now() AT TIME ZONE %(tz)s AS t;
... """).t
Query(args=[u'tz'], mode=u'one', readonly=True,
      text=u'SELECT now() AT TIME ZONE %(tz)s AS t;')

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

query-selector-0.99.1.tar.gz (4.3 kB view details)

Uploaded Source

File details

Details for the file query-selector-0.99.1.tar.gz.

File metadata

File hashes

Hashes for query-selector-0.99.1.tar.gz
Algorithm Hash digest
SHA256 cca45f2b8e2359804ba6de1ebc4055e431e0487b4d8165306c877d2728dd5a36
MD5 04131e61c77cd291578063f79a358d18
BLAKE2b-256 4a2795e76908d4574233e381a039faeeae76e912ffa11cf61caba346fbd9c57d

See more details on using hashes here.

Supported by

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