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
)
16 if values
== None or len(values
) == 0:
19 assert len(values
) == 1
22 class connect(object):
23 def __init__(self
, dsn
):
27 self
.driver
= psycopg2
.connect(**dsn
)
29 except psycopg2
.OperationalError
, e
:
35 self
.driver
.set_client_encoding('UNICODE')
36 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_AUTOCOMMIT
)
46 def __exit__(self
, type, value
, traceback
):
51 cursor
= self
.driver
.cursor(cursor_factory
=psycopg2
.extras
.DictCursor
)
58 def execute(self
, statement
, depth
=0, context
=None):
59 with self
.cursor() as cursor
:
60 # two frames, accounting for execute() and @contextmanager
61 locals = inspect
.currentframe(depth
+ 2).f_locals
65 cursor
.execute(statement
.format(**locals), context
)
71 def transact(self
, synchronous_commit
=True):
72 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_READ_COMMITTED
)
74 with self
.cursor() as cursor
:
75 if not synchronous_commit
:
76 cursor
.execute('set local synchronous_commit = off')
81 self
.driver
.rollback()
84 self
.driver
.set_isolation_level(psycopg2
.extensions
.ISOLATION_LEVEL_AUTOCOMMIT
)
86 def one_(self
, statement
):
87 with self
.execute(statement
, 2) as cursor
:
88 one
= cursor
.fetchone()
92 assert cursor
.fetchone() == None
95 def __call__(self
, procedure
, *parameters
):
96 with self
.execute(statement
, 1) as cursor
:
97 return cursor
.callproc(procedure
, *parameters
)
99 def run(self
, statement
, locals=None):
100 with self
.execute(statement
, 1, locals) as cursor
:
101 return cursor
.rowcount
104 def set(self
, statement
):
105 with self
.execute(statement
, 1) as cursor
:
108 def all(self
, statement
):
109 with self
.execute(statement
, 1) as cursor
:
110 return cursor
.fetchall()
112 def one(self
, statement
):
113 return self
.one_(statement
)
115 def has(self
, statement
):
116 return one(self
.one_('select exists(%s)' % (statement
,)))
120 def replaced(*args
, **kw
):
121 with connect(dsn
) as sql
:
122 return method(*args
, sql
=sql
, **kw
)
127 def transact(dsn
, *args
, **kw
):
128 with connect(dsn
) as connection
:
129 with connection
.transact(*args
, **kw
):
133 def slap_(sql, table, keys, values, path):
136 csr.execute('savepoint iou')
138 both = dict(keys, **values)
142 insert into %s (%s) values (%s)
146 ', '.join(['%s' for key in fields])
148 except psycopg2.IntegrityError, e:
149 csr.execute('rollback to savepoint iou')
152 update %s set %s where %s
157 for key in values.keys()]),
160 for key in keys.keys()])
161 ), values.values() + keys.values())
163 return path_(csr, path)