1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 from sqlalchemy
import create_engine
, event
21 from mediagoblin
.db
.base
import Base
, Session
22 from mediagoblin
import mg_globals
24 _log
= logging
.getLogger(__name__
)
27 class DatabaseMaster(object):
28 def __init__(self
, engine
):
31 for k
, v
in Base
._decl
_class
_registry
.iteritems():
41 def check_session_clean(self
):
42 for dummy
in Session():
43 _log
.warn("STRANGE: There are elements in the sql session. "
44 "Please report this and help us track this down.")
47 def reset_after_request(self
):
52 def load_models(app_config
):
53 import mediagoblin
.db
.models
55 for plugin
in mg_globals
.global_config
.get('plugins', {}).keys():
56 _log
.debug("Loading %s.models", plugin
)
58 __import__(plugin
+ ".models")
59 except ImportError as exc
:
60 _log
.debug("Could not load {0}.models: {1}".format(
65 def _sqlite_fk_pragma_on_connect(dbapi_con
, con_record
):
66 """Enable foreign key checking on each new sqlite connection"""
67 dbapi_con
.execute('pragma foreign_keys=on')
70 def _sqlite_disable_fk_pragma_on_connect(dbapi_con
, con_record
):
72 Disable foreign key checking on each new sqlite connection
73 (Good for migrations!)
75 dbapi_con
.execute('pragma foreign_keys=off')
78 def setup_connection_and_db_from_config(app_config
, migrations
=False):
79 engine
= create_engine(app_config
['sql_engine'])
81 # Enable foreign key checking for sqlite
82 if app_config
['sql_engine'].startswith('sqlite://'):
84 event
.listen(engine
, 'connect',
85 _sqlite_disable_fk_pragma_on_connect
)
87 event
.listen(engine
, 'connect', _sqlite_fk_pragma_on_connect
)
89 # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
91 Session
.configure(bind
=engine
)
93 return DatabaseMaster(engine
)
96 def check_db_migrations_current(db
):