author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Thu, 02 Jul 2009 10:30:44 +0200 | |
branch | stable |
changeset 2233 | bf3603caaf0d |
parent 2124 | 5a0b02f37b23 |
child 2275 | bc0bed0616a3 |
permissions | -rw-r--r-- |
0 | 1 |
"""a class implementing basic actions used in migration scripts. |
2 |
||
3 |
The following schema actions are supported for now: |
|
4 |
* add/drop/rename attribute |
|
5 |
* add/drop entity/relation type |
|
6 |
* rename entity type |
|
7 |
||
8 |
The following data actions are supported for now: |
|
9 |
* add an entity |
|
10 |
* execute raw RQL queries |
|
11 |
||
12 |
||
13 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1790
diff
changeset
|
14 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 15 |
: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:
1790
diff
changeset
|
16 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 17 |
""" |
18 |
__docformat__ = "restructuredtext en" |
|
19 |
||
20 |
import sys |
|
21 |
import os |
|
22 |
from os.path import join, exists |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
972
diff
changeset
|
23 |
from datetime import datetime |
0 | 24 |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
25 |
from logilab.common.deprecation import deprecated_function, obsolete |
2107
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
26 |
from logilab.common.decorators import cached, clear_cache |
0 | 27 |
from logilab.common.adbh import get_adv_func_helper |
28 |
||
29 |
from yams.constraints import SizeConstraint |
|
30 |
from yams.schema2sql import eschema2sql, rschema2sql |
|
31 |
||
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
32 |
from cubicweb import AuthenticationError, ETYPE_NAME_MAP |
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
33 |
from cubicweb.schema import CubicWebRelationSchema |
0 | 34 |
from cubicweb.dbapi import get_repository, repo_connect |
35 |
from cubicweb.common.migration import MigrationHelper, yes |
|
36 |
||
37 |
try: |
|
2107
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
38 |
from cubicweb.server import SOURCE_TYPES, schemaserial as ss |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
39 |
from cubicweb.server.utils import manager_userpasswd, ask_source_config |
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:
1240
diff
changeset
|
40 |
from cubicweb.server.sqlutils import sqlexec, SQL_PREFIX |
0 | 41 |
except ImportError: # LAX |
42 |
pass |
|
43 |
||
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:
1240
diff
changeset
|
44 |
|
0 | 45 |
class ServerMigrationHelper(MigrationHelper): |
46 |
"""specific migration helper for server side migration scripts, |
|
47 |
providind actions related to schema/data migration |
|
48 |
""" |
|
49 |
||
50 |
def __init__(self, config, schema, interactive=True, |
|
51 |
repo=None, cnx=None, verbosity=1, connect=True): |
|
52 |
MigrationHelper.__init__(self, config, interactive, verbosity) |
|
53 |
if not interactive: |
|
54 |
assert cnx |
|
55 |
assert repo |
|
56 |
if cnx is not None: |
|
57 |
assert repo |
|
58 |
self._cnx = cnx |
|
59 |
self.repo = repo |
|
60 |
elif connect: |
|
61 |
self.repo_connect() |
|
62 |
if not schema: |
|
63 |
schema = config.load_schema(expand_cubes=True) |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
64 |
self.fs_schema = schema |
0 | 65 |
self._synchronized = set() |
66 |
||
67 |
@cached |
|
68 |
def repo_connect(self): |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
69 |
self.repo = get_repository(method='inmemory', config=self.config) |
0 | 70 |
return self.repo |
1477 | 71 |
|
0 | 72 |
def shutdown(self): |
73 |
if self.repo is not None: |
|
74 |
self.repo.shutdown() |
|
1477 | 75 |
|
0 | 76 |
def rewrite_vcconfiguration(self): |
77 |
"""write current installed versions (of cubicweb software |
|
78 |
and of each used cube) into the database |
|
79 |
""" |
|
2107
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
80 |
self.cmd_set_property('system.version.cubicweb', |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
81 |
self.config.cubicweb_version()) |
0 | 82 |
for pkg in self.config.cubes(): |
83 |
pkgversion = self.config.cube_version(pkg) |
|
84 |
self.cmd_set_property('system.version.%s' % pkg.lower(), pkgversion) |
|
85 |
self.commit() |
|
1477 | 86 |
|
0 | 87 |
def backup_database(self, backupfile=None, askconfirm=True): |
88 |
config = self.config |
|
89 |
source = config.sources()['system'] |
|
90 |
helper = get_adv_func_helper(source['db-driver']) |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
972
diff
changeset
|
91 |
date = datetime.now().strftime('%Y-%m-%d_%H:%M:%S') |
0 | 92 |
app = config.appid |
93 |
backupfile = backupfile or join(config.backup_dir(), |
|
94 |
'%s-%s.dump' % (app, date)) |
|
95 |
if exists(backupfile): |
|
96 |
if not self.confirm('a backup already exists for %s, overwrite it?' % app): |
|
97 |
return |
|
98 |
elif askconfirm and not self.confirm('backup %s database?' % app): |
|
99 |
return |
|
100 |
cmd = helper.backup_command(source['db-name'], source.get('db-host'), |
|
101 |
source.get('db-user'), backupfile, |
|
102 |
keepownership=False) |
|
103 |
while True: |
|
104 |
print cmd |
|
105 |
if os.system(cmd): |
|
106 |
print 'error while backuping the base' |
|
107 |
answer = self.confirm('continue anyway?', |
|
108 |
shell=False, abort=False, retry=True) |
|
109 |
if not answer: |
|
110 |
raise SystemExit(1) |
|
111 |
if answer == 1: # 1: continue, 2: retry |
|
112 |
break |
|
113 |
else: |
|
1240
6a9f621e07cc
restrict read perms to user on backup files
sylvain.thenault@logilab.fr
parents:
1080
diff
changeset
|
114 |
from cubicweb.toolsutils import restrict_perms_to_user |
0 | 115 |
print 'database backup:', backupfile |
1240
6a9f621e07cc
restrict read perms to user on backup files
sylvain.thenault@logilab.fr
parents:
1080
diff
changeset
|
116 |
restrict_perms_to_user(backupfile, self.info) |
0 | 117 |
break |
1477 | 118 |
|
0 | 119 |
def restore_database(self, backupfile, drop=True): |
120 |
config = self.config |
|
121 |
source = config.sources()['system'] |
|
122 |
helper = get_adv_func_helper(source['db-driver']) |
|
123 |
app = config.appid |
|
124 |
if not exists(backupfile): |
|
125 |
raise Exception("backup file %s doesn't exist" % backupfile) |
|
126 |
if self.confirm('restore %s database from %s ?' % (app, backupfile)): |
|
127 |
for cmd in helper.restore_commands(source['db-name'], source.get('db-host'), |
|
128 |
source.get('db-user'), backupfile, |
|
129 |
source['db-encoding'], |
|
130 |
keepownership=False, drop=drop): |
|
131 |
while True: |
|
132 |
print cmd |
|
133 |
if os.system(cmd): |
|
134 |
print 'error while restoring the base' |
|
135 |
answer = self.confirm('continue anyway?', |
|
136 |
shell=False, abort=False, retry=True) |
|
137 |
if not answer: |
|
138 |
raise SystemExit(1) |
|
139 |
if answer == 1: # 1: continue, 2: retry |
|
140 |
break |
|
141 |
else: |
|
142 |
break |
|
143 |
print 'database restored' |
|
1477 | 144 |
|
0 | 145 |
def migrate(self, vcconf, toupgrade, options): |
146 |
if not options.fs_only: |
|
147 |
if options.backup_db is None: |
|
148 |
self.backup_database() |
|
149 |
elif options.backup_db: |
|
150 |
self.backup_database(askconfirm=False) |
|
151 |
super(ServerMigrationHelper, self).migrate(vcconf, toupgrade, options) |
|
1477 | 152 |
|
0 | 153 |
def process_script(self, migrscript, funcname=None, *args, **kwargs): |
154 |
"""execute a migration script |
|
155 |
in interactive mode, display the migration script path, ask for |
|
156 |
confirmation and execute it if confirmed |
|
157 |
""" |
|
158 |
if migrscript.endswith('.sql'): |
|
159 |
if self.execscript_confirm(migrscript): |
|
160 |
sqlexec(open(migrscript).read(), self.session.system_sql) |
|
161 |
else: |
|
162 |
return super(ServerMigrationHelper, self).process_script( |
|
163 |
migrscript, funcname, *args, **kwargs) |
|
1477 | 164 |
|
0 | 165 |
@property |
166 |
def cnx(self): |
|
167 |
"""lazy connection""" |
|
168 |
try: |
|
169 |
return self._cnx |
|
170 |
except AttributeError: |
|
171 |
sourcescfg = self.repo.config.sources() |
|
172 |
try: |
|
173 |
login = sourcescfg['admin']['login'] |
|
174 |
pwd = sourcescfg['admin']['password'] |
|
175 |
except KeyError: |
|
176 |
login, pwd = manager_userpasswd() |
|
177 |
while True: |
|
178 |
try: |
|
179 |
self._cnx = repo_connect(self.repo, login, pwd) |
|
180 |
if not 'managers' in self._cnx.user(self.session).groups: |
|
181 |
print 'migration need an account in the managers group' |
|
182 |
else: |
|
183 |
break |
|
184 |
except AuthenticationError: |
|
185 |
print 'wrong user/password' |
|
186 |
except (KeyboardInterrupt, EOFError): |
|
187 |
print 'aborting...' |
|
188 |
sys.exit(0) |
|
189 |
try: |
|
190 |
login, pwd = manager_userpasswd() |
|
191 |
except (KeyboardInterrupt, EOFError): |
|
192 |
print 'aborting...' |
|
193 |
sys.exit(0) |
|
194 |
return self._cnx |
|
195 |
||
196 |
@property |
|
197 |
def session(self): |
|
198 |
return self.repo._get_session(self.cnx.sessionid) |
|
1477 | 199 |
|
0 | 200 |
@property |
201 |
@cached |
|
202 |
def rqlcursor(self): |
|
203 |
"""lazy rql cursor""" |
|
1080
7437abc17e02
should not give session as cnx.cursor(), else we may try to execute some query while no pool is set on the session
sylvain.thenault@logilab.fr
parents:
972
diff
changeset
|
204 |
# should not give session as cnx.cursor(), else we may try to execute |
7437abc17e02
should not give session as cnx.cursor(), else we may try to execute some query while no pool is set on the session
sylvain.thenault@logilab.fr
parents:
972
diff
changeset
|
205 |
# some query while no pool is set on the session (eg on entity attribute |
7437abc17e02
should not give session as cnx.cursor(), else we may try to execute some query while no pool is set on the session
sylvain.thenault@logilab.fr
parents:
972
diff
changeset
|
206 |
# access for instance) |
7437abc17e02
should not give session as cnx.cursor(), else we may try to execute some query while no pool is set on the session
sylvain.thenault@logilab.fr
parents:
972
diff
changeset
|
207 |
return self.cnx.cursor() |
1477 | 208 |
|
0 | 209 |
def commit(self): |
210 |
if hasattr(self, '_cnx'): |
|
211 |
self._cnx.commit() |
|
1477 | 212 |
|
0 | 213 |
def rollback(self): |
214 |
if hasattr(self, '_cnx'): |
|
215 |
self._cnx.rollback() |
|
1477 | 216 |
|
0 | 217 |
def rqlexecall(self, rqliter, cachekey=None, ask_confirm=True): |
218 |
for rql, kwargs in rqliter: |
|
219 |
self.rqlexec(rql, kwargs, cachekey, ask_confirm) |
|
220 |
||
221 |
@cached |
|
222 |
def _create_context(self): |
|
223 |
"""return a dictionary to use as migration script execution context""" |
|
224 |
context = super(ServerMigrationHelper, self)._create_context() |
|
225 |
context.update({'checkpoint': self.checkpoint, |
|
226 |
'sql': self.sqlexec, |
|
227 |
'rql': self.rqlexec, |
|
228 |
'rqliter': self.rqliter, |
|
229 |
'schema': self.repo.schema, |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
230 |
'fsschema': self.fs_schema, |
0 | 231 |
'session' : self.session, |
232 |
'repo' : self.repo, |
|
1790
a3e2b079de00
previous form actually worked??
sylvain.thenault@logilab.fr
parents:
1477
diff
changeset
|
233 |
'synchronize_schema': deprecated_function(self.cmd_sync_schema_props_perms), |
a3e2b079de00
previous form actually worked??
sylvain.thenault@logilab.fr
parents:
1477
diff
changeset
|
234 |
'synchronize_eschema': deprecated_function(self.cmd_sync_schema_props_perms), |
a3e2b079de00
previous form actually worked??
sylvain.thenault@logilab.fr
parents:
1477
diff
changeset
|
235 |
'synchronize_rschema': deprecated_function(self.cmd_sync_schema_props_perms), |
0 | 236 |
}) |
237 |
return context |
|
238 |
||
239 |
@cached |
|
240 |
def group_mapping(self): |
|
241 |
"""cached group mapping""" |
|
242 |
return ss.group_mapping(self.rqlcursor) |
|
1477 | 243 |
|
0 | 244 |
def exec_event_script(self, event, cubepath=None, funcname=None, |
1477 | 245 |
*args, **kwargs): |
0 | 246 |
if cubepath: |
247 |
apc = join(cubepath, 'migration', '%s.py' % event) |
|
248 |
else: |
|
249 |
apc = join(self.config.migration_scripts_dir(), '%s.py' % event) |
|
250 |
if exists(apc): |
|
251 |
if self.config.free_wheel: |
|
252 |
from cubicweb.server.hooks import setowner_after_add_entity |
|
253 |
self.repo.hm.unregister_hook(setowner_after_add_entity, |
|
254 |
'after_add_entity', '') |
|
255 |
self.deactivate_verification_hooks() |
|
256 |
self.info('executing %s', apc) |
|
257 |
confirm = self.confirm |
|
258 |
execscript_confirm = self.execscript_confirm |
|
259 |
self.confirm = yes |
|
260 |
self.execscript_confirm = yes |
|
261 |
try: |
|
262 |
return self.process_script(apc, funcname, *args, **kwargs) |
|
263 |
finally: |
|
264 |
self.confirm = confirm |
|
265 |
self.execscript_confirm = execscript_confirm |
|
266 |
if self.config.free_wheel: |
|
267 |
self.repo.hm.register_hook(setowner_after_add_entity, |
|
268 |
'after_add_entity', '') |
|
269 |
self.reactivate_verification_hooks() |
|
270 |
||
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
271 |
# schema synchronization internals ######################################## |
0 | 272 |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
273 |
def _synchronize_permissions(self, ertype): |
0 | 274 |
"""permission synchronization for an entity or relation type""" |
275 |
if ertype in ('eid', 'has_text', 'identity'): |
|
276 |
return |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
277 |
newrschema = self.fs_schema[ertype] |
0 | 278 |
teid = self.repo.schema[ertype].eid |
279 |
if 'update' in newrschema.ACTIONS or newrschema.is_final(): |
|
280 |
# entity type |
|
281 |
exprtype = u'ERQLExpression' |
|
282 |
else: |
|
283 |
# relation type |
|
284 |
exprtype = u'RRQLExpression' |
|
285 |
assert teid, ertype |
|
286 |
gm = self.group_mapping() |
|
287 |
confirm = self.verbosity >= 2 |
|
288 |
# * remove possibly deprecated permission (eg in the persistent schema |
|
289 |
# but not in the new schema) |
|
290 |
# * synchronize existing expressions |
|
291 |
# * add new groups/expressions |
|
292 |
for action in newrschema.ACTIONS: |
|
293 |
perm = '%s_permission' % action |
|
294 |
# handle groups |
|
295 |
newgroups = list(newrschema.get_groups(action)) |
|
296 |
for geid, gname in self.rqlexec('Any G, GN WHERE T %s G, G name GN, ' |
|
297 |
'T eid %%(x)s' % perm, {'x': teid}, 'x', |
|
298 |
ask_confirm=False): |
|
299 |
if not gname in newgroups: |
|
300 |
if not confirm or self.confirm('remove %s permission of %s to %s?' |
|
301 |
% (action, ertype, gname)): |
|
302 |
self.rqlexec('DELETE T %s G WHERE G eid %%(x)s, T eid %s' |
|
303 |
% (perm, teid), |
|
304 |
{'x': geid}, 'x', ask_confirm=False) |
|
305 |
else: |
|
306 |
newgroups.remove(gname) |
|
307 |
for gname in newgroups: |
|
308 |
if not confirm or self.confirm('grant %s permission of %s to %s?' |
|
309 |
% (action, ertype, gname)): |
|
310 |
self.rqlexec('SET T %s G WHERE G eid %%(x)s, T eid %s' |
|
311 |
% (perm, teid), |
|
312 |
{'x': gm[gname]}, 'x', ask_confirm=False) |
|
313 |
# handle rql expressions |
|
314 |
newexprs = dict((expr.expression, expr) for expr in newrschema.get_rqlexprs(action)) |
|
315 |
for expreid, expression in self.rqlexec('Any E, EX WHERE T %s E, E expression EX, ' |
|
316 |
'T eid %s' % (perm, teid), |
|
317 |
ask_confirm=False): |
|
318 |
if not expression in newexprs: |
|
319 |
if not confirm or self.confirm('remove %s expression for %s permission of %s?' |
|
320 |
% (expression, action, ertype)): |
|
321 |
# deleting the relation will delete the expression entity |
|
322 |
self.rqlexec('DELETE T %s E WHERE E eid %%(x)s, T eid %s' |
|
323 |
% (perm, teid), |
|
324 |
{'x': expreid}, 'x', ask_confirm=False) |
|
325 |
else: |
|
326 |
newexprs.pop(expression) |
|
327 |
for expression in newexprs.values(): |
|
328 |
expr = expression.expression |
|
329 |
if not confirm or self.confirm('add %s expression for %s permission of %s?' |
|
330 |
% (expr, action, ertype)): |
|
331 |
self.rqlexec('INSERT RQLExpression X: X exprtype %%(exprtype)s, ' |
|
332 |
'X expression %%(expr)s, X mainvars %%(vars)s, T %s X ' |
|
333 |
'WHERE T eid %%(x)s' % perm, |
|
334 |
{'expr': expr, 'exprtype': exprtype, |
|
335 |
'vars': expression.mainvars, 'x': teid}, 'x', |
|
336 |
ask_confirm=False) |
|
1477 | 337 |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
338 |
def _synchronize_rschema(self, rtype, syncrdefs=True, syncperms=True): |
0 | 339 |
"""synchronize properties of the persistent relation schema against its |
340 |
current definition: |
|
1477 | 341 |
|
0 | 342 |
* description |
343 |
* symetric, meta |
|
344 |
* inlined |
|
345 |
* relation definitions if `syncrdefs` |
|
346 |
* permissions if `syncperms` |
|
1477 | 347 |
|
0 | 348 |
physical schema changes should be handled by repository's schema hooks |
349 |
""" |
|
350 |
rtype = str(rtype) |
|
351 |
if rtype in self._synchronized: |
|
352 |
return |
|
353 |
self._synchronized.add(rtype) |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
354 |
rschema = self.fs_schema.rschema(rtype) |
0 | 355 |
self.rqlexecall(ss.updaterschema2rql(rschema), |
356 |
ask_confirm=self.verbosity>=2) |
|
357 |
reporschema = self.repo.schema.rschema(rtype) |
|
358 |
if syncrdefs: |
|
359 |
for subj, obj in rschema.iter_rdefs(): |
|
360 |
if not reporschema.has_rdef(subj, obj): |
|
361 |
continue |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
362 |
self._synchronize_rdef_schema(subj, rschema, obj) |
0 | 363 |
if syncperms: |
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
364 |
self._synchronize_permissions(rtype) |
1477 | 365 |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
366 |
def _synchronize_eschema(self, etype, syncperms=True): |
0 | 367 |
"""synchronize properties of the persistent entity schema against |
368 |
its current definition: |
|
1477 | 369 |
|
0 | 370 |
* description |
371 |
* internationalizable, fulltextindexed, indexed, meta |
|
372 |
* relations from/to this entity |
|
373 |
* permissions if `syncperms` |
|
374 |
""" |
|
375 |
etype = str(etype) |
|
376 |
if etype in self._synchronized: |
|
377 |
return |
|
378 |
self._synchronized.add(etype) |
|
379 |
repoeschema = self.repo.schema.eschema(etype) |
|
380 |
try: |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
381 |
eschema = self.fs_schema.eschema(etype) |
0 | 382 |
except KeyError: |
383 |
return |
|
384 |
repospschema = repoeschema.specializes() |
|
385 |
espschema = eschema.specializes() |
|
386 |
if repospschema and not espschema: |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
387 |
self.rqlexec('DELETE X specializes Y WHERE X is CWEType, X name %(x)s', |
447 | 388 |
{'x': str(repoeschema)}) |
0 | 389 |
elif not repospschema and espschema: |
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
390 |
self.rqlexec('SET X specializes Y WHERE X is CWEType, X name %(x)s, ' |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
391 |
'Y is CWEType, Y name %(y)s', |
447 | 392 |
{'x': str(repoeschema), 'y': str(espschema)}) |
0 | 393 |
self.rqlexecall(ss.updateeschema2rql(eschema), |
394 |
ask_confirm=self.verbosity >= 2) |
|
395 |
for rschema, targettypes, x in eschema.relation_definitions(True): |
|
396 |
if x == 'subject': |
|
397 |
if not rschema in repoeschema.subject_relations(): |
|
398 |
continue |
|
399 |
subjtypes, objtypes = [etype], targettypes |
|
400 |
else: # x == 'object' |
|
401 |
if not rschema in repoeschema.object_relations(): |
|
402 |
continue |
|
403 |
subjtypes, objtypes = targettypes, [etype] |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
404 |
self._synchronize_rschema(rschema, syncperms=syncperms, |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
405 |
syncrdefs=False) |
0 | 406 |
reporschema = self.repo.schema.rschema(rschema) |
407 |
for subj in subjtypes: |
|
408 |
for obj in objtypes: |
|
409 |
if not reporschema.has_rdef(subj, obj): |
|
410 |
continue |
|
1414
448c9802d7df
does not apply any more
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1409
diff
changeset
|
411 |
self._synchronize_rdef_schema(subj, rschema, obj) |
0 | 412 |
if syncperms: |
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
413 |
self._synchronize_permissions(etype) |
0 | 414 |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
415 |
def _synchronize_rdef_schema(self, subjtype, rtype, objtype): |
0 | 416 |
"""synchronize properties of the persistent relation definition schema |
417 |
against its current definition: |
|
418 |
* order and other properties |
|
419 |
* constraints |
|
420 |
""" |
|
421 |
subjtype, objtype = str(subjtype), str(objtype) |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
422 |
rschema = self.fs_schema.rschema(rtype) |
0 | 423 |
reporschema = self.repo.schema.rschema(rschema) |
424 |
if (subjtype, rschema, objtype) in self._synchronized: |
|
425 |
return |
|
426 |
self._synchronized.add((subjtype, rschema, objtype)) |
|
427 |
if rschema.symetric: |
|
428 |
self._synchronized.add((objtype, rschema, subjtype)) |
|
429 |
confirm = self.verbosity >= 2 |
|
430 |
# properties |
|
431 |
self.rqlexecall(ss.updaterdef2rql(rschema, subjtype, objtype), |
|
432 |
ask_confirm=confirm) |
|
433 |
# constraints |
|
434 |
newconstraints = list(rschema.rproperty(subjtype, objtype, 'constraints')) |
|
435 |
# 1. remove old constraints and update constraints of the same type |
|
436 |
# NOTE: don't use rschema.constraint_by_type because it may be |
|
437 |
# out of sync with newconstraints when multiple |
|
438 |
# constraints of the same type are used |
|
439 |
for cstr in reporschema.rproperty(subjtype, objtype, 'constraints'): |
|
440 |
for newcstr in newconstraints: |
|
441 |
if newcstr.type() == cstr.type(): |
|
442 |
break |
|
443 |
else: |
|
444 |
newcstr = None |
|
445 |
if newcstr is None: |
|
446 |
self.rqlexec('DELETE X constrained_by C WHERE C eid %(x)s', |
|
447 |
{'x': cstr.eid}, 'x', |
|
448 |
ask_confirm=confirm) |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
449 |
self.rqlexec('DELETE CWConstraint C WHERE C eid %(x)s', |
0 | 450 |
{'x': cstr.eid}, 'x', |
451 |
ask_confirm=confirm) |
|
452 |
else: |
|
453 |
newconstraints.remove(newcstr) |
|
454 |
values = {'x': cstr.eid, |
|
455 |
'v': unicode(newcstr.serialize())} |
|
456 |
self.rqlexec('SET X value %(v)s WHERE X eid %(x)s', |
|
457 |
values, 'x', ask_confirm=confirm) |
|
458 |
# 2. add new constraints |
|
459 |
for newcstr in newconstraints: |
|
460 |
self.rqlexecall(ss.constraint2rql(rschema, subjtype, objtype, |
|
461 |
newcstr), |
|
462 |
ask_confirm=confirm) |
|
1477 | 463 |
|
0 | 464 |
# base actions ############################################################ |
465 |
||
466 |
def checkpoint(self): |
|
467 |
"""checkpoint action""" |
|
468 |
if self.confirm('commit now ?', shell=False): |
|
469 |
self.commit() |
|
470 |
||
471 |
def cmd_add_cube(self, cube, update_database=True): |
|
676
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
472 |
self.cmd_add_cubes( (cube,), update_database) |
1477 | 473 |
|
676
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
474 |
def cmd_add_cubes(self, cubes, update_database=True): |
0 | 475 |
"""update_database is telling if the database schema should be updated |
476 |
or if only the relevant eproperty should be inserted (for the case where |
|
477 |
a cube has been extracted from an existing application, so the |
|
478 |
cube schema is already in there) |
|
479 |
""" |
|
676
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
480 |
newcubes = super(ServerMigrationHelper, self).cmd_add_cubes(cubes) |
0 | 481 |
if not newcubes: |
482 |
return |
|
2107
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
483 |
for cube in newcubes: |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
484 |
self.cmd_set_property('system.version.'+cube, |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
485 |
self.config.cube_version(cube)) |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
486 |
if cube in SOURCE_TYPES: |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
487 |
# don't use config.sources() in case some sources have been |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
488 |
# disabled for migration |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
489 |
sourcescfg = self.config.read_sources_file() |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
490 |
sourcescfg[cube] = ask_source_config(cube) |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
491 |
self.config.write_sources_file(sourcescfg) |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
492 |
clear_cache(self.config, 'read_sources_file') |
0 | 493 |
if not update_database: |
494 |
self.commit() |
|
495 |
return |
|
1036
593df4919845
when reading the schema while adding/removing cubes, read schema in non-strict mode
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
496 |
newcubes_schema = self.config.load_schema(construction_mode='non-strict') |
0 | 497 |
new = set() |
498 |
# execute pre-create files |
|
499 |
for pack in reversed(newcubes): |
|
500 |
self.exec_event_script('precreate', self.config.cube_dir(pack)) |
|
501 |
# add new entity and relation types |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
502 |
for rschema in newcubes_schema.relations(): |
0 | 503 |
if not rschema in self.repo.schema: |
504 |
self.cmd_add_relation_type(rschema.type) |
|
505 |
new.add(rschema.type) |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
506 |
for eschema in newcubes_schema.entities(): |
0 | 507 |
if not eschema in self.repo.schema: |
508 |
self.cmd_add_entity_type(eschema.type) |
|
509 |
new.add(eschema.type) |
|
510 |
# check if attributes has been added to existing entities |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
511 |
for rschema in newcubes_schema.relations(): |
0 | 512 |
existingschema = self.repo.schema.rschema(rschema.type) |
513 |
for (fromtype, totype) in rschema.iter_rdefs(): |
|
514 |
if existingschema.has_rdef(fromtype, totype): |
|
515 |
continue |
|
516 |
# check we should actually add the relation definition |
|
517 |
if not (fromtype in new or totype in new or rschema in new): |
|
518 |
continue |
|
1477 | 519 |
self.cmd_add_relation_definition(str(fromtype), rschema.type, |
0 | 520 |
str(totype)) |
521 |
# execute post-create files |
|
522 |
for pack in reversed(newcubes): |
|
523 |
self.exec_event_script('postcreate', self.config.cube_dir(pack)) |
|
1477 | 524 |
self.commit() |
525 |
||
2124
5a0b02f37b23
set removedeps to False by default, raise an exception instead of a simple assertion for error, more remove_cube tests
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2122
diff
changeset
|
526 |
def cmd_remove_cube(self, cube, removedeps=False): |
2122
4ea13a828513
add removedeps option to remove_cube to control wether a cube's dependencies should be removed as well or not
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2107
diff
changeset
|
527 |
removedcubes = super(ServerMigrationHelper, self).cmd_remove_cube( |
4ea13a828513
add removedeps option to remove_cube to control wether a cube's dependencies should be removed as well or not
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2107
diff
changeset
|
528 |
cube, removedeps) |
0 | 529 |
if not removedcubes: |
530 |
return |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
531 |
fsschema = self.fs_schema |
1036
593df4919845
when reading the schema while adding/removing cubes, read schema in non-strict mode
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
532 |
removedcubes_schema = self.config.load_schema(construction_mode='non-strict') |
0 | 533 |
reposchema = self.repo.schema |
534 |
# execute pre-remove files |
|
535 |
for pack in reversed(removedcubes): |
|
536 |
self.exec_event_script('preremove', self.config.cube_dir(pack)) |
|
537 |
# remove cubes'entity and relation types |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
538 |
for rschema in fsschema.relations(): |
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
539 |
if not rschema in removedcubes_schema and rschema in reposchema: |
0 | 540 |
self.cmd_drop_relation_type(rschema.type) |
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
541 |
for eschema in fsschema.entities(): |
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
542 |
if not eschema in removedcubes_schema and eschema in reposchema: |
0 | 543 |
self.cmd_drop_entity_type(eschema.type) |
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
544 |
for rschema in fsschema.relations(): |
1477 | 545 |
if rschema in removedcubes_schema and rschema in reposchema: |
546 |
# check if attributes/relations has been added to entities from |
|
0 | 547 |
# other cubes |
548 |
for fromtype, totype in rschema.iter_rdefs(): |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
549 |
if not removedcubes_schema[rschema.type].has_rdef(fromtype, totype) and \ |
0 | 550 |
reposchema[rschema.type].has_rdef(fromtype, totype): |
551 |
self.cmd_drop_relation_definition( |
|
552 |
str(fromtype), rschema.type, str(totype)) |
|
553 |
# execute post-remove files |
|
554 |
for pack in reversed(removedcubes): |
|
555 |
self.exec_event_script('postremove', self.config.cube_dir(pack)) |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
556 |
self.rqlexec('DELETE CWProperty X WHERE X pkey %(pk)s', |
0 | 557 |
{'pk': u'system.version.'+pack}, ask_confirm=False) |
558 |
self.commit() |
|
1477 | 559 |
|
0 | 560 |
# schema migration actions ################################################ |
1477 | 561 |
|
0 | 562 |
def cmd_add_attribute(self, etype, attrname, attrtype=None, commit=True): |
563 |
"""add a new attribute on the given entity type""" |
|
564 |
if attrtype is None: |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
565 |
rschema = self.fs_schema.rschema(attrname) |
0 | 566 |
attrtype = rschema.objects(etype)[0] |
567 |
self.cmd_add_relation_definition(etype, attrname, attrtype, commit=commit) |
|
1477 | 568 |
|
0 | 569 |
def cmd_drop_attribute(self, etype, attrname, commit=True): |
570 |
"""drop an existing attribute from the given entity type |
|
1477 | 571 |
|
0 | 572 |
`attrname` is a string giving the name of the attribute to drop |
573 |
""" |
|
574 |
rschema = self.repo.schema.rschema(attrname) |
|
575 |
attrtype = rschema.objects(etype)[0] |
|
576 |
self.cmd_drop_relation_definition(etype, attrname, attrtype, commit=commit) |
|
577 |
||
578 |
def cmd_rename_attribute(self, etype, oldname, newname, commit=True): |
|
579 |
"""rename an existing attribute of the given entity type |
|
1477 | 580 |
|
0 | 581 |
`oldname` is a string giving the name of the existing attribute |
582 |
`newname` is a string giving the name of the renamed attribute |
|
583 |
""" |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
584 |
eschema = self.fs_schema.eschema(etype) |
0 | 585 |
attrtype = eschema.destination(newname) |
586 |
# have to commit this first step anyway to get the definition |
|
587 |
# actually in the schema |
|
588 |
self.cmd_add_attribute(etype, newname, attrtype, commit=True) |
|
589 |
# skipp NULL values if the attribute is required |
|
590 |
rql = 'SET X %s VAL WHERE X is %s, X %s VAL' % (newname, etype, oldname) |
|
591 |
card = eschema.rproperty(newname, 'cardinality')[0] |
|
592 |
if card == '1': |
|
593 |
rql += ', NOT X %s NULL' % oldname |
|
594 |
self.rqlexec(rql, ask_confirm=self.verbosity>=2) |
|
595 |
self.cmd_drop_attribute(etype, oldname, commit=commit) |
|
1477 | 596 |
|
0 | 597 |
def cmd_add_entity_type(self, etype, auto=True, commit=True): |
598 |
"""register a new entity type |
|
1477 | 599 |
|
0 | 600 |
in auto mode, automatically register entity's relation where the |
601 |
targeted type is known |
|
602 |
""" |
|
603 |
applschema = self.repo.schema |
|
604 |
if etype in applschema: |
|
605 |
eschema = applschema[etype] |
|
606 |
if eschema.is_final(): |
|
607 |
applschema.del_entity_type(etype) |
|
608 |
else: |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
609 |
eschema = self.fs_schema.eschema(etype) |
0 | 610 |
confirm = self.verbosity >= 2 |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
611 |
# register the entity into CWEType |
0 | 612 |
self.rqlexecall(ss.eschema2rql(eschema), ask_confirm=confirm) |
613 |
# add specializes relation if needed |
|
614 |
self.rqlexecall(ss.eschemaspecialize2rql(eschema), ask_confirm=confirm) |
|
615 |
# register groups / permissions for the entity |
|
616 |
self.rqlexecall(ss.erperms2rql(eschema, self.group_mapping()), |
|
617 |
ask_confirm=confirm) |
|
618 |
# register entity's attributes |
|
619 |
for rschema, attrschema in eschema.attribute_definitions(): |
|
620 |
# ignore those meta relations, they will be automatically added |
|
621 |
if rschema.type in ('eid', 'creation_date', 'modification_date'): |
|
622 |
continue |
|
623 |
if not rschema.type in applschema: |
|
624 |
# need to add the relation type and to commit to get it |
|
625 |
# actually in the schema |
|
626 |
self.cmd_add_relation_type(rschema.type, False, commit=True) |
|
627 |
# register relation definition |
|
628 |
self.rqlexecall(ss.rdef2rql(rschema, etype, attrschema.type), |
|
629 |
ask_confirm=confirm) |
|
630 |
if auto: |
|
631 |
# we have commit here to get relation types actually in the schema |
|
632 |
self.commit() |
|
633 |
added = [] |
|
634 |
for rschema in eschema.subject_relations(): |
|
635 |
# attribute relation have already been processed and |
|
636 |
# 'owned_by'/'created_by' will be automatically added |
|
1477 | 637 |
if rschema.final or rschema.type in ('owned_by', 'created_by', 'is', 'is_instance_of'): |
0 | 638 |
continue |
639 |
rtypeadded = rschema.type in applschema |
|
640 |
for targetschema in rschema.objects(etype): |
|
641 |
# ignore relations where the targeted type is not in the |
|
642 |
# current application schema |
|
643 |
targettype = targetschema.type |
|
644 |
if not targettype in applschema and targettype != etype: |
|
645 |
continue |
|
646 |
if not rtypeadded: |
|
647 |
# need to add the relation type and to commit to get it |
|
648 |
# actually in the schema |
|
649 |
added.append(rschema.type) |
|
650 |
self.cmd_add_relation_type(rschema.type, False, commit=True) |
|
651 |
rtypeadded = True |
|
652 |
# register relation definition |
|
653 |
# remember this two avoid adding twice non symetric relation |
|
654 |
# such as "Emailthread forked_from Emailthread" |
|
655 |
added.append((etype, rschema.type, targettype)) |
|
656 |
self.rqlexecall(ss.rdef2rql(rschema, etype, targettype), |
|
657 |
ask_confirm=confirm) |
|
658 |
for rschema in eschema.object_relations(): |
|
659 |
rtypeadded = rschema.type in applschema or rschema.type in added |
|
660 |
for targetschema in rschema.subjects(etype): |
|
661 |
# ignore relations where the targeted type is not in the |
|
662 |
# current application schema |
|
663 |
targettype = targetschema.type |
|
664 |
# don't check targettype != etype since in this case the |
|
665 |
# relation has already been added as a subject relation |
|
666 |
if not targettype in applschema: |
|
667 |
continue |
|
668 |
if not rtypeadded: |
|
669 |
# need to add the relation type and to commit to get it |
|
670 |
# actually in the schema |
|
671 |
self.cmd_add_relation_type(rschema.type, False, commit=True) |
|
672 |
rtypeadded = True |
|
673 |
elif (targettype, rschema.type, etype) in added: |
|
674 |
continue |
|
675 |
# register relation definition |
|
676 |
self.rqlexecall(ss.rdef2rql(rschema, targettype, etype), |
|
677 |
ask_confirm=confirm) |
|
678 |
if commit: |
|
679 |
self.commit() |
|
1477 | 680 |
|
0 | 681 |
def cmd_drop_entity_type(self, etype, commit=True): |
682 |
"""unregister an existing entity type |
|
1477 | 683 |
|
0 | 684 |
This will trigger deletion of necessary relation types and definitions |
685 |
""" |
|
686 |
# XXX what if we delete an entity type which is specialized by other types |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
687 |
# unregister the entity from CWEType |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
688 |
self.rqlexec('DELETE CWEType X WHERE X name %(etype)s', {'etype': etype}, |
0 | 689 |
ask_confirm=self.verbosity>=2) |
690 |
if commit: |
|
691 |
self.commit() |
|
692 |
||
693 |
def cmd_rename_entity_type(self, oldname, newname, commit=True): |
|
694 |
"""rename an existing entity type in the persistent schema |
|
1477 | 695 |
|
0 | 696 |
`oldname` is a string giving the name of the existing entity type |
697 |
`newname` is a string giving the name of the renamed entity type |
|
698 |
""" |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
699 |
self.rqlexec('SET ET name %(newname)s WHERE ET is CWEType, ET name %(oldname)s', |
2107
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
700 |
{'newname' : unicode(newname), 'oldname' : oldname}, |
6c4a4c514ac2
add source to sources configuration when adding a cube defining a source
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
701 |
ask_confirm=False) |
0 | 702 |
if commit: |
703 |
self.commit() |
|
1477 | 704 |
|
0 | 705 |
def cmd_add_relation_type(self, rtype, addrdef=True, commit=True): |
706 |
"""register a new relation type named `rtype`, as described in the |
|
707 |
schema description file. |
|
708 |
||
709 |
`addrdef` is a boolean value; when True, it will also add all relations |
|
710 |
of the type just added found in the schema definition file. Note that it |
|
711 |
implies an intermediate "commit" which commits the relation type |
|
712 |
creation (but not the relation definitions themselves, for which |
|
713 |
committing depends on the `commit` argument value). |
|
1477 | 714 |
|
0 | 715 |
""" |
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
716 |
rschema = self.fs_schema.rschema(rtype) |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
717 |
# register the relation into CWRType and insert necessary relation |
0 | 718 |
# definitions |
719 |
self.rqlexecall(ss.rschema2rql(rschema, addrdef=False), |
|
720 |
ask_confirm=self.verbosity>=2) |
|
721 |
# register groups / permissions for the relation |
|
722 |
self.rqlexecall(ss.erperms2rql(rschema, self.group_mapping()), |
|
723 |
ask_confirm=self.verbosity>=2) |
|
724 |
if addrdef: |
|
725 |
self.commit() |
|
726 |
self.rqlexecall(ss.rdef2rql(rschema), |
|
727 |
ask_confirm=self.verbosity>=2) |
|
728 |
if commit: |
|
729 |
self.commit() |
|
1477 | 730 |
|
0 | 731 |
def cmd_drop_relation_type(self, rtype, commit=True): |
732 |
"""unregister an existing relation type""" |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
733 |
# unregister the relation from CWRType |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
734 |
self.rqlexec('DELETE CWRType X WHERE X name %r' % rtype, |
0 | 735 |
ask_confirm=self.verbosity>=2) |
736 |
if commit: |
|
737 |
self.commit() |
|
1477 | 738 |
|
0 | 739 |
def cmd_rename_relation(self, oldname, newname, commit=True): |
740 |
"""rename an existing relation |
|
1477 | 741 |
|
0 | 742 |
`oldname` is a string giving the name of the existing relation |
743 |
`newname` is a string giving the name of the renamed relation |
|
744 |
""" |
|
745 |
self.cmd_add_relation_type(newname, commit=True) |
|
746 |
self.rqlexec('SET X %s Y WHERE X %s Y' % (newname, oldname), |
|
747 |
ask_confirm=self.verbosity>=2) |
|
748 |
self.cmd_drop_relation_type(oldname, commit=commit) |
|
749 |
||
750 |
def cmd_add_relation_definition(self, subjtype, rtype, objtype, commit=True): |
|
751 |
"""register a new relation definition, from its definition found in the |
|
752 |
schema definition file |
|
753 |
""" |
|
934
f94e34795586
better variable/attribute names; fix remove_cube, it should not alter the .fs_schema attribute (former .new_schema)
sylvain.thenault@logilab.fr
parents:
676
diff
changeset
|
754 |
rschema = self.fs_schema.rschema(rtype) |
0 | 755 |
if not rtype in self.repo.schema: |
756 |
self.cmd_add_relation_type(rtype, addrdef=False, commit=True) |
|
757 |
self.rqlexecall(ss.rdef2rql(rschema, subjtype, objtype), |
|
758 |
ask_confirm=self.verbosity>=2) |
|
759 |
if commit: |
|
760 |
self.commit() |
|
1477 | 761 |
|
0 | 762 |
def cmd_drop_relation_definition(self, subjtype, rtype, objtype, commit=True): |
763 |
"""unregister an existing relation definition""" |
|
764 |
rschema = self.repo.schema.rschema(rtype) |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
765 |
# unregister the definition from CWAttribute or CWRelation |
0 | 766 |
if rschema.is_final(): |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
767 |
etype = 'CWAttribute' |
0 | 768 |
else: |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
769 |
etype = 'CWRelation' |
0 | 770 |
rql = ('DELETE %s X WHERE X from_entity FE, FE name "%s",' |
771 |
'X relation_type RT, RT name "%s", X to_entity TE, TE name "%s"') |
|
772 |
self.rqlexec(rql % (etype, subjtype, rtype, objtype), |
|
773 |
ask_confirm=self.verbosity>=2) |
|
774 |
if commit: |
|
775 |
self.commit() |
|
1477 | 776 |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
777 |
def cmd_sync_schema_props_perms(self, ertype=None, syncperms=True, |
1409
f4dee84a618f
sql attributes bugfix
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1399
diff
changeset
|
778 |
syncprops=True, syncrdefs=True, commit=True): |
0 | 779 |
"""synchronize the persistent schema against the current definition |
780 |
schema. |
|
1477 | 781 |
|
0 | 782 |
It will synch common stuff between the definition schema and the |
783 |
actual persistent schema, it won't add/remove any entity or relation. |
|
784 |
""" |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
785 |
assert syncperms or syncprops, 'nothing to do' |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
786 |
if ertype is not None: |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
787 |
if isinstance(ertype, (tuple, list)): |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
788 |
assert len(ertype) == 3, 'not a relation definition' |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
789 |
assert syncprops, 'can\'t update permission for a relation definition' |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
790 |
self._synchronize_rdef_schema(*ertype) |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
791 |
elif syncprops: |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
792 |
erschema = self.repo.schema[ertype] |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
793 |
if isinstance(erschema, CubicWebRelationSchema): |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
794 |
self._synchronize_rschema(erschema, syncperms=syncperms, |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
795 |
syncrdefs=syncrdefs) |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
796 |
else: |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
797 |
self._synchronize_eschema(erschema, syncperms=syncperms) |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
798 |
else: |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
799 |
self._synchronize_permissions(ertype) |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
800 |
else: |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
801 |
for etype in self.repo.schema.entities(): |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
802 |
if syncprops: |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
803 |
self._synchronize_eschema(etype, syncperms=syncperms) |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
804 |
else: |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
805 |
self._synchronize_permissions(etype) |
0 | 806 |
if commit: |
807 |
self.commit() |
|
1477 | 808 |
|
0 | 809 |
def cmd_change_relation_props(self, subjtype, rtype, objtype, |
810 |
commit=True, **kwargs): |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
811 |
"""change some properties of a relation definition |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
812 |
|
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
813 |
you usually want to use sync_schema_props_perms instead. |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
814 |
""" |
0 | 815 |
assert kwargs |
816 |
restriction = [] |
|
817 |
if subjtype and subjtype != 'Any': |
|
818 |
restriction.append('X from_entity FE, FE name "%s"' % subjtype) |
|
819 |
if objtype and objtype != 'Any': |
|
820 |
restriction.append('X to_entity TE, TE name "%s"' % objtype) |
|
821 |
if rtype and rtype != 'Any': |
|
822 |
restriction.append('X relation_type RT, RT name "%s"' % rtype) |
|
823 |
assert restriction |
|
824 |
values = [] |
|
825 |
for k, v in kwargs.items(): |
|
826 |
values.append('X %s %%(%s)s' % (k, k)) |
|
827 |
if isinstance(v, str): |
|
828 |
kwargs[k] = unicode(v) |
|
829 |
rql = 'SET %s WHERE %s' % (','.join(values), ','.join(restriction)) |
|
830 |
self.rqlexec(rql, kwargs, ask_confirm=self.verbosity>=2) |
|
831 |
if commit: |
|
832 |
self.commit() |
|
833 |
||
834 |
def cmd_set_size_constraint(self, etype, rtype, size, commit=True): |
|
835 |
"""set change size constraint of a string attribute |
|
836 |
||
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
837 |
if size is None any size constraint will be removed. |
1477 | 838 |
|
839 |
you usually want to use sync_schema_props_perms instead. |
|
0 | 840 |
""" |
841 |
oldvalue = None |
|
842 |
for constr in self.repo.schema.eschema(etype).constraints(rtype): |
|
843 |
if isinstance(constr, SizeConstraint): |
|
844 |
oldvalue = constr.max |
|
845 |
if oldvalue == size: |
|
846 |
return |
|
847 |
if oldvalue is None and not size is None: |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
848 |
ceid = self.rqlexec('INSERT CWConstraint C: C value %(v)s, C cstrtype CT ' |
0 | 849 |
'WHERE CT name "SizeConstraint"', |
850 |
{'v': SizeConstraint(size).serialize()}, |
|
851 |
ask_confirm=self.verbosity>=2)[0][0] |
|
852 |
self.rqlexec('SET X constrained_by C WHERE X from_entity S, X relation_type R, ' |
|
853 |
'S name "%s", R name "%s", C eid %s' % (etype, rtype, ceid), |
|
854 |
ask_confirm=self.verbosity>=2) |
|
855 |
elif not oldvalue is None: |
|
856 |
if not size is None: |
|
857 |
self.rqlexec('SET C value %%(v)s WHERE X from_entity S, X relation_type R,' |
|
858 |
'X constrained_by C, C cstrtype CT, CT name "SizeConstraint",' |
|
859 |
'S name "%s", R name "%s"' % (etype, rtype), |
|
860 |
{'v': unicode(SizeConstraint(size).serialize())}, |
|
861 |
ask_confirm=self.verbosity>=2) |
|
862 |
else: |
|
863 |
self.rqlexec('DELETE X constrained_by C WHERE X from_entity S, X relation_type R,' |
|
864 |
'X constrained_by C, C cstrtype CT, CT name "SizeConstraint",' |
|
865 |
'S name "%s", R name "%s"' % (etype, rtype), |
|
866 |
ask_confirm=self.verbosity>=2) |
|
867 |
# cleanup unused constraints |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
868 |
self.rqlexec('DELETE CWConstraint C WHERE NOT X constrained_by C') |
0 | 869 |
if commit: |
870 |
self.commit() |
|
1399
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
871 |
|
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
872 |
@obsolete('use sync_schema_props_perms(ertype, syncprops=False)') |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
873 |
def cmd_synchronize_permissions(self, ertype, commit=True): |
3f408c7a164e
unify schema sync migration commands with (hopefuly) a clearer name
sylvain.thenault@logilab.fr
parents:
1398
diff
changeset
|
874 |
self.cmd_sync_schema_props_perms(ertype, syncprops=False, commit=commit) |
1477 | 875 |
|
0 | 876 |
# Workflows handling ###################################################### |
1477 | 877 |
|
0 | 878 |
def cmd_add_state(self, name, stateof, initial=False, commit=False, **kwargs): |
879 |
"""method to ease workflow definition: add a state for one or more |
|
880 |
entity type(s) |
|
881 |
""" |
|
882 |
stateeid = self.cmd_add_entity('State', name=name, **kwargs) |
|
883 |
if not isinstance(stateof, (list, tuple)): |
|
884 |
stateof = (stateof,) |
|
885 |
for etype in stateof: |
|
886 |
# XXX ensure etype validity |
|
887 |
self.rqlexec('SET X state_of Y WHERE X eid %(x)s, Y name %(et)s', |
|
888 |
{'x': stateeid, 'et': etype}, 'x', ask_confirm=False) |
|
889 |
if initial: |
|
890 |
self.rqlexec('SET ET initial_state S WHERE ET name %(et)s, S eid %(x)s', |
|
891 |
{'x': stateeid, 'et': etype}, 'x', ask_confirm=False) |
|
892 |
if commit: |
|
893 |
self.commit() |
|
894 |
return stateeid |
|
1477 | 895 |
|
0 | 896 |
def cmd_add_transition(self, name, transitionof, fromstates, tostate, |
897 |
requiredgroups=(), conditions=(), commit=False, **kwargs): |
|
898 |
"""method to ease workflow definition: add a transition for one or more |
|
899 |
entity type(s), from one or more state and to a single state |
|
900 |
""" |
|
901 |
treid = self.cmd_add_entity('Transition', name=name, **kwargs) |
|
902 |
if not isinstance(transitionof, (list, tuple)): |
|
903 |
transitionof = (transitionof,) |
|
904 |
for etype in transitionof: |
|
905 |
# XXX ensure etype validity |
|
906 |
self.rqlexec('SET X transition_of Y WHERE X eid %(x)s, Y name %(et)s', |
|
907 |
{'x': treid, 'et': etype}, 'x', ask_confirm=False) |
|
908 |
for stateeid in fromstates: |
|
909 |
self.rqlexec('SET X allowed_transition Y WHERE X eid %(x)s, Y eid %(y)s', |
|
910 |
{'x': stateeid, 'y': treid}, 'x', ask_confirm=False) |
|
911 |
self.rqlexec('SET X destination_state Y WHERE X eid %(x)s, Y eid %(y)s', |
|
912 |
{'x': treid, 'y': tostate}, 'x', ask_confirm=False) |
|
913 |
self.cmd_set_transition_permissions(treid, requiredgroups, conditions, |
|
914 |
reset=False) |
|
915 |
if commit: |
|
916 |
self.commit() |
|
917 |
return treid |
|
918 |
||
919 |
def cmd_set_transition_permissions(self, treid, |
|
920 |
requiredgroups=(), conditions=(), |
|
921 |
reset=True, commit=False): |
|
922 |
"""set or add (if `reset` is False) groups and conditions for a |
|
923 |
transition |
|
924 |
""" |
|
925 |
if reset: |
|
926 |
self.rqlexec('DELETE T require_group G WHERE T eid %(x)s', |
|
927 |
{'x': treid}, 'x', ask_confirm=False) |
|
928 |
self.rqlexec('DELETE T condition R WHERE T eid %(x)s', |
|
929 |
{'x': treid}, 'x', ask_confirm=False) |
|
930 |
for gname in requiredgroups: |
|
931 |
### XXX ensure gname validity |
|
932 |
self.rqlexec('SET T require_group G WHERE T eid %(x)s, G name %(gn)s', |
|
933 |
{'x': treid, 'gn': gname}, 'x', ask_confirm=False) |
|
934 |
if isinstance(conditions, basestring): |
|
935 |
conditions = (conditions,) |
|
936 |
for expr in conditions: |
|
937 |
if isinstance(expr, str): |
|
938 |
expr = unicode(expr) |
|
939 |
self.rqlexec('INSERT RQLExpression X: X exprtype "ERQLExpression", ' |
|
940 |
'X expression %(expr)s, T condition X ' |
|
941 |
'WHERE T eid %(x)s', |
|
942 |
{'x': treid, 'expr': expr}, 'x', ask_confirm=False) |
|
943 |
if commit: |
|
944 |
self.commit() |
|
945 |
||
972 | 946 |
def cmd_set_state(self, eid, statename, commit=False): |
947 |
self.session.set_pool() # ensure pool is set |
|
948 |
entity = self.session.eid_rset(eid).get_entity(0, 0) |
|
949 |
entity.change_state(entity.wf_state(statename).eid) |
|
950 |
if commit: |
|
951 |
self.commit() |
|
1477 | 952 |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
953 |
# CWProperty handling ###################################################### |
0 | 954 |
|
955 |
def cmd_property_value(self, pkey): |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
956 |
rql = 'Any V WHERE X is CWProperty, X pkey %(k)s, X value V' |
0 | 957 |
rset = self.rqlexec(rql, {'k': pkey}, ask_confirm=False) |
958 |
return rset[0][0] |
|
959 |
||
960 |
def cmd_set_property(self, pkey, value): |
|
961 |
value = unicode(value) |
|
962 |
try: |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
963 |
prop = self.rqlexec('CWProperty X WHERE X pkey %(k)s', {'k': pkey}, |
0 | 964 |
ask_confirm=False).get_entity(0, 0) |
965 |
except: |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
966 |
self.cmd_add_entity('CWProperty', pkey=unicode(pkey), value=value) |
0 | 967 |
else: |
968 |
self.rqlexec('SET X value %(v)s WHERE X pkey %(k)s', |
|
969 |
{'k': pkey, 'v': value}, ask_confirm=False) |
|
970 |
||
971 |
# other data migration commands ########################################### |
|
1477 | 972 |
|
0 | 973 |
def cmd_add_entity(self, etype, *args, **kwargs): |
974 |
"""add a new entity of the given type""" |
|
975 |
rql = 'INSERT %s X' % etype |
|
976 |
relations = [] |
|
977 |
restrictions = [] |
|
978 |
for rtype, rvar in args: |
|
979 |
relations.append('X %s %s' % (rtype, rvar)) |
|
980 |
restrictions.append('%s eid %s' % (rvar, kwargs.pop(rvar))) |
|
981 |
commit = kwargs.pop('commit', False) |
|
982 |
for attr in kwargs: |
|
983 |
relations.append('X %s %%(%s)s' % (attr, attr)) |
|
984 |
if relations: |
|
985 |
rql = '%s: %s' % (rql, ', '.join(relations)) |
|
986 |
if restrictions: |
|
987 |
rql = '%s WHERE %s' % (rql, ', '.join(restrictions)) |
|
988 |
eid = self.rqlexec(rql, kwargs, ask_confirm=self.verbosity>=2).rows[0][0] |
|
989 |
if commit: |
|
990 |
self.commit() |
|
991 |
return eid |
|
1477 | 992 |
|
0 | 993 |
def sqlexec(self, sql, args=None, ask_confirm=True): |
994 |
"""execute the given sql if confirmed |
|
1477 | 995 |
|
0 | 996 |
should only be used for low level stuff undoable with existing higher |
997 |
level actions |
|
998 |
""" |
|
999 |
if not ask_confirm or self.confirm('execute sql: %s ?' % sql): |
|
1000 |
self.session.set_pool() # ensure pool is set |
|
1001 |
try: |
|
1002 |
cu = self.session.system_sql(sql, args) |
|
1003 |
except: |
|
1004 |
ex = sys.exc_info()[1] |
|
1005 |
if self.confirm('error: %s\nabort?' % ex): |
|
1006 |
raise |
|
1007 |
return |
|
1008 |
try: |
|
1009 |
return cu.fetchall() |
|
1010 |
except: |
|
1011 |
# no result to fetch |
|
1012 |
return |
|
1477 | 1013 |
|
0 | 1014 |
def rqlexec(self, rql, kwargs=None, cachekey=None, ask_confirm=True): |
1015 |
"""rql action""" |
|
1016 |
if not isinstance(rql, (tuple, list)): |
|
1017 |
rql = ( (rql, kwargs), ) |
|
1018 |
res = None |
|
1019 |
for rql, kwargs in rql: |
|
1020 |
if kwargs: |
|
1021 |
msg = '%s (%s)' % (rql, kwargs) |
|
1022 |
else: |
|
1023 |
msg = rql |
|
1024 |
if not ask_confirm or self.confirm('execute rql: %s ?' % msg): |
|
1025 |
try: |
|
1026 |
res = self.rqlcursor.execute(rql, kwargs, cachekey) |
|
1027 |
except Exception, ex: |
|
1028 |
if self.confirm('error: %s\nabort?' % ex): |
|
1029 |
raise |
|
1030 |
return res |
|
1031 |
||
1032 |
def rqliter(self, rql, kwargs=None, ask_confirm=True): |
|
1033 |
return ForRqlIterator(self, rql, None, ask_confirm) |
|
1034 |
||
1035 |
def cmd_deactivate_verification_hooks(self): |
|
1036 |
self.repo.hm.deactivate_verification_hooks() |
|
1037 |
||
1038 |
def cmd_reactivate_verification_hooks(self): |
|
1039 |
self.repo.hm.reactivate_verification_hooks() |
|
1477 | 1040 |
|
0 | 1041 |
# broken db commands ###################################################### |
1042 |
||
1043 |
def cmd_change_attribute_type(self, etype, attr, newtype, commit=True): |
|
1044 |
"""low level method to change the type of an entity attribute. This is |
|
1045 |
a quick hack which has some drawback: |
|
1046 |
* only works when the old type can be changed to the new type by the |
|
1047 |
underlying rdbms (eg using ALTER TABLE) |
|
1048 |
* the actual schema won't be updated until next startup |
|
1049 |
""" |
|
1050 |
rschema = self.repo.schema.rschema(attr) |
|
1051 |
oldtype = rschema.objects(etype)[0] |
|
1052 |
rdefeid = rschema.rproperty(etype, oldtype, 'eid') |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
1053 |
sql = ("UPDATE CWAttribute " |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
1054 |
"SET to_entity=(SELECT eid FROM CWEType WHERE name='%s')" |
0 | 1055 |
"WHERE eid=%s") % (newtype, rdefeid) |
1056 |
self.sqlexec(sql, ask_confirm=False) |
|
1057 |
dbhelper = self.repo.system_source.dbhelper |
|
1058 |
sqltype = dbhelper.TYPE_MAPPING[newtype] |
|
1059 |
sql = 'ALTER TABLE %s ALTER COLUMN %s TYPE %s' % (etype, attr, sqltype) |
|
1060 |
self.sqlexec(sql, ask_confirm=False) |
|
1061 |
if commit: |
|
1062 |
self.commit() |
|
1477 | 1063 |
|
0 | 1064 |
def cmd_add_entity_type_table(self, etype, commit=True): |
1065 |
"""low level method to create the sql table for an existing entity. |
|
1066 |
This may be useful on accidental desync between the repository schema |
|
1067 |
and a sql database |
|
1068 |
""" |
|
1069 |
dbhelper = self.repo.system_source.dbhelper |
|
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:
1240
diff
changeset
|
1070 |
tablesql = eschema2sql(dbhelper, self.repo.schema.eschema(etype), |
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:
1240
diff
changeset
|
1071 |
prefix=SQL_PREFIX) |
0 | 1072 |
for sql in tablesql.split(';'): |
1073 |
if sql.strip(): |
|
1074 |
self.sqlexec(sql) |
|
1075 |
if commit: |
|
1076 |
self.commit() |
|
1477 | 1077 |
|
0 | 1078 |
def cmd_add_relation_type_table(self, rtype, commit=True): |
1079 |
"""low level method to create the sql table for an existing relation. |
|
1080 |
This may be useful on accidental desync between the repository schema |
|
1081 |
and a sql database |
|
1082 |
""" |
|
1083 |
dbhelper = self.repo.system_source.dbhelper |
|
1084 |
tablesql = rschema2sql(dbhelper, self.repo.schema.rschema(rtype)) |
|
1085 |
for sql in tablesql.split(';'): |
|
1086 |
if sql.strip(): |
|
1087 |
self.sqlexec(sql) |
|
1088 |
if commit: |
|
1089 |
self.commit() |
|
1477 | 1090 |
|
0 | 1091 |
|
1092 |
class ForRqlIterator: |
|
1093 |
"""specific rql iterator to make the loop skipable""" |
|
1094 |
def __init__(self, helper, rql, kwargs, ask_confirm): |
|
1095 |
self._h = helper |
|
1096 |
self.rql = rql |
|
1097 |
self.kwargs = kwargs |
|
1098 |
self.ask_confirm = ask_confirm |
|
1099 |
self._rsetit = None |
|
1477 | 1100 |
|
0 | 1101 |
def __iter__(self): |
1102 |
return self |
|
1477 | 1103 |
|
0 | 1104 |
def next(self): |
1105 |
if self._rsetit is not None: |
|
1106 |
return self._rsetit.next() |
|
1107 |
rql, kwargs = self.rql, self.kwargs |
|
1108 |
if kwargs: |
|
1109 |
msg = '%s (%s)' % (rql, kwargs) |
|
1110 |
else: |
|
1111 |
msg = rql |
|
1112 |
if self.ask_confirm: |
|
1113 |
if not self._h.confirm('execute rql: %s ?' % msg): |
|
1114 |
raise StopIteration |
|
1115 |
try: |
|
1116 |
rset = self._h.rqlcursor.execute(rql, kwargs) |
|
1117 |
except Exception, ex: |
|
1118 |
if self._h.confirm('error: %s\nabort?' % ex): |
|
1119 |
raise |
|
1120 |
else: |
|
1121 |
raise StopIteration |
|
1122 |
self._rsetit = iter(rset) |
|
1123 |
return self._rsetit.next() |