forked from pallets-eco/flask-sqlalchemy
/
sqlalchemy.py
635 lines (514 loc) · 21.9 KB
/
sqlalchemy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# -*- coding: utf-8 -*-
"""
flaskext.sqlalchemy
~~~~~~~~~~~~~~~~~~~
Adds basic SQLAlchemy support to your application.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement, absolute_import
import re
import sys
import time
import sqlalchemy
from math import ceil
from functools import partial
from flask import _request_ctx_stack, abort
from flask.signals import Namespace
from operator import itemgetter
from threading import Lock
from sqlalchemy import orm
from sqlalchemy.orm.exc import UnmappedClassError
from sqlalchemy.orm.mapper import Mapper
from sqlalchemy.orm.session import Session
from sqlalchemy.orm.interfaces import MapperExtension, SessionExtension, \
EXT_CONTINUE
from sqlalchemy.interfaces import ConnectionProxy
from sqlalchemy.engine.url import make_url
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.util import to_list
# the best timer function for the platform
if sys.platform == 'win32':
_timer = time.clock
else:
_timer = time.time
_camelcase_re = re.compile(r'([A-Z]+)(?=[a-z0-9])')
_signals = Namespace()
models_committed = _signals.signal('models-committed')
before_models_committed = _signals.signal('before-models-committed')
def _create_scoped_session(db, options):
if options is None:
options = {}
return orm.scoped_session(partial(_SignallingSession, db, **options))
def _make_table(db):
def _make_table(*args, **kwargs):
if len(args) > 1 and isinstance(args[1], db.Column):
args = (args[0], db.metadata) + args[1:]
return sqlalchemy.Table(*args, **kwargs)
return _make_table
def _include_sqlalchemy(obj):
for module in sqlalchemy, sqlalchemy.orm:
for key in module.__all__:
if not hasattr(obj, key):
setattr(obj, key, getattr(module, key))
obj.Table = _make_table(obj)
class _DebugQueryTuple(tuple):
statement = property(itemgetter(0))
parameters = property(itemgetter(1))
start_time = property(itemgetter(2))
end_time = property(itemgetter(3))
context = property(itemgetter(4))
@property
def duration(self):
return self.end_time - self.start_time
def __repr__(self):
return '<query statement="%s" parameters=%r duration=%.03f>' % (
self.statement,
self.parameters,
self.duration
)
def _calling_context(app_path):
frm = sys._getframe(1)
while frm.f_back is not None:
name = frm.f_globals.get('__name__')
if name and (name == app_path or name.startswith(app_path + '.')):
funcname = frm.f_code.co_name
return '%s:%s (%s)' % (
frm.f_code.co_filename,
frm.f_lineno,
funcname
)
frm = frm.f_back
return '<unknown>'
class _ConnectionDebugProxy(ConnectionProxy):
"""Helps debugging the database."""
def __init__(self, import_name):
self.app_package = import_name
def cursor_execute(self, execute, cursor, statement, parameters,
context, executemany):
start = _timer()
try:
return execute(cursor, statement, parameters, context)
finally:
ctx = _request_ctx_stack.top
if ctx is not None:
queries = getattr(ctx, 'sqlalchemy_queries', None)
if queries is None:
queries = []
setattr(ctx, 'sqlalchemy_queries', queries)
queries.append(_DebugQueryTuple((
statement, parameters, start, _timer(),
_calling_context(self.app_package))))
class _SignalTrackingMapperExtension(MapperExtension):
def after_delete(self, mapper, connection, instance):
return self._record(mapper, instance, 'delete')
def after_insert(self, mapper, connection, instance):
return self._record(mapper, instance, 'insert')
def after_update(self, mapper, connection, instance):
return self._record(mapper, instance, 'update')
def _record(self, mapper, model, operation):
pk = tuple(mapper.primary_key_from_instance(model))
orm.object_session(model)._model_changes[pk] = (model, operation)
return EXT_CONTINUE
class _SignalTrackingMapper(Mapper):
def __init__(self, *args, **kwargs):
extensions = to_list(kwargs.pop('extension', None), [])
extensions.append(_SignalTrackingMapperExtension())
kwargs['extension'] = extensions
Mapper.__init__(self, *args, **kwargs)
class _SignallingSessionExtension(SessionExtension):
def before_commit(self, session):
d = session._model_changes
if d:
before_models_committed.send(session.app, changes=d.values())
return EXT_CONTINUE
def after_commit(self, session):
d = session._model_changes
if d:
models_committed.send(session.app, changes=d.values())
d.clear()
return EXT_CONTINUE
def after_rollback(self, session):
session._model_changes.clear()
return EXT_CONTINUE
class _SignallingSession(Session):
def __init__(self, db, autocommit=False, autoflush=False, **options):
Session.__init__(self, autocommit=autocommit, autoflush=autoflush,
extension=db.session_extensions,
bind=db.engine, **options)
self.app = db.app or _request_ctx_stack.top.app
self._model_changes = {}
def get_debug_queries():
"""In debug mode Flask-SQLAlchemy will log all the SQL queries sent
to the database. This information is available until the end of request
which makes it possible to easily ensure that the SQL generated is the
one expected on errors or in unittesting. If you don't want to enable
the DEBUG mode for your unittests you can also enable the query
recording by setting the ``'SQLALCHEMY_RECORD_QUERIES'`` config variable
to `True`. This is automatically enabled if Flask is in testing mode.
The value returned will be a list of named tuples with the following
attributes:
`statement`
The SQL statement issued
`parameters`
The parameters for the SQL statement
`start_time` / `end_time`
Time the query started / the results arrived. Please keep in mind
that the timer function used depends on your platform. These
values are only useful for sorting or comparing. They do not
necessarily represent an absolute timestamp.
`duration`
Time the query took in seconds
`context`
A string giving a rough estimation of where in your application
query was issued. The exact format is undefined so don't try
to reconstruct filename or function name.
"""
return getattr(_request_ctx_stack.top, 'sqlalchemy_queries', [])
class Pagination(object):
"""Internal helper class returned by :meth:`BaseQuery.paginate`. You
can also construct it from any other SQLAlchemy query object if you are
working with other libraries. Additionally it is possible to pass `None`
as query object in which case the :meth:`prev` and :meth:`next` will
no longer work.
"""
def __init__(self, query, page, per_page, total, items):
#: the unlimited query object that was used to create this
#: pagination object.
self.query = query
#: the current page number (1 indexed)
self.page = page
#: the number of items to be displayed on a page.
self.per_page = per_page
#: the total number of items matching the query
self.total = total
#: the items for the current page
self.items = items
@property
def pages(self):
"""The total number of pages"""
return int(ceil(self.total / float(self.per_page)))
def prev(self, error_out=False):
"""Returns a :class:`Pagination` object for the previous page."""
assert self.query is not None, 'a query object is required ' \
'for this method to work'
return self.query.paginate(self.page - 1, self.per_page, error_out)
@property
def prev_num(self):
"""Number of the previous page."""
return self.page - 1
@property
def has_prev(self):
"""True if a previous page exists"""
return self.page > 1
def next(self, error_out=False):
"""Returns a :class:`Pagination` object for the next page."""
assert self.query is not None, 'a query object is required ' \
'for this method to work'
return self.query.paginate(self.page + 1, self.per_page, error_out)
@property
def has_next(self):
"""True if a next page exists."""
return self.page < self.pages
@property
def next_num(self):
"""Number of the next page"""
return self.page + 1
def iter_pages(self, left_edge=2, left_current=2,
right_current=5, right_edge=2):
"""Iterates over the page numbers in the pagination. The four
parameters control the thresholds how many numbers should be produced
from the sides. Skipped page numbers are represented as `None`.
This is how you could render such a pagination in the templates:
.. sourcecode:: html+jinja
{% macro render_pagination(pagination, endpoint) %}
<div class=pagination>
{%- for page in pagination.iter_pages() %}
{% if page %}
{% if page != pagination.page %}
<a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a>
{% else %}
<strong>{{ page }}</strong>
{% endif %}
{% else %}
<span class=ellipsis>…</span>
{% endif %}
{%- endfor %}
</div>
{% endmacro %}
"""
last = 0
for num in xrange(1, self.pages + 1):
if num <= left_edge or \
(num > self.page - left_current - 1 and \
num < self.page + right_current) or \
num > self.pages - right_edge:
if last + 1 != num:
yield None
yield num
last = num
class BaseQuery(orm.Query):
"""The default query object used for models. This can be subclassed and
replaced for individual models by setting the :attr:`~Model.query_class`
attribute. This is a subclass of a standard SQLAlchemy
:class:`~sqlalchemy.orm.query.Query` class and has all the methods of a
standard query as well.
"""
def get_or_404(self, ident):
"""Like :meth:`get` but aborts with 404 if not found instead of
returning `None`.
"""
rv = self.get(ident)
if rv is None:
abort(404)
return rv
def first_or_404(self):
"""Like :meth:`first` but aborts with 404 if not found instead of
returning `None`.
"""
rv = self.first()
if rv is None:
abort(404)
return rv
def paginate(self, page, per_page=20, error_out=True):
"""Returns `per_page` items from page `page`. By default it will
abort with 404 if no items were found and the page was larger than
1. This behavor can be disabled by setting `error_out` to `False`.
Returns an :class:`Pagination` object.
"""
if error_out and page < 1:
abort(404)
items = self.limit(per_page).offset((page - 1) * per_page).all()
if not items and page != 1 and error_out:
abort(404)
return Pagination(self, page, per_page, self.count(), items)
class _QueryProperty(object):
def __init__(self, sa):
self.sa = sa
def __get__(self, obj, type):
try:
mapper = orm.class_mapper(type)
if mapper:
return type.query_class(mapper, session=self.sa.session())
except UnmappedClassError:
return None
def _record_queries(app):
if app.debug:
return True
rq = app.config['SQLALCHEMY_RECORD_QUERIES']
if rq is not None:
return rq
return bool(app.config.get('TESTING'))
class _EngineConnector(object):
def __init__(self, sa, app):
self._sa = sa
self._app = app
self._engine = None
self._connected_for = None
self._lock = Lock()
def get_engine(self):
with self._lock:
uri = self._app.config['SQLALCHEMY_DATABASE_URI']
echo = self._app.config['SQLALCHEMY_ECHO']
if (uri, echo) == self._connected_for:
return self._engine
info = make_url(uri)
options = {'convert_unicode': True}
self._sa.apply_pool_defaults(self._app, options)
self._sa.apply_driver_hacks(self._app, info, options)
if _record_queries(self._app):
options['proxy'] = _ConnectionDebugProxy(self._app.import_name)
if echo:
options['echo'] = True
self._engine = rv = sqlalchemy.create_engine(info, **options)
self._connected_for = (uri, echo)
return rv
class _ModelTableNameDescriptor(object):
def __get__(self, obj, type):
tablename = type.__dict__.get('__tablename__')
if not tablename:
def _join(match):
word = match.group()
if len(word) > 1:
return ('_%s_%s' % (word[:-1], word[-1])).lower()
return '_' + word.lower()
tablename = _camelcase_re.sub(_join, type.__name__).lstrip('_')
setattr(type, '__tablename__', tablename)
return tablename
class Model(object):
"""Baseclass for custom user models."""
#: the query class used. The :attr:`query` attribute is an instance
#: of this class. By default a :class:`BaseQuery` is used.
query_class = BaseQuery
#: an instance of :attr:`query_class`. Can be used to query the
#: database for instances of this model.
query = None
#: arguments for the mapper
__mapper_cls__ = _SignalTrackingMapper
__tablename__ = _ModelTableNameDescriptor()
class SQLAlchemy(object):
"""This class is used to control the SQLAlchemy integration to one
or more Flask applications. Depending on how you initialize the
object it is usable right away or will attach as needed to a
Flask application.
There are two usage modes which work very similar. One is binding
the instance to a very specific Flask application::
app = Flask(__name__)
db = SQLAlchemy(app)
The second possibility is to create the object once and configure the
application later to support it::
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
db.init_app(app)
return app
The difference between the two is that in the first case methods like
:meth:`create_all` and :meth:`drop_all` will work all the time but in
the second case a :meth:`flask.Flask.request_context` has to exist.
By default Flask-SQLAlchemy will apply some backend-specific settings
to improve your experience with them. As of SQLAlchemy 0.6 SQLAlchemy
will probe the library for native unicode support. If it detects
unicode it will let the library handle that, otherwise do that itself.
Sometimes this detection can fail in which case you might want to set
`use_native_unicode` (or the ``SQLALCHEMY_NATIVE_UNICODE`` configuration
key) to `False`. Note that the configuration key overrides the
value you pass to the constructor.
Additionally this class also provides access to all the SQLAlchemy
functions from the :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` modules.
So you can declare models like this::
class User(db.Model):
username = db.Column(db.String(80), unique=True)
pw_hash = db.Column(db.String(80))
You may also define your own SessionExtension instances as well when
defining your SQLAlchemy class instance. You may pass your custom instances
to the `session_extensions` keyword. This can be either a single
SessionExtension instance, or a list of SessionExtension instances. In the
following use case we use the VersionedListener from the SQLAlchemy
versioning examples.::
from history_meta import VersionedMeta, VersionedListener
app = Flask(__name__)
db = SQLAlchemy(app, session_extensions=[VersionedListener()])
class User(db.Model):
__metaclass__ = VersionedMeta
username = db.Column(db.String(80), unique=True)
pw_hash = db.Column(db.String(80))
The `session_options` parameter can be used to override session
options. If provided it's a dict of parameters passed to the
session's constructor.
.. versionadded:: 0.10
The `session_options` parameter was added.
"""
def __init__(self, app=None, use_native_unicode=True,
session_extensions=None, session_options=None):
self.use_native_unicode = use_native_unicode
self.session_extensions = to_list(session_extensions, []) + \
[_SignallingSessionExtension()]
self.session = _create_scoped_session(self, session_options)
self.Model = declarative_base(cls=Model, name='Model')
self.Model.query = _QueryProperty(self)
self._engine_lock = Lock()
if app is not None:
self.app = app
self.init_app(app)
else:
self.app = None
_include_sqlalchemy(self)
@property
def metadata(self):
"""Returns the metadata"""
return self.Model.metadata
def init_app(self, app):
"""This callback can be used to initialize an application for the
use with this database setup. Never use a database in the context
of an application not initialized that way or connections will
leak.
"""
app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite://')
app.config.setdefault('SQLALCHEMY_NATIVE_UNICODE', None)
app.config.setdefault('SQLALCHEMY_ECHO', False)
app.config.setdefault('SQLALCHEMY_RECORD_QUERIES', None)
app.config.setdefault('SQLALCHEMY_POOL_SIZE', None)
app.config.setdefault('SQLALCHEMY_POOL_TIMEOUT', None)
app.config.setdefault('SQLALCHEMY_POOL_RECYCLE', None)
@app.after_request
def shutdown_session(response):
self.session.remove()
return response
def apply_pool_defaults(self, app, options):
def _setdefault(optionkey, configkey):
value = app.config[configkey]
if value is not None:
options[optionkey] = value
_setdefault('pool_size', 'SQLALCHEMY_POOL_SIZE')
_setdefault('pool_timeout', 'SQLALCHEMY_POOL_TIMEOUT')
_setdefault('pool_recycle', 'SQLALCHEMY_POOL_RECYCLE')
def apply_driver_hacks(self, app, info, options):
if info.drivername == 'mysql':
info.query.setdefault('charset', 'utf8')
options.setdefault('pool_size', 10)
options.setdefault('pool_recycle', 7200)
elif info.drivername == 'sqlite':
pool_size = options.get('pool_size')
# we go to memory and the pool size was explicitly set to 0
# which is fail. Let the user know that
if info.database in (None, '', ':memory:'):
if pool_size == 0:
raise RuntimeError('SQLite in memory database with an '
'empty queue not possible due to data '
'loss.')
# if pool size is None or explicitly set to 0 we assume the
# user did not want a queue for this sqlite connection and
# hook in the null pool.
elif not pool_size:
from sqlalchemy.pool import NullPool
options['poolclass'] = NullPool
unu = app.config['SQLALCHEMY_NATIVE_UNICODE']
if unu is None:
unu = self.use_native_unicode
if not unu:
options['use_native_unicode'] = False
@property
def engine(self):
"""Gives access to the engine. If the database configuration is bound
to a specific application (initialized with an application) this will
always return a database connection. If however the current application
is used this might raise a :exc:`RuntimeError` if no application is
active at the moment.
"""
with self._engine_lock:
if self.app is not None:
app = self.app
else:
ctx = _request_ctx_stack.top
if ctx is not None:
app = ctx.app
else:
raise RuntimeError('application not registered on db '
'instance and no application bound '
'to current context')
connector = getattr(app, '_sqlalchemy_connector', None)
if connector is None:
connector = _EngineConnector(self, app)
app._sqlalchemy_connector = connector
return connector.get_engine()
def create_all(self):
"""Creates all tables."""
self.Model.metadata.create_all(bind=self.engine)
def drop_all(self):
"""Drops all tables."""
self.Model.metadata.drop_all(bind=self.engine)
def reflect(self):
"""Reflects tables from the database."""
self.Model.metadata.reflect(bind=self.engine)
def __repr__(self):
app = None
if self.app is not None:
app = self.app
else:
ctx = _request_ctx_stack.top
if ctx is not None:
app = ctx.app
return '<%s engine=%r>' % (
self.__class__.__name__,
app and app.config['SQLALCHEMY_DATABASE_URI'] or None
)