Recolored the cropped Kecleon purple. :3
[zzz-pokedex.git] / pokedex / db / __init__.py
1 from sqlalchemy import MetaData, Table, create_engine, orm
2
3 from .tables import metadata
4
5 def connect(uri, **kwargs):
6 """Connects to the requested URI. Returns a session object.
7
8 Calling this function also binds the metadata object to the created engine.
9 """
10
11 ### Do some fixery for MySQL
12 if uri[0:5] == 'mysql':
13 # MySQL uses latin1 for connections by default even if the server is
14 # otherwise oozing with utf8; charset fixes this
15 if 'charset' not in uri:
16 uri += '?charset=utf8'
17
18 # Tables should be InnoDB, in the event that we're creating them, and
19 # use UTF-8 goddammit!
20 for table in metadata.tables.values():
21 table.kwargs['mysql_engine'] = 'InnoDB'
22 table.kwargs['mysql_charset'] = 'utf8'
23
24 ### Connect
25 engine = create_engine(uri)
26 conn = engine.connect()
27 metadata.bind = engine
28
29 session_args = dict(autoflush=True, autocommit=False, bind=engine)
30 session_args.update(kwargs)
31 sm = orm.sessionmaker(**session_args)
32 session = orm.scoped_session(sm)
33
34 return session