|
166 | 166 | except ImportError: # Python 3
|
167 | 167 | import urllib.parse as urlparse
|
168 | 168 | from collections import namedtuple
|
| 169 | +from inspect import isclass |
169 | 170 |
|
170 | 171 | import psycopg2
|
171 | 172 | from postgres.orm import Model
|
@@ -409,7 +410,15 @@ def one(self, sql, parameters=None, back_as=None, default=None, *a, **kw):
|
409 | 410 | >>> db.one("SELECT * FROM foo WHERE bar='blam'", default=False)
|
410 | 411 | False
|
411 | 412 |
|
412 |
| - We specifically don't support passing lambdas or other callables for |
| 413 | + If you pass an :py:class:`Exception` instance or subclass, we will |
| 414 | + raise that for you: |
| 415 | +
|
| 416 | + >>> db.one("SELECT * FROM foo WHERE bar='blam'", default=Exception) |
| 417 | + Traceback (most recent call last): |
| 418 | + ... |
| 419 | + Exception |
| 420 | +
|
| 421 | + We specifically stop short of supporting lambdas or other callables for |
413 | 422 | the :py:attr:`default` parameter. That gets complicated quickly, and
|
414 | 423 | it's easy to just check the return value in the caller and do your
|
415 | 424 | extra logic there.
|
@@ -471,6 +480,8 @@ def one(self, sql, parameters=None, back_as=None, default=None, *a, **kw):
|
471 | 480 |
|
472 | 481 | # default
|
473 | 482 | if out is None:
|
| 483 | + if isexception(default): |
| 484 | + raise default |
474 | 485 | out = default
|
475 | 486 |
|
476 | 487 | return out
|
@@ -900,6 +911,17 @@ def make(self, values):
|
900 | 911 | return DelegatingCaster
|
901 | 912 |
|
902 | 913 |
|
| 914 | +def isexception(obj): |
| 915 | + """Given an object, return a boolean indicating whether it is an instance |
| 916 | + or subclass of Exception. |
| 917 | + """ |
| 918 | + if isinstance(obj, Exception): |
| 919 | + return True |
| 920 | + if isclass(obj) and issubclass(obj, Exception): |
| 921 | + return True |
| 922 | + return False |
| 923 | + |
| 924 | + |
903 | 925 | if __name__ == '__main__':
|
904 | 926 | db = Postgres("postgres://jrandom@localhost/test")
|
905 | 927 | db.run("DROP SCHEMA IF EXISTS public CASCADE")
|
|
0 commit comments