#$Id: example1.py 262 2008-05-12 15:06:27Z svilen_dobrev $
# -*- coding: cp1251 -*-

# get a builder
import dbcook.usage.plainwrap as o2r

# define some types
class Text( o2r.Type): pass
class Int(  o2r.Type): pass

Base = o2r.Base

####### start actual model-definition

class GenProduct( Base):
    DBCOOK_inheritance = 'joined'   #for subclasses - this(base) one is always concrete anyway
    name    = Text()
    price   = Int()
    DBCOOK_has_instances = True     #by default only class-tree leaves have instances

class ElProduct( GenProduct):
    voltage = Int()

class FoodProduct( GenProduct):
    calories = Int()

####### endof model-definition


import sys
import sqlalchemy
import sqlalchemy.orm
meta = sqlalchemy.MetaData( sqlalchemy.create_engine('sqlite:///', echo= 'echo' in sys.argv ))

# map attr-types to sql-column-types
fieldtypemap = {
    Text: dict( type= sqlalchemy.String(100), ),
    Int : dict( type= sqlalchemy.Integer, ),
}

# build the mapping
mybuild = o2r.Builder( meta,
        locals(),       #just scan anything here that looks like subclass of Base
        fieldtypemap,
        generator =True     #lets see how this would look in plain sqlalchemy
    )

#### that was it. lets use it... ####

#see how this should look in plain SA calls
if mybuild.generator:
    print '========= generated SA set-up'
    print mybuild.generator.out
    print '========= eo generated SA set-up'


def populate():
    #...
    session = sqlalchemy.orm.create_session()
    #anything off Base, go to db
    for a in locals().values():
        if isinstance( a, Base): session.save( a)
    session.flush()

# vim:ts=4:sw=4:expandtab
