[migration] Add IF EXISTS on DROP CONSTRAINT
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Thu, 23 Jun 2016 15:45:30 +0200
changeset 11363 e5fe836df6f1
parent 11362 ebe75d73acdd
child 11364 a702d31ddd8f
[migration] Add IF EXISTS on DROP CONSTRAINT problem encountered on migration of a legacy database
cubicweb/misc/migration/3.23.0_Any.py
--- a/cubicweb/misc/migration/3.23.0_Any.py	Mon Jun 20 18:00:00 2016 +0200
+++ b/cubicweb/misc/migration/3.23.0_Any.py	Thu Jun 23 15:45:30 2016 +0200
@@ -9,6 +9,7 @@
 sql = partial(sql, ask_confirm=False)
 
 source = repo.system_source
+helper = source.dbhelper
 
 for rschema in schema.relations():
     if rschema.rule or rschema in PURE_VIRTUAL_RTYPES:
@@ -19,7 +20,7 @@
             column = 'cw_{0}'.format(rdef.rtype)
             if any(isinstance(cstr, UniqueConstraint) for cstr in rdef.constraints):
                 old_name = '%s_%s_key' % (table.lower(), column.lower())
-                sql('ALTER TABLE %s DROP CONSTRAINT %s' % (table, old_name))
+                sql('ALTER TABLE %s DROP CONSTRAINT IF EXISTS %s' % (table, old_name))
                 source.create_index(cnx, table, column, unique=True)
             if rschema.inlined or rdef.indexed:
                 old_name = '%s_%s_idx' % (table.lower(), column.lower())
@@ -38,12 +39,10 @@
 
 # we changed constraint serialization, which also changes their name
 
-helper = repo.system_source.dbhelper
-
 for table, cstr in sql("""
     SELECT table_name, constraint_name FROM information_schema.constraint_column_usage
     WHERE constraint_name LIKE 'cstr%'"""):
-    sql("ALTER TABLE %(table)s DROP CONSTRAINT %(cstr)s" % locals())
+    sql("ALTER TABLE %(table)s DROP CONSTRAINT IF EXISTS %(cstr)s" % locals())
 
 for cwconstraint in rql('Any C WHERE R constrained_by C').entities():
     cwrdef = cwconstraint.reverse_constrained_by[0]