author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Wed, 23 Dec 2009 08:56:38 +0100 | |
branch | stable |
changeset 4198 | 8d644eb862b9 |
parent 4195 | 86dcaf6bb92f |
child 4204 | 60256056bda6 |
child 4212 | ab6573088b4a |
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 |
|
3835
a191b3b9e455
more sensible default values to c-c "create" inputs
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3689
diff
changeset
|
21 |
from logilab.common.configuration import Method |
0 | 22 |
from logilab.common.adbh import get_adv_func_helper |
3835
a191b3b9e455
more sensible default values to c-c "create" inputs
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3689
diff
changeset
|
23 |
from logilab.common.shellutils import getlogin |
0 | 24 |
|
25 |
from indexer import get_indexer |
|
26 |
||
27 |
from cubicweb import UnknownEid, AuthenticationError, Binary, server |
|
3835
a191b3b9e455
more sensible default values to c-c "create" inputs
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3689
diff
changeset
|
28 |
from cubicweb.cwconfig import CubicWebNoAppConfiguration |
0 | 29 |
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
|
30 |
from cubicweb.server.sqlutils import SQL_PREFIX, SQLAdapterMixIn |
0 | 31 |
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
|
32 |
from cubicweb.server.sources import AbstractSource, dbg_st_search, dbg_results |
0 | 33 |
from cubicweb.server.sources.rql2sql import SQLGenerator |
34 |
||
35 |
||
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
|
36 |
ATTR_MAP = {} |
0 | 37 |
NONSYSTEM_ETYPES = set() |
38 |
NONSYSTEM_RELATIONS = set() |
|
39 |
||
40 |
class LogCursor(object): |
|
41 |
def __init__(self, cursor): |
|
42 |
self.cu = cursor |
|
1792 | 43 |
|
0 | 44 |
def execute(self, query, args=None): |
45 |
"""Execute a query. |
|
46 |
it's a function just so that it shows up in profiling |
|
47 |
""" |
|
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
|
48 |
if server.DEBUG & server.DBG_SQL: |
0 | 49 |
print 'exec', query, args |
50 |
try: |
|
51 |
self.cu.execute(str(query), args) |
|
52 |
except Exception, ex: |
|
53 |
print "sql: %r\n args: %s\ndbms message: %r" % ( |
|
54 |
query, args, ex.args[0]) |
|
55 |
raise |
|
1792 | 56 |
|
0 | 57 |
def fetchall(self): |
58 |
return self.cu.fetchall() |
|
1792 | 59 |
|
0 | 60 |
def fetchone(self): |
61 |
return self.cu.fetchone() |
|
1792 | 62 |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
63 |
|
0 | 64 |
def make_schema(selected, solution, table, typemap): |
65 |
"""return a sql schema to store RQL query result""" |
|
66 |
sql = [] |
|
67 |
varmap = {} |
|
68 |
for i, term in enumerate(selected): |
|
69 |
name = 'C%s' % i |
|
70 |
key = term.as_string() |
|
71 |
varmap[key] = '%s.%s' % (table, name) |
|
72 |
ttype = term.get_type(solution) |
|
73 |
try: |
|
74 |
sql.append('%s %s' % (name, typemap[ttype])) |
|
75 |
except KeyError: |
|
3689
deb13e88e037
follow yams 0.25 api changes to improve performance
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3497
diff
changeset
|
76 |
# assert not schema(ttype).final |
0 | 77 |
sql.append('%s %s' % (name, typemap['Int'])) |
78 |
return ','.join(sql), varmap |
|
79 |
||
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
80 |
|
0 | 81 |
def _modified_sql(table, etypes): |
82 |
# XXX protect against sql injection |
|
83 |
if len(etypes) > 1: |
|
84 |
restr = 'type IN (%s)' % ','.join("'%s'" % etype for etype in etypes) |
|
85 |
else: |
|
86 |
restr = "type='%s'" % etypes[0] |
|
87 |
if table == 'entities': |
|
88 |
attr = 'mtime' |
|
89 |
else: |
|
90 |
attr = 'dtime' |
|
91 |
return 'SELECT type, eid FROM %s WHERE %s AND %s > %%(time)s' % ( |
|
92 |
table, restr, attr) |
|
93 |
||
94 |
||
95 |
class NativeSQLSource(SQLAdapterMixIn, AbstractSource): |
|
96 |
"""adapter for source using the native cubicweb schema (see below) |
|
97 |
""" |
|
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
|
98 |
sqlgen_class = SQLGenerator |
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', |
|
3835
a191b3b9e455
more sensible default values to c-c "create" inputs
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3689
diff
changeset
|
125 |
'default': Method('default_instance_id'), |
0 | 126 |
'help': 'database name', |
127 |
'group': 'native-source', 'inputlevel': 0, |
|
128 |
}), |
|
129 |
('db-user', |
|
130 |
{'type' : 'string', |
|
3835
a191b3b9e455
more sensible default values to c-c "create" inputs
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3689
diff
changeset
|
131 |
'default': CubicWebNoAppConfiguration.mode == 'user' and getlogin() or 'cubicweb', |
0 | 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 |
|
4195
86dcaf6bb92f
closes #601987
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4185
diff
changeset
|
217 |
def restore(self, backupfile, confirm, 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: |
4195
86dcaf6bb92f
closes #601987
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4185
diff
changeset
|
222 |
self.restore_from_file(backupfile, confirm, drop=drop) |
2759
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() |
229 |
||
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
|
230 |
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
|
231 |
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
|
232 |
|
0 | 233 |
# ISource interface ####################################################### |
234 |
||
235 |
def compile_rql(self, rql): |
|
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3041
diff
changeset
|
236 |
rqlst = self.repo.vreg.rqlhelper.parse(rql) |
0 | 237 |
rqlst.restricted_vars = () |
238 |
rqlst.children[0].solutions = self._sols |
|
239 |
self.repo.querier.sqlgen_annotate(rqlst) |
|
438 | 240 |
set_qdata(self.schema.rschema, rqlst, ()) |
0 | 241 |
return rqlst |
1792 | 242 |
|
0 | 243 |
def set_schema(self, schema): |
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2354
diff
changeset
|
244 |
"""set the instance'schema""" |
0 | 245 |
self._cache = Cache(self.repo.config['rql-cache-size']) |
246 |
self.cache_hit, self.cache_miss, self.no_cache = 0, 0, 0 |
|
247 |
self.schema = schema |
|
248 |
try: |
|
249 |
self._rql_sqlgen.schema = schema |
|
250 |
except AttributeError: |
|
251 |
pass # __init__ |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
252 |
if 'CWUser' in schema: # probably an empty schema if not true... |
0 | 253 |
# rql syntax trees used to authenticate users |
254 |
self._passwd_rqlst = self.compile_rql(self.passwd_rql) |
|
255 |
self._auth_rqlst = self.compile_rql(self.auth_rql) |
|
1792 | 256 |
|
0 | 257 |
def support_entity(self, etype, write=False): |
258 |
"""return true if the given entity's type is handled by this adapter |
|
259 |
if write is true, return true only if it's a RW support |
|
260 |
""" |
|
261 |
return not etype in NONSYSTEM_ETYPES |
|
1792 | 262 |
|
0 | 263 |
def support_relation(self, rtype, write=False): |
264 |
"""return true if the given relation's type is handled by this adapter |
|
265 |
if write is true, return true only if it's a RW support |
|
266 |
""" |
|
267 |
if write: |
|
268 |
return not rtype in NONSYSTEM_RELATIONS |
|
269 |
# due to current multi-sources implementation, the system source |
|
1792 | 270 |
# can't claim not supporting a relation |
0 | 271 |
return True #not rtype == 'content_for' |
272 |
||
3041
782fa7566a22
[multi-sources] new may_cross_relation method on sources
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2967
diff
changeset
|
273 |
def may_cross_relation(self, rtype): |
782fa7566a22
[multi-sources] new may_cross_relation method on sources
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2967
diff
changeset
|
274 |
return True |
782fa7566a22
[multi-sources] new may_cross_relation method on sources
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2967
diff
changeset
|
275 |
|
0 | 276 |
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
|
277 |
"""return CWUser eid for the given login/password if this account is |
0 | 278 |
defined in this source, else raise `AuthenticationError` |
279 |
||
280 |
two queries are needed since passwords are stored crypted, so we have |
|
281 |
to fetch the salt first |
|
282 |
""" |
|
283 |
args = {'login': login, 'pwd' : password} |
|
284 |
if password is not None: |
|
285 |
rset = self.syntax_tree_search(session, self._passwd_rqlst, args) |
|
286 |
try: |
|
287 |
pwd = rset[0][0] |
|
288 |
except IndexError: |
|
289 |
raise AuthenticationError('bad login') |
|
1954 | 290 |
# passwords are stored using the Bytes type, so we get a StringIO |
0 | 291 |
if pwd is not None: |
4185
ed99de8f93f2
should turn password into a Binary properly
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4113
diff
changeset
|
292 |
args['pwd'] = Binary(crypt_password(password, pwd.getvalue()[:2])) |
0 | 293 |
# get eid from login and (crypted) password |
4185
ed99de8f93f2
should turn password into a Binary properly
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4113
diff
changeset
|
294 |
# XXX why not simply compare password? |
0 | 295 |
rset = self.syntax_tree_search(session, self._auth_rqlst, args) |
296 |
try: |
|
297 |
return rset[0][0] |
|
298 |
except IndexError: |
|
299 |
raise AuthenticationError('bad password') |
|
1792 | 300 |
|
301 |
def syntax_tree_search(self, session, union, args=None, cachekey=None, |
|
0 | 302 |
varmap=None): |
303 |
"""return result from this source for a rql query (actually from |
|
304 |
a rql syntax tree and a solution dictionary mapping each used |
|
305 |
variable to a possible type). If cachekey is given, the query |
|
306 |
necessary to fetch the results (but not the results themselves) |
|
307 |
may be cached using this key. |
|
308 |
""" |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
309 |
assert dbg_st_search(self.uri, union, varmap, args, cachekey) |
0 | 310 |
# remember number of actually selected term (sql generation may append some) |
311 |
if cachekey is None: |
|
312 |
self.no_cache += 1 |
|
313 |
# generate sql query if we are able to do so (not supported types...) |
|
314 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
315 |
else: |
|
316 |
# sql may be cached |
|
317 |
try: |
|
318 |
sql, query_args = self._cache[cachekey] |
|
319 |
self.cache_hit += 1 |
|
320 |
except KeyError: |
|
321 |
self.cache_miss += 1 |
|
322 |
sql, query_args = self._rql_sqlgen.generate(union, args, varmap) |
|
323 |
self._cache[cachekey] = sql, query_args |
|
324 |
args = self.merge_args(args, query_args) |
|
325 |
assert isinstance(sql, basestring), repr(sql) |
|
326 |
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
|
327 |
cursor = self.doexec(session, sql, args) |
0 | 328 |
except (self.dbapi_module.OperationalError, |
329 |
self.dbapi_module.InterfaceError): |
|
330 |
# FIXME: better detection of deconnection pb |
|
331 |
self.info("request failed '%s' ... retry with a new cursor", sql) |
|
332 |
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
|
333 |
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
|
334 |
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
|
335 |
assert dbg_results(results) |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
336 |
return results |
1792 | 337 |
|
0 | 338 |
def flying_insert(self, table, session, union, args=None, varmap=None): |
339 |
"""similar as .syntax_tree_search, but inserts data in the |
|
340 |
temporary table (on-the-fly if possible, eg for the system |
|
341 |
source whose the given cursor come from). If not possible, |
|
342 |
inserts all data by calling .executemany(). |
|
343 |
""" |
|
2625
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
344 |
assert dbg_st_search( |
2638 | 345 |
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
|
346 |
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
|
347 |
# 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
|
348 |
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
|
349 |
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
|
350 |
self.doexec(session, query, self.merge_args(args, query_args)) |
1792 | 351 |
|
2627
d710278e0c1c
manual_insert is a public method
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2625
diff
changeset
|
352 |
def manual_insert(self, results, table, session): |
0 | 353 |
"""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
|
354 |
if server.DEBUG & server.DBG_RQL: |
3958
505025eb0d37
fix name error while debugging
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3835
diff
changeset
|
355 |
print ' manual insertion of', results, 'into', table |
0 | 356 |
if not results: |
357 |
return |
|
358 |
query_args = ['%%(%s)s' % i for i in xrange(len(results[0]))] |
|
359 |
query = 'INSERT INTO %s VALUES(%s)' % (table, ','.join(query_args)) |
|
360 |
kwargs_list = [] |
|
361 |
for row in results: |
|
362 |
kwargs = {} |
|
363 |
row = tuple(row) |
|
364 |
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
|
365 |
if isinstance(cell, Binary): |
0 | 366 |
cell = self.binary(cell.getvalue()) |
367 |
kwargs[str(index)] = cell |
|
368 |
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
|
369 |
self.doexecmany(session, query, kwargs_list) |
0 | 370 |
|
371 |
def clean_temp_data(self, session, temptables): |
|
372 |
"""remove temporary data, usually associated to temporary tables""" |
|
373 |
if temptables: |
|
374 |
for table in temptables: |
|
375 |
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
|
376 |
self.doexec(session,'DROP TABLE %s' % table) |
0 | 377 |
except: |
378 |
pass |
|
379 |
try: |
|
380 |
del self._temp_table_data[table] |
|
381 |
except KeyError: |
|
382 |
continue |
|
1792 | 383 |
|
0 | 384 |
def add_entity(self, session, entity): |
385 |
"""add a new entity to the source""" |
|
386 |
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
|
387 |
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
|
388 |
self.doexec(session, sql, attrs) |
1792 | 389 |
|
0 | 390 |
def update_entity(self, session, entity): |
391 |
"""replace an entity in the source""" |
|
392 |
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
|
393 |
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
|
394 |
self.doexec(session, sql, attrs) |
0 | 395 |
|
396 |
def delete_entity(self, session, etype, eid): |
|
397 |
"""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
|
398 |
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
|
399 |
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
|
400 |
self.doexec(session, sql, attrs) |
0 | 401 |
|
402 |
def add_relation(self, session, subject, rtype, object): |
|
403 |
"""add a relation to the source""" |
|
404 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
405 |
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
|
406 |
self.doexec(session, sql, attrs) |
1792 | 407 |
|
0 | 408 |
def delete_relation(self, session, subject, rtype, object): |
409 |
"""delete a relation from the source""" |
|
410 |
rschema = self.schema.rschema(rtype) |
|
411 |
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
|
412 |
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
|
413 |
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
|
414 |
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
|
415 |
SQL_PREFIX) |
0 | 416 |
attrs = {'eid' : subject} |
417 |
else: |
|
418 |
attrs = {'eid_from': subject, 'eid_to': object} |
|
419 |
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
|
420 |
self.doexec(session, sql, attrs) |
0 | 421 |
|
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
|
422 |
def doexec(self, session, query, args=None, rollback=True): |
0 | 423 |
"""Execute a query. |
424 |
it's a function just so that it shows up in profiling |
|
425 |
""" |
|
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
|
426 |
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
|
427 |
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
|
428 |
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
|
429 |
# 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
|
430 |
# instance |
d6012db7b93e
R [server debug] more server side debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2620
diff
changeset
|
431 |
print 'exec', query, args, getattr(cnx, '_cnx', cnx) |
0 | 432 |
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
|
433 |
# str(query) to avoid error if it's an unicode string |
0 | 434 |
cursor.execute(str(query), args) |
435 |
except Exception, ex: |
|
436 |
self.critical("sql: %r\n args: %s\ndbms message: %r", |
|
437 |
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
|
438 |
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
|
439 |
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
|
440 |
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
|
441 |
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
|
442 |
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
|
443 |
pass |
0 | 444 |
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
|
445 |
return cursor |
1792 | 446 |
|
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
|
447 |
def doexecmany(self, session, query, args): |
0 | 448 |
"""Execute a query. |
449 |
it's a function just so that it shows up in profiling |
|
450 |
""" |
|
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
|
451 |
if server.DEBUG & server.DBG_SQL: |
0 | 452 |
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
|
453 |
cursor = session.pool[self.uri] |
0 | 454 |
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
|
455 |
# str(query) to avoid error if it's an unicode string |
0 | 456 |
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
|
457 |
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
|
458 |
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
|
459 |
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
|
460 |
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
|
461 |
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
|
462 |
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
|
463 |
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
|
464 |
pass |
0 | 465 |
raise |
1792 | 466 |
|
0 | 467 |
# short cut to method requiring advanced db helper usage ################## |
1792 | 468 |
|
0 | 469 |
def create_index(self, session, table, column, unique=False): |
470 |
cursor = LogCursor(session.pool[self.uri]) |
|
471 |
self.dbhelper.create_index(cursor, table, column, unique) |
|
1792 | 472 |
|
0 | 473 |
def drop_index(self, session, table, column, unique=False): |
474 |
cursor = LogCursor(session.pool[self.uri]) |
|
475 |
self.dbhelper.drop_index(cursor, table, column, unique) |
|
476 |
||
477 |
# system source interface ################################################# |
|
478 |
||
479 |
def eid_type_source(self, session, eid): |
|
480 |
"""return a tuple (type, source, extid) for the entity with id <eid>""" |
|
481 |
sql = 'SELECT type, source, extid FROM entities WHERE eid=%s' % eid |
|
482 |
try: |
|
483 |
res = session.system_sql(sql).fetchone() |
|
484 |
except: |
|
1079
452cb76fe07a
backport typo fix
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
973
diff
changeset
|
485 |
assert session.pool, 'session has no pool set' |
0 | 486 |
raise UnknownEid(eid) |
487 |
if res is None: |
|
488 |
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
|
489 |
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
|
490 |
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
|
491 |
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
|
492 |
res[-1] = b64decode(res[-1]) |
0 | 493 |
return res |
494 |
||
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
|
495 |
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
|
496 |
"""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
|
497 |
assert isinstance(extid, str) |
0 | 498 |
cursor = session.system_sql('SELECT eid FROM entities WHERE ' |
499 |
'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
|
500 |
{'x': b64encode(extid), 's': source.uri}) |
0 | 501 |
# XXX testing rowcount cause strange bug with sqlite, results are there |
502 |
# but rowcount is 0 |
|
1792 | 503 |
#if cursor.rowcount > 0: |
0 | 504 |
try: |
505 |
result = cursor.fetchone() |
|
506 |
if result: |
|
1954 | 507 |
return result[0] |
0 | 508 |
except: |
509 |
pass |
|
510 |
return None |
|
1792 | 511 |
|
0 | 512 |
def temp_table_def(self, selected, sol, table): |
513 |
return make_schema(selected, sol, table, self.dbhelper.TYPE_MAPPING) |
|
514 |
||
515 |
def create_temp_table(self, session, table, schema): |
|
516 |
# we don't want on commit drop, this may cause problem when |
|
517 |
# running with an ldap source, and table will be deleted manually any way |
|
518 |
# on commit |
|
519 |
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
|
520 |
self.doexec(session, sql) |
1792 | 521 |
|
0 | 522 |
def create_eid(self, session): |
523 |
self._eid_creation_lock.acquire() |
|
524 |
try: |
|
525 |
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
|
526 |
cursor = self.doexec(session, sql) |
0 | 527 |
return cursor.fetchone()[0] |
528 |
finally: |
|
529 |
self._eid_creation_lock.release() |
|
530 |
||
531 |
def add_info(self, session, entity, source, extid=None): |
|
532 |
"""add type and source info for an eid into the system table""" |
|
533 |
# 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
|
534 |
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
|
535 |
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
|
536 |
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
|
537 |
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
|
538 |
'source': source.uri, 'mtime': datetime.now()} |
0 | 539 |
session.system_sql(self.sqlgen.insert('entities', attrs), attrs) |
540 |
||
541 |
def delete_info(self, session, eid, etype, uri, extid): |
|
542 |
"""delete system information on deletion of an entity by transfering |
|
543 |
record from the entities table to the deleted_entities table |
|
544 |
""" |
|
545 |
attrs = {'eid': eid} |
|
546 |
session.system_sql(self.sqlgen.delete('entities', attrs), attrs) |
|
2955
6bb5025c9fc7
remove some pretty old deprecation code
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
547 |
if extid is not None: |
6bb5025c9fc7
remove some pretty old deprecation code
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
548 |
assert isinstance(extid, str), type(extid) |
6bb5025c9fc7
remove some pretty old deprecation code
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
549 |
extid = b64encode(extid) |
6bb5025c9fc7
remove some pretty old deprecation code
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
550 |
attrs = {'type': etype, 'eid': eid, 'extid': extid, |
6bb5025c9fc7
remove some pretty old deprecation code
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
551 |
'source': uri, 'dtime': datetime.now()} |
6bb5025c9fc7
remove some pretty old deprecation code
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
552 |
session.system_sql(self.sqlgen.insert('deleted_entities', attrs), attrs) |
1792 | 553 |
|
0 | 554 |
def fti_unindex_entity(self, session, eid): |
555 |
"""remove text content for entity with the given eid from the full text |
|
556 |
index |
|
557 |
""" |
|
558 |
try: |
|
559 |
self.indexer.cursor_unindex_object(eid, session.pool['system']) |
|
3497
63b9541dd36f
[fti] don't catch BaseException subclasses
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3240
diff
changeset
|
560 |
except Exception: # let KeyboardInterrupt / SystemExit propagate |
0 | 561 |
if self.indexer is not None: |
562 |
self.exception('error while unindexing %s', eid) |
|
1792 | 563 |
|
0 | 564 |
def fti_index_entity(self, session, entity): |
565 |
"""add text content of a created/modified entity to the full text index |
|
566 |
""" |
|
567 |
self.info('reindexing %r', entity.eid) |
|
568 |
try: |
|
569 |
self.indexer.cursor_reindex_object(entity.eid, entity, |
|
570 |
session.pool['system']) |
|
3497
63b9541dd36f
[fti] don't catch BaseException subclasses
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3240
diff
changeset
|
571 |
except Exception: # let KeyboardInterrupt / SystemExit propagate |
0 | 572 |
if self.indexer is not None: |
573 |
self.exception('error while reindexing %s', entity) |
|
574 |
# update entities.mtime |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
973
diff
changeset
|
575 |
attrs = {'eid': entity.eid, 'mtime': datetime.now()} |
0 | 576 |
session.system_sql(self.sqlgen.update('entities', attrs, ['eid']), attrs) |
1792 | 577 |
|
0 | 578 |
def modified_entities(self, session, etypes, mtime): |
579 |
"""return a 2-uple: |
|
580 |
* list of (etype, eid) of entities of the given types which have been |
|
581 |
modified since the given timestamp (actually entities whose full text |
|
582 |
index content has changed) |
|
583 |
* list of (etype, eid) of entities of the given types which have been |
|
584 |
deleted since the given timestamp |
|
585 |
""" |
|
586 |
modsql = _modified_sql('entities', etypes) |
|
587 |
cursor = session.system_sql(modsql, {'time': mtime}) |
|
588 |
modentities = cursor.fetchall() |
|
589 |
delsql = _modified_sql('deleted_entities', etypes) |
|
590 |
cursor = session.system_sql(delsql, {'time': mtime}) |
|
591 |
delentities = cursor.fetchall() |
|
592 |
return modentities, delentities |
|
593 |
||
594 |
||
595 |
def sql_schema(driver): |
|
596 |
helper = get_adv_func_helper(driver) |
|
4198
8d644eb862b9
TYPE_MAPPING expected to be a mapping from yams type to db type, and timestamp is the Datetime yams type
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4195
diff
changeset
|
597 |
tstamp_col_type = helper.TYPE_MAPPING['Datetime'] |
0 | 598 |
schema = """ |
599 |
/* Create the repository's system database */ |
|
600 |
||
601 |
%s |
|
602 |
||
603 |
CREATE TABLE entities ( |
|
604 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
605 |
type VARCHAR(64) NOT NULL, |
|
606 |
source VARCHAR(64) NOT NULL, |
|
4113
986fc01be83c
TIMESTAMP column type has a special meaning for SQLServer,
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3958
diff
changeset
|
607 |
mtime %s NOT NULL, |
0 | 608 |
extid VARCHAR(256) |
609 |
); |
|
610 |
CREATE INDEX entities_type_idx ON entities(type); |
|
611 |
CREATE INDEX entities_mtime_idx ON entities(mtime); |
|
612 |
CREATE INDEX entities_extid_idx ON entities(extid); |
|
613 |
||
614 |
CREATE TABLE deleted_entities ( |
|
615 |
eid INTEGER PRIMARY KEY NOT NULL, |
|
616 |
type VARCHAR(64) NOT NULL, |
|
617 |
source VARCHAR(64) NOT NULL, |
|
4113
986fc01be83c
TIMESTAMP column type has a special meaning for SQLServer,
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3958
diff
changeset
|
618 |
dtime %s NOT NULL, |
0 | 619 |
extid VARCHAR(256) |
620 |
); |
|
621 |
CREATE INDEX deleted_entities_type_idx ON deleted_entities(type); |
|
622 |
CREATE INDEX deleted_entities_dtime_idx ON deleted_entities(dtime); |
|
623 |
CREATE INDEX deleted_entities_extid_idx ON deleted_entities(extid); |
|
4113
986fc01be83c
TIMESTAMP column type has a special meaning for SQLServer,
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3958
diff
changeset
|
624 |
""" % (helper.sql_create_sequence('entities_id_seq'), tstamp_col_type, tstamp_col_type) |
0 | 625 |
return schema |
626 |
||
627 |
||
628 |
def sql_drop_schema(driver): |
|
629 |
helper = get_adv_func_helper(driver) |
|
630 |
return """ |
|
631 |
%s |
|
632 |
DROP TABLE entities; |
|
633 |
DROP TABLE deleted_entities; |
|
634 |
""" % helper.sql_drop_sequence('entities_id_seq') |
|
635 |
||
636 |
||
637 |
def grant_schema(user, set_owner=True): |
|
638 |
result = '' |
|
639 |
if set_owner: |
|
640 |
result = 'ALTER TABLE entities OWNER TO %s;\n' % user |
|
641 |
result += 'ALTER TABLE deleted_entities OWNER TO %s;\n' % user |
|
642 |
result += 'ALTER TABLE entities_id_seq OWNER TO %s;\n' % user |
|
643 |
result += 'GRANT ALL ON entities TO %s;\n' % user |
|
644 |
result += 'GRANT ALL ON deleted_entities TO %s;\n' % user |
|
645 |
result += 'GRANT ALL ON entities_id_seq TO %s;\n' % user |
|
646 |
return result |