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