import elixir from elixir import Field, ManyToOne, OneToMany, OneToOne, ColumnProperty, using_options, using_options_defaults from sqlalchemy import types as T from sqlalchemy import sql from functools import partial from collections import namedtuple __all__ = ["Category", "SingleExpense", "ConstExpense", "CatExpense", "MonthExpense", "session"] # # DB Setup # elixir.metadata.bind = "sqlite:///test.sqlite" elixir.metadata.bind.echo = True # # Global definitions # ReqField = partial(Field, required = True) ExpNum = T.Numeric(scale = 2, precision = 10) class Entity (elixir.Entity): using_options(abstract = True) using_options_defaults(shortnames = True) # # Database Entities # class Category (Entity): name = Field(T.String(50), unique = True) parent = ManyToOne('Category') children = OneToMany('Category') def __repr__ (self): if self.parent: return '' % (self.name, self.parent.name) else: return '' % self.name class Expense (Entity): using_options(abstract = True) description = Field(T.String(50)) expense = ReqField(ExpNum) category = ManyToOne('Category', required = True, innerjoin = True) class SingleExpense (Expense): year = ReqField(T.Integer) month = ReqField(T.SmallInteger) day = ReqField(T.SmallInteger) @classmethod def of_month (cls, month, year): comp = sql.and_( cls.month == month, cls.year == year) return cls.query.filter(comp) class ConstExpense (Expense): months = ReqField(T.SmallInteger) start_year = ReqField(T.Integer) start_month = ReqField(T.SmallInteger) end_year = ReqField(T.Integer) end_month = ReqField(T.SmallInteger) next = OneToOne('ConstExpense', inverse = 'prev') prev = ManyToOne('ConstExpense') monthly = ColumnProperty(lambda c: sql.cast(c.expense / c.months, ExpNum), deferred = True) @classmethod def of_month (cls, month, year): c1 = sql.or_( cls.start_year < year, sql.and_( cls.start_year == year, cls.start_month <= month )) c2 = sql.or_( cls.end_year > year, sql.and_( cls.end_year == year, cls.end_month >= month )) return cls.query.filter(sql.and_(c1,c2)) # # Work entities (not stored in DB) # CatExpense = namedtuple('CatExpense', 'cat expense') class MonthExpense (namedtuple('MonthExpense', 'date const catexps')): __slots__ = () @property def sum (self): return self.const + sum(x.expense for x in self.catexps) def __str__ (self): return '' % (self.date, self.sum) # # Rest # elixir.setup_all() session = elixir.session if __name__ == "__main__": elixir.create_all()