1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 from sqlalchemy import Column, DateTime
18 from sqlalchemy.event import listen
19 from sqlalchemy.ext.declarative import declarative_base
20 from sqlalchemy.schema import DDL, Table
21 from sqlalchemy.sql import func
22
23
24 Base = declarative_base()
28 __abstract__ = True
29
30 @classmethod
31 - def get(cls, primary_key, session):
32 '''
33 This is a support function that allows getting an object by its primary
34 key.
35
36 Architecture.get(3[, session])
37
38 instead of the more verbose
39
40 session.query(Architecture).get(3)
41 '''
42 return session.query(cls).get(primary_key)
43
46 __abstract__ = True
47
48 created = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
49 modified = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
50
51 modified_trigger_function = DDL("""
52 CREATE OR REPLACE FUNCTION tfunc_set_modified() RETURNS trigger
53 LANGUAGE plpgsql
54 AS $$
55 BEGIN NEW.modified = now(); return NEW; END;
56 $$
57 """)
58
59 modified_trigger = DDL("""
60 CREATE TRIGGER %(table)s_modified BEFORE UPDATE ON %(fullname)s
61 FOR EACH ROW EXECUTE PROCEDURE tfunc_set_modified()
62 """)
63
64 @classmethod
66 table = Table(*arg, **kw)
67 listen(
68 table,
69 'after_create',
70 cls.modified_trigger_function.execute_if(dialect='postgresql'),
71 )
72 listen(
73 table,
74 'after_create',
75 cls.modified_trigger.execute_if(dialect='postgresql'),
76 )
77 return table
78