Added HG/SS egg and level moves. (Thanks, Arty2)
[zzz-pokedex.git] / pokedex / db / __init__.py
1 import pkg_resources
2
3 from sqlalchemy import MetaData, Table, create_engine, orm
4
5 from .tables import metadata
6
7 def connect(uri=None, **kwargs):
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 # Default to a URI within the package, which was hopefully created at some point
17 if not uri:
18 sqlite_path = pkg_resources.resource_filename('pokedex',
19 'data/pokedex.sqlite')
20 uri = 'sqlite:///' + sqlite_path
21
22 ### Do some fixery for MySQL
23 if uri[0:5] == 'mysql':
24 # MySQL uses latin1 for connections by default even if the server is
25 # otherwise oozing with utf8; charset fixes this
26 if 'charset' not in uri:
27 uri += '?charset=utf8'
28
29 # Tables should be InnoDB, in the event that we're creating them, and
30 # use UTF-8 goddammit!
31 for table in metadata.tables.values():
32 table.kwargs['mysql_engine'] = 'InnoDB'
33 table.kwargs['mysql_charset'] = 'utf8'
34
35 ### Connect
36 engine = create_engine(uri)
37 conn = engine.connect()
38 metadata.bind = engine
39
40 session_args = dict(autoflush=True, autocommit=False, bind=engine)
41 session_args.update(kwargs)
42 sm = orm.sessionmaker(**session_args)
43 session = orm.scoped_session(sm)
44
45 return session