author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 05 Jun 2009 19:04:20 +0200 | |
changeset 2059 | af33833d7571 |
parent 1977 | 606923dff11b |
child 2056 | 57d287a2132a |
permissions | -rw-r--r-- |
0 | 1 |
"""Adapters for native cubicweb sources. |
2 |
||
1952
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
3 |
Notes: |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
4 |
* extid (aka external id, the primary key of an entity in the external source |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
5 |
from which it comes from) are stored in a varchar column encoded as a base64 |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
6 |
string. This is because it should actually be Bytes but we want an index on |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
7 |
it for fast querying. |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
8 |
|
0 | 9 |
:organization: Logilab |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1954
diff
changeset
|
10 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 11 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1954
diff
changeset
|
12 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 13 |
""" |
14 |
__docformat__ = "restructuredtext en" |
|
15 |
||
16 |
from threading import Lock |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
17 |
from datetime import datetime |
1952
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
18 |
from base64 import b64decode, b64encode |
0 | 19 |
|
20 |
from logilab.common.cache import Cache |
|
21 |
from logilab.common.configuration import REQUIRED |
|
22 |
from logilab.common.adbh import get_adv_func_helper |
|
23 |
||
24 |
from indexer import get_indexer |
|
25 |
||
26 |
from cubicweb import UnknownEid, AuthenticationError, Binary, server |
|
27 |
from cubicweb.server.utils import crypt_password |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
28 |
from cubicweb.server.sqlutils import SQL_PREFIX, SQLAdapterMixIn |
0 | 29 |
from cubicweb.server.rqlannotation import set_qdata |
30 |
from cubicweb.server.sources import AbstractSource |
|
31 |
from cubicweb.server.sources.rql2sql import SQLGenerator |
|
32 |
||
33 |
||
34 |
NONSYSTEM_ETYPES = set() |
|
35 |
NONSYSTEM_RELATIONS = set() |
|
36 |
||
37 |
class LogCursor(object): |
|
38 |
def __init__(self, cursor): |
|
39 |
self.cu = cursor |
|
1792 | 40 |
|
0 | 41 |
def execute(self, query, args=None): |
42 |
"""Execute a query. |
|
43 |
it's a function just so that it shows up in profiling |
|
44 |
""" |
|
45 |
if server.DEBUG: |
|
46 |
print 'exec', query, args |
|
47 |
try: |
|
48 |
self.cu.execute(str(query), args) |
|
49 |
except Exception, ex: |
|
50 |
print "sql: %r\n args: %s\ndbms message: %r" % ( |
|
51 |
query, args, ex.args[0]) |
|
52 |
raise |
|
1792 | 53 |
|
0 | 54 |
def fetchall(self): |
55 |
return self.cu.fetchall() |
|
1792 | 56 |
|
0 | 57 |
def fetchone(self): |
58 |
return self.cu.fetchone() |
|
1792 | 59 |
|
0 | 60 |
def make_schema(selected, solution, table, typemap): |
61 |
"""return a sql schema to store RQL query result""" |
|
62 |
sql = [] |
|
63 |
varmap = {} |
|
64 |
for i, term in enumerate(selected): |
|
65 |
name = 'C%s' % i |
|
66 |
key = term.as_string() |
|
67 |
varmap[key] = '%s.%s' % (table, name) |
|
68 |
ttype = term.get_type(solution) |
|
69 |
try: |
|
70 |
sql.append('%s %s' % (name, typemap[ttype])) |
|
71 |
except KeyError: |
|
72 |
# assert not schema(ttype).is_final() |
|
73 |
sql.append('%s %s' % (name, typemap['Int'])) |
|
74 |
return ','.join(sql), varmap |
|
75 |
||
76 |
def _modified_sql(table, etypes): |
|
77 |
# XXX protect against sql injection |
|
78 |
if len(etypes) > 1: |
|
79 |
restr = 'type IN (%s)' % ','.join("'%s'" % etype for etype in etypes) |
|
80 |
else: |
|
81 |
restr = "type='%s'" % etypes[0] |
|
82 |
if table == 'entities': |
|
83 |
attr = 'mtime' |
|
84 |
else: |
|
85 |
attr = 'dtime' |
|
86 |
return 'SELECT type, eid FROM %s WHERE %s AND %s > %%(time)s' % ( |
|
87 |
table, restr, attr) |
|
88 |
||
89 |
||
90 |
class NativeSQLSource(SQLAdapterMixIn, AbstractSource): |
|
91 |
"""adapter for source using the native cubicweb schema (see below) |
|
92 |
""" |
|
93 |
# need default value on class since migration doesn't call init method |
|
94 |
has_deleted_entitites_table = True |
|
1792 | 95 |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
96 |
passwd_rql = "Any P WHERE X is CWUser, X login %(login)s, X upassword P" |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
97 |
auth_rql = "Any X WHERE X is CWUser, X login %(login)s, X upassword %(pwd)s" |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
98 |
_sols = ({'X': 'CWUser', 'P': 'Password'},) |
1792 | 99 |
|
0 | 100 |
options = ( |
101 |
('db-driver', |
|
102 |
{'type' : 'string', |
|
103 |
'default': 'postgres', |
|
104 |
'help': 'database driver (postgres or sqlite)', |
|
105 |
'group': 'native-source', 'inputlevel': 1, |
|
106 |
}), |
|
107 |
('db-host', |
|
108 |
{'type' : 'string', |
|
109 |
'default': '', |
|
110 |
'help': 'database host', |
|
111 |
'group': 'native-source', 'inputlevel': 1, |
|
112 |
}), |
|
113 |
('db-name', |
|
114 |
{'type' : 'string', |
|
115 |
'default': REQUIRED, |
|
116 |
'help': 'database name', |
|
117 |
'group': 'native-source', 'inputlevel': 0, |
|
118 |
}), |
|
119 |
('db-user', |
|
120 |
{'type' : 'string', |
|
121 |
'default': 'cubicweb', |
|
122 |
'help': 'database user', |
|
123 |
'group': 'native-source', 'inputlevel': 0, |
|
124 |
}), |
|
125 |
('db-password', |
|
126 |
{'type' : 'password', |
|
127 |
'default': '', |
|
128 |
'help': 'database password', |
|
129 |
'group': 'native-source', 'inputlevel': 0, |
|
130 |
}), |
|
131 |
('db-encoding', |
|
132 |
{'type' : 'string', |
|
133 |
'default': 'utf8', |
|
134 |
'help': 'database encoding', |
|
135 |
'group': 'native-source', 'inputlevel': 1, |
|
136 |
}), |
|
137 |
) |
|
1792 | 138 |
|
0 | 139 |
def __init__(self, repo, appschema, source_config, *args, **kwargs): |
140 |
SQLAdapterMixIn.__init__(self, source_config) |
|
141 |
AbstractSource.__init__(self, repo, appschema, source_config, |
|
142 |
*args, **kwargs) |
|
143 |
# sql generator |
|
144 |
self._rql_sqlgen = SQLGenerator(appschema, self.dbhelper, |
|
145 |
self.encoding) |
|
146 |
# full text index helper |
|
147 |
self.indexer = get_indexer(self.dbdriver, self.encoding) |
|
148 |
# advanced functionality helper |
|
149 |
self.dbhelper.fti_uid_attr = self.indexer.uid_attr |
|
150 |
self.dbhelper.fti_table = self.indexer.table |
|
151 |
self.dbhelper.fti_restriction_sql = self.indexer.restriction_sql |
|
152 |
self.dbhelper.fti_need_distinct_query = self.indexer.need_distinct |
|
153 |
# sql queries cache |
|
154 |
self._cache = Cache(repo.config['rql-cache-size']) |
|
155 |
self._temp_table_data = {} |
|
156 |
self._eid_creation_lock = Lock() |
|
157 |
||
158 |
def reset_caches(self): |
|
159 |
"""method called during test to reset potential source caches""" |
|
160 |
self._cache = Cache(self.repo.config['rql-cache-size']) |
|
1792 | 161 |
|
0 | 162 |
def clear_eid_cache(self, eid, etype): |
163 |
"""clear potential caches for the given eid""" |
|
164 |
self._cache.pop('%s X WHERE X eid %s' % (etype, eid), None) |
|
165 |
self._cache.pop('Any X WHERE X eid %s' % eid, None) |
|
1792 | 166 |
|
0 | 167 |
def sqlexec(self, session, sql, args=None): |
168 |
"""execute the query and return its result""" |
|
169 |
cursor = session.pool[self.uri] |
|
170 |
self.doexec(cursor, sql, args) |
|
171 |
return self.process_result(cursor) |
|
1792 | 172 |
|
0 | 173 |
def init_creating(self): |
174 |
# check full text index availibility |
|
175 |
pool = self.repo._get_pool() |
|
176 |
if not self.indexer.has_fti_table(pool['system']): |
|
177 |
self.error('no text index table') |
|
178 |
self.indexer = None |
|
179 |
self.repo._free_pool(pool) |
|
180 |
||
181 |
def init(self): |
|
1792 | 182 |
self.init_creating() |
0 | 183 |
pool = self.repo._get_pool() |
184 |
# XXX cubicweb < 2.42 compat |
|
185 |
if 'deleted_entities' in self.dbhelper.list_tables(pool['system']): |
|
186 |
self.has_deleted_entitites_table = True |
|
187 |
else: |
|
188 |
self.has_deleted_entitites_table = False |
|
189 |
self.repo._free_pool(pool) |
|
1792 | 190 |
|
0 | 191 |
# ISource interface ####################################################### |
192 |
||
193 |
def compile_rql(self, rql): |
|
194 |
rqlst = self.repo.querier._rqlhelper.parse(rql) |
|
195 |
rqlst.restricted_vars = () |
|
196 |
rqlst.children[0].solutions = self._sols |
|
197 |
self.repo.querier.sqlgen_annotate(rqlst) |
|
438 | 198 |
set_qdata(self.schema.rschema, rqlst, ()) |
0 | 199 |
return rqlst |
1792 | 200 |
|
0 | 201 |
def set_schema(self, schema): |
202 |
"""set the application'schema""" |
|
203 |
self._cache = Cache(self.repo.config['rql-cache-size']) |
|
204 |
self.cache_hit, self.cache_miss, self.no_cache = 0, 0, 0 |
|
205 |
self.schema = schema |
|
206 |
try: |
|
207 |
self._rql_sqlgen.schema = schema |
|
208 |
except AttributeError: |
|
209 |
pass # __init__ |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
210 |
if 'CWUser' in schema: # probably an empty schema if not true... |
0 | 211 |
# rql syntax trees used to authenticate users |
212 |
self._passwd_rqlst = self.compile_rql(self.passwd_rql) |
|
213 |
self._auth_rqlst = self.compile_rql(self.auth_rql) |
|
1792 | 214 |
|
0 | 215 |
def support_entity(self, etype, write=False): |
216 |
"""return true if the given entity's type is handled by this adapter |
|
217 |
if write is true, return true only if it's a RW support |
|
218 |
""" |
|
219 |
return not etype in NONSYSTEM_ETYPES |
|
1792 | 220 |
|
0 | 221 |
def support_relation(self, rtype, write=False): |
222 |
"""return true if the given relation's type is handled by this adapter |
|
223 |
if write is true, return true only if it's a RW support |
|
224 |
""" |
|
225 |
if write: |
|
226 |
return not rtype in NONSYSTEM_RELATIONS |
|
227 |
# due to current multi-sources implementation, the system source |
|
1792 | 228 |
# can't claim not supporting a relation |
0 | 229 |
return True #not rtype == 'content_for' |
230 |
||
231 |
def authenticate(self, session, login, password): |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
232 |
"""return CWUser eid for the given login/password if this account is |
0 | 233 |
defined in this source, else raise `AuthenticationError` |
234 |
||
235 |
two queries are needed since passwords are stored crypted, so we have |
|
236 |
to fetch the salt first |
|
237 |
""" |
|
238 |
args = {'login': login, 'pwd' : password} |
|
239 |
if password is not None: |
|
240 |
rset = self.syntax_tree_search(session, self._passwd_rqlst, args) |
|
241 |
try: |
|
242 |
pwd = rset[0][0] |
|
243 |
except IndexError: |
|
244 |
raise AuthenticationError('bad login') |
|
1954 | 245 |
# passwords are stored using the Bytes type, so we get a StringIO |
0 | 246 |
if pwd is not None: |
247 |
args['pwd'] = crypt_password(password, pwd.getvalue()[:2]) |
|
248 |
# get eid from login and (crypted) password |
|
249 |
rset = self.syntax_tree_search(session, self._auth_rqlst, args) |
|
250 |
try: |
|
251 |
return rset[0][0] |
|
252 |
except IndexError: |
|
253 |
raise AuthenticationError('bad password') |
|
1792 | 254 |
|
255 |
def syntax_tree_search(self, session, union, args=None, cachekey=None, |
|
0 | 256 |
varmap=None): |
257 |
"""return result from this source for a rql query (actually from |
|
258 |
a rql syntax tree and a solution dictionary mapping each used |
|
259 |
variable to a possible type). If cachekey is given, the query |
|
260 |
necessary to fetch the results (but not the results themselves) |
|
261 |
may be cached using this key. |
|
262 |
""" |
|
263 |
if server.DEBUG: |
|
264 |
print 'RQL FOR NATIVE SOURCE', self.uri, cachekey |
|
265 |
if varmap: |
|
266 |
print 'USING VARMAP', varmap |
|
267 |
print union.as_string() |
|
268 |
if args: print 'ARGS', args |
|
269 |
print 'SOLUTIONS', ','.join(str(s.solutions) for s in union.children) |
|
270 |
# remember number of actually selected term (sql generation may append some) |
|
271 |
if cachekey is None: |
|
272 |
self.no_cache += 1 |
|
273 |
# generate sql query if we are able to do so (not supported types...) |
|
274 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
275 |
else: |
|
276 |
# sql may be cached |
|
277 |
try: |
|
278 |
sql, query_args = self._cache[cachekey] |
|
279 |
self.cache_hit += 1 |
|
280 |
except KeyError: |
|
281 |
self.cache_miss += 1 |
|
282 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
283 |
self._cache[cachekey] = sql, query_args |
|
284 |
args = self.merge_args(args, query_args) |
|
285 |
cursor = session.pool[self.uri] |
|
286 |
assert isinstance(sql, basestring), repr(sql) |
|
287 |
try: |
|
288 |
self.doexec(cursor, sql, args) |
|
289 |
except (self.dbapi_module.OperationalError, |
|
290 |
self.dbapi_module.InterfaceError): |
|
291 |
# FIXME: better detection of deconnection pb |
|
292 |
self.info("request failed '%s' ... retry with a new cursor", sql) |
|
293 |
session.pool.reconnect(self) |
|
294 |
cursor = session.pool[self.uri] |
|
295 |
self.doexec(cursor, sql, args) |
|
296 |
res = self.process_result(cursor) |
|
297 |
if server.DEBUG: |
|
298 |
print '------>', res |
|
299 |
return res |
|
1792 | 300 |
|
0 | 301 |
def flying_insert(self, table, session, union, args=None, varmap=None): |
302 |
"""similar as .syntax_tree_search, but inserts data in the |
|
303 |
temporary table (on-the-fly if possible, eg for the system |
|
304 |
source whose the given cursor come from). If not possible, |
|
305 |
inserts all data by calling .executemany(). |
|
306 |
""" |
|
307 |
if self.uri == 'system': |
|
308 |
if server.DEBUG: |
|
309 |
print 'FLYING RQL FOR SOURCE', self.uri |
|
310 |
if varmap: |
|
311 |
print 'USING VARMAP', varmap |
|
312 |
print union.as_string() |
|
313 |
print 'SOLUTIONS', ','.join(str(s.solutions) for s in union.children) |
|
314 |
# generate sql queries if we are able to do so |
|
315 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
316 |
query = 'INSERT INTO %s %s' % (table, sql.encode(self.encoding)) |
|
317 |
self.doexec(session.pool[self.uri], query, |
|
318 |
self.merge_args(args, query_args)) |
|
319 |
# XXX commented until it's proved to be necessary |
|
320 |
# # XXX probably inefficient |
|
321 |
# tempdata = self._temp_table_data.setdefault(table, set()) |
|
322 |
# cursor = session.pool[self.uri] |
|
323 |
# cursor.execute('select * from %s' % table) |
|
324 |
# for row in cursor.fetchall(): |
|
325 |
# print 'data', row |
|
326 |
# tempdata.add(tuple(row)) |
|
327 |
else: |
|
328 |
super(NativeSQLSource, self).flying_insert(table, session, union, |
|
329 |
args, varmap) |
|
1792 | 330 |
|
0 | 331 |
def _manual_insert(self, results, table, session): |
332 |
"""insert given result into a temporary table on the system source""" |
|
333 |
#print 'manual insert', table, results |
|
334 |
if not results: |
|
335 |
return |
|
336 |
#cursor.execute('select * from %s'%table) |
|
337 |
#assert len(cursor.fetchall())== 0 |
|
338 |
encoding = self.encoding |
|
339 |
# added chr to be sqlite compatible |
|
340 |
query_args = ['%%(%s)s' % i for i in xrange(len(results[0]))] |
|
341 |
query = 'INSERT INTO %s VALUES(%s)' % (table, ','.join(query_args)) |
|
342 |
kwargs_list = [] |
|
343 |
# tempdata = self._temp_table_data.setdefault(table, set()) |
|
344 |
for row in results: |
|
345 |
kwargs = {} |
|
346 |
row = tuple(row) |
|
347 |
# XXX commented until it's proved to be necessary |
|
348 |
# if row in tempdata: |
|
349 |
# continue |
|
350 |
# tempdata.add(row) |
|
351 |
for index, cell in enumerate(row): |
|
352 |
if type(cell) is unicode: |
|
353 |
cell = cell.encode(encoding) |
|
354 |
elif isinstance(cell, Binary): |
|
355 |
cell = self.binary(cell.getvalue()) |
|
356 |
kwargs[str(index)] = cell |
|
357 |
kwargs_list.append(kwargs) |
|
358 |
self.doexecmany(session.pool[self.uri], query, kwargs_list) |
|
359 |
||
360 |
def clean_temp_data(self, session, temptables): |
|
361 |
"""remove temporary data, usually associated to temporary tables""" |
|
362 |
if temptables: |
|
363 |
cursor = session.pool[self.uri] |
|
364 |
for table in temptables: |
|
365 |
try: |
|
366 |
self.doexec(cursor,'DROP TABLE %s' % table) |
|
367 |
except: |
|
368 |
pass |
|
369 |
try: |
|
370 |
del self._temp_table_data[table] |
|
371 |
except KeyError: |
|
372 |
continue |
|
1792 | 373 |
|
0 | 374 |
def add_entity(self, session, entity): |
375 |
"""add a new entity to the source""" |
|
376 |
attrs = self.preprocess_entity(entity) |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
377 |
sql = self.sqlgen.insert(SQL_PREFIX + str(entity.e_schema), attrs) |
0 | 378 |
self.doexec(session.pool[self.uri], sql, attrs) |
1792 | 379 |
|
0 | 380 |
def update_entity(self, session, entity): |
381 |
"""replace an entity in the source""" |
|
382 |
attrs = self.preprocess_entity(entity) |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
383 |
sql = self.sqlgen.update(SQL_PREFIX + str(entity.e_schema), attrs, [SQL_PREFIX + 'eid']) |
0 | 384 |
self.doexec(session.pool[self.uri], sql, attrs) |
385 |
||
386 |
def delete_entity(self, session, etype, eid): |
|
387 |
"""delete an entity from the source""" |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
388 |
attrs = {SQL_PREFIX + 'eid': eid} |
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
389 |
sql = self.sqlgen.delete(SQL_PREFIX + etype, attrs) |
0 | 390 |
self.doexec(session.pool[self.uri], sql, attrs) |
391 |
||
392 |
def add_relation(self, session, subject, rtype, object): |
|
393 |
"""add a relation to the source""" |
|
394 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
395 |
sql = self.sqlgen.insert('%s_relation' % rtype, attrs) |
|
396 |
self.doexec(session.pool[self.uri], sql, attrs) |
|
1792 | 397 |
|
0 | 398 |
def delete_relation(self, session, subject, rtype, object): |
399 |
"""delete a relation from the source""" |
|
400 |
rschema = self.schema.rschema(rtype) |
|
401 |
if rschema.inlined: |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
402 |
table = SQL_PREFIX + session.describe(subject)[0] |
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
403 |
column = SQL_PREFIX + rtype |
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
404 |
sql = 'UPDATE %s SET %s=NULL WHERE %seid=%%(eid)s' % (table, column, |
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
1079
diff
changeset
|
405 |
SQL_PREFIX) |
0 | 406 |
attrs = {'eid' : subject} |
407 |
else: |
|
408 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
409 |
sql = self.sqlgen.delete('%s_relation' % rtype, attrs) |
|
1792 | 410 |
self.doexec(session.pool[self.uri], sql, attrs) |
0 | 411 |
|
412 |
def doexec(self, cursor, query, args=None): |
|
413 |
"""Execute a query. |
|
414 |
it's a function just so that it shows up in profiling |
|
415 |
""" |
|
416 |
#t1 = time() |
|
417 |
if server.DEBUG: |
|
418 |
print 'exec', query, args |
|
419 |
#import sys |
|
420 |
#sys.stdout.flush() |
|
421 |
# str(query) to avoid error if it's an unicode string |
|
422 |
try: |
|
423 |
cursor.execute(str(query), args) |
|
424 |
except Exception, ex: |
|
425 |
self.critical("sql: %r\n args: %s\ndbms message: %r", |
|
426 |
query, args, ex.args[0]) |
|
427 |
raise |
|
1792 | 428 |
|
0 | 429 |
def doexecmany(self, cursor, query, args): |
430 |
"""Execute a query. |
|
431 |
it's a function just so that it shows up in profiling |
|
432 |
""" |
|
433 |
#t1 = time() |
|
434 |
if server.DEBUG: |
|
435 |
print 'execmany', query, 'with', len(args), 'arguments' |
|
436 |
#import sys |
|
437 |
#sys.stdout.flush() |
|
438 |
# str(query) to avoid error if it's an unicode string |
|
439 |
try: |
|
440 |
cursor.executemany(str(query), args) |
|
441 |
except: |
|
442 |
self.critical("sql many: %r\n args: %s", query, args) |
|
443 |
raise |
|
1792 | 444 |
|
0 | 445 |
# short cut to method requiring advanced db helper usage ################## |
1792 | 446 |
|
0 | 447 |
def create_index(self, session, table, column, unique=False): |
448 |
cursor = LogCursor(session.pool[self.uri]) |
|
449 |
self.dbhelper.create_index(cursor, table, column, unique) |
|
1792 | 450 |
|
0 | 451 |
def drop_index(self, session, table, column, unique=False): |
452 |
cursor = LogCursor(session.pool[self.uri]) |
|
453 |
self.dbhelper.drop_index(cursor, table, column, unique) |
|
454 |
||
455 |
# system source interface ################################################# |
|
456 |
||
457 |
def eid_type_source(self, session, eid): |
|
458 |
"""return a tuple (type, source, extid) for the entity with id <eid>""" |
|
459 |
sql = 'SELECT type, source, extid FROM entities WHERE eid=%s' % eid |
|
460 |
try: |
|
461 |
res = session.system_sql(sql).fetchone() |
|
462 |
except: |
|
1079
452cb76fe07a
backport typo fix
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
973
diff
changeset
|
463 |
assert session.pool, 'session has no pool set' |
0 | 464 |
raise UnknownEid(eid) |
465 |
if res is None: |
|
466 |
raise UnknownEid(eid) |
|
1952
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
467 |
if res[-1] is not None: |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
468 |
if not isinstance(res, list): |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
469 |
res = list(res) |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
470 |
res[-1] = b64decode(res[-1]) |
0 | 471 |
return res |
472 |
||
1952
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
473 |
def extid2eid(self, session, source, extid): |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
474 |
"""get eid from an external id. Return None if no record found.""" |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
475 |
assert isinstance(extid, str) |
0 | 476 |
cursor = session.system_sql('SELECT eid FROM entities WHERE ' |
477 |
'extid=%(x)s AND source=%(s)s', |
|
1952
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
478 |
{'x': b64encode(extid), 's': source.uri}) |
0 | 479 |
# XXX testing rowcount cause strange bug with sqlite, results are there |
480 |
# but rowcount is 0 |
|
1792 | 481 |
#if cursor.rowcount > 0: |
0 | 482 |
try: |
483 |
result = cursor.fetchone() |
|
484 |
if result: |
|
1954 | 485 |
return result[0] |
0 | 486 |
except: |
487 |
pass |
|
488 |
return None |
|
1792 | 489 |
|
0 | 490 |
def temp_table_def(self, selected, sol, table): |
491 |
return make_schema(selected, sol, table, self.dbhelper.TYPE_MAPPING) |
|
492 |
||
493 |
def create_temp_table(self, session, table, schema): |
|
494 |
# we don't want on commit drop, this may cause problem when |
|
495 |
# running with an ldap source, and table will be deleted manually any way |
|
496 |
# on commit |
|
497 |
sql = self.dbhelper.sql_temporary_table(table, schema, False) |
|
498 |
self.doexec(session.pool[self.uri], sql) |
|
1792 | 499 |
|
0 | 500 |
def create_eid(self, session): |
501 |
self._eid_creation_lock.acquire() |
|
502 |
try: |
|
503 |
cursor = session.pool[self.uri] |
|
504 |
for sql in self.dbhelper.sqls_increment_sequence('entities_id_seq'): |
|
505 |
self.doexec(cursor, sql) |
|
506 |
return cursor.fetchone()[0] |
|
507 |
finally: |
|
508 |
self._eid_creation_lock.release() |
|
509 |
||
510 |
def add_info(self, session, entity, source, extid=None): |
|
511 |
"""add type and source info for an eid into the system table""" |
|
512 |
# begin by inserting eid/type/source/extid into the entities table |
|
1952
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
513 |
if extid is not None: |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
514 |
assert isinstance(extid, str) |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
515 |
extid = b64encode(extid) |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
516 |
attrs = {'type': entity.id, 'eid': entity.eid, 'extid': extid, |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
517 |
'source': source.uri, 'mtime': datetime.now()} |
0 | 518 |
session.system_sql(self.sqlgen.insert('entities', attrs), attrs) |
519 |
||
520 |
def delete_info(self, session, eid, etype, uri, extid): |
|
521 |
"""delete system information on deletion of an entity by transfering |
|
522 |
record from the entities table to the deleted_entities table |
|
523 |
""" |
|
524 |
attrs = {'eid': eid} |
|
525 |
session.system_sql(self.sqlgen.delete('entities', attrs), attrs) |
|
526 |
if self.has_deleted_entitites_table: |
|
1952
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
527 |
if extid is not None: |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
528 |
assert isinstance(extid, str), type(extid) |
8e19c813750d
fix extid handling: ensure encoded string is given, and store them as base64 (see note in native.py).
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1792
diff
changeset
|
529 |
extid = b64encode(extid) |
0 | 530 |
attrs = {'type': etype, 'eid': eid, 'extid': extid, |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
531 |
'source': uri, 'dtime': datetime.now()} |
0 | 532 |
session.system_sql(self.sqlgen.insert('deleted_entities', attrs), attrs) |
1792 | 533 |
|
0 | 534 |
def fti_unindex_entity(self, session, eid): |
535 |
"""remove text content for entity with the given eid from the full text |
|
536 |
index |
|
537 |
""" |
|
538 |
try: |
|
539 |
self.indexer.cursor_unindex_object(eid, session.pool['system']) |
|
540 |
except: |
|
541 |
if self.indexer is not None: |
|
542 |
self.exception('error while unindexing %s', eid) |
|
1792 | 543 |
|
0 | 544 |
def fti_index_entity(self, session, entity): |
545 |
"""add text content of a created/modified entity to the full text index |
|
546 |
""" |
|
547 |
self.info('reindexing %r', entity.eid) |
|
548 |
try: |
|
549 |
self.indexer.cursor_reindex_object(entity.eid, entity, |
|
550 |
session.pool['system']) |
|
551 |
except: |
|
552 |
if self.indexer is not None: |
|
553 |
self.exception('error while reindexing %s', entity) |
|
554 |
# update entities.mtime |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
555 |
attrs = {'eid': entity.eid, 'mtime': datetime.now()} |
0 | 556 |
session.system_sql(self.sqlgen.update('entities', attrs, ['eid']), attrs) |
1792 | 557 |
|
0 | 558 |
def modified_entities(self, session, etypes, mtime): |
559 |
"""return a 2-uple: |
|
560 |
* list of (etype, eid) of entities of the given types which have been |
|
561 |
modified since the given timestamp (actually entities whose full text |
|
562 |
index content has changed) |
|
563 |
* list of (etype, eid) of entities of the given types which have been |
|
564 |
deleted since the given timestamp |
|
565 |
""" |
|
566 |
modsql = _modified_sql('entities', etypes) |
|
567 |
cursor = session.system_sql(modsql, {'time': mtime}) |
|
568 |
modentities = cursor.fetchall() |
|
569 |
delsql = _modified_sql('deleted_entities', etypes) |
|
570 |
cursor = session.system_sql(delsql, {'time': mtime}) |
|
571 |
delentities = cursor.fetchall() |
|
572 |
return modentities, delentities |
|
573 |
||
574 |
||
575 |
def sql_schema(driver): |
|
576 |
helper = get_adv_func_helper(driver) |
|
577 |
schema = """ |
|
578 |
/* Create the repository's system database */ |
|
579 |
||
580 |
%s |
|
581 |
||
582 |
CREATE TABLE entities ( |
|
583 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
584 |
type VARCHAR(64) NOT NULL, |
|
585 |
source VARCHAR(64) NOT NULL, |
|
586 |
mtime TIMESTAMP NOT NULL, |
|
587 |
extid VARCHAR(256) |
|
588 |
); |
|
589 |
CREATE INDEX entities_type_idx ON entities(type); |
|
590 |
CREATE INDEX entities_mtime_idx ON entities(mtime); |
|
591 |
CREATE INDEX entities_extid_idx ON entities(extid); |
|
592 |
||
593 |
CREATE TABLE deleted_entities ( |
|
594 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
595 |
type VARCHAR(64) NOT NULL, |
|
596 |
source VARCHAR(64) NOT NULL, |
|
597 |
dtime TIMESTAMP NOT NULL, |
|
598 |
extid VARCHAR(256) |
|
599 |
); |
|
600 |
CREATE INDEX deleted_entities_type_idx ON deleted_entities(type); |
|
601 |
CREATE INDEX deleted_entities_dtime_idx ON deleted_entities(dtime); |
|
602 |
CREATE INDEX deleted_entities_extid_idx ON deleted_entities(extid); |
|
603 |
""" % helper.sql_create_sequence('entities_id_seq') |
|
604 |
return schema |
|
605 |
||
606 |
||
607 |
def sql_drop_schema(driver): |
|
608 |
helper = get_adv_func_helper(driver) |
|
609 |
return """ |
|
610 |
%s |
|
611 |
DROP TABLE entities; |
|
612 |
DROP TABLE deleted_entities; |
|
613 |
""" % helper.sql_drop_sequence('entities_id_seq') |
|
614 |
||
615 |
||
616 |
def grant_schema(user, set_owner=True): |
|
617 |
result = '' |
|
618 |
if set_owner: |
|
619 |
result = 'ALTER TABLE entities OWNER TO %s;\n' % user |
|
620 |
result += 'ALTER TABLE deleted_entities OWNER TO %s;\n' % user |
|
621 |
result += 'ALTER TABLE entities_id_seq OWNER TO %s;\n' % user |
|
622 |
result += 'GRANT ALL ON entities TO %s;\n' % user |
|
623 |
result += 'GRANT ALL ON deleted_entities TO %s;\n' % user |
|
624 |
result += 'GRANT ALL ON entities_id_seq TO %s;\n' % user |
|
625 |
return result |