1 from __future__
import absolute_import
2 from __future__
import division
3 from __future__
import print_function
4 from __future__
import unicode_literals
6 from future_builtins
import ascii
, filter, hex, map, oct, zip
11 from contextlib
import contextmanager
14 import psycopg2
.extras
17 psycopg2
.extensions
.register_type(psycopg2
.extensions
.UNICODE
)
19 class connect(object):
20 def __init__(self
, dsn
):
24 self
.driver
= psycopg2
.connect(**dsn
)
26 except psycopg2
.OperationalError
, e
:
32 self
.driver
.set_client_encoding('UNICODE')
33 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_AUTOCOMMIT
)
43 def __exit__(self
, type, value
, traceback
):
48 cursor
= self
.driver
.cursor(cursor_factory
=psycopg2
.extras
.DictCursor
)
55 def execute(self
, statement
, depth
=0, context
=None):
56 with self
.cursor() as cursor
:
57 # two frames, accounting for execute() and @contextmanager
58 locals = inspect
.currentframe(depth
+ 2).f_locals
62 cursor
.execute(statement
.format(**locals), context
)
68 def transact(self
, synchronous_commit
=True):
69 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_READ_COMMITTED
)
71 with self
.cursor() as cursor
:
72 if not synchronous_commit
:
73 cursor
.execute('set local synchronous_commit = off')
78 self
.driver
.rollback()
81 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_AUTOCOMMIT
)
83 def one_(self
, statement
):
84 with self
.execute(statement
, 2) as cursor
:
85 one
= cursor
.fetchone()
89 assert cursor
.fetchone() == None
92 def __call__(self
, procedure
, *parameters
):
93 with self
.execute(statement
, 1) as cursor
:
94 return cursor
.callproc(procedure
, *parameters
)
96 def run(self
, statement
, locals=None):
97 with self
.execute(statement
, 1, locals) as cursor
:
98 return cursor
.rowcount
101 def set(self
, statement
):
102 with self
.execute(statement
, 1) as cursor
:
105 def all(self
, statement
):
106 with self
.execute(statement
, 1) as cursor
:
107 return cursor
.fetchall()
109 def one(self
, statement
):
110 return self
.one_(statement
)
112 def has(self
, statement
):
113 exists
, = self
.one_('select exists(%s)' % (statement
,))
118 def replaced(*args
, **kw
):
119 with connect(dsn
) as sql
:
120 return method(*args
, sql
=sql
, **kw
)
125 def transact(dsn
, *args
, **kw
):
126 with connect(dsn
) as connection
:
127 with connection
.transact(*args
, **kw
):
131 def slap_(sql, table, keys, values, path):
134 csr.execute('savepoint iou')
136 both = dict(keys, **values)
140 insert into %s (%s) values (%s)
144 ', '.join(['%s' for key in fields])
146 except psycopg2.IntegrityError, e:
147 csr.execute('rollback to savepoint iou')
150 update %s set %s where %s
155 for key in values.keys()]),
158 for key in keys.keys()])
159 ), values.values() + keys.values())
161 return path_(csr, path)