sqlobject 3.13.1__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlobject/__init__.py +15 -0
- sqlobject/__version__.py +8 -0
- sqlobject/boundattributes.py +124 -0
- sqlobject/cache.py +376 -0
- sqlobject/classregistry.py +138 -0
- sqlobject/col.py +2187 -0
- sqlobject/compat.py +59 -0
- sqlobject/conftest.py +64 -0
- sqlobject/constraints.py +77 -0
- sqlobject/converters.py +278 -0
- sqlobject/dbconnection.py +1137 -0
- sqlobject/dberrors.py +54 -0
- sqlobject/declarative.py +211 -0
- sqlobject/events.py +365 -0
- sqlobject/firebird/__init__.py +8 -0
- sqlobject/firebird/firebirdconnection.py +463 -0
- sqlobject/include/__init__.py +1 -0
- sqlobject/include/hashcol.py +109 -0
- sqlobject/include/tests/__init__.py +1 -0
- sqlobject/include/tests/test_hashcol.py +84 -0
- sqlobject/index.py +189 -0
- sqlobject/inheritance/__init__.py +551 -0
- sqlobject/inheritance/iteration.py +106 -0
- sqlobject/inheritance/tests/__init__.py +1 -0
- sqlobject/inheritance/tests/test_aggregates.py +23 -0
- sqlobject/inheritance/tests/test_asdict.py +48 -0
- sqlobject/inheritance/tests/test_deep_inheritance.py +114 -0
- sqlobject/inheritance/tests/test_destroy_cascade.py +23 -0
- sqlobject/inheritance/tests/test_foreignKey.py +94 -0
- sqlobject/inheritance/tests/test_indexes.py +42 -0
- sqlobject/inheritance/tests/test_inheritance.py +164 -0
- sqlobject/inheritance/tests/test_inheritance_tree.py +50 -0
- sqlobject/joins.py +656 -0
- sqlobject/main.py +1880 -0
- sqlobject/manager/__init__.py +1 -0
- sqlobject/manager/command.py +1309 -0
- sqlobject/maxdb/__init__.py +8 -0
- sqlobject/maxdb/maxdbconnection.py +320 -0
- sqlobject/maxdb/readme.txt +27 -0
- sqlobject/mssql/__init__.py +8 -0
- sqlobject/mssql/mssqlconnection.py +417 -0
- sqlobject/mysql/__init__.py +8 -0
- sqlobject/mysql/mysqlconnection.py +562 -0
- sqlobject/postgres/__init__.py +8 -0
- sqlobject/postgres/pgconnection.py +619 -0
- sqlobject/sqlbuilder.py +1655 -0
- sqlobject/sqlite/__init__.py +8 -0
- sqlobject/sqlite/sqliteconnection.py +418 -0
- sqlobject/sresults.py +377 -0
- sqlobject/styles.py +174 -0
- sqlobject/sybase/__init__.py +8 -0
- sqlobject/sybase/sybaseconnection.py +183 -0
- sqlobject/tests/__init__.py +1 -0
- sqlobject/tests/dbtest.py +363 -0
- sqlobject/tests/test_ForeignKey.py +133 -0
- sqlobject/tests/test_ForeignKey_cascade.py +150 -0
- sqlobject/tests/test_NoneValuedResultItem.py +33 -0
- sqlobject/tests/test_SQLMultipleJoin.py +65 -0
- sqlobject/tests/test_SQLRelatedJoin.py +114 -0
- sqlobject/tests/test_SingleJoin.py +30 -0
- sqlobject/tests/test_aggregates.py +75 -0
- sqlobject/tests/test_aliases.py +49 -0
- sqlobject/tests/test_asdict.py +18 -0
- sqlobject/tests/test_auto.py +218 -0
- sqlobject/tests/test_basic.py +359 -0
- sqlobject/tests/test_blob.py +34 -0
- sqlobject/tests/test_boundattributes.py +67 -0
- sqlobject/tests/test_cache.py +57 -0
- sqlobject/tests/test_class_hash.py +22 -0
- sqlobject/tests/test_columns_order.py +18 -0
- sqlobject/tests/test_combining_joins.py +47 -0
- sqlobject/tests/test_comparison.py +24 -0
- sqlobject/tests/test_compat.py +10 -0
- sqlobject/tests/test_complex_sorting.py +77 -0
- sqlobject/tests/test_constraints.py +43 -0
- sqlobject/tests/test_converters.py +276 -0
- sqlobject/tests/test_create_drop.py +29 -0
- sqlobject/tests/test_csvexport.py +101 -0
- sqlobject/tests/test_csvimport.py +21 -0
- sqlobject/tests/test_cyclic_reference.py +55 -0
- sqlobject/tests/test_datetime.py +171 -0
- sqlobject/tests/test_dbconnection.py +17 -0
- sqlobject/tests/test_decimal.py +63 -0
- sqlobject/tests/test_declarative.py +83 -0
- sqlobject/tests/test_default_style.py +65 -0
- sqlobject/tests/test_delete.py +74 -0
- sqlobject/tests/test_distinct.py +36 -0
- sqlobject/tests/test_empty.py +22 -0
- sqlobject/tests/test_enum.py +75 -0
- sqlobject/tests/test_events.py +142 -0
- sqlobject/tests/test_exceptions.py +40 -0
- sqlobject/tests/test_expire.py +29 -0
- sqlobject/tests/test_groupBy.py +45 -0
- sqlobject/tests/test_identity.py +29 -0
- sqlobject/tests/test_indexes.py +100 -0
- sqlobject/tests/test_inheritance.py +35 -0
- sqlobject/tests/test_joins.py +160 -0
- sqlobject/tests/test_joins_conditional.py +143 -0
- sqlobject/tests/test_jsonbcol.py +53 -0
- sqlobject/tests/test_jsoncol.py +56 -0
- sqlobject/tests/test_lazy.py +165 -0
- sqlobject/tests/test_md5.py +13 -0
- sqlobject/tests/test_mysql.py +50 -0
- sqlobject/tests/test_new_joins.py +165 -0
- sqlobject/tests/test_parse_uri.py +147 -0
- sqlobject/tests/test_paste.py +92 -0
- sqlobject/tests/test_perConnection.py +20 -0
- sqlobject/tests/test_pickle.py +42 -0
- sqlobject/tests/test_picklecol.py +44 -0
- sqlobject/tests/test_postgres.py +82 -0
- sqlobject/tests/test_reparent_sqlmeta.py +33 -0
- sqlobject/tests/test_schema.py +30 -0
- sqlobject/tests/test_select.py +218 -0
- sqlobject/tests/test_select_through.py +63 -0
- sqlobject/tests/test_setters.py +23 -0
- sqlobject/tests/test_slice.py +59 -0
- sqlobject/tests/test_sorting.py +80 -0
- sqlobject/tests/test_sqlbuilder.py +134 -0
- sqlobject/tests/test_sqlbuilder_dbspecific.py +66 -0
- sqlobject/tests/test_sqlbuilder_importproxy.py +55 -0
- sqlobject/tests/test_sqlbuilder_joins_instances.py +90 -0
- sqlobject/tests/test_sqlite.py +160 -0
- sqlobject/tests/test_sqlmeta_idName.py +52 -0
- sqlobject/tests/test_sqlobject_admin.py +38 -0
- sqlobject/tests/test_string_id.py +79 -0
- sqlobject/tests/test_style.py +36 -0
- sqlobject/tests/test_subqueries.py +142 -0
- sqlobject/tests/test_transactions.py +122 -0
- sqlobject/tests/test_unicode.py +84 -0
- sqlobject/tests/test_uuidcol.py +40 -0
- sqlobject/tests/test_validation.py +125 -0
- sqlobject/tests/test_views.py +159 -0
- sqlobject/util/__init__.py +1 -0
- sqlobject/util/csvexport.py +210 -0
- sqlobject/util/csvimport.py +366 -0
- sqlobject/util/moduleloader.py +35 -0
- sqlobject/util/threadinglocal.py +6 -0
- sqlobject/versioning/__init__.py +120 -0
- sqlobject/versioning/test/__init__.py +0 -0
- sqlobject/versioning/test/test_version.py +183 -0
- sqlobject/views.py +151 -0
- sqlobject/wsgi_middleware.py +109 -0
- sqlobject-3.13.1.data/scripts/sqlobject-admin +36 -0
- sqlobject-3.13.1.data/scripts/sqlobject-convertOldURI +19 -0
- sqlobject-3.13.1.dist-info/METADATA +177 -0
- sqlobject-3.13.1.dist-info/RECORD +149 -0
- sqlobject-3.13.1.dist-info/WHEEL +6 -0
- sqlobject-3.13.1.dist-info/entry_points.txt +4 -0
- sqlobject-3.13.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1137 @@
|
|
|
1
|
+
import atexit
|
|
2
|
+
import inspect
|
|
3
|
+
import sys
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
import types
|
|
7
|
+
try:
|
|
8
|
+
from urlparse import urlparse, parse_qsl
|
|
9
|
+
from urllib import unquote, quote, urlencode
|
|
10
|
+
except ImportError:
|
|
11
|
+
from urllib.parse import urlparse, parse_qsl, unquote, quote, urlencode
|
|
12
|
+
|
|
13
|
+
import warnings
|
|
14
|
+
import weakref
|
|
15
|
+
|
|
16
|
+
from . import classregistry
|
|
17
|
+
from . import col
|
|
18
|
+
from . import sqlbuilder
|
|
19
|
+
from .cache import CacheSet
|
|
20
|
+
from .compat import PY2, string_type, unicode_type
|
|
21
|
+
from .converters import sqlrepr
|
|
22
|
+
from .events import send, CommitSignal, RollbackSignal
|
|
23
|
+
from .util.threadinglocal import local as threading_local
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
warnings.filterwarnings("ignore", "DB-API extension cursor.lastrowid used")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _closeConnection(ref):
|
|
30
|
+
conn = ref()
|
|
31
|
+
if conn is not None:
|
|
32
|
+
conn.close()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ConsoleWriter:
|
|
36
|
+
def __init__(self, connection, loglevel):
|
|
37
|
+
# loglevel: None or empty string for stdout; or 'stderr'
|
|
38
|
+
self.loglevel = loglevel or "stdout"
|
|
39
|
+
self.dbEncoding = getattr(connection, "dbEncoding", None) or "ascii"
|
|
40
|
+
|
|
41
|
+
def write(self, text):
|
|
42
|
+
logfile = getattr(sys, self.loglevel)
|
|
43
|
+
if PY2 and isinstance(text, unicode_type):
|
|
44
|
+
try:
|
|
45
|
+
text = text.encode(self.dbEncoding)
|
|
46
|
+
except UnicodeEncodeError:
|
|
47
|
+
text = repr(text)[2:-1] # Remove u'...' from the repr
|
|
48
|
+
logfile.write(text + '\n')
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class LogWriter:
|
|
52
|
+
def __init__(self, connection, logger, loglevel):
|
|
53
|
+
self.logger = logger
|
|
54
|
+
self.loglevel = loglevel
|
|
55
|
+
self.logmethod = getattr(logger, loglevel)
|
|
56
|
+
|
|
57
|
+
def write(self, text):
|
|
58
|
+
self.logmethod(text)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def makeDebugWriter(connection, loggerName, loglevel):
|
|
62
|
+
if not loggerName:
|
|
63
|
+
return ConsoleWriter(connection, loglevel)
|
|
64
|
+
import logging
|
|
65
|
+
logger = logging.getLogger(loggerName)
|
|
66
|
+
return LogWriter(connection, logger, loglevel)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Boolean(object):
|
|
70
|
+
"""A bool class that also understands some special string keywords
|
|
71
|
+
|
|
72
|
+
Understands: yes/no, true/false, on/off, 1/0, case ignored.
|
|
73
|
+
|
|
74
|
+
"""
|
|
75
|
+
_keywords = {'1': True, 'yes': True, 'true': True, 'on': True,
|
|
76
|
+
'0': False, 'no': False, 'false': False, 'off': False}
|
|
77
|
+
|
|
78
|
+
def __new__(cls, value):
|
|
79
|
+
try:
|
|
80
|
+
return Boolean._keywords[value.lower()]
|
|
81
|
+
except (AttributeError, KeyError):
|
|
82
|
+
return bool(value)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class DBConnection:
|
|
86
|
+
|
|
87
|
+
def __init__(self, name=None, debug=False, debugOutput=False,
|
|
88
|
+
cache=True, style=None, autoCommit=True,
|
|
89
|
+
debugThreading=False, registry=None,
|
|
90
|
+
logger=None, loglevel=None):
|
|
91
|
+
self.name = name
|
|
92
|
+
self.debug = Boolean(debug)
|
|
93
|
+
self.debugOutput = Boolean(debugOutput)
|
|
94
|
+
self.debugThreading = Boolean(debugThreading)
|
|
95
|
+
self.debugWriter = makeDebugWriter(self, logger, loglevel)
|
|
96
|
+
self.doCache = Boolean(cache)
|
|
97
|
+
self.cache = CacheSet(cache=self.doCache)
|
|
98
|
+
self.style = style
|
|
99
|
+
self._connectionNumbers = {}
|
|
100
|
+
self._connectionCount = 1
|
|
101
|
+
self.autoCommit = Boolean(autoCommit)
|
|
102
|
+
self.registry = registry or None
|
|
103
|
+
classregistry.registry(self.registry).addCallback(self.soClassAdded)
|
|
104
|
+
registerConnectionInstance(self)
|
|
105
|
+
atexit.register(_closeConnection, weakref.ref(self))
|
|
106
|
+
|
|
107
|
+
def oldUri(self):
|
|
108
|
+
auth = getattr(self, 'user', '') or ''
|
|
109
|
+
if auth:
|
|
110
|
+
if self.password:
|
|
111
|
+
auth += ':' + self.password
|
|
112
|
+
auth += '@'
|
|
113
|
+
else:
|
|
114
|
+
assert not getattr(self, 'password', None), (
|
|
115
|
+
'URIs cannot express passwords without usernames')
|
|
116
|
+
uri = '%s://%s' % (self.dbName, auth)
|
|
117
|
+
if self.host:
|
|
118
|
+
uri += self.host
|
|
119
|
+
if self.port:
|
|
120
|
+
uri += ':%d' % self.port
|
|
121
|
+
uri += '/'
|
|
122
|
+
db = self.db
|
|
123
|
+
if db.startswith('/'):
|
|
124
|
+
db = db[1:]
|
|
125
|
+
return uri + db
|
|
126
|
+
|
|
127
|
+
def uri(self):
|
|
128
|
+
auth = getattr(self, 'user', '') or ''
|
|
129
|
+
if auth:
|
|
130
|
+
auth = quote(auth)
|
|
131
|
+
if self.password:
|
|
132
|
+
auth += ':' + quote(self.password)
|
|
133
|
+
auth += '@'
|
|
134
|
+
else:
|
|
135
|
+
assert not getattr(self, 'password', None), (
|
|
136
|
+
'URIs cannot express passwords without usernames')
|
|
137
|
+
uri = '%s://%s' % (self.dbName, auth)
|
|
138
|
+
if self.host:
|
|
139
|
+
uri += self.host
|
|
140
|
+
if self.port:
|
|
141
|
+
uri += ':%d' % self.port
|
|
142
|
+
uri += '/'
|
|
143
|
+
db = self.db
|
|
144
|
+
if db.startswith('/'):
|
|
145
|
+
db = db[1:]
|
|
146
|
+
return uri + quote(db)
|
|
147
|
+
|
|
148
|
+
@classmethod
|
|
149
|
+
def connectionFromOldURI(cls, uri):
|
|
150
|
+
return cls._connectionFromParams(*cls._parseOldURI(uri))
|
|
151
|
+
|
|
152
|
+
@classmethod
|
|
153
|
+
def connectionFromURI(cls, uri):
|
|
154
|
+
return cls._connectionFromParams(*cls._parseURI(uri))
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def _parseOldURI(uri):
|
|
158
|
+
schema, rest = uri.split(':', 1)
|
|
159
|
+
assert rest.startswith('/'), \
|
|
160
|
+
"URIs must start with scheme:/ -- " \
|
|
161
|
+
"you did not include a / (in %r)" % rest
|
|
162
|
+
if rest.startswith('/') and not rest.startswith('//'):
|
|
163
|
+
host = None
|
|
164
|
+
rest = rest[1:]
|
|
165
|
+
elif rest.startswith('///'):
|
|
166
|
+
host = None
|
|
167
|
+
rest = rest[3:]
|
|
168
|
+
else:
|
|
169
|
+
rest = rest[2:]
|
|
170
|
+
if rest.find('/') == -1:
|
|
171
|
+
host = rest
|
|
172
|
+
rest = ''
|
|
173
|
+
else:
|
|
174
|
+
host, rest = rest.split('/', 1)
|
|
175
|
+
if host and host.find('@') != -1:
|
|
176
|
+
user, host = host.rsplit('@', 1)
|
|
177
|
+
if user.find(':') != -1:
|
|
178
|
+
user, password = user.split(':', 1)
|
|
179
|
+
else:
|
|
180
|
+
password = None
|
|
181
|
+
else:
|
|
182
|
+
user = password = None
|
|
183
|
+
if host and host.find(':') != -1:
|
|
184
|
+
_host, port = host.split(':')
|
|
185
|
+
try:
|
|
186
|
+
port = int(port)
|
|
187
|
+
except ValueError:
|
|
188
|
+
raise ValueError("port must be integer, "
|
|
189
|
+
"got '%s' instead" % port)
|
|
190
|
+
if not (1 <= port <= 65535):
|
|
191
|
+
raise ValueError("port must be integer in the range 1-65535, "
|
|
192
|
+
"got '%d' instead" % port)
|
|
193
|
+
host = _host
|
|
194
|
+
else:
|
|
195
|
+
port = None
|
|
196
|
+
path = '/' + rest
|
|
197
|
+
if os.name == 'nt':
|
|
198
|
+
if (len(rest) > 1) and (rest[1] == '|'):
|
|
199
|
+
path = "%s:%s" % (rest[0], rest[2:])
|
|
200
|
+
args = {}
|
|
201
|
+
if path.find('?') != -1:
|
|
202
|
+
path, arglist = path.split('?', 1)
|
|
203
|
+
arglist = arglist.split('&')
|
|
204
|
+
for single in arglist:
|
|
205
|
+
argname, argvalue = single.split('=', 1)
|
|
206
|
+
argvalue = unquote(argvalue)
|
|
207
|
+
args[argname] = argvalue
|
|
208
|
+
return user, password, host, port, path, args
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def _parseURI(uri):
|
|
212
|
+
parsed = urlparse(uri)
|
|
213
|
+
host, path = parsed.hostname, parsed.path
|
|
214
|
+
user, password, port = None, None, None
|
|
215
|
+
if parsed.username:
|
|
216
|
+
user = unquote(parsed.username)
|
|
217
|
+
if parsed.password:
|
|
218
|
+
password = unquote(parsed.password)
|
|
219
|
+
if parsed.port:
|
|
220
|
+
port = int(parsed.port)
|
|
221
|
+
|
|
222
|
+
path = unquote(path)
|
|
223
|
+
if (os.name == 'nt') and (len(path) > 2):
|
|
224
|
+
# Preserve backward compatibility with URIs like /C|/path;
|
|
225
|
+
# replace '|' by ':'
|
|
226
|
+
if path[2] == '|':
|
|
227
|
+
path = "%s:%s" % (path[0:2], path[3:])
|
|
228
|
+
# Remove leading slash
|
|
229
|
+
if (path[0] == '/') and (path[2] == ':'):
|
|
230
|
+
path = path[1:]
|
|
231
|
+
|
|
232
|
+
query = parsed.query
|
|
233
|
+
# hash-tag / fragment is ignored
|
|
234
|
+
|
|
235
|
+
args = {}
|
|
236
|
+
if query:
|
|
237
|
+
for name, value in parse_qsl(query):
|
|
238
|
+
args[name] = value
|
|
239
|
+
|
|
240
|
+
return user, password, host, port, path, args
|
|
241
|
+
|
|
242
|
+
def soClassAdded(self, soClass):
|
|
243
|
+
"""
|
|
244
|
+
This is called for each new class; we use this opportunity
|
|
245
|
+
to create an instance method that is bound to the class
|
|
246
|
+
and this connection.
|
|
247
|
+
"""
|
|
248
|
+
name = soClass.__name__
|
|
249
|
+
assert not hasattr(self, name), (
|
|
250
|
+
"Connection %r already has an attribute with the name "
|
|
251
|
+
"%r (and you just created the conflicting class %r)"
|
|
252
|
+
% (self, name, soClass))
|
|
253
|
+
setattr(self, name, ConnWrapper(soClass, self))
|
|
254
|
+
|
|
255
|
+
def expireAll(self):
|
|
256
|
+
"""
|
|
257
|
+
Expire all instances of objects for this connection.
|
|
258
|
+
"""
|
|
259
|
+
cache_set = self.cache
|
|
260
|
+
cache_set.weakrefAll()
|
|
261
|
+
for item in cache_set.getAll():
|
|
262
|
+
item.expire()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class ConnWrapper(object):
|
|
266
|
+
|
|
267
|
+
"""
|
|
268
|
+
This represents a SQLObject class that is bound to a specific
|
|
269
|
+
connection (instances have a connection instance variable, but
|
|
270
|
+
classes are global, so this is binds the connection variable
|
|
271
|
+
lazily when a class method is accessed)
|
|
272
|
+
"""
|
|
273
|
+
# @@: methods that take connection arguments should be explicitly
|
|
274
|
+
# marked up instead of the implicit use of a connection argument
|
|
275
|
+
# and inspect.getargspec()
|
|
276
|
+
|
|
277
|
+
def __init__(self, soClass, connection):
|
|
278
|
+
self._soClass = soClass
|
|
279
|
+
self._connection = connection
|
|
280
|
+
|
|
281
|
+
def __call__(self, *args, **kw):
|
|
282
|
+
kw['connection'] = self._connection
|
|
283
|
+
return self._soClass(*args, **kw)
|
|
284
|
+
|
|
285
|
+
def __getattr__(self, attr):
|
|
286
|
+
meth = getattr(self._soClass, attr)
|
|
287
|
+
if not isinstance(meth, types.MethodType):
|
|
288
|
+
# We don't need to wrap non-methods
|
|
289
|
+
return meth
|
|
290
|
+
try:
|
|
291
|
+
takes_conn = meth.takes_connection
|
|
292
|
+
except AttributeError:
|
|
293
|
+
args, varargs, varkw, defaults = inspect.getargspec(meth)
|
|
294
|
+
assert not varkw and not varargs, (
|
|
295
|
+
"I cannot tell whether I must wrap this method, "
|
|
296
|
+
"because it takes **kw: %r"
|
|
297
|
+
% meth)
|
|
298
|
+
takes_conn = 'connection' in args
|
|
299
|
+
meth.__func__.takes_connection = takes_conn
|
|
300
|
+
if not takes_conn:
|
|
301
|
+
return meth
|
|
302
|
+
return ConnMethodWrapper(meth, self._connection)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class ConnMethodWrapper(object):
|
|
306
|
+
|
|
307
|
+
def __init__(self, method, connection):
|
|
308
|
+
self._method = method
|
|
309
|
+
self._connection = connection
|
|
310
|
+
|
|
311
|
+
def __getattr__(self, attr):
|
|
312
|
+
return getattr(self._method, attr)
|
|
313
|
+
|
|
314
|
+
def __call__(self, *args, **kw):
|
|
315
|
+
kw['connection'] = self._connection
|
|
316
|
+
return self._method(*args, **kw)
|
|
317
|
+
|
|
318
|
+
def __repr__(self):
|
|
319
|
+
return '<Wrapped %r with connection %r>' % (
|
|
320
|
+
self._method, self._connection)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class DBAPI(DBConnection):
|
|
324
|
+
|
|
325
|
+
"""
|
|
326
|
+
Subclass must define a `makeConnection()` method, which
|
|
327
|
+
returns a newly-created connection object.
|
|
328
|
+
|
|
329
|
+
``queryInsertID`` must also be defined.
|
|
330
|
+
"""
|
|
331
|
+
dbName = None
|
|
332
|
+
|
|
333
|
+
def __init__(self, **kw):
|
|
334
|
+
self._pool = []
|
|
335
|
+
self._poolLock = threading.Lock()
|
|
336
|
+
DBConnection.__init__(self, **kw)
|
|
337
|
+
self._binaryType = type(self.module.Binary(b''))
|
|
338
|
+
|
|
339
|
+
def _runWithConnection(self, meth, *args):
|
|
340
|
+
conn = self.getConnection()
|
|
341
|
+
try:
|
|
342
|
+
val = meth(conn, *args)
|
|
343
|
+
finally:
|
|
344
|
+
self.releaseConnection(conn)
|
|
345
|
+
return val
|
|
346
|
+
|
|
347
|
+
def getConnection(self):
|
|
348
|
+
self._poolLock.acquire()
|
|
349
|
+
try:
|
|
350
|
+
if not self._pool:
|
|
351
|
+
conn = self.makeConnection()
|
|
352
|
+
self._connectionNumbers[id(conn)] = self._connectionCount
|
|
353
|
+
self._connectionCount += 1
|
|
354
|
+
else:
|
|
355
|
+
conn = self._pool.pop()
|
|
356
|
+
if self.debug:
|
|
357
|
+
s = 'ACQUIRE'
|
|
358
|
+
if self._pool is not None:
|
|
359
|
+
s += ' pool=[%s]' % ', '.join(
|
|
360
|
+
[str(self._connectionNumbers[id(v)])
|
|
361
|
+
for v in self._pool])
|
|
362
|
+
self.printDebug(conn, s, 'Pool')
|
|
363
|
+
return conn
|
|
364
|
+
finally:
|
|
365
|
+
self._poolLock.release()
|
|
366
|
+
|
|
367
|
+
def releaseConnection(self, conn, explicit=False):
|
|
368
|
+
if self.debug:
|
|
369
|
+
if explicit:
|
|
370
|
+
s = 'RELEASE (explicit)'
|
|
371
|
+
else:
|
|
372
|
+
s = 'RELEASE (implicit, autocommit=%s)' % self.autoCommit
|
|
373
|
+
if self._pool is None:
|
|
374
|
+
s += ' no pooling'
|
|
375
|
+
else:
|
|
376
|
+
s += ' pool=[%s]' % ', '.join(
|
|
377
|
+
[str(self._connectionNumbers[id(v)]) for v in self._pool])
|
|
378
|
+
self.printDebug(conn, s, 'Pool')
|
|
379
|
+
if self.supportTransactions and not explicit:
|
|
380
|
+
if self.autoCommit == 'exception':
|
|
381
|
+
if self.debug:
|
|
382
|
+
self.printDebug(conn, 'auto/exception', 'ROLLBACK')
|
|
383
|
+
conn.rollback()
|
|
384
|
+
raise Exception('Object used outside of a transaction; '
|
|
385
|
+
'implicit COMMIT or ROLLBACK not allowed')
|
|
386
|
+
elif self.autoCommit:
|
|
387
|
+
if self.debug:
|
|
388
|
+
self.printDebug(conn, 'auto', 'COMMIT')
|
|
389
|
+
if not getattr(conn, 'autocommit', False):
|
|
390
|
+
conn.commit()
|
|
391
|
+
else:
|
|
392
|
+
if self.debug:
|
|
393
|
+
self.printDebug(conn, 'auto', 'ROLLBACK')
|
|
394
|
+
conn.rollback()
|
|
395
|
+
if self._pool is not None:
|
|
396
|
+
if conn not in self._pool:
|
|
397
|
+
# @@: We can get duplicate releasing of connections with
|
|
398
|
+
# the __del__ in Iteration (unfortunately, not sure why
|
|
399
|
+
# it happens)
|
|
400
|
+
self._pool.insert(0, conn)
|
|
401
|
+
else:
|
|
402
|
+
conn.close()
|
|
403
|
+
|
|
404
|
+
def printDebug(self, conn, s, name, type='query'):
|
|
405
|
+
if name == 'Pool' and self.debug != 'Pool':
|
|
406
|
+
return
|
|
407
|
+
if type == 'query':
|
|
408
|
+
sep = ': '
|
|
409
|
+
else:
|
|
410
|
+
sep = '->'
|
|
411
|
+
s = repr(s)
|
|
412
|
+
n = self._connectionNumbers[id(conn)]
|
|
413
|
+
spaces = ' ' * (8 - len(name))
|
|
414
|
+
if self.debugThreading:
|
|
415
|
+
threadName = threading.currentThread().getName()
|
|
416
|
+
threadName = (':' + threadName + ' ' * (8 - len(threadName)))
|
|
417
|
+
else:
|
|
418
|
+
threadName = ''
|
|
419
|
+
msg = '%(n)2i%(threadName)s/%(name)s%(spaces)s%(sep)s %(s)s' % locals()
|
|
420
|
+
self.debugWriter.write(msg)
|
|
421
|
+
|
|
422
|
+
def _executeRetry(self, conn, cursor, query):
|
|
423
|
+
if self.debug:
|
|
424
|
+
self.printDebug(conn, query, 'QueryR')
|
|
425
|
+
return cursor.execute(query)
|
|
426
|
+
|
|
427
|
+
def _query(self, conn, s):
|
|
428
|
+
if self.debug:
|
|
429
|
+
self.printDebug(conn, s, 'Query')
|
|
430
|
+
c = conn.cursor()
|
|
431
|
+
self._executeRetry(conn, c, s)
|
|
432
|
+
c.close()
|
|
433
|
+
|
|
434
|
+
def query(self, s):
|
|
435
|
+
return self._runWithConnection(self._query, s)
|
|
436
|
+
|
|
437
|
+
def _queryAll(self, conn, s):
|
|
438
|
+
if self.debug:
|
|
439
|
+
self.printDebug(conn, s, 'QueryAll')
|
|
440
|
+
c = conn.cursor()
|
|
441
|
+
self._executeRetry(conn, c, s)
|
|
442
|
+
value = c.fetchall()
|
|
443
|
+
c.close()
|
|
444
|
+
if self.debugOutput:
|
|
445
|
+
self.printDebug(conn, value, 'QueryAll', 'result')
|
|
446
|
+
return value
|
|
447
|
+
|
|
448
|
+
def queryAll(self, s):
|
|
449
|
+
return self._runWithConnection(self._queryAll, s)
|
|
450
|
+
|
|
451
|
+
def _queryAllDescription(self, conn, s):
|
|
452
|
+
"""
|
|
453
|
+
Like queryAll, but returns (description, rows), where the
|
|
454
|
+
description is cursor.description (which gives row types)
|
|
455
|
+
"""
|
|
456
|
+
if self.debug:
|
|
457
|
+
self.printDebug(conn, s, 'QueryAllDesc')
|
|
458
|
+
c = conn.cursor()
|
|
459
|
+
self._executeRetry(conn, c, s)
|
|
460
|
+
value = c.fetchall()
|
|
461
|
+
c.close()
|
|
462
|
+
if self.debugOutput:
|
|
463
|
+
self.printDebug(conn, value, 'QueryAll', 'result')
|
|
464
|
+
return c.description, value
|
|
465
|
+
|
|
466
|
+
def queryAllDescription(self, s):
|
|
467
|
+
return self._runWithConnection(self._queryAllDescription, s)
|
|
468
|
+
|
|
469
|
+
def _queryOne(self, conn, s):
|
|
470
|
+
if self.debug:
|
|
471
|
+
self.printDebug(conn, s, 'QueryOne')
|
|
472
|
+
c = conn.cursor()
|
|
473
|
+
self._executeRetry(conn, c, s)
|
|
474
|
+
value = c.fetchone()
|
|
475
|
+
c.close()
|
|
476
|
+
if self.debugOutput:
|
|
477
|
+
self.printDebug(conn, value, 'QueryOne', 'result')
|
|
478
|
+
return value
|
|
479
|
+
|
|
480
|
+
def queryOne(self, s):
|
|
481
|
+
return self._runWithConnection(self._queryOne, s)
|
|
482
|
+
|
|
483
|
+
def _insertSQL(self, table, names, values):
|
|
484
|
+
return ("INSERT INTO %s (%s) VALUES (%s)" %
|
|
485
|
+
(table, ', '.join(names),
|
|
486
|
+
', '.join([self.sqlrepr(v) for v in values])))
|
|
487
|
+
|
|
488
|
+
def transaction(self):
|
|
489
|
+
return Transaction(self)
|
|
490
|
+
|
|
491
|
+
def queryInsertID(self, soInstance, id, names, values):
|
|
492
|
+
return self._runWithConnection(self._queryInsertID, soInstance, id,
|
|
493
|
+
names, values)
|
|
494
|
+
|
|
495
|
+
def iterSelect(self, select):
|
|
496
|
+
return select.IterationClass(self, self.getConnection(),
|
|
497
|
+
select, keepConnection=False)
|
|
498
|
+
|
|
499
|
+
def accumulateSelect(self, select, *expressions):
|
|
500
|
+
""" Apply an accumulate function(s) (SUM, COUNT, MIN, AVG, MAX, etc...)
|
|
501
|
+
to the select object.
|
|
502
|
+
"""
|
|
503
|
+
q = select.queryForSelect().newItems(expressions).\
|
|
504
|
+
unlimited().orderBy(None)
|
|
505
|
+
q = self.sqlrepr(q)
|
|
506
|
+
val = self.queryOne(q)
|
|
507
|
+
if len(expressions) == 1:
|
|
508
|
+
val = val[0]
|
|
509
|
+
return val
|
|
510
|
+
|
|
511
|
+
def queryForSelect(self, select):
|
|
512
|
+
return self.sqlrepr(select.queryForSelect())
|
|
513
|
+
|
|
514
|
+
def _SO_createJoinTable(self, join):
|
|
515
|
+
self.query(self._SO_createJoinTableSQL(join))
|
|
516
|
+
|
|
517
|
+
def _SO_createJoinTableSQL(self, join):
|
|
518
|
+
return ('CREATE TABLE %s (\n%s %s,\n%s %s\n)' %
|
|
519
|
+
(join.intermediateTable,
|
|
520
|
+
join.joinColumn,
|
|
521
|
+
self.joinSQLType(join),
|
|
522
|
+
join.otherColumn,
|
|
523
|
+
self.joinSQLType(join)))
|
|
524
|
+
|
|
525
|
+
def _SO_dropJoinTable(self, join):
|
|
526
|
+
self.query("DROP TABLE %s" % join.intermediateTable)
|
|
527
|
+
|
|
528
|
+
def _SO_createIndex(self, soClass, index):
|
|
529
|
+
self.query(self.createIndexSQL(soClass, index))
|
|
530
|
+
|
|
531
|
+
def createIndexSQL(self, soClass, index):
|
|
532
|
+
assert 0, 'Implement in subclasses'
|
|
533
|
+
|
|
534
|
+
def createTable(self, soClass):
|
|
535
|
+
createSql, constraints = self.createTableSQL(soClass)
|
|
536
|
+
self.query(createSql)
|
|
537
|
+
|
|
538
|
+
return constraints
|
|
539
|
+
|
|
540
|
+
def createReferenceConstraints(self, soClass):
|
|
541
|
+
refConstraints = [self.createReferenceConstraint(soClass, column)
|
|
542
|
+
for column in soClass.sqlmeta.columnList
|
|
543
|
+
if isinstance(column, col.SOForeignKey)]
|
|
544
|
+
refConstraintDefs = [constraint for constraint in refConstraints
|
|
545
|
+
if constraint]
|
|
546
|
+
return refConstraintDefs
|
|
547
|
+
|
|
548
|
+
def createSQL(self, soClass):
|
|
549
|
+
tableCreateSQLs = getattr(soClass.sqlmeta, 'createSQL', None)
|
|
550
|
+
if tableCreateSQLs:
|
|
551
|
+
assert isinstance(tableCreateSQLs, (str, list, dict, tuple)), (
|
|
552
|
+
'%s.sqlmeta.createSQL must be a str, list, dict or tuple.' %
|
|
553
|
+
(soClass.__name__))
|
|
554
|
+
if isinstance(tableCreateSQLs, dict):
|
|
555
|
+
tableCreateSQLs = tableCreateSQLs.get(
|
|
556
|
+
soClass._connection.dbName, [])
|
|
557
|
+
if isinstance(tableCreateSQLs, str):
|
|
558
|
+
tableCreateSQLs = [tableCreateSQLs]
|
|
559
|
+
if isinstance(tableCreateSQLs, tuple):
|
|
560
|
+
tableCreateSQLs = list(tableCreateSQLs)
|
|
561
|
+
assert isinstance(tableCreateSQLs, list), (
|
|
562
|
+
'Unable to create a list from %s.sqlmeta.createSQL' %
|
|
563
|
+
(soClass.__name__))
|
|
564
|
+
return tableCreateSQLs or []
|
|
565
|
+
|
|
566
|
+
def createTableSQL(self, soClass):
|
|
567
|
+
constraints = self.createReferenceConstraints(soClass)
|
|
568
|
+
extraSQL = self.createSQL(soClass)
|
|
569
|
+
createSql = ('CREATE TABLE %s (\n%s\n)' %
|
|
570
|
+
(soClass.sqlmeta.table, self.createColumns(soClass)))
|
|
571
|
+
return createSql, constraints + extraSQL
|
|
572
|
+
|
|
573
|
+
def createColumns(self, soClass):
|
|
574
|
+
columnDefs = [self.createIDColumn(soClass)] \
|
|
575
|
+
+ [self.createColumn(soClass, col)
|
|
576
|
+
for col in soClass.sqlmeta.columnList]
|
|
577
|
+
return ",\n".join([" %s" % c for c in columnDefs])
|
|
578
|
+
|
|
579
|
+
def createReferenceConstraint(self, soClass, col):
|
|
580
|
+
assert 0, "Implement in subclasses"
|
|
581
|
+
|
|
582
|
+
def createColumn(self, soClass, col):
|
|
583
|
+
assert 0, "Implement in subclasses"
|
|
584
|
+
|
|
585
|
+
def dropTable(self, tableName, cascade=False):
|
|
586
|
+
self.query("DROP TABLE %s" % tableName)
|
|
587
|
+
|
|
588
|
+
def clearTable(self, tableName):
|
|
589
|
+
# 3-03 @@: Should this have a WHERE 1 = 1 or similar
|
|
590
|
+
# clause? In some configurations without the WHERE clause
|
|
591
|
+
# the query won't go through, but maybe we shouldn't override
|
|
592
|
+
# that.
|
|
593
|
+
self.query("DELETE FROM %s" % tableName)
|
|
594
|
+
|
|
595
|
+
def createBinary(self, value):
|
|
596
|
+
"""
|
|
597
|
+
Create a binary object wrapper for the given database.
|
|
598
|
+
"""
|
|
599
|
+
# Default is Binary() function from the connection driver.
|
|
600
|
+
return self.module.Binary(value)
|
|
601
|
+
|
|
602
|
+
# The _SO_* series of methods are sorts of "friend" methods
|
|
603
|
+
# with SQLObject. They grab values from the SQLObject instances
|
|
604
|
+
# or classes freely, but keep the SQLObject class from accessing
|
|
605
|
+
# the database directly. This way no SQL is actually created
|
|
606
|
+
# in the SQLObject class.
|
|
607
|
+
|
|
608
|
+
def _SO_update(self, so, values):
|
|
609
|
+
self.query("UPDATE %s SET %s WHERE %s = (%s)" %
|
|
610
|
+
(so.sqlmeta.table,
|
|
611
|
+
", ".join(["%s = (%s)" % (dbName, self.sqlrepr(value))
|
|
612
|
+
for dbName, value in values]),
|
|
613
|
+
so.sqlmeta.idName,
|
|
614
|
+
self.sqlrepr(so.id)))
|
|
615
|
+
|
|
616
|
+
def _SO_selectOne(self, so, columnNames):
|
|
617
|
+
return self._SO_selectOneAlt(so, columnNames, so.q.id == so.id)
|
|
618
|
+
|
|
619
|
+
def _SO_selectOneAlt(self, so, columnNames, condition):
|
|
620
|
+
if columnNames:
|
|
621
|
+
columns = [isinstance(x, string_type)
|
|
622
|
+
and sqlbuilder.SQLConstant(x)
|
|
623
|
+
or x for x in columnNames]
|
|
624
|
+
else:
|
|
625
|
+
columns = None
|
|
626
|
+
return self.queryOne(self.sqlrepr(sqlbuilder.Select(
|
|
627
|
+
columns, staticTables=[so.sqlmeta.table], clause=condition)))
|
|
628
|
+
|
|
629
|
+
def _SO_delete(self, so):
|
|
630
|
+
self.query("DELETE FROM %s WHERE %s = (%s)" %
|
|
631
|
+
(so.sqlmeta.table,
|
|
632
|
+
so.sqlmeta.idName,
|
|
633
|
+
self.sqlrepr(so.id)))
|
|
634
|
+
|
|
635
|
+
def _SO_selectJoin(self, soClass, column, value):
|
|
636
|
+
return self.queryAll("SELECT %s FROM %s WHERE %s = (%s)" %
|
|
637
|
+
(soClass.sqlmeta.idName,
|
|
638
|
+
soClass.sqlmeta.table,
|
|
639
|
+
column,
|
|
640
|
+
self.sqlrepr(value)))
|
|
641
|
+
|
|
642
|
+
def _SO_intermediateJoin(self, table, getColumn, joinColumn, value):
|
|
643
|
+
return self.queryAll("SELECT %s FROM %s WHERE %s = (%s)" %
|
|
644
|
+
(getColumn,
|
|
645
|
+
table,
|
|
646
|
+
joinColumn,
|
|
647
|
+
self.sqlrepr(value)))
|
|
648
|
+
|
|
649
|
+
def _SO_intermediateDelete(self, table, firstColumn, firstValue,
|
|
650
|
+
secondColumn, secondValue):
|
|
651
|
+
self.query("DELETE FROM %s WHERE %s = (%s) AND %s = (%s)" %
|
|
652
|
+
(table,
|
|
653
|
+
firstColumn,
|
|
654
|
+
self.sqlrepr(firstValue),
|
|
655
|
+
secondColumn,
|
|
656
|
+
self.sqlrepr(secondValue)))
|
|
657
|
+
|
|
658
|
+
def _SO_intermediateInsert(self, table, firstColumn, firstValue,
|
|
659
|
+
secondColumn, secondValue):
|
|
660
|
+
self.query("INSERT INTO %s (%s, %s) VALUES (%s, %s)" %
|
|
661
|
+
(table,
|
|
662
|
+
firstColumn,
|
|
663
|
+
secondColumn,
|
|
664
|
+
self.sqlrepr(firstValue),
|
|
665
|
+
self.sqlrepr(secondValue)))
|
|
666
|
+
|
|
667
|
+
def _SO_columnClause(self, soClass, kw):
|
|
668
|
+
from . import main
|
|
669
|
+
data = []
|
|
670
|
+
if 'id' in kw:
|
|
671
|
+
data.append((soClass.sqlmeta.idName, kw.pop('id')))
|
|
672
|
+
for soColumn in soClass.sqlmeta.columnList:
|
|
673
|
+
key = soColumn.name
|
|
674
|
+
if key in kw:
|
|
675
|
+
val = kw.pop(key)
|
|
676
|
+
if soColumn.from_python:
|
|
677
|
+
val = soColumn.from_python(
|
|
678
|
+
val,
|
|
679
|
+
sqlbuilder.SQLObjectState(soClass, connection=self))
|
|
680
|
+
data.append((soColumn.dbName, val))
|
|
681
|
+
elif soColumn.foreignName in kw:
|
|
682
|
+
obj = kw.pop(soColumn.foreignName)
|
|
683
|
+
if isinstance(obj, main.SQLObject):
|
|
684
|
+
data.append((soColumn.dbName, obj.id))
|
|
685
|
+
else:
|
|
686
|
+
data.append((soColumn.dbName, obj))
|
|
687
|
+
if kw:
|
|
688
|
+
# pick the first key from kw to use to raise the error,
|
|
689
|
+
raise TypeError("got an unexpected keyword argument(s): "
|
|
690
|
+
"%r" % kw.keys())
|
|
691
|
+
|
|
692
|
+
if not data:
|
|
693
|
+
return None
|
|
694
|
+
return ' AND '.join(
|
|
695
|
+
['%s %s %s' %
|
|
696
|
+
(dbName, "IS" if value is None else "=", self.sqlrepr(value))
|
|
697
|
+
for dbName, value
|
|
698
|
+
in data])
|
|
699
|
+
|
|
700
|
+
def sqlrepr(self, v):
|
|
701
|
+
return sqlrepr(v, self.dbName)
|
|
702
|
+
|
|
703
|
+
def __del__(self):
|
|
704
|
+
self.close()
|
|
705
|
+
|
|
706
|
+
def close(self):
|
|
707
|
+
if not hasattr(self, '_pool'):
|
|
708
|
+
# Probably there was an exception while creating this
|
|
709
|
+
# instance, so it is incomplete.
|
|
710
|
+
return
|
|
711
|
+
if not self._pool:
|
|
712
|
+
return
|
|
713
|
+
self._poolLock.acquire()
|
|
714
|
+
try:
|
|
715
|
+
if not self._pool: # _pool could be filled in a different thread
|
|
716
|
+
return
|
|
717
|
+
conns = self._pool[:]
|
|
718
|
+
self._pool[:] = []
|
|
719
|
+
for conn in conns:
|
|
720
|
+
try:
|
|
721
|
+
conn.close()
|
|
722
|
+
except self.module.Error:
|
|
723
|
+
pass
|
|
724
|
+
del conn
|
|
725
|
+
del conns
|
|
726
|
+
finally:
|
|
727
|
+
self._poolLock.release()
|
|
728
|
+
|
|
729
|
+
def createEmptyDatabase(self):
|
|
730
|
+
"""
|
|
731
|
+
Create an empty database.
|
|
732
|
+
"""
|
|
733
|
+
raise NotImplementedError
|
|
734
|
+
|
|
735
|
+
def make_odbc_conn_str(self, odb_source, db, host=None, port=None,
|
|
736
|
+
user=None, password=None):
|
|
737
|
+
odbc_conn_parts = ['Driver={%s}' % odb_source]
|
|
738
|
+
for odbc_keyword, value in \
|
|
739
|
+
zip(self.odbc_keywords, (host, port, user, password, db)):
|
|
740
|
+
if value is not None:
|
|
741
|
+
odbc_conn_parts.append('%s=%s' % (odbc_keyword, value))
|
|
742
|
+
self.odbc_conn_str = ';'.join(odbc_conn_parts)
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
class Iteration(object):
|
|
746
|
+
|
|
747
|
+
def __init__(self, dbconn, rawconn, select, keepConnection=False):
|
|
748
|
+
self.dbconn = dbconn
|
|
749
|
+
self.rawconn = rawconn
|
|
750
|
+
self.select = select
|
|
751
|
+
self.keepConnection = keepConnection
|
|
752
|
+
self.cursor = rawconn.cursor()
|
|
753
|
+
self.query = self.dbconn.queryForSelect(select)
|
|
754
|
+
if dbconn.debug:
|
|
755
|
+
dbconn.printDebug(rawconn, self.query, 'Select')
|
|
756
|
+
self.dbconn._executeRetry(self.rawconn, self.cursor, self.query)
|
|
757
|
+
|
|
758
|
+
def __iter__(self):
|
|
759
|
+
return self
|
|
760
|
+
|
|
761
|
+
def __next__(self):
|
|
762
|
+
return self.next()
|
|
763
|
+
|
|
764
|
+
def next(self):
|
|
765
|
+
result = self.cursor.fetchone()
|
|
766
|
+
if result is None:
|
|
767
|
+
self._cleanup()
|
|
768
|
+
raise StopIteration
|
|
769
|
+
if result[0] is None:
|
|
770
|
+
return None
|
|
771
|
+
if self.select.ops.get('lazyColumns', 0):
|
|
772
|
+
obj = self.select.sourceClass.get(result[0],
|
|
773
|
+
connection=self.dbconn)
|
|
774
|
+
return obj
|
|
775
|
+
else:
|
|
776
|
+
obj = self.select.sourceClass.get(result[0],
|
|
777
|
+
selectResults=result[1:],
|
|
778
|
+
connection=self.dbconn)
|
|
779
|
+
return obj
|
|
780
|
+
|
|
781
|
+
def _cleanup(self):
|
|
782
|
+
if getattr(self, 'query', None) is None:
|
|
783
|
+
# already cleaned up
|
|
784
|
+
return
|
|
785
|
+
self.cursor.close()
|
|
786
|
+
if not self.keepConnection:
|
|
787
|
+
self.dbconn.releaseConnection(self.rawconn)
|
|
788
|
+
self.query = self.dbconn = self.rawconn = \
|
|
789
|
+
self.select = self.cursor = None
|
|
790
|
+
|
|
791
|
+
def __del__(self):
|
|
792
|
+
self._cleanup()
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
class Transaction(object):
|
|
796
|
+
|
|
797
|
+
def __init__(self, dbConnection):
|
|
798
|
+
# this is to skip __del__ in case of an exception in this __init__
|
|
799
|
+
self._obsolete = True
|
|
800
|
+
self._dbConnection = dbConnection
|
|
801
|
+
self._connection = dbConnection.getConnection()
|
|
802
|
+
self._dbConnection._setAutoCommit(self._connection, False)
|
|
803
|
+
self.cache = CacheSet(cache=dbConnection.doCache)
|
|
804
|
+
self._deletedCache = {}
|
|
805
|
+
self._obsolete = False
|
|
806
|
+
|
|
807
|
+
def assertActive(self):
|
|
808
|
+
assert not self._obsolete, \
|
|
809
|
+
"This transaction has already gone through ROLLBACK; " \
|
|
810
|
+
"begin another transaction"
|
|
811
|
+
|
|
812
|
+
def query(self, s):
|
|
813
|
+
self.assertActive()
|
|
814
|
+
return self._dbConnection._query(self._connection, s)
|
|
815
|
+
|
|
816
|
+
def queryAll(self, s):
|
|
817
|
+
self.assertActive()
|
|
818
|
+
return self._dbConnection._queryAll(self._connection, s)
|
|
819
|
+
|
|
820
|
+
def queryOne(self, s):
|
|
821
|
+
self.assertActive()
|
|
822
|
+
return self._dbConnection._queryOne(self._connection, s)
|
|
823
|
+
|
|
824
|
+
def queryInsertID(self, soInstance, id, names, values):
|
|
825
|
+
self.assertActive()
|
|
826
|
+
return self._dbConnection._queryInsertID(
|
|
827
|
+
self._connection, soInstance, id, names, values)
|
|
828
|
+
|
|
829
|
+
def iterSelect(self, select):
|
|
830
|
+
self.assertActive()
|
|
831
|
+
# We can't keep the cursor open with results in a transaction,
|
|
832
|
+
# because we might want to use the connection while we're
|
|
833
|
+
# still iterating through the results.
|
|
834
|
+
# @@: But would it be okay for psycopg, with threadsafety
|
|
835
|
+
# level 2?
|
|
836
|
+
return iter(list(select.IterationClass(self, self._connection,
|
|
837
|
+
select, keepConnection=True)))
|
|
838
|
+
|
|
839
|
+
def _SO_delete(self, inst):
|
|
840
|
+
cls = inst.__class__.__name__
|
|
841
|
+
if cls not in self._deletedCache:
|
|
842
|
+
self._deletedCache[cls] = []
|
|
843
|
+
self._deletedCache[cls].append(inst.id)
|
|
844
|
+
if PY2:
|
|
845
|
+
meth = types.MethodType(self._dbConnection._SO_delete.__func__,
|
|
846
|
+
self, self.__class__)
|
|
847
|
+
else:
|
|
848
|
+
meth = types.MethodType(self._dbConnection._SO_delete.__func__,
|
|
849
|
+
self)
|
|
850
|
+
return meth(inst)
|
|
851
|
+
|
|
852
|
+
def commit(self, close=False):
|
|
853
|
+
if self._obsolete:
|
|
854
|
+
# @@: is it okay to get extraneous commits?
|
|
855
|
+
return
|
|
856
|
+
if self._dbConnection.debug:
|
|
857
|
+
self._dbConnection.printDebug(self._connection, '', 'COMMIT')
|
|
858
|
+
self._send_event(CommitSignal)
|
|
859
|
+
self._connection.commit()
|
|
860
|
+
subCaches = [(sub[0], sub[1].allIDs())
|
|
861
|
+
for sub in self.cache.allSubCachesByClassNames().items()]
|
|
862
|
+
subCaches.extend([(x[0], x[1]) for x in self._deletedCache.items()])
|
|
863
|
+
for cls, ids in subCaches:
|
|
864
|
+
for id in list(ids):
|
|
865
|
+
inst = self._dbConnection.cache.tryGetByName(id, cls)
|
|
866
|
+
if inst is not None:
|
|
867
|
+
inst.expire()
|
|
868
|
+
if close:
|
|
869
|
+
self._makeObsolete()
|
|
870
|
+
|
|
871
|
+
def rollback(self):
|
|
872
|
+
if self._obsolete:
|
|
873
|
+
# @@: is it okay to get extraneous rollbacks?
|
|
874
|
+
return
|
|
875
|
+
if self._dbConnection.debug:
|
|
876
|
+
self._dbConnection.printDebug(self._connection, '', 'ROLLBACK')
|
|
877
|
+
subCaches = [(sub, sub.allIDs()) for sub in self.cache.allSubCaches()]
|
|
878
|
+
self._send_event(RollbackSignal)
|
|
879
|
+
self._connection.rollback()
|
|
880
|
+
|
|
881
|
+
for subCache, ids in subCaches:
|
|
882
|
+
for id in list(ids):
|
|
883
|
+
inst = subCache.tryGet(id)
|
|
884
|
+
if inst is not None:
|
|
885
|
+
inst.expire()
|
|
886
|
+
self._makeObsolete()
|
|
887
|
+
|
|
888
|
+
def _send_event(self, signal):
|
|
889
|
+
"""
|
|
890
|
+
Pushes a list of class_names and related ids in cache.
|
|
891
|
+
:param signal: Type of event signal to use
|
|
892
|
+
"""
|
|
893
|
+
cached_classes_and_ids = [
|
|
894
|
+
(class_name, cache.allIDs()) for class_name, cache in
|
|
895
|
+
self.cache.allSubCachesByClassNames().items()
|
|
896
|
+
]
|
|
897
|
+
|
|
898
|
+
if cached_classes_and_ids:
|
|
899
|
+
from .main import sqlmeta # Import here to avoid circular import
|
|
900
|
+
send(signal, sqlmeta, cached_classes_and_ids)
|
|
901
|
+
|
|
902
|
+
def __getattr__(self, attr):
|
|
903
|
+
"""
|
|
904
|
+
If nothing else works, let the parent connection handle it.
|
|
905
|
+
Except with this transaction as 'self'. Poor man's
|
|
906
|
+
acquisition? Bad programming? Okay, maybe.
|
|
907
|
+
"""
|
|
908
|
+
self.assertActive()
|
|
909
|
+
attr = getattr(self._dbConnection, attr)
|
|
910
|
+
try:
|
|
911
|
+
func = attr.__func__
|
|
912
|
+
except AttributeError:
|
|
913
|
+
if isinstance(attr, ConnWrapper):
|
|
914
|
+
return ConnWrapper(attr._soClass, self)
|
|
915
|
+
else:
|
|
916
|
+
return attr
|
|
917
|
+
else:
|
|
918
|
+
if PY2:
|
|
919
|
+
meth = types.MethodType(func, self, self.__class__)
|
|
920
|
+
else:
|
|
921
|
+
meth = types.MethodType(func, self)
|
|
922
|
+
return meth
|
|
923
|
+
|
|
924
|
+
def _makeObsolete(self):
|
|
925
|
+
self._obsolete = True
|
|
926
|
+
if self._dbConnection.autoCommit:
|
|
927
|
+
self._dbConnection._setAutoCommit(self._connection, True)
|
|
928
|
+
self._dbConnection.releaseConnection(self._connection,
|
|
929
|
+
explicit=True)
|
|
930
|
+
self._connection = None
|
|
931
|
+
self._deletedCache = {}
|
|
932
|
+
|
|
933
|
+
def begin(self):
|
|
934
|
+
# @@: Should we do this, or should begin() be a no-op when we're
|
|
935
|
+
# not already obsolete?
|
|
936
|
+
assert self._obsolete, \
|
|
937
|
+
"You cannot begin a new transaction session " \
|
|
938
|
+
"without rolling back this one"
|
|
939
|
+
self._obsolete = False
|
|
940
|
+
self._connection = self._dbConnection.getConnection()
|
|
941
|
+
self._dbConnection._setAutoCommit(self._connection, False)
|
|
942
|
+
|
|
943
|
+
def __del__(self):
|
|
944
|
+
if self._obsolete:
|
|
945
|
+
return
|
|
946
|
+
self.rollback()
|
|
947
|
+
|
|
948
|
+
def close(self):
|
|
949
|
+
raise TypeError('You cannot just close transaction - '
|
|
950
|
+
'you should either call rollback(), commit() '
|
|
951
|
+
'or commit(close=True) '
|
|
952
|
+
'to close the underlying connection.')
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
class ConnectionHub(object):
|
|
956
|
+
|
|
957
|
+
"""
|
|
958
|
+
This object serves as a hub for connections, so that you can pass
|
|
959
|
+
in a ConnectionHub to a SQLObject subclass as though it was a
|
|
960
|
+
connection, but actually bind a real database connection later.
|
|
961
|
+
You can also bind connections on a per-thread basis.
|
|
962
|
+
|
|
963
|
+
You must hang onto the original ConnectionHub instance, as you
|
|
964
|
+
cannot retrieve it again from the class or instance.
|
|
965
|
+
|
|
966
|
+
To use the hub, do something like::
|
|
967
|
+
|
|
968
|
+
hub = ConnectionHub()
|
|
969
|
+
class MyClass(SQLObject):
|
|
970
|
+
_connection = hub
|
|
971
|
+
|
|
972
|
+
hub.threadConnection = connectionFromURI('...')
|
|
973
|
+
|
|
974
|
+
"""
|
|
975
|
+
|
|
976
|
+
def __init__(self):
|
|
977
|
+
self.threadingLocal = threading_local()
|
|
978
|
+
|
|
979
|
+
def __get__(self, obj, type=None):
|
|
980
|
+
# I'm a little surprised we have to do this, but apparently
|
|
981
|
+
# the object's private dictionary of attributes doesn't
|
|
982
|
+
# override this descriptor.
|
|
983
|
+
if (obj is not None) and '_connection' in obj.__dict__:
|
|
984
|
+
return obj.__dict__['_connection']
|
|
985
|
+
return self.getConnection()
|
|
986
|
+
|
|
987
|
+
def __set__(self, obj, value):
|
|
988
|
+
obj.__dict__['_connection'] = value
|
|
989
|
+
|
|
990
|
+
def getConnection(self):
|
|
991
|
+
try:
|
|
992
|
+
connection = self.threadingLocal.connection
|
|
993
|
+
if isinstance(connection, string_type):
|
|
994
|
+
connection = connectionForURI(connection)
|
|
995
|
+
self.threadingLocal.connection = connection
|
|
996
|
+
except AttributeError:
|
|
997
|
+
try:
|
|
998
|
+
connection = self.processConnection
|
|
999
|
+
if isinstance(connection, string_type):
|
|
1000
|
+
connection = connectionForURI(connection)
|
|
1001
|
+
self.processConnection = connection
|
|
1002
|
+
except AttributeError:
|
|
1003
|
+
raise AttributeError(
|
|
1004
|
+
"No connection has been defined for this thread "
|
|
1005
|
+
"or process")
|
|
1006
|
+
return connection
|
|
1007
|
+
|
|
1008
|
+
def doInTransaction(self, func, *args, **kw):
|
|
1009
|
+
"""
|
|
1010
|
+
This routine can be used to run a function in a transaction,
|
|
1011
|
+
rolling the transaction back if any exception is raised from
|
|
1012
|
+
that function, and committing otherwise.
|
|
1013
|
+
|
|
1014
|
+
Use like::
|
|
1015
|
+
|
|
1016
|
+
sqlhub.doInTransaction(process_request, os.environ)
|
|
1017
|
+
|
|
1018
|
+
This will run ``process_request(os.environ)``. The return
|
|
1019
|
+
value will be preserved.
|
|
1020
|
+
"""
|
|
1021
|
+
# @@: In Python 2.5, something usable with with: should also
|
|
1022
|
+
# be added.
|
|
1023
|
+
try:
|
|
1024
|
+
old_conn = self.threadingLocal.connection
|
|
1025
|
+
old_conn_is_threading = True
|
|
1026
|
+
except AttributeError:
|
|
1027
|
+
old_conn = self.processConnection
|
|
1028
|
+
old_conn_is_threading = False
|
|
1029
|
+
if isinstance(old_conn, string_type):
|
|
1030
|
+
old_conn = connectionForURI(old_conn)
|
|
1031
|
+
conn = old_conn.transaction()
|
|
1032
|
+
if old_conn_is_threading:
|
|
1033
|
+
self.threadConnection = conn
|
|
1034
|
+
else:
|
|
1035
|
+
self.processConnection = conn
|
|
1036
|
+
try:
|
|
1037
|
+
try:
|
|
1038
|
+
value = func(*args, **kw)
|
|
1039
|
+
except Exception:
|
|
1040
|
+
conn.rollback()
|
|
1041
|
+
raise
|
|
1042
|
+
else:
|
|
1043
|
+
conn.commit(close=True)
|
|
1044
|
+
return value
|
|
1045
|
+
finally:
|
|
1046
|
+
if old_conn_is_threading:
|
|
1047
|
+
self.threadConnection = old_conn
|
|
1048
|
+
else:
|
|
1049
|
+
self.processConnection = old_conn
|
|
1050
|
+
|
|
1051
|
+
def _set_threadConnection(self, value):
|
|
1052
|
+
self.threadingLocal.connection = value
|
|
1053
|
+
|
|
1054
|
+
def _get_threadConnection(self):
|
|
1055
|
+
return self.threadingLocal.connection
|
|
1056
|
+
|
|
1057
|
+
def _del_threadConnection(self):
|
|
1058
|
+
del self.threadingLocal.connection
|
|
1059
|
+
|
|
1060
|
+
threadConnection = property(_get_threadConnection,
|
|
1061
|
+
_set_threadConnection,
|
|
1062
|
+
_del_threadConnection)
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
class ConnectionURIOpener(object):
|
|
1066
|
+
|
|
1067
|
+
def __init__(self):
|
|
1068
|
+
self.schemeBuilders = {}
|
|
1069
|
+
self.instanceNames = {}
|
|
1070
|
+
self.cachedURIs = {}
|
|
1071
|
+
|
|
1072
|
+
def registerConnection(self, schemes, builder):
|
|
1073
|
+
for uriScheme in schemes:
|
|
1074
|
+
assert uriScheme not in self.schemeBuilders \
|
|
1075
|
+
or self.schemeBuilders[uriScheme] is builder, \
|
|
1076
|
+
"A driver has already been registered " \
|
|
1077
|
+
"for the URI scheme %s" % uriScheme
|
|
1078
|
+
self.schemeBuilders[uriScheme] = builder
|
|
1079
|
+
|
|
1080
|
+
def registerConnectionInstance(self, inst):
|
|
1081
|
+
if inst.name:
|
|
1082
|
+
assert (inst.name not in self.instanceNames
|
|
1083
|
+
or self.instanceNames[inst.name] is self.__class__
|
|
1084
|
+
), ("An instance has already been registered "
|
|
1085
|
+
"with the name %s" % inst.name)
|
|
1086
|
+
assert inst.name.find(':') == -1, \
|
|
1087
|
+
"You cannot include ':' " \
|
|
1088
|
+
"in your DB connection names (%r)" % inst.name
|
|
1089
|
+
self.instanceNames[inst.name] = inst
|
|
1090
|
+
|
|
1091
|
+
def connectionForURI(self, uri, oldUri=False, **args):
|
|
1092
|
+
if args:
|
|
1093
|
+
if '?' not in uri:
|
|
1094
|
+
uri += '?' + urlencode(args)
|
|
1095
|
+
else:
|
|
1096
|
+
uri += '&' + urlencode(args)
|
|
1097
|
+
if uri in self.cachedURIs:
|
|
1098
|
+
return self.cachedURIs[uri]
|
|
1099
|
+
if uri.find(':') != -1:
|
|
1100
|
+
scheme, rest = uri.split(':', 1)
|
|
1101
|
+
connCls = self.dbConnectionForScheme(scheme)
|
|
1102
|
+
if oldUri:
|
|
1103
|
+
conn = connCls.connectionFromOldURI(uri)
|
|
1104
|
+
else:
|
|
1105
|
+
conn = connCls.connectionFromURI(uri)
|
|
1106
|
+
else:
|
|
1107
|
+
# We just have a name, not a URI
|
|
1108
|
+
assert uri in self.instanceNames, \
|
|
1109
|
+
"No SQLObject driver exists under the name %s" % uri
|
|
1110
|
+
conn = self.instanceNames[uri]
|
|
1111
|
+
# @@: Do we care if we clobber another connection?
|
|
1112
|
+
self.cachedURIs[uri] = conn
|
|
1113
|
+
return conn
|
|
1114
|
+
|
|
1115
|
+
def dbConnectionForScheme(self, scheme):
|
|
1116
|
+
assert scheme in self.schemeBuilders, (
|
|
1117
|
+
"No SQLObject driver exists for %s (only %s)" % (
|
|
1118
|
+
scheme,
|
|
1119
|
+
', '.join(self.schemeBuilders.keys())))
|
|
1120
|
+
return self.schemeBuilders[scheme]()
|
|
1121
|
+
|
|
1122
|
+
TheURIOpener = ConnectionURIOpener()
|
|
1123
|
+
|
|
1124
|
+
registerConnection = TheURIOpener.registerConnection
|
|
1125
|
+
registerConnectionInstance = TheURIOpener.registerConnectionInstance
|
|
1126
|
+
connectionForURI = TheURIOpener.connectionForURI
|
|
1127
|
+
dbConnectionForScheme = TheURIOpener.dbConnectionForScheme
|
|
1128
|
+
|
|
1129
|
+
# Register DB URI schemas -- do import for side effects
|
|
1130
|
+
# noqa is a directive for flake8 to ignore seemingly unused imports
|
|
1131
|
+
from . import firebird # noqa
|
|
1132
|
+
from . import maxdb # noqa
|
|
1133
|
+
from . import mssql # noqa
|
|
1134
|
+
from . import mysql # noqa
|
|
1135
|
+
from . import postgres # noqa
|
|
1136
|
+
from . import sqlite # noqa
|
|
1137
|
+
from . import sybase # noqa
|