]>
git.saurik.com Git - cyql.git/blob - __init__.py
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 # two frames, accounting for execute() and @contextmanager
31 locals = inspect
.currentframe(depth
+ 2).f_locals
33 cursor
.execute(statement
.format(**locals), locals)
39 def transact(self
, synchronous_commit
=True):
40 with self
.cursor() as cursor
:
41 if not synchronous_commit
:
42 cursor
.execute('set local synchronous_commit = off')
45 yield transaction(self
)
48 self
.driver
.rollback()
51 class transaction(object):
52 def __init__(self
, connection
):
53 self
.connection
= connection
55 def pull(self
, statement
):
56 with self
.connection
.execute(statement
, 1) as cursor
:
57 return cursor
.fetchall()
59 def yank(self
, statement
, offset
=0):
60 with self
.connection
.execute(statement
, 1 + offset
) as cursor
:
61 rows
= cursor
.fetchall()
62 return rows
[0] if len(rows
) != 0 else None
64 def push(self
, statement
):
65 with self
.connection
.execute(statement
, 1) as cursor
:
68 def exists(self
, statement
):
73 '''.format(**locals()), 1)[0]
80 driver
= psycopg2
.connect(**dsn
)
82 except psycopg2
.OperationalError
, e
:
88 driver
.set_client_encoding('UNICODE')
89 yield connection(driver
)
95 def replaced(*args
, **kw
):
96 with connect(dsn
) as connection
:
97 return method(connection
, *args
, **kw
)
102 def transact(dsn
, **args
):
103 with connect(dsn
) as connection
:
104 with connection
.transact(**args
) as cursor
:
108 def slap_(sql, table, keys, values, path):
111 csr.execute('savepoint iou')
113 both = dict(keys, **values)
117 insert into %s (%s) values (%s)
121 ', '.join(['%s' for key in fields])
123 except psycopg2.IntegrityError, e:
124 csr.execute('rollback to savepoint iou')
127 update %s set %s where %s
132 for key in values.keys()]),
135 for key in keys.keys()])
136 ), values.values() + keys.values())
138 return path_(csr, path)