34
34
>>> db.all("SELECT * FROM foo ORDER BY bar")
35
35
[{'bar': 'baz'}, {'bar': 'buz'}]
36
36
37
- Use :py:meth:`~postgres.Postgres.one` to fetch exactly one result:
38
-
39
- >>> db.one("SELECT * FROM foo WHERE bar='baz'")
40
- {'bar': 'baz'}
41
-
42
37
Use :py:meth:`~postgres.Postgres.one_or_zero` to fetch one result or
43
38
:py:class:`None`:
44
39
45
- >>> db.one("SELECT * FROM foo WHERE bar='blam'")
40
+ >>> db.one_or_zero("SELECT * FROM foo WHERE bar='baz'")
41
+ {'bar': 'baz'}
42
+ >>> db.one_or_zero("SELECT * FROM foo WHERE bar='blam'")
46
43
47
44
48
45
Bind Parameters
67
64
++++++++++++++++
68
65
69
66
Eighty percent of your database usage should be covered by the simple
70
- :py:meth:`~postgres.Postgres.run`, :py:meth:`~postgres.Postgres.one `,
71
- :py:meth:`~postgres.Postgres.all ` API introduced above. For the other 20%,
72
- :py:mod:`postgres` provides context managers for working at increasingly lower
73
- levels of abstraction. The lowest level of abstraction in :py:mod:`postgres` is
74
- a :py:mod:`psycopg2` `connection pool
67
+ :py:meth:`~postgres.Postgres.run`, :py:meth:`~postgres.Postgres.all `,
68
+ :py:meth:`~postgres.Postgres.one_or_zero ` API introduced above. For the other
69
+ 20%, :py:mod:`postgres` provides context managers for working at increasingly
70
+ lower levels of abstraction. The lowest level of abstraction in
71
+ :py:mod:`postgres` is a :py:mod:`psycopg2` `connection pool
75
72
<http://initd.org/psycopg/docs/pool.html>`_ that we configure and manage for
76
73
you. Everything in :py:mod:`postgres`, both the simple API and the context
77
74
managers, uses this connection pool.
@@ -252,19 +249,20 @@ class Postgres(object):
252
249
:py:class:`NamedTupleCursor`.
253
250
254
251
The names in our simple API, :py:meth:`~postgres.Postgres.run`,
255
- :py:meth:`~postgres.Postgres.one`, and :py:meth:`~postgres.Postgres.all`,
256
- were chosen to be short and memorable, and to not conflict with the DB-API
257
- 2.0 :py:meth:`execute`, :py:meth:`fetchone`, and :py:meth:`fetchall`
258
- methods, which have slightly different semantics (under DB-API 2.0 you call
259
- :py:meth:`execute` on a cursor and then call one of the :py:meth:`fetch*`
260
- methods on the same cursor to retrieve rows; with our simple API there is
261
- no second :py:meth:`fetch` step). See `this ticket`_ for more of the
262
- rationale behind these names. The context managers on this class are named
263
- starting with :py:meth:`get_` to set them apart from the simple-case API.
264
- Note that when working inside a block under one of the context managers,
265
- you're using DB-API 2.0 (:py:meth:`execute` + :py:meth:`fetch*`), not our
266
- simple API (:py:meth:`~postgres.Postgres.run` /
267
- :py:meth:`~postgres.Postgres.one` / :py:meth:`~postgres.Postgres.all`).
252
+ :py:meth:`~postgres.Postgres.all`, and
253
+ :py:meth:`~postgres.Postgres.one_or_zero`, were chosen to be short and
254
+ memorable, and to not conflict with the DB-API 2.0 :py:meth:`execute`,
255
+ :py:meth:`fetchone`, and :py:meth:`fetchall` methods, which have slightly
256
+ different semantics (under DB-API 2.0 you call :py:meth:`execute` on a
257
+ cursor and then call one of the :py:meth:`fetch*` methods on the same
258
+ cursor to retrieve rows; with our simple API there is no second
259
+ :py:meth:`fetch` step). See `this ticket`_ for more of the rationale behind
260
+ these names. The context managers on this class are named starting with
261
+ :py:meth:`get_` to set them apart from the simple-case API. Note that when
262
+ working inside a block under one of the context managers, you're using
263
+ DB-API 2.0 (:py:meth:`execute` + :py:meth:`fetch*`), not our simple API
264
+ (:py:meth:`~postgres.Postgres.run` / :py:meth:`~postgres.Postgres.one` /
265
+ :py:meth:`~postgres.Postgres.all`).
268
266
269
267
.. _this ticket: https://github.com/gittip/postgres.py/issues/16
270
268
@@ -332,6 +330,28 @@ def rows(self, *a, **kw):
332
330
return self .all (* a , ** kw )
333
331
334
332
333
+ def one_or_zero (self , sql , parameters = None ):
334
+ """Execute a query and return a single result or :py:class:`None`.
335
+
336
+ :param unicode sql: the SQL statement to execute
337
+ :param parameters: the bind parameters for the SQL statement
338
+ :type parameters: dict or tuple
339
+ :returns: a single row or :py:const:`None`
340
+ :raises: :py:exc:`~postgres.TooFew` or :py:exc:`~postgres.TooMany`
341
+
342
+ Use this for the common case where there should only be one record, but
343
+ it may not exist yet.
344
+
345
+ >>> row = db.one_or_zero("SELECT * FROM foo WHERE bar='blam'")
346
+ >>> if row is None:
347
+ ... print("No blam yet.")
348
+ ...
349
+ No blam yet.
350
+
351
+ """
352
+ return self ._some (sql , parameters , 0 , 1 )
353
+
354
+
335
355
def one (self , sql , parameters = None , strict = None ):
336
356
"""Execute a query and return a single result.
337
357
@@ -377,28 +397,6 @@ def one(self, sql, parameters=None, strict=None):
377
397
return out
378
398
379
399
380
- def one_or_zero (self , sql , parameters = None ):
381
- """Execute a query and return a single result or :py:class:`None`.
382
-
383
- :param unicode sql: the SQL statement to execute
384
- :param parameters: the bind parameters for the SQL statement
385
- :type parameters: dict or tuple
386
- :returns: a single row or :py:const:`None`
387
- :raises: :py:exc:`~postgres.TooFew` or :py:exc:`~postgres.TooMany`
388
-
389
- Use this for the common case where there should only be one record, but
390
- it may not exist yet.
391
-
392
- >>> row = db.one_or_zero("SELECT * FROM foo WHERE bar='blam'")
393
- >>> if row is None:
394
- ... print("No blam yet.")
395
- ...
396
- No blam yet.
397
-
398
- """
399
- return self ._some (sql , parameters , 0 , 1 )
400
-
401
-
402
400
def _some (self , sql , parameters = None , lo = 0 , hi = 1 ):
403
401
404
402
# This is undocumented (and largely untested) because I think it's a
@@ -420,11 +418,10 @@ def get_cursor(self, *a, **kw):
420
418
"""Return a :py:class:`~postgres.CursorContextManager` that uses our
421
419
connection pool.
422
420
423
- This is what :py:meth:`~postgres.Postgres.run`,
424
- :py:meth:`~postgres.Postgres.one`, and
425
- :py:meth:`~postgres.Postgres.all` use under the hood. You might
426
- use it if you want to access `cursor attributes
427
- <http://initd.org/psycopg/docs/cursor.html>`_, for example.
421
+ This gets you a cursor with :py:attr:`autocommit` turned on on its
422
+ connection. The context manager closes the cursor when the block ends.
423
+
424
+ Use this when you want a simple cursor.
428
425
429
426
>>> with db.get_cursor() as cursor:
430
427
... cursor.execute("SELECT * FROM foo")
@@ -439,11 +436,15 @@ def get_transaction(self, *a, **kw):
439
436
"""Return a :py:class:`~postgres.TransactionContextManager` that uses
440
437
our connection pool.
441
438
439
+ This gets you a cursor with :py:attr:`autocommit` turned off on its
440
+ connection. If your code block inside the :py:obj:`with` statement
441
+ raises an exception, the transaction will be rolled back. Otherwise,
442
+ it'll be committed. The context manager closes the cursor when the
443
+ block ends.
444
+
442
445
Use this when you want a series of statements to be part of one
443
446
transaction, but you don't need fine-grained control over the
444
- transaction. If your code block inside the :py:obj:`with` statement
445
- raises an exception, the transaction will be rolled back. Otherwise,
446
- it'll be committed.
447
+ transaction.
447
448
448
449
>>> with db.get_transaction() as txn:
449
450
... txn.execute("SELECT * FROM foo")
@@ -509,7 +510,7 @@ class CursorContextManager(object):
509
510
arguments to our constructor are passed through to the cursor constructor.
510
511
The :py:class:`~postgres.Connection` underlying the cursor is checked
511
512
out of the connection pool when the block starts, and checked back in when
512
- the block ends.
513
+ the block ends. Also when the block ends, the cursor is closed.
513
514
514
515
"""
515
516
@@ -544,8 +545,9 @@ class TransactionContextManager(object):
544
545
cursor is checked out of the connection pool and :py:attr:`autocommit` is
545
546
set to :py:const:`False`. If the block raises an exception, the
546
547
:py:class:`~postgres.Connection` is rolled back. Otherwise it's committed.
547
- In either case, :py:attr:`autocommit` is restored to :py:const:`True` and
548
- the :py:class:`~postgres.Connection` is put back in the pool.
548
+ In either case, the cursor is closed, :py:attr:`autocommit` is restored to
549
+ :py:const:`True`, and the :py:class:`~postgres.Connection` is put back in
550
+ the pool.
549
551
550
552
"""
551
553
0 commit comments