Initial commit from Paster template
[xonotic/xonstat.git] / xonstat / models.py
1 import transaction
2
3 from sqlalchemy import Column
4 from sqlalchemy import Integer
5 from sqlalchemy import Unicode
6
7 from sqlalchemy.exc import IntegrityError
8 from sqlalchemy.ext.declarative import declarative_base
9
10 from sqlalchemy.orm import scoped_session
11 from sqlalchemy.orm import sessionmaker
12
13 from zope.sqlalchemy import ZopeTransactionExtension
14
15 DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
16 Base = declarative_base()
17
18 class MyModel(Base):
19     __tablename__ = 'models'
20     id = Column(Integer, primary_key=True)
21     name = Column(Unicode(255), unique=True)
22     value = Column(Integer)
23
24     def __init__(self, name, value):
25         self.name = name
26         self.value = value
27
28 def populate():
29     session = DBSession()
30     model = MyModel(name=u'root', value=55)
31     session.add(model)
32     session.flush()
33     transaction.commit()
34     
35 def initialize_sql(engine):
36     DBSession.configure(bind=engine)
37     Base.metadata.bind = engine
38     Base.metadata.create_all(engine)
39     try:
40         populate()
41     except IntegrityError:
42         DBSession.rollback()