author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Tue, 18 Aug 2009 09:25:26 +0200 | |
changeset 2901 | 8f4d495c94c2 |
parent 2759 | 23d7a75693f8 |
child 2955 | 6bb5025c9fc7 |
child 2959 | daabb9bc5233 |
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. |
2056 | 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 |
|
2759
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
28 |
from cubicweb.server.sqlutils import SQL_PREFIX, SQLAdapterMixIn |
0 | 29 |
from cubicweb.server.rqlannotation import set_qdata |
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
30 |
from cubicweb.server.sources import AbstractSource, dbg_st_search, dbg_results |
0 | 31 |
from cubicweb.server.sources.rql2sql import SQLGenerator |
32 |
||
33 |
||
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2310
diff
changeset
|
34 |
ATTR_MAP = {} |
0 | 35 |
NONSYSTEM_ETYPES = set() |
36 |
NONSYSTEM_RELATIONS = set() |
|
37 |
||
38 |
class LogCursor(object): |
|
39 |
def __init__(self, cursor): |
|
40 |
self.cu = cursor |
|
1792 | 41 |
|
0 | 42 |
def execute(self, query, args=None): |
43 |
"""Execute a query. |
|
44 |
it's a function just so that it shows up in profiling |
|
45 |
""" |
|
2593
16d9419a4a79
F: start to handle binary debug log level on the server side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2589
diff
changeset
|
46 |
if server.DEBUG & server.DBG_SQL: |
0 | 47 |
print 'exec', query, args |
48 |
try: |
|
49 |
self.cu.execute(str(query), args) |
|
50 |
except Exception, ex: |
|
51 |
print "sql: %r\n args: %s\ndbms message: %r" % ( |
|
52 |
query, args, ex.args[0]) |
|
53 |
raise |
|
1792 | 54 |
|
0 | 55 |
def fetchall(self): |
56 |
return self.cu.fetchall() |
|
1792 | 57 |
|
0 | 58 |
def fetchone(self): |
59 |
return self.cu.fetchone() |
|
1792 | 60 |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
61 |
|
0 | 62 |
def make_schema(selected, solution, table, typemap): |
63 |
"""return a sql schema to store RQL query result""" |
|
64 |
sql = [] |
|
65 |
varmap = {} |
|
66 |
for i, term in enumerate(selected): |
|
67 |
name = 'C%s' % i |
|
68 |
key = term.as_string() |
|
69 |
varmap[key] = '%s.%s' % (table, name) |
|
70 |
ttype = term.get_type(solution) |
|
71 |
try: |
|
72 |
sql.append('%s %s' % (name, typemap[ttype])) |
|
73 |
except KeyError: |
|
74 |
# assert not schema(ttype).is_final() |
|
75 |
sql.append('%s %s' % (name, typemap['Int'])) |
|
76 |
return ','.join(sql), varmap |
|
77 |
||
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
78 |
|
0 | 79 |
def _modified_sql(table, etypes): |
80 |
# XXX protect against sql injection |
|
81 |
if len(etypes) > 1: |
|
82 |
restr = 'type IN (%s)' % ','.join("'%s'" % etype for etype in etypes) |
|
83 |
else: |
|
84 |
restr = "type='%s'" % etypes[0] |
|
85 |
if table == 'entities': |
|
86 |
attr = 'mtime' |
|
87 |
else: |
|
88 |
attr = 'dtime' |
|
89 |
return 'SELECT type, eid FROM %s WHERE %s AND %s > %%(time)s' % ( |
|
90 |
table, restr, attr) |
|
91 |
||
92 |
||
93 |
class NativeSQLSource(SQLAdapterMixIn, AbstractSource): |
|
94 |
"""adapter for source using the native cubicweb schema (see below) |
|
95 |
""" |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2310
diff
changeset
|
96 |
sqlgen_class = SQLGenerator |
0 | 97 |
# need default value on class since migration doesn't call init method |
98 |
has_deleted_entitites_table = True |
|
1792 | 99 |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
100 |
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
|
101 |
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
|
102 |
_sols = ({'X': 'CWUser', 'P': 'Password'},) |
1792 | 103 |
|
0 | 104 |
options = ( |
105 |
('db-driver', |
|
106 |
{'type' : 'string', |
|
107 |
'default': 'postgres', |
|
108 |
'help': 'database driver (postgres or sqlite)', |
|
109 |
'group': 'native-source', 'inputlevel': 1, |
|
110 |
}), |
|
111 |
('db-host', |
|
112 |
{'type' : 'string', |
|
113 |
'default': '', |
|
114 |
'help': 'database host', |
|
115 |
'group': 'native-source', 'inputlevel': 1, |
|
116 |
}), |
|
2566
714a8743d423
missing db-port option to source's option definitions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
117 |
('db-port', |
714a8743d423
missing db-port option to source's option definitions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
118 |
{'type' : 'string', |
714a8743d423
missing db-port option to source's option definitions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
119 |
'default': '', |
714a8743d423
missing db-port option to source's option definitions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
120 |
'help': 'database port', |
714a8743d423
missing db-port option to source's option definitions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
121 |
'group': 'native-source', 'inputlevel': 1, |
714a8743d423
missing db-port option to source's option definitions
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
122 |
}), |
0 | 123 |
('db-name', |
124 |
{'type' : 'string', |
|
125 |
'default': REQUIRED, |
|
126 |
'help': 'database name', |
|
127 |
'group': 'native-source', 'inputlevel': 0, |
|
128 |
}), |
|
129 |
('db-user', |
|
130 |
{'type' : 'string', |
|
131 |
'default': 'cubicweb', |
|
132 |
'help': 'database user', |
|
133 |
'group': 'native-source', 'inputlevel': 0, |
|
134 |
}), |
|
135 |
('db-password', |
|
136 |
{'type' : 'password', |
|
137 |
'default': '', |
|
138 |
'help': 'database password', |
|
139 |
'group': 'native-source', 'inputlevel': 0, |
|
140 |
}), |
|
141 |
('db-encoding', |
|
142 |
{'type' : 'string', |
|
143 |
'default': 'utf8', |
|
144 |
'help': 'database encoding', |
|
145 |
'group': 'native-source', 'inputlevel': 1, |
|
146 |
}), |
|
147 |
) |
|
1792 | 148 |
|
0 | 149 |
def __init__(self, repo, appschema, source_config, *args, **kwargs): |
150 |
SQLAdapterMixIn.__init__(self, source_config) |
|
151 |
AbstractSource.__init__(self, repo, appschema, source_config, |
|
152 |
*args, **kwargs) |
|
153 |
# sql generator |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2310
diff
changeset
|
154 |
self._rql_sqlgen = self.sqlgen_class(appschema, self.dbhelper, |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2310
diff
changeset
|
155 |
self.encoding, ATTR_MAP.copy()) |
0 | 156 |
# full text index helper |
157 |
self.indexer = get_indexer(self.dbdriver, self.encoding) |
|
158 |
# advanced functionality helper |
|
159 |
self.dbhelper.fti_uid_attr = self.indexer.uid_attr |
|
160 |
self.dbhelper.fti_table = self.indexer.table |
|
161 |
self.dbhelper.fti_restriction_sql = self.indexer.restriction_sql |
|
162 |
self.dbhelper.fti_need_distinct_query = self.indexer.need_distinct |
|
163 |
# sql queries cache |
|
164 |
self._cache = Cache(repo.config['rql-cache-size']) |
|
165 |
self._temp_table_data = {} |
|
166 |
self._eid_creation_lock = Lock() |
|
2072
8008e8812d76
deactivate sqlite connection wrapping for unittest_multisources for now
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2066
diff
changeset
|
167 |
# XXX no_sqlite_wrap trick since we've a sqlite locking pb when |
8008e8812d76
deactivate sqlite connection wrapping for unittest_multisources for now
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2066
diff
changeset
|
168 |
# running unittest_multisources with the wrapping below |
8008e8812d76
deactivate sqlite connection wrapping for unittest_multisources for now
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2066
diff
changeset
|
169 |
if self.dbdriver == 'sqlite' and \ |
8008e8812d76
deactivate sqlite connection wrapping for unittest_multisources for now
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2066
diff
changeset
|
170 |
not getattr(repo.config, 'no_sqlite_wrap', False): |
2064
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
171 |
from cubicweb.server.sources.extlite import ConnectionWrapper |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
172 |
self.get_connection = lambda: ConnectionWrapper(self) |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
173 |
self.check_connection = lambda cnx: cnx |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
174 |
def pool_reset(cnx): |
2620
de68f84b8f54
R [sql source] cnx._cnx checked in cnx.close, don't do it here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2619
diff
changeset
|
175 |
cnx.close() |
2064
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
176 |
self.pool_reset = pool_reset |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
177 |
|
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
178 |
@property |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
179 |
def _sqlcnx(self): |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
180 |
# XXX: sqlite connections can only be used in the same thread, so |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
181 |
# create a new one each time necessary. If it appears to be time |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
182 |
# consuming, find another way |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
183 |
return SQLAdapterMixIn.get_connection(self) |
0 | 184 |
|
185 |
def reset_caches(self): |
|
186 |
"""method called during test to reset potential source caches""" |
|
187 |
self._cache = Cache(self.repo.config['rql-cache-size']) |
|
1792 | 188 |
|
0 | 189 |
def clear_eid_cache(self, eid, etype): |
190 |
"""clear potential caches for the given eid""" |
|
2610
2933cc6bf9ad
[F native source] fix attempts to clear cache key
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2593
diff
changeset
|
191 |
self._cache.pop('Any X WHERE X eid %s, X is %s' % (eid, etype), None) |
0 | 192 |
self._cache.pop('Any X WHERE X eid %s' % eid, None) |
2610
2933cc6bf9ad
[F native source] fix attempts to clear cache key
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2593
diff
changeset
|
193 |
self._cache.pop('Any %s' % eid, None) |
1792 | 194 |
|
0 | 195 |
def sqlexec(self, session, sql, args=None): |
196 |
"""execute the query and return its result""" |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
197 |
return self.process_result(self.doexec(session, sql, args)) |
1792 | 198 |
|
0 | 199 |
def init_creating(self): |
2064
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
200 |
pool = self.repo._get_pool() |
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
201 |
pool.pool_set() |
0 | 202 |
# check full text index availibility |
203 |
if not self.indexer.has_fti_table(pool['system']): |
|
204 |
self.error('no text index table') |
|
205 |
self.indexer = None |
|
2064
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
206 |
pool.pool_reset() |
0 | 207 |
self.repo._free_pool(pool) |
208 |
||
2759
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
209 |
def backup(self, backupfile): |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
210 |
"""method called to create a backup of the source's data""" |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
211 |
self.close_pool_connections() |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
212 |
try: |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
213 |
self.backup_to_file(backupfile) |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
214 |
finally: |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
215 |
self.open_pool_connections() |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
216 |
|
2759
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
217 |
def restore(self, backupfile, drop): |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
218 |
"""method called to restore a backup of source's data""" |
2759
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
219 |
self.close_pool_connections() |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
220 |
try: |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
221 |
self.restore_from_file(backupfile, drop) |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
222 |
finally: |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
223 |
self.open_pool_connections() |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
224 |
|
0 | 225 |
def init(self): |
1792 | 226 |
self.init_creating() |
0 | 227 |
pool = self.repo._get_pool() |
2064
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
228 |
pool.pool_set() |
0 | 229 |
# XXX cubicweb < 2.42 compat |
230 |
if 'deleted_entities' in self.dbhelper.list_tables(pool['system']): |
|
231 |
self.has_deleted_entitites_table = True |
|
232 |
else: |
|
233 |
self.has_deleted_entitites_table = False |
|
2064
a5cd3a92314a
properly call [re]set_pool, fix connection handling so we have a change to get cw running on top of a sqlite dabase with threads activated
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2056
diff
changeset
|
234 |
pool.pool_reset() |
0 | 235 |
self.repo._free_pool(pool) |
1792 | 236 |
|
2354
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2310
diff
changeset
|
237 |
def map_attribute(self, etype, attr, cb): |
9b4bac626977
ability to map attributes to something else than usual cw mapping on sql generation
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2310
diff
changeset
|
238 |
self._rql_sqlgen.attr_map['%s.%s' % (etype, attr)] = cb |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
239 |
|
0 | 240 |
# ISource interface ####################################################### |
241 |
||
242 |
def compile_rql(self, rql): |
|
243 |
rqlst = self.repo.querier._rqlhelper.parse(rql) |
|
244 |
rqlst.restricted_vars = () |
|
245 |
rqlst.children[0].solutions = self._sols |
|
246 |
self.repo.querier.sqlgen_annotate(rqlst) |
|
438 | 247 |
set_qdata(self.schema.rschema, rqlst, ()) |
0 | 248 |
return rqlst |
1792 | 249 |
|
0 | 250 |
def set_schema(self, schema): |
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
251 |
"""set the instance'schema""" |
0 | 252 |
self._cache = Cache(self.repo.config['rql-cache-size']) |
253 |
self.cache_hit, self.cache_miss, self.no_cache = 0, 0, 0 |
|
254 |
self.schema = schema |
|
255 |
try: |
|
256 |
self._rql_sqlgen.schema = schema |
|
257 |
except AttributeError: |
|
258 |
pass # __init__ |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
259 |
if 'CWUser' in schema: # probably an empty schema if not true... |
0 | 260 |
# rql syntax trees used to authenticate users |
261 |
self._passwd_rqlst = self.compile_rql(self.passwd_rql) |
|
262 |
self._auth_rqlst = self.compile_rql(self.auth_rql) |
|
1792 | 263 |
|
0 | 264 |
def support_entity(self, etype, write=False): |
265 |
"""return true if the given entity's type is handled by this adapter |
|
266 |
if write is true, return true only if it's a RW support |
|
267 |
""" |
|
268 |
return not etype in NONSYSTEM_ETYPES |
|
1792 | 269 |
|
0 | 270 |
def support_relation(self, rtype, write=False): |
271 |
"""return true if the given relation's type is handled by this adapter |
|
272 |
if write is true, return true only if it's a RW support |
|
273 |
""" |
|
274 |
if write: |
|
275 |
return not rtype in NONSYSTEM_RELATIONS |
|
276 |
# due to current multi-sources implementation, the system source |
|
1792 | 277 |
# can't claim not supporting a relation |
0 | 278 |
return True #not rtype == 'content_for' |
279 |
||
280 |
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
|
281 |
"""return CWUser eid for the given login/password if this account is |
0 | 282 |
defined in this source, else raise `AuthenticationError` |
283 |
||
284 |
two queries are needed since passwords are stored crypted, so we have |
|
285 |
to fetch the salt first |
|
286 |
""" |
|
287 |
args = {'login': login, 'pwd' : password} |
|
288 |
if password is not None: |
|
289 |
rset = self.syntax_tree_search(session, self._passwd_rqlst, args) |
|
290 |
try: |
|
291 |
pwd = rset[0][0] |
|
292 |
except IndexError: |
|
293 |
raise AuthenticationError('bad login') |
|
1954 | 294 |
# passwords are stored using the Bytes type, so we get a StringIO |
0 | 295 |
if pwd is not None: |
296 |
args['pwd'] = crypt_password(password, pwd.getvalue()[:2]) |
|
297 |
# get eid from login and (crypted) password |
|
298 |
rset = self.syntax_tree_search(session, self._auth_rqlst, args) |
|
299 |
try: |
|
300 |
return rset[0][0] |
|
301 |
except IndexError: |
|
302 |
raise AuthenticationError('bad password') |
|
1792 | 303 |
|
304 |
def syntax_tree_search(self, session, union, args=None, cachekey=None, |
|
0 | 305 |
varmap=None): |
306 |
"""return result from this source for a rql query (actually from |
|
307 |
a rql syntax tree and a solution dictionary mapping each used |
|
308 |
variable to a possible type). If cachekey is given, the query |
|
309 |
necessary to fetch the results (but not the results themselves) |
|
310 |
may be cached using this key. |
|
311 |
""" |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
312 |
assert dbg_st_search(self.uri, union, varmap, args, cachekey) |
0 | 313 |
# remember number of actually selected term (sql generation may append some) |
314 |
if cachekey is None: |
|
315 |
self.no_cache += 1 |
|
316 |
# generate sql query if we are able to do so (not supported types...) |
|
317 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
318 |
else: |
|
319 |
# sql may be cached |
|
320 |
try: |
|
321 |
sql, query_args = self._cache[cachekey] |
|
322 |
self.cache_hit += 1 |
|
323 |
except KeyError: |
|
324 |
self.cache_miss += 1 |
|
325 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
326 |
self._cache[cachekey] = sql, query_args |
|
327 |
args = self.merge_args(args, query_args) |
|
328 |
assert isinstance(sql, basestring), repr(sql) |
|
329 |
try: |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
330 |
cursor = self.doexec(session, sql, args) |
0 | 331 |
except (self.dbapi_module.OperationalError, |
332 |
self.dbapi_module.InterfaceError): |
|
333 |
# FIXME: better detection of deconnection pb |
|
334 |
self.info("request failed '%s' ... retry with a new cursor", sql) |
|
335 |
session.pool.reconnect(self) |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
336 |
cursor = self.doexec(session, sql, args) |
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
337 |
results = self.process_result(cursor) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
338 |
assert dbg_results(results) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
339 |
return results |
1792 | 340 |
|
0 | 341 |
def flying_insert(self, table, session, union, args=None, varmap=None): |
342 |
"""similar as .syntax_tree_search, but inserts data in the |
|
343 |
temporary table (on-the-fly if possible, eg for the system |
|
344 |
source whose the given cursor come from). If not possible, |
|
345 |
inserts all data by calling .executemany(). |
|
346 |
""" |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
347 |
assert dbg_st_search( |
2638 | 348 |
self.uri, union, varmap, args, |
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
349 |
prefix='ON THE FLY temp data insertion into %s from' % table) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
350 |
# generate sql queries if we are able to do so |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
351 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
352 |
query = 'INSERT INTO %s %s' % (table, sql.encode(self.encoding)) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
353 |
self.doexec(session, query, self.merge_args(args, query_args)) |
1792 | 354 |
|
2627
d710278e0c1c
manual_insert is a public method
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2625
diff
changeset
|
355 |
def manual_insert(self, results, table, session): |
0 | 356 |
"""insert given result into a temporary table on the system source""" |
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
357 |
if server.DEBUG & server.DBG_RQL: |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
358 |
print ' manual insertion of', res, 'into', table |
0 | 359 |
if not results: |
360 |
return |
|
361 |
query_args = ['%%(%s)s' % i for i in xrange(len(results[0]))] |
|
362 |
query = 'INSERT INTO %s VALUES(%s)' % (table, ','.join(query_args)) |
|
363 |
kwargs_list = [] |
|
364 |
for row in results: |
|
365 |
kwargs = {} |
|
366 |
row = tuple(row) |
|
367 |
for index, cell in enumerate(row): |
|
2066
2c4bf4ee88a2
cleanup, stop encoding unicode string in manual_insert, no more necessary and make crash recent sqlite w/ 8bit string
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2064
diff
changeset
|
368 |
if isinstance(cell, Binary): |
0 | 369 |
cell = self.binary(cell.getvalue()) |
370 |
kwargs[str(index)] = cell |
|
371 |
kwargs_list.append(kwargs) |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
372 |
self.doexecmany(session, query, kwargs_list) |
0 | 373 |
|
374 |
def clean_temp_data(self, session, temptables): |
|
375 |
"""remove temporary data, usually associated to temporary tables""" |
|
376 |
if temptables: |
|
377 |
for table in temptables: |
|
378 |
try: |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
379 |
self.doexec(session,'DROP TABLE %s' % table) |
0 | 380 |
except: |
381 |
pass |
|
382 |
try: |
|
383 |
del self._temp_table_data[table] |
|
384 |
except KeyError: |
|
385 |
continue |
|
1792 | 386 |
|
0 | 387 |
def add_entity(self, session, entity): |
388 |
"""add a new entity to the source""" |
|
389 |
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
|
390 |
sql = self.sqlgen.insert(SQL_PREFIX + str(entity.e_schema), attrs) |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
391 |
self.doexec(session, sql, attrs) |
1792 | 392 |
|
0 | 393 |
def update_entity(self, session, entity): |
394 |
"""replace an entity in the source""" |
|
395 |
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
|
396 |
sql = self.sqlgen.update(SQL_PREFIX + str(entity.e_schema), attrs, [SQL_PREFIX + 'eid']) |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
397 |
self.doexec(session, sql, attrs) |
0 | 398 |
|
399 |
def delete_entity(self, session, etype, eid): |
|
400 |
"""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
|
401 |
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
|
402 |
sql = self.sqlgen.delete(SQL_PREFIX + etype, attrs) |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
403 |
self.doexec(session, sql, attrs) |
0 | 404 |
|
405 |
def add_relation(self, session, subject, rtype, object): |
|
406 |
"""add a relation to the source""" |
|
407 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
408 |
sql = self.sqlgen.insert('%s_relation' % rtype, attrs) |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
409 |
self.doexec(session, sql, attrs) |
1792 | 410 |
|
0 | 411 |
def delete_relation(self, session, subject, rtype, object): |
412 |
"""delete a relation from the source""" |
|
413 |
rschema = self.schema.rschema(rtype) |
|
414 |
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
|
415 |
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
|
416 |
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
|
417 |
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
|
418 |
SQL_PREFIX) |
0 | 419 |
attrs = {'eid' : subject} |
420 |
else: |
|
421 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
422 |
sql = self.sqlgen.delete('%s_relation' % rtype, attrs) |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
423 |
self.doexec(session, sql, attrs) |
0 | 424 |
|
2618
ff9b0d5bd884
[F repo sqlite schema changes] don't rollback on potentially expected schema changes failure
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2611
diff
changeset
|
425 |
def doexec(self, session, query, args=None, rollback=True): |
0 | 426 |
"""Execute a query. |
427 |
it's a function just so that it shows up in profiling |
|
428 |
""" |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
429 |
cursor = session.pool[self.uri] |
2593
16d9419a4a79
F: start to handle binary debug log level on the server side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2589
diff
changeset
|
430 |
if server.DEBUG & server.DBG_SQL: |
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
431 |
cnx = session.pool.connection(self.uri) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
432 |
# getattr to get the actual connection if cnx is a ConnectionWrapper |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
433 |
# instance |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
434 |
print 'exec', query, args, getattr(cnx, '_cnx', cnx) |
0 | 435 |
try: |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
436 |
# str(query) to avoid error if it's an unicode string |
0 | 437 |
cursor.execute(str(query), args) |
438 |
except Exception, ex: |
|
439 |
self.critical("sql: %r\n args: %s\ndbms message: %r", |
|
440 |
query, args, ex.args[0]) |
|
2618
ff9b0d5bd884
[F repo sqlite schema changes] don't rollback on potentially expected schema changes failure
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2611
diff
changeset
|
441 |
if rollback: |
ff9b0d5bd884
[F repo sqlite schema changes] don't rollback on potentially expected schema changes failure
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2611
diff
changeset
|
442 |
try: |
ff9b0d5bd884
[F repo sqlite schema changes] don't rollback on potentially expected schema changes failure
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2611
diff
changeset
|
443 |
session.pool.connection(self.uri).rollback() |
ff9b0d5bd884
[F repo sqlite schema changes] don't rollback on potentially expected schema changes failure
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2611
diff
changeset
|
444 |
self.critical('transaction has been rollbacked') |
ff9b0d5bd884
[F repo sqlite schema changes] don't rollback on potentially expected schema changes failure
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2611
diff
changeset
|
445 |
except: |
ff9b0d5bd884
[F repo sqlite schema changes] don't rollback on potentially expected schema changes failure
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2611
diff
changeset
|
446 |
pass |
0 | 447 |
raise |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
448 |
return cursor |
1792 | 449 |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
450 |
def doexecmany(self, session, query, args): |
0 | 451 |
"""Execute a query. |
452 |
it's a function just so that it shows up in profiling |
|
453 |
""" |
|
2593
16d9419a4a79
F: start to handle binary debug log level on the server side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2589
diff
changeset
|
454 |
if server.DEBUG & server.DBG_SQL: |
0 | 455 |
print 'execmany', query, 'with', len(args), 'arguments' |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
456 |
cursor = session.pool[self.uri] |
0 | 457 |
try: |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
458 |
# str(query) to avoid error if it's an unicode string |
0 | 459 |
cursor.executemany(str(query), args) |
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
460 |
except Exception, ex: |
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
461 |
self.critical("sql many: %r\n args: %s\ndbms message: %r", |
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
462 |
query, args, ex.args[0]) |
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
463 |
try: |
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
464 |
session.pool.connection(self.uri).rollback() |
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
465 |
self.critical('transaction has been rollbacked') |
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
466 |
except: |
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
467 |
pass |
0 | 468 |
raise |
1792 | 469 |
|
0 | 470 |
# short cut to method requiring advanced db helper usage ################## |
1792 | 471 |
|
0 | 472 |
def create_index(self, session, table, column, unique=False): |
473 |
cursor = LogCursor(session.pool[self.uri]) |
|
474 |
self.dbhelper.create_index(cursor, table, column, unique) |
|
1792 | 475 |
|
0 | 476 |
def drop_index(self, session, table, column, unique=False): |
477 |
cursor = LogCursor(session.pool[self.uri]) |
|
478 |
self.dbhelper.drop_index(cursor, table, column, unique) |
|
479 |
||
480 |
# system source interface ################################################# |
|
481 |
||
482 |
def eid_type_source(self, session, eid): |
|
483 |
"""return a tuple (type, source, extid) for the entity with id <eid>""" |
|
484 |
sql = 'SELECT type, source, extid FROM entities WHERE eid=%s' % eid |
|
485 |
try: |
|
486 |
res = session.system_sql(sql).fetchone() |
|
487 |
except: |
|
1079
452cb76fe07a
backport typo fix
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
973
diff
changeset
|
488 |
assert session.pool, 'session has no pool set' |
0 | 489 |
raise UnknownEid(eid) |
490 |
if res is None: |
|
491 |
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
|
492 |
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
|
493 |
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
|
494 |
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
|
495 |
res[-1] = b64decode(res[-1]) |
0 | 496 |
return res |
497 |
||
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
|
498 |
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
|
499 |
"""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
|
500 |
assert isinstance(extid, str) |
0 | 501 |
cursor = session.system_sql('SELECT eid FROM entities WHERE ' |
502 |
'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
|
503 |
{'x': b64encode(extid), 's': source.uri}) |
0 | 504 |
# XXX testing rowcount cause strange bug with sqlite, results are there |
505 |
# but rowcount is 0 |
|
1792 | 506 |
#if cursor.rowcount > 0: |
0 | 507 |
try: |
508 |
result = cursor.fetchone() |
|
509 |
if result: |
|
1954 | 510 |
return result[0] |
0 | 511 |
except: |
512 |
pass |
|
513 |
return None |
|
1792 | 514 |
|
0 | 515 |
def temp_table_def(self, selected, sol, table): |
516 |
return make_schema(selected, sol, table, self.dbhelper.TYPE_MAPPING) |
|
517 |
||
518 |
def create_temp_table(self, session, table, schema): |
|
519 |
# we don't want on commit drop, this may cause problem when |
|
520 |
# running with an ldap source, and table will be deleted manually any way |
|
521 |
# on commit |
|
522 |
sql = self.dbhelper.sql_temporary_table(table, schema, False) |
|
2306
95da5d9f0870
give session to doexec so it's able to rollback the connection on unexpected error
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2072
diff
changeset
|
523 |
self.doexec(session, sql) |
1792 | 524 |
|
0 | 525 |
def create_eid(self, session): |
526 |
self._eid_creation_lock.acquire() |
|
527 |
try: |
|
528 |
for sql in self.dbhelper.sqls_increment_sequence('entities_id_seq'): |
|
2310
80fcdfbb8eed
oops, needs the cursor
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2306
diff
changeset
|
529 |
cursor = self.doexec(session, sql) |
0 | 530 |
return cursor.fetchone()[0] |
531 |
finally: |
|
532 |
self._eid_creation_lock.release() |
|
533 |
||
534 |
def add_info(self, session, entity, source, extid=None): |
|
535 |
"""add type and source info for an eid into the system table""" |
|
536 |
# 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
|
537 |
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
|
538 |
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
|
539 |
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
|
540 |
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
|
541 |
'source': source.uri, 'mtime': datetime.now()} |
0 | 542 |
session.system_sql(self.sqlgen.insert('entities', attrs), attrs) |
543 |
||
544 |
def delete_info(self, session, eid, etype, uri, extid): |
|
545 |
"""delete system information on deletion of an entity by transfering |
|
546 |
record from the entities table to the deleted_entities table |
|
547 |
""" |
|
548 |
attrs = {'eid': eid} |
|
549 |
session.system_sql(self.sqlgen.delete('entities', attrs), attrs) |
|
550 |
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
|
551 |
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
|
552 |
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
|
553 |
extid = b64encode(extid) |
0 | 554 |
attrs = {'type': etype, 'eid': eid, 'extid': extid, |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
555 |
'source': uri, 'dtime': datetime.now()} |
0 | 556 |
session.system_sql(self.sqlgen.insert('deleted_entities', attrs), attrs) |
1792 | 557 |
|
0 | 558 |
def fti_unindex_entity(self, session, eid): |
559 |
"""remove text content for entity with the given eid from the full text |
|
560 |
index |
|
561 |
""" |
|
562 |
try: |
|
563 |
self.indexer.cursor_unindex_object(eid, session.pool['system']) |
|
564 |
except: |
|
565 |
if self.indexer is not None: |
|
566 |
self.exception('error while unindexing %s', eid) |
|
1792 | 567 |
|
0 | 568 |
def fti_index_entity(self, session, entity): |
569 |
"""add text content of a created/modified entity to the full text index |
|
570 |
""" |
|
571 |
self.info('reindexing %r', entity.eid) |
|
572 |
try: |
|
573 |
self.indexer.cursor_reindex_object(entity.eid, entity, |
|
574 |
session.pool['system']) |
|
575 |
except: |
|
576 |
if self.indexer is not None: |
|
577 |
self.exception('error while reindexing %s', entity) |
|
578 |
# update entities.mtime |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
579 |
attrs = {'eid': entity.eid, 'mtime': datetime.now()} |
0 | 580 |
session.system_sql(self.sqlgen.update('entities', attrs, ['eid']), attrs) |
1792 | 581 |
|
0 | 582 |
def modified_entities(self, session, etypes, mtime): |
583 |
"""return a 2-uple: |
|
584 |
* list of (etype, eid) of entities of the given types which have been |
|
585 |
modified since the given timestamp (actually entities whose full text |
|
586 |
index content has changed) |
|
587 |
* list of (etype, eid) of entities of the given types which have been |
|
588 |
deleted since the given timestamp |
|
589 |
""" |
|
590 |
modsql = _modified_sql('entities', etypes) |
|
591 |
cursor = session.system_sql(modsql, {'time': mtime}) |
|
592 |
modentities = cursor.fetchall() |
|
593 |
delsql = _modified_sql('deleted_entities', etypes) |
|
594 |
cursor = session.system_sql(delsql, {'time': mtime}) |
|
595 |
delentities = cursor.fetchall() |
|
596 |
return modentities, delentities |
|
597 |
||
598 |
||
599 |
def sql_schema(driver): |
|
600 |
helper = get_adv_func_helper(driver) |
|
601 |
schema = """ |
|
602 |
/* Create the repository's system database */ |
|
603 |
||
604 |
%s |
|
605 |
||
606 |
CREATE TABLE entities ( |
|
607 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
608 |
type VARCHAR(64) NOT NULL, |
|
609 |
source VARCHAR(64) NOT NULL, |
|
610 |
mtime TIMESTAMP NOT NULL, |
|
611 |
extid VARCHAR(256) |
|
612 |
); |
|
613 |
CREATE INDEX entities_type_idx ON entities(type); |
|
614 |
CREATE INDEX entities_mtime_idx ON entities(mtime); |
|
615 |
CREATE INDEX entities_extid_idx ON entities(extid); |
|
616 |
||
617 |
CREATE TABLE deleted_entities ( |
|
618 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
619 |
type VARCHAR(64) NOT NULL, |
|
620 |
source VARCHAR(64) NOT NULL, |
|
621 |
dtime TIMESTAMP NOT NULL, |
|
622 |
extid VARCHAR(256) |
|
623 |
); |
|
624 |
CREATE INDEX deleted_entities_type_idx ON deleted_entities(type); |
|
625 |
CREATE INDEX deleted_entities_dtime_idx ON deleted_entities(dtime); |
|
626 |
CREATE INDEX deleted_entities_extid_idx ON deleted_entities(extid); |
|
627 |
""" % helper.sql_create_sequence('entities_id_seq') |
|
628 |
return schema |
|
629 |
||
630 |
||
631 |
def sql_drop_schema(driver): |
|
632 |
helper = get_adv_func_helper(driver) |
|
633 |
return """ |
|
634 |
%s |
|
635 |
DROP TABLE entities; |
|
636 |
DROP TABLE deleted_entities; |
|
637 |
""" % helper.sql_drop_sequence('entities_id_seq') |
|
638 |
||
639 |
||
640 |
def grant_schema(user, set_owner=True): |
|
641 |
result = '' |
|
642 |
if set_owner: |
|
643 |
result = 'ALTER TABLE entities OWNER TO %s;\n' % user |
|
644 |
result += 'ALTER TABLE deleted_entities OWNER TO %s;\n' % user |
|
645 |
result += 'ALTER TABLE entities_id_seq OWNER TO %s;\n' % user |
|
646 |
result += 'GRANT ALL ON entities TO %s;\n' % user |
|
647 |
result += 'GRANT ALL ON deleted_entities TO %s;\n' % user |
|
648 |
result += 'GRANT ALL ON entities_id_seq TO %s;\n' % user |
|
649 |
return result |