traits-sqlalchemy provides utilities for mapping HasTraits classes to a relational database using
SQLAlchemy. This example demonstrates using traits-sqlalchemy to create a simple, one-table mapping with a HasDBTraits
class.
In [163]:
import sqlalchemy as sql
from sqlalchemy import orm
import traitsql as tsql
from traits.api import TraitError
In [164]:
metadata = sql.MetaData()
foo = sql.Table('foo', metadata,
sql.Column('id', sql.Integer, primary_key=True),
sql.Column('int', sql.Integer),
sql.Column('float', sql.Float),
sql.Column('string', sql.String(16), unique = True))
In [152]:
class Foo(tsql.HasDBTraits):
id = tsql.DBIntKey
int = tsql.DBInt
float = tsql.DBFloat
string = tsql.DBStr
def __repr__(self):
return 'Foo(id=%i, int=%i, float=%f, string=%s)'%(
self.id, self.int, self.float, self.string)
In [153]:
orm.mapper(Foo, foo)
Out[153]:
In [154]:
db = sql.create_engine('sqlite:///:memory:')
metadata.bind = db
metadata.create_all()
conn = db.connect()
session = orm.sessionmaker()()
In [155]:
session.add(Foo(int=10, float=20.0, string='foo'))
session.commit()
foo = session.query(Foo).first()
foo
Out[155]:
In [156]:
try:
foo.int ='int'
except(TraitError) as e:
print(e)
In [157]:
foo.int = 12
session.commit()
session.query(Foo).first()
Out[157]:
In [158]:
session.add(Foo(int=11, float=20.0, string='dank'))
session.add(Foo(int=12, float=40.0, string='stank'))
session.add(Foo(int=13, float=30.0, string='wank'))
session.add(Foo(int=14, float=10.0, string='pank'))
session.commit()
In [159]:
q = session.query(Foo)
q.all()
Out[159]:
In [160]:
session.add(Foo(int=14, float=10.0, string='pank'))
try:
session.commit()
except(sql.exc.IntegrityError) as e:
print(e)
In [161]:
conn.close()
metadata.bind = None