author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Fri, 11 Sep 2009 20:37:30 +0200 | |
branch | stable |
changeset 3194 | 650637d4d764 |
parent 2959 | daabb9bc5233 |
child 2967 | e7d348134006 |
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""" |
2959
daabb9bc5233
make db-restore command work even with no/corrupted database
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
219 |
if self.repo.config.open_connections_pools: |
daabb9bc5233
make db-restore command work even with no/corrupted database
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
220 |
self.close_pool_connections() |
2759
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
221 |
try: |
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2638
diff
changeset
|
222 |
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
|
223 |
finally: |
2959
daabb9bc5233
make db-restore command work even with no/corrupted database
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
224 |
if self.repo.config.open_connections_pools: |
daabb9bc5233
make db-restore command work even with no/corrupted database
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
225 |
self.open_pool_connections() |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
226 |
|
0 | 227 |
def init(self): |
1792 | 228 |
self.init_creating() |
0 | 229 |
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
|
230 |
pool.pool_set() |
0 | 231 |
# XXX cubicweb < 2.42 compat |
232 |
if 'deleted_entities' in self.dbhelper.list_tables(pool['system']): |
|
233 |
self.has_deleted_entitites_table = True |
|
234 |
else: |
|
235 |
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
|
236 |
pool.pool_reset() |
0 | 237 |
self.repo._free_pool(pool) |
1792 | 238 |
|
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
|
239 |
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
|
240 |
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
|
241 |
|
0 | 242 |
# ISource interface ####################################################### |
243 |
||
244 |
def compile_rql(self, rql): |
|
245 |
rqlst = self.repo.querier._rqlhelper.parse(rql) |
|
246 |
rqlst.restricted_vars = () |
|
247 |
rqlst.children[0].solutions = self._sols |
|
248 |
self.repo.querier.sqlgen_annotate(rqlst) |
|
438 | 249 |
set_qdata(self.schema.rschema, rqlst, ()) |
0 | 250 |
return rqlst |
1792 | 251 |
|
0 | 252 |
def set_schema(self, schema): |
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
253 |
"""set the instance'schema""" |
0 | 254 |
self._cache = Cache(self.repo.config['rql-cache-size']) |
255 |
self.cache_hit, self.cache_miss, self.no_cache = 0, 0, 0 |
|
256 |
self.schema = schema |
|
257 |
try: |
|
258 |
self._rql_sqlgen.schema = schema |
|
259 |
except AttributeError: |
|
260 |
pass # __init__ |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
261 |
if 'CWUser' in schema: # probably an empty schema if not true... |
0 | 262 |
# rql syntax trees used to authenticate users |
263 |
self._passwd_rqlst = self.compile_rql(self.passwd_rql) |
|
264 |
self._auth_rqlst = self.compile_rql(self.auth_rql) |
|
1792 | 265 |
|
0 | 266 |
def support_entity(self, etype, write=False): |
267 |
"""return true if the given entity's type is handled by this adapter |
|
268 |
if write is true, return true only if it's a RW support |
|
269 |
""" |
|
270 |
return not etype in NONSYSTEM_ETYPES |
|
1792 | 271 |
|
0 | 272 |
def support_relation(self, rtype, write=False): |
273 |
"""return true if the given relation's type is handled by this adapter |
|
274 |
if write is true, return true only if it's a RW support |
|
275 |
""" |
|
276 |
if write: |
|
277 |
return not rtype in NONSYSTEM_RELATIONS |
|
278 |
# due to current multi-sources implementation, the system source |
|
1792 | 279 |
# can't claim not supporting a relation |
0 | 280 |
return True #not rtype == 'content_for' |
281 |
||
282 |
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
|
283 |
"""return CWUser eid for the given login/password if this account is |
0 | 284 |
defined in this source, else raise `AuthenticationError` |
285 |
||
286 |
two queries are needed since passwords are stored crypted, so we have |
|
287 |
to fetch the salt first |
|
288 |
""" |
|
289 |
args = {'login': login, 'pwd' : password} |
|
290 |
if password is not None: |
|
291 |
rset = self.syntax_tree_search(session, self._passwd_rqlst, args) |
|
292 |
try: |
|
293 |
pwd = rset[0][0] |
|
294 |
except IndexError: |
|
295 |
raise AuthenticationError('bad login') |
|
1954 | 296 |
# passwords are stored using the Bytes type, so we get a StringIO |
0 | 297 |
if pwd is not None: |
298 |
args['pwd'] = crypt_password(password, pwd.getvalue()[:2]) |
|
299 |
# get eid from login and (crypted) password |
|
300 |
rset = self.syntax_tree_search(session, self._auth_rqlst, args) |
|
301 |
try: |
|
302 |
return rset[0][0] |
|
303 |
except IndexError: |
|
304 |
raise AuthenticationError('bad password') |
|
1792 | 305 |
|
306 |
def syntax_tree_search(self, session, union, args=None, cachekey=None, |
|
0 | 307 |
varmap=None): |
308 |
"""return result from this source for a rql query (actually from |
|
309 |
a rql syntax tree and a solution dictionary mapping each used |
|
310 |
variable to a possible type). If cachekey is given, the query |
|
311 |
necessary to fetch the results (but not the results themselves) |
|
312 |
may be cached using this key. |
|
313 |
""" |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
314 |
assert dbg_st_search(self.uri, union, varmap, args, cachekey) |
0 | 315 |
# remember number of actually selected term (sql generation may append some) |
316 |
if cachekey is None: |
|
317 |
self.no_cache += 1 |
|
318 |
# generate sql query if we are able to do so (not supported types...) |
|
319 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
320 |
else: |
|
321 |
# sql may be cached |
|
322 |
try: |
|
323 |
sql, query_args = self._cache[cachekey] |
|
324 |
self.cache_hit += 1 |
|
325 |
except KeyError: |
|
326 |
self.cache_miss += 1 |
|
327 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
328 |
self._cache[cachekey] = sql, query_args |
|
329 |
args = self.merge_args(args, query_args) |
|
330 |
assert isinstance(sql, basestring), repr(sql) |
|
331 |
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
|
332 |
cursor = self.doexec(session, sql, args) |
0 | 333 |
except (self.dbapi_module.OperationalError, |
334 |
self.dbapi_module.InterfaceError): |
|
335 |
# FIXME: better detection of deconnection pb |
|
336 |
self.info("request failed '%s' ... retry with a new cursor", sql) |
|
337 |
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
|
338 |
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
|
339 |
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
|
340 |
assert dbg_results(results) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
341 |
return results |
1792 | 342 |
|
0 | 343 |
def flying_insert(self, table, session, union, args=None, varmap=None): |
344 |
"""similar as .syntax_tree_search, but inserts data in the |
|
345 |
temporary table (on-the-fly if possible, eg for the system |
|
346 |
source whose the given cursor come from). If not possible, |
|
347 |
inserts all data by calling .executemany(). |
|
348 |
""" |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
349 |
assert dbg_st_search( |
2638 | 350 |
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
|
351 |
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
|
352 |
# 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
|
353 |
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
|
354 |
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
|
355 |
self.doexec(session, query, self.merge_args(args, query_args)) |
1792 | 356 |
|
2627
d710278e0c1c
manual_insert is a public method
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2625
diff
changeset
|
357 |
def manual_insert(self, results, table, session): |
0 | 358 |
"""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
|
359 |
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
|
360 |
print ' manual insertion of', res, 'into', table |
0 | 361 |
if not results: |
362 |
return |
|
363 |
query_args = ['%%(%s)s' % i for i in xrange(len(results[0]))] |
|
364 |
query = 'INSERT INTO %s VALUES(%s)' % (table, ','.join(query_args)) |
|
365 |
kwargs_list = [] |
|
366 |
for row in results: |
|
367 |
kwargs = {} |
|
368 |
row = tuple(row) |
|
369 |
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
|
370 |
if isinstance(cell, Binary): |
0 | 371 |
cell = self.binary(cell.getvalue()) |
372 |
kwargs[str(index)] = cell |
|
373 |
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
|
374 |
self.doexecmany(session, query, kwargs_list) |
0 | 375 |
|
376 |
def clean_temp_data(self, session, temptables): |
|
377 |
"""remove temporary data, usually associated to temporary tables""" |
|
378 |
if temptables: |
|
379 |
for table in temptables: |
|
380 |
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
|
381 |
self.doexec(session,'DROP TABLE %s' % table) |
0 | 382 |
except: |
383 |
pass |
|
384 |
try: |
|
385 |
del self._temp_table_data[table] |
|
386 |
except KeyError: |
|
387 |
continue |
|
1792 | 388 |
|
0 | 389 |
def add_entity(self, session, entity): |
390 |
"""add a new entity to the source""" |
|
391 |
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
|
392 |
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
|
393 |
self.doexec(session, sql, attrs) |
1792 | 394 |
|
0 | 395 |
def update_entity(self, session, entity): |
396 |
"""replace an entity in the source""" |
|
397 |
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
|
398 |
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
|
399 |
self.doexec(session, sql, attrs) |
0 | 400 |
|
401 |
def delete_entity(self, session, etype, eid): |
|
402 |
"""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
|
403 |
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
|
404 |
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
|
405 |
self.doexec(session, sql, attrs) |
0 | 406 |
|
407 |
def add_relation(self, session, subject, rtype, object): |
|
408 |
"""add a relation to the source""" |
|
409 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
410 |
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
|
411 |
self.doexec(session, sql, attrs) |
1792 | 412 |
|
0 | 413 |
def delete_relation(self, session, subject, rtype, object): |
414 |
"""delete a relation from the source""" |
|
415 |
rschema = self.schema.rschema(rtype) |
|
416 |
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
|
417 |
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
|
418 |
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
|
419 |
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
|
420 |
SQL_PREFIX) |
0 | 421 |
attrs = {'eid' : subject} |
422 |
else: |
|
423 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
424 |
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
|
425 |
self.doexec(session, sql, attrs) |
0 | 426 |
|
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
|
427 |
def doexec(self, session, query, args=None, rollback=True): |
0 | 428 |
"""Execute a query. |
429 |
it's a function just so that it shows up in profiling |
|
430 |
""" |
|
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
|
431 |
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
|
432 |
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
|
433 |
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
|
434 |
# 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
|
435 |
# instance |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
436 |
print 'exec', query, args, getattr(cnx, '_cnx', cnx) |
0 | 437 |
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
|
438 |
# str(query) to avoid error if it's an unicode string |
0 | 439 |
cursor.execute(str(query), args) |
440 |
except Exception, ex: |
|
441 |
self.critical("sql: %r\n args: %s\ndbms message: %r", |
|
442 |
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
|
443 |
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
|
444 |
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
|
445 |
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
|
446 |
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
|
447 |
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
|
448 |
pass |
0 | 449 |
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
|
450 |
return cursor |
1792 | 451 |
|
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
|
452 |
def doexecmany(self, session, query, args): |
0 | 453 |
"""Execute a query. |
454 |
it's a function just so that it shows up in profiling |
|
455 |
""" |
|
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
|
456 |
if server.DEBUG & server.DBG_SQL: |
0 | 457 |
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
|
458 |
cursor = session.pool[self.uri] |
0 | 459 |
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
|
460 |
# str(query) to avoid error if it's an unicode string |
0 | 461 |
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
|
462 |
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
|
463 |
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
|
464 |
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
|
465 |
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
|
466 |
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
|
467 |
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
|
468 |
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
|
469 |
pass |
0 | 470 |
raise |
1792 | 471 |
|
0 | 472 |
# short cut to method requiring advanced db helper usage ################## |
1792 | 473 |
|
0 | 474 |
def create_index(self, session, table, column, unique=False): |
475 |
cursor = LogCursor(session.pool[self.uri]) |
|
476 |
self.dbhelper.create_index(cursor, table, column, unique) |
|
1792 | 477 |
|
0 | 478 |
def drop_index(self, session, table, column, unique=False): |
479 |
cursor = LogCursor(session.pool[self.uri]) |
|
480 |
self.dbhelper.drop_index(cursor, table, column, unique) |
|
481 |
||
482 |
# system source interface ################################################# |
|
483 |
||
484 |
def eid_type_source(self, session, eid): |
|
485 |
"""return a tuple (type, source, extid) for the entity with id <eid>""" |
|
486 |
sql = 'SELECT type, source, extid FROM entities WHERE eid=%s' % eid |
|
487 |
try: |
|
488 |
res = session.system_sql(sql).fetchone() |
|
489 |
except: |
|
1079
452cb76fe07a
backport typo fix
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
973
diff
changeset
|
490 |
assert session.pool, 'session has no pool set' |
0 | 491 |
raise UnknownEid(eid) |
492 |
if res is None: |
|
493 |
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
|
494 |
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
|
495 |
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
|
496 |
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
|
497 |
res[-1] = b64decode(res[-1]) |
0 | 498 |
return res |
499 |
||
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
|
500 |
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
|
501 |
"""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
|
502 |
assert isinstance(extid, str) |
0 | 503 |
cursor = session.system_sql('SELECT eid FROM entities WHERE ' |
504 |
'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
|
505 |
{'x': b64encode(extid), 's': source.uri}) |
0 | 506 |
# XXX testing rowcount cause strange bug with sqlite, results are there |
507 |
# but rowcount is 0 |
|
1792 | 508 |
#if cursor.rowcount > 0: |
0 | 509 |
try: |
510 |
result = cursor.fetchone() |
|
511 |
if result: |
|
1954 | 512 |
return result[0] |
0 | 513 |
except: |
514 |
pass |
|
515 |
return None |
|
1792 | 516 |
|
0 | 517 |
def temp_table_def(self, selected, sol, table): |
518 |
return make_schema(selected, sol, table, self.dbhelper.TYPE_MAPPING) |
|
519 |
||
520 |
def create_temp_table(self, session, table, schema): |
|
521 |
# we don't want on commit drop, this may cause problem when |
|
522 |
# running with an ldap source, and table will be deleted manually any way |
|
523 |
# on commit |
|
524 |
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
|
525 |
self.doexec(session, sql) |
1792 | 526 |
|
0 | 527 |
def create_eid(self, session): |
528 |
self._eid_creation_lock.acquire() |
|
529 |
try: |
|
530 |
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
|
531 |
cursor = self.doexec(session, sql) |
0 | 532 |
return cursor.fetchone()[0] |
533 |
finally: |
|
534 |
self._eid_creation_lock.release() |
|
535 |
||
536 |
def add_info(self, session, entity, source, extid=None): |
|
537 |
"""add type and source info for an eid into the system table""" |
|
538 |
# 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
|
539 |
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
|
540 |
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
|
541 |
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
|
542 |
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
|
543 |
'source': source.uri, 'mtime': datetime.now()} |
0 | 544 |
session.system_sql(self.sqlgen.insert('entities', attrs), attrs) |
545 |
||
546 |
def delete_info(self, session, eid, etype, uri, extid): |
|
547 |
"""delete system information on deletion of an entity by transfering |
|
548 |
record from the entities table to the deleted_entities table |
|
549 |
""" |
|
550 |
attrs = {'eid': eid} |
|
551 |
session.system_sql(self.sqlgen.delete('entities', attrs), attrs) |
|
552 |
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
|
553 |
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
|
554 |
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
|
555 |
extid = b64encode(extid) |
0 | 556 |
attrs = {'type': etype, 'eid': eid, 'extid': extid, |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
557 |
'source': uri, 'dtime': datetime.now()} |
0 | 558 |
session.system_sql(self.sqlgen.insert('deleted_entities', attrs), attrs) |
1792 | 559 |
|
0 | 560 |
def fti_unindex_entity(self, session, eid): |
561 |
"""remove text content for entity with the given eid from the full text |
|
562 |
index |
|
563 |
""" |
|
564 |
try: |
|
565 |
self.indexer.cursor_unindex_object(eid, session.pool['system']) |
|
566 |
except: |
|
567 |
if self.indexer is not None: |
|
568 |
self.exception('error while unindexing %s', eid) |
|
1792 | 569 |
|
0 | 570 |
def fti_index_entity(self, session, entity): |
571 |
"""add text content of a created/modified entity to the full text index |
|
572 |
""" |
|
573 |
self.info('reindexing %r', entity.eid) |
|
574 |
try: |
|
575 |
self.indexer.cursor_reindex_object(entity.eid, entity, |
|
576 |
session.pool['system']) |
|
577 |
except: |
|
578 |
if self.indexer is not None: |
|
579 |
self.exception('error while reindexing %s', entity) |
|
580 |
# update entities.mtime |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
581 |
attrs = {'eid': entity.eid, 'mtime': datetime.now()} |
0 | 582 |
session.system_sql(self.sqlgen.update('entities', attrs, ['eid']), attrs) |
1792 | 583 |
|
0 | 584 |
def modified_entities(self, session, etypes, mtime): |
585 |
"""return a 2-uple: |
|
586 |
* list of (etype, eid) of entities of the given types which have been |
|
587 |
modified since the given timestamp (actually entities whose full text |
|
588 |
index content has changed) |
|
589 |
* list of (etype, eid) of entities of the given types which have been |
|
590 |
deleted since the given timestamp |
|
591 |
""" |
|
592 |
modsql = _modified_sql('entities', etypes) |
|
593 |
cursor = session.system_sql(modsql, {'time': mtime}) |
|
594 |
modentities = cursor.fetchall() |
|
595 |
delsql = _modified_sql('deleted_entities', etypes) |
|
596 |
cursor = session.system_sql(delsql, {'time': mtime}) |
|
597 |
delentities = cursor.fetchall() |
|
598 |
return modentities, delentities |
|
599 |
||
600 |
||
601 |
def sql_schema(driver): |
|
602 |
helper = get_adv_func_helper(driver) |
|
603 |
schema = """ |
|
604 |
/* Create the repository's system database */ |
|
605 |
||
606 |
%s |
|
607 |
||
608 |
CREATE TABLE entities ( |
|
609 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
610 |
type VARCHAR(64) NOT NULL, |
|
611 |
source VARCHAR(64) NOT NULL, |
|
612 |
mtime TIMESTAMP NOT NULL, |
|
613 |
extid VARCHAR(256) |
|
614 |
); |
|
615 |
CREATE INDEX entities_type_idx ON entities(type); |
|
616 |
CREATE INDEX entities_mtime_idx ON entities(mtime); |
|
617 |
CREATE INDEX entities_extid_idx ON entities(extid); |
|
618 |
||
619 |
CREATE TABLE deleted_entities ( |
|
620 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
621 |
type VARCHAR(64) NOT NULL, |
|
622 |
source VARCHAR(64) NOT NULL, |
|
623 |
dtime TIMESTAMP NOT NULL, |
|
624 |
extid VARCHAR(256) |
|
625 |
); |
|
626 |
CREATE INDEX deleted_entities_type_idx ON deleted_entities(type); |
|
627 |
CREATE INDEX deleted_entities_dtime_idx ON deleted_entities(dtime); |
|
628 |
CREATE INDEX deleted_entities_extid_idx ON deleted_entities(extid); |
|
629 |
""" % helper.sql_create_sequence('entities_id_seq') |
|
630 |
return schema |
|
631 |
||
632 |
||
633 |
def sql_drop_schema(driver): |
|
634 |
helper = get_adv_func_helper(driver) |
|
635 |
return """ |
|
636 |
%s |
|
637 |
DROP TABLE entities; |
|
638 |
DROP TABLE deleted_entities; |
|
639 |
""" % helper.sql_drop_sequence('entities_id_seq') |
|
640 |
||
641 |
||
642 |
def grant_schema(user, set_owner=True): |
|
643 |
result = '' |
|
644 |
if set_owner: |
|
645 |
result = 'ALTER TABLE entities OWNER TO %s;\n' % user |
|
646 |
result += 'ALTER TABLE deleted_entities OWNER TO %s;\n' % user |
|
647 |
result += 'ALTER TABLE entities_id_seq OWNER TO %s;\n' % user |
|
648 |
result += 'GRANT ALL ON entities TO %s;\n' % user |
|
649 |
result += 'GRANT ALL ON deleted_entities TO %s;\n' % user |
|
650 |
result += 'GRANT ALL ON entities_id_seq TO %s;\n' % user |
|
651 |
return result |