base.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # This program is free software; you can redistribute it and/or modify
  2. # it under the terms of the GNU General Public License as published by
  3. # the Free Software Foundation; either version 2 of the License, or
  4. # (at your option) any later version.
  5. # This program is distributed in the hope that it will be useful,
  6. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  7. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  8. # GNU General Public License for more details.
  9. # You should have received a copy of the GNU General Public License
  10. # along with this program; if not, write to the Free Software
  11. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  12. ################################################################################
  13. from sqlalchemy import Column, DateTime
  14. from sqlalchemy.event import listen
  15. from sqlalchemy.ext.declarative import declarative_base
  16. from sqlalchemy.schema import DDL, Table
  17. from sqlalchemy.sql import func
  18. Base = declarative_base()
  19. class BaseMethods(Base):
  20. __abstract__ = True
  21. @classmethod
  22. def get(cls, primary_key, session):
  23. '''
  24. This is a support function that allows getting an object by its primary
  25. key.
  26. Architecture.get(3[, session])
  27. instead of the more verbose
  28. session.query(Architecture).get(3)
  29. '''
  30. return session.query(cls).get(primary_key)
  31. class BaseTimestamp(BaseMethods):
  32. __abstract__ = True
  33. created = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
  34. modified = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
  35. modified_trigger_function = DDL("""
  36. CREATE OR REPLACE FUNCTION tfunc_set_modified() RETURNS trigger
  37. LANGUAGE plpgsql
  38. AS $$
  39. BEGIN NEW.modified = now(); return NEW; END;
  40. $$
  41. """)
  42. modified_trigger = DDL("""
  43. CREATE TRIGGER %(table)s_modified BEFORE UPDATE ON %(fullname)s
  44. FOR EACH ROW EXECUTE PROCEDURE tfunc_set_modified()
  45. """)
  46. @classmethod
  47. def __table_cls__(cls, *arg, **kw):
  48. table = Table(*arg, **kw)
  49. listen(
  50. table,
  51. 'after_create',
  52. cls.modified_trigger_function.execute_if(dialect='postgresql'),
  53. )
  54. listen(
  55. table,
  56. 'after_create',
  57. cls.modified_trigger.execute_if(dialect='postgresql'),
  58. )
  59. return table