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 

6# This program is distributed in the hope that it will be useful, 

7# but WITHOUT ANY WARRANTY; without even the implied warranty of 

8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

9# GNU General Public License for more details. 

10 

11# You should have received a copy of the GNU General Public License 

12# along with this program; if not, write to the Free Software 

13# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 

14 

15################################################################################ 

16 

17from sqlalchemy import Column, DateTime 

18from sqlalchemy.event import listen 

19from sqlalchemy.ext.declarative import declarative_base 

20from sqlalchemy.schema import DDL, Table 

21from sqlalchemy.sql import func 

22 

23 

24Base = declarative_base() 

25 

26 

27class BaseMethods(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 

44 

45class BaseTimestamp(BaseMethods): 

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(""" 

52CREATE OR REPLACE FUNCTION tfunc_set_modified() RETURNS trigger 

53LANGUAGE plpgsql 

54AS $$ 

55 BEGIN NEW.modified = now(); return NEW; END; 

56$$ 

57 """) 

58 

59 modified_trigger = DDL(""" 

60CREATE TRIGGER %(table)s_modified BEFORE UPDATE ON %(fullname)s 

61FOR EACH ROW EXECUTE PROCEDURE tfunc_set_modified() 

62 """) 

63 

64 @classmethod 

65 def __table_cls__(cls, *arg, **kw): 

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