1 from __future__
import unicode_literals
2 from __future__
import print_function
7 from contextlib
import contextmanager
10 import psycopg2
.extras
13 psycopg2
.extensions
.register_type(psycopg2
.extensions
.UNICODE
)
15 class connect(object):
16 def __init__(self
, dsn
):
20 self
.driver
= psycopg2
.connect(**dsn
)
22 except psycopg2
.OperationalError
, e
:
28 self
.driver
.set_client_encoding('UNICODE')
29 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_AUTOCOMMIT
)
39 def __exit__(self
, type, value
, traceback
):
44 cursor
= self
.driver
.cursor(cursor_factory
=psycopg2
.extras
.DictCursor
)
51 def execute(self
, statement
, depth
=0, context
=None):
52 with self
.cursor() as cursor
:
53 # two frames, accounting for execute() and @contextmanager
54 locals = inspect
.currentframe(depth
+ 2).f_locals
58 cursor
.execute(statement
.format(**locals), context
)
64 def transact(self
, synchronous_commit
=True):
65 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_READ_COMMITTED
)
67 with self
.cursor() as cursor
:
68 if not synchronous_commit
:
69 cursor
.execute('set local synchronous_commit = off')
74 self
.driver
.rollback()
77 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_AUTOCOMMIT
)
79 def one_(self
, statement
):
80 with self
.execute(statement
, 2) as cursor
:
81 one
= cursor
.fetchone()
85 assert cursor
.fetchone() == None
88 def __call__(self
, procedure
, *parameters
):
89 with self
.execute(statement
, 1) as cursor
:
90 return cursor
.callproc(procedure
, *parameters
)
92 def run(self
, statement
, locals=None):
93 with self
.execute(statement
, 1, locals) as cursor
:
94 return cursor
.rowcount
97 def set(self
, statement
):
98 with self
.execute(statement
, 1) as cursor
:
101 def all(self
, statement
):
102 with self
.execute(statement
, 1) as cursor
:
103 return cursor
.fetchall()
105 def one(self
, statement
):
106 return self
.one_(statement
)
108 def has(self
, statement
):
109 exists
, = self
.one_('select exists(%s)' % (statement
,))
114 def replaced(*args
, **kw
):
115 with connect(dsn
) as sql
:
116 return method(*args
, sql
=sql
, **kw
)
121 def transact(dsn
, *args
, **kw
):
122 with connect(dsn
) as connection
:
123 with connection
.transact(*args
, **kw
):
127 def slap_(sql, table, keys, values, path):
130 csr.execute('savepoint iou')
132 both = dict(keys, **values)
136 insert into %s (%s) values (%s)
140 ', '.join(['%s' for key in fields])
142 except psycopg2.IntegrityError, e:
143 csr.execute('rollback to savepoint iou')
146 update %s set %s where %s
151 for key in values.keys()]),
154 for key in keys.keys()])
155 ), values.values() + keys.values())
157 return path_(csr, path)