Added SQLAlchemy to setup.py and fixed a typo in .gitignore.
[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):
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
19 for table in metadata.tables.values():
20 table.kwargs['mysql_engine'] = 'InnoDB'
21
22 ### Connect
23 engine = create_engine(uri)
24 conn = engine.connect()
25 metadata.bind = engine
26
27 sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine)
28 session = orm.scoped_session(sm)
29
30 return session