Re-rip G/S/C egg moves.
[zzz-pokedex.git] / pokedex / db / __init__.py
1 from sqlalchemy import MetaData, Table, create_engine, orm
2
3 from ..defaults import get_default_db_uri
4 from .tables import metadata
5
6
7 def connect(uri=None, session_args={}, engine_args={}):
8 """Connects to the requested URI. Returns a session object.
9
10 With the URI omitted, attempts to connect to a default SQLite database
11 contained within the package directory.
12
13 Calling this function also binds the metadata object to the created engine.
14 """
15
16 # If we didn't get a uri, fall back to the default
17 if uri is None:
18 uri = get_default_db_uri()
19
20 ### Do some fixery for MySQL
21 if uri[0:5] == 'mysql':
22 # MySQL uses latin1 for connections by default even if the server is
23 # otherwise oozing with utf8; charset fixes this
24 if 'charset' not in uri:
25 uri += '?charset=utf8'
26
27 # Tables should be InnoDB, in the event that we're creating them, and
28 # use UTF-8 goddammit!
29 for table in metadata.tables.values():
30 table.kwargs['mysql_engine'] = 'InnoDB'
31 table.kwargs['mysql_charset'] = 'utf8'
32
33 ### Connect
34 engine = create_engine(uri, **engine_args)
35 conn = engine.connect()
36 metadata.bind = engine
37
38 all_session_args = dict(autoflush=True, autocommit=False, bind=engine)
39 all_session_args.update(session_args)
40 sm = orm.sessionmaker(**all_session_args)
41 session = orm.scoped_session(sm)
42
43 return session