]>
git.saurik.com Git - cyql.git/blob - __init__.py
944869580e1161cdc91ea15d9e39a72e875b860e
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
, locals):
29 with self
.cursor() as cursor
:
30 cursor
.execute(statement
.format(**locals), locals)
34 def execute(self
, statement
, depth
=0):
35 with self
.cursor() as cursor
:
36 # two frames, accounting for execute() and @contextmanager
37 locals = inspect
.currentframe(depth
+ 2).f_locals
39 cursor
.execute(statement
.format(**locals), locals)
45 def transact(self
, synchronous_commit
=True):
46 with self
.cursor() as cursor
:
47 if not synchronous_commit
:
48 cursor
.execute('set local synchronous_commit = off')
51 yield transaction(self
)
54 self
.driver
.rollback()
57 class transaction(object):
58 def __init__(self
, connection
):
59 self
.connection
= connection
61 def pull(self
, statement
):
62 with self
.connection
.execute(statement
, 1) as cursor
:
63 return cursor
.fetchall()
65 def yank(self
, statement
, offset
=0):
66 with self
.connection
.execute(statement
, 1 + offset
) as cursor
:
67 rows
= cursor
.fetchall()
68 return rows
[0] if len(rows
) != 0 else None
70 def push(self
, statement
):
71 with self
.connection
.execute(statement
, 1) as cursor
:
74 def push_(self
, statement
, locals):
75 with self
.connection
.execute_(statement
, locals) as cursor
:
78 def exists(self
, statement
):
83 '''.format(**locals()), 1)[0]
90 driver
= psycopg2
.connect(**dsn
)
92 except psycopg2
.OperationalError
, e
:
98 driver
.set_client_encoding('UNICODE')
99 yield connection(driver
)
105 def replaced(*args
, **kw
):
106 with connect(dsn
) as connection
:
107 return method(connection
, *args
, **kw
)
112 def transact(dsn
, **args
):
113 with connect(dsn
) as connection
:
114 with connection
.transact(**args
) as cursor
:
118 def slap_(sql, table, keys, values, path):
121 csr.execute('savepoint iou')
123 both = dict(keys, **values)
127 insert into %s (%s) values (%s)
131 ', '.join(['%s' for key in fields])
133 except psycopg2.IntegrityError, e:
134 csr.execute('rollback to savepoint iou')
137 update %s set %s where %s
142 for key in values.keys()]),
145 for key in keys.keys()])
146 ), values.values() + keys.values())
148 return path_(csr, path)