]>
git.saurik.com Git - cyql.git/blob - __init__.py
6eafaee13b6d2f4e60736a1540231bca0577d748
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 connection(object):
16 def __init__(self
, driver
):
22 cursor
= self
.driver
.cursor(cursor_factory
=psycopg2
.extras
.DictCursor
)
28 def execute(self
, statement
, depth
=0):
29 with self
.cursor() as cursor
:
30 locals = inspect
.currentframe(depth
+ 1).f_locals
31 cursor
.execute(statement
.format(**locals), locals)
35 def transact(self
, synchronous_commit
=True):
36 with self
.cursor() as cursor
:
37 if not synchronous_commit
:
38 cursor
.execute('set local synchronous_commit = off')
41 yield transaction(self
)
44 self
.driver
.rollback()
47 class transaction(object):
48 def __init__(self
, connection
):
49 self
.connection
= connection
51 def pull(self
, statement
):
52 with self
.connection
.execute(statement
, 1) as cursor
:
53 return cursor
.fetchall()
55 def yank(self
, statement
):
56 with self
.connection
.execute(statement
, 1) as cursor
:
57 rows
= cursor
.fetchall()
58 return rows
[0] if len(rows
) != 0 else None
60 def push(self
, statement
):
61 with self
.connection
.execute(statement
, 1) as cursor
:
69 driver
= psycopg2
.connect(**dsn
)
71 except psycopg2
.OperationalError
, e
:
77 driver
.set_client_encoding('UNICODE')
78 yield connection(driver
)
83 def slap_(sql, table, keys, values, path):
86 csr.execute('savepoint iou')
88 both = dict(keys, **values)
92 insert into %s (%s) values (%s)
96 ', '.join(['%s' for key in fields])
98 except psycopg2.IntegrityError, e:
99 csr.execute('rollback to savepoint iou')
102 update %s set %s where %s
107 for key in values.keys()]),
110 for key in keys.keys()])
111 ), values.values() + keys.values())
113 return path_(csr, path)