]>
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
, locals):
29 with self
.cursor() as cursor
:
30 cursor
.execute(statement
.format(**locals), locals)
34 def execute(self
, statement
, depth
=0, context
=None):
35 with self
.cursor() as cursor
:
36 # two frames, accounting for execute() and @contextmanager
37 locals = inspect
.currentframe(depth
+ 2).f_locals
41 cursor
.execute(statement
.format(**locals), context
)
47 def transact(self
, synchronous_commit
=True):
48 with self
.cursor() as cursor
:
49 if not synchronous_commit
:
50 cursor
.execute('set local synchronous_commit = off')
53 yield transaction(self
)
56 self
.driver
.rollback()
59 class transaction(object):
60 def __init__(self
, connection
):
61 self
.connection
= connection
63 def pull(self
, statement
):
64 with self
.connection
.execute(statement
, 1) as cursor
:
65 return cursor
.fetchall()
67 def yank(self
, statement
, offset
=0):
68 with self
.connection
.execute(statement
, 1 + offset
) as cursor
:
69 rows
= cursor
.fetchall()
70 return rows
[0] if len(rows
) != 0 else None
72 def push(self
, statement
):
73 with self
.connection
.execute(statement
, 1) as cursor
:
76 def push_(self
, statement
, locals):
77 with self
.connection
.execute_(statement
, locals) as cursor
:
80 def exists(self
, statement
):
85 '''.format(**locals()), 1)[0]
92 driver
= psycopg2
.connect(**dsn
)
94 except psycopg2
.OperationalError
, e
:
100 driver
.set_client_encoding('UNICODE')
101 yield connection(driver
)
107 def replaced(*args
, **kw
):
108 with connect(dsn
) as connection
:
109 return method(connection
, *args
, **kw
)
114 def transact(dsn
, **args
):
115 with connect(dsn
) as connection
:
116 with connection
.transact(**args
) as cursor
:
120 def slap_(sql, table, keys, values, path):
123 csr.execute('savepoint iou')
125 both = dict(keys, **values)
129 insert into %s (%s) values (%s)
133 ', '.join(['%s' for key in fields])
135 except psycopg2.IntegrityError, e:
136 csr.execute('rollback to savepoint iou')
139 update %s set %s where %s
144 for key in values.keys()]),
147 for key in keys.keys()])
148 ), values.values() + keys.values())
150 return path_(csr, path)