-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSession.py
More file actions
158 lines (126 loc) · 5.74 KB
/
Session.py
File metadata and controls
158 lines (126 loc) · 5.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#! /bin/env python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8 :
# Argentum SQLAlchemy extension
# Copyright (C) 2008 Egil Moeller <egil.moller@freecode.no>
# Copyright (C) 2008 FreeCode AS, Egil Moeller <egil.moller@freecode.no>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
# Some parts developed as part of the CliqueClique project and
# extracted from there.
# Some parts developed as part of the Worm project and extracted from
# there.
import sqlalchemy, sqlalchemy.engine, sqlalchemy.exceptions
import sqlalchemy.sql, sqlalchemy.orm, sqlalchemy.pool
import Entity
BaseConnection = sqlalchemy.engine.base.Connection
class Connection(BaseConnection):
is_refreshing = False
@property
def should_close_with_result(self):
return not self.is_refreshing and BaseConnection.should_close_with_result.__get__(self)
def execute(self, *arg, **kw):
if hasattr(self,'_Connection__close_with_result'):
tmp = self._Connection__close_with_result
self._Connection__close_with_result=False
if hasattr(self,'__close_with_result'):
tmp2 = self.__close_with_result
self.__close_with_result=False
try:
if not self.is_refreshing:
self.is_refreshing = True
Entity.refresh_views(arg[0], self)
except Exception, instance:
print "Unexpected error while performing refresh:", instance
if hasattr(self,'_Connection__close_with_result'):
self.__close_with_result = tmp
if hasattr(self,'__close_with_result'):
self.__close_with_result = tmp2
self.is_refreshing = False
return BaseConnection.execute(self, *arg, **kw)
sqlalchemy.engine.base.Connection = Connection
def create_engine(url):
# Setup a connection pool. To get this working parsing of the URL
# to get the dialect -> dbapi to create a connect function.
url_parsed = sqlalchemy.engine.url.make_url(url)
dialect_cls = url_parsed.get_dialect()
dbapi = dialect_cls.dbapi()
dialect = dialect_cls(dbapi=dbapi)
(cargs, cparams) = dialect.create_connect_args(url_parsed)
def connect():
try:
return dbapi.connect(*cargs, **cparams)
except Exception, e:
raise sqlalchemy.exceptions.DBAPIError.instance(None, None, e)
pool = sqlalchemy.pool.QueuePool(connect, max_overflow=-1, timeout=15)
engine = sqlalchemy.create_engine(url, pool=pool)
engine.session_arguments = {'autoflush': True,
'transactional': True,
}
def sessions(**kws):
real_kws = {}
real_kws.update(engine.session_arguments)
real_kws.update(kws)
print "Real kws",real_kws
BaseSession = sqlalchemy.orm.sessionmaker(bind=engine, **real_kws)
class Session(BaseSession):
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if type is None and value is None and traceback is None:
self.commit()
else:
self.rollback()
self.close()
def save(self, instance, *arg, **kw):
BaseSession.save(self, instance, *arg, **kw)
return instance
def save_or_update(self, instance, *arg, **kw):
BaseSession.save_or_update(self, instance, *arg, **kw)
return instance
def expire(self, instance = None, attrs = None):
if instance is not None:
if self.autoflush:
self.flush([instance])
if attrs is not None:
BaseSession.expire(self, instance, attrs)
else:
BaseSession.expire(self, instance)
return instance
if self.autoflush:
self.flush()
for instance in self.identity_map.values():
self.expire(instance)
return None
def save_and_expire(self, instance = None, *arg, **kw):
if instance:
self.save(instance, *arg, **kw)
self.flush()
return self.expire(instance, *arg, **kw)
for instance in self.identity_map.values():
self.save_and_expire(instance, *arg, **kw)
def load_from_session(self, instance):
#### fixme ####
# name = """SQLAlchemy: merge clashes with
# many-to-many"""
# description = """Uggly hack since merge does not
# seem to work when you have many-to-many
# relationships!!! So when no fields are changed, at
# least you can do this instead..."""
#### end ####
t = type(instance)
return self.query(t).filter(t.id == instance.id)[0]
return Session
engine.sessions = sessions
engine.Session = sessions()
return engine