@@ -0,0 +1,2378 @@
+# Copyright (C) 2016 Google Inc.%0A# Licensed under http://www.apache.org/licenses/LICENSE-2.0 %3Csee LICENSE file%3E%0A%0A%22%22%22%0ARemove bad CA names%0A%0ACreate Date: 2016-10-20 12:56:20.500665%0A%22%22%22%0A# disable Invalid constant name pylint warning for mandatory Alembic variables.%0A# pylint: disable=invalid-name%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Afrom sqlalchemy.sql import table, column, select%0A%0A%0A# revision identifiers, used by Alembic.%0Arevision = %221db61b597d2d%22%0Adown_revision = %2253206b20c12b%22%0A%0AMAX_TRIES = 100%0A%0ACAD = table(%0A    %22custom_attribute_definitions%22,%0A    column(%22id%22, sa.Integer),%0A    column(%22title%22, sa.String),%0A    column(%22definition_id%22, sa.Integer),%0A    column(%22definition_type%22, sa.String),%0A)%0A%0A%0Adef _update_at_cad_titles(old_titles, new_titles):%0A  %22%22%22Update Assessment template CAD titles.%22%22%22%0A  for old, new in zip(old_titles, new_titles):%0A    op.execute(%0A        CAD.update()%0A      .where(CAD.c.title == old)%0A      .where(CAD.c.definition_type == %22assessment_template%22)%0A      .values(title=new)%0A    )%0A%0A%0Adef upgrade():%0A  %22%22%22Upgrade database schema and/or data, creating a new revision.%0A%0A  The global CAD titles to be replaced can be found with the sql statement:%0A    SELECT title%0A    FROM custom_attribute_definitions%0A    WHERE definition_type = %22assessment_template%22%0A    AND title IN (%0A        SELECT DISTINCT(title)%0A        FROM custom_attribute_definitions%0A        WHERE definition_type = %22assessment%22%0A        AND definition_id IS NULL%0A    )%0A  %22%22%22%0A  connection = op.get_bind()%0A%0A  assessment_global_titles = select(%5BCAD.c.title%5D)%5C%0A      .where(CAD.c.definition_type == %22assessment%22)%5C%0A      .where(CAD.c.definition_id.is_(None))%0A  bad_rows_sql = select(%5BCAD.c.title%5D)%5C%0A      .where(CAD.c.definition_type == %22assessment_template%22)%5C%0A      .where(CAD.c.title.in_(assessment_global_titles))%0A  bad_rows = connection.execute(bad_rows_sql).fetchall()%0A  bad_titles = %5Brow.title for row in bad_rows%5D%0A%0A  if not bad_titles:%0A    return%0A%0A  for counter in range(1, MAX_TRIES):%0A    new_titles = %5Bu%22%7B%7D (%7B%7D)%22.format(title, counter) for title in bad_titles%5D%0A    collisions = connection.execute(%0A        CAD.select().where(CAD.c.title.in_(new_titles))%0A    ).fetchall()%0A    if not collisions:%0A      _update_at_cad_titles(bad_titles, new_titles)%0A      break%0A%0A%0Adef downgrade():%0A  %22%22%22Ignore downgrade function.%0A%0A  Fixing title names can't be reversed so there is nothing to do here.%0A  %22%22%22%0A

Add migration for fixing bad CA names