|
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 2 | +# you may not use this file except in compliance with the License. |
| 3 | +# You may obtain a copy of the License at |
| 4 | +# |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +# See the License for the specific language governing permissions and |
| 11 | +# limitations under the License. |
| 12 | +""" |
| 13 | +Unique normalized organization names |
| 14 | +
|
| 15 | +Revision ID: f609b35e981b |
| 16 | +Revises: 4f8982e60deb |
| 17 | +Create Date: 2025-04-21 16:23:05.015207 |
| 18 | +""" |
| 19 | + |
| 20 | +import sqlalchemy as sa |
| 21 | + |
| 22 | +from alembic import op |
| 23 | + |
| 24 | +revision = "f609b35e981b" |
| 25 | +down_revision = "4f8982e60deb" |
| 26 | + |
| 27 | + |
| 28 | +def upgrade(): |
| 29 | + op.add_column( |
| 30 | + "organizations", sa.Column("normalized_name", sa.String(), nullable=True) |
| 31 | + ) |
| 32 | + op.execute( |
| 33 | + """ |
| 34 | + UPDATE organizations |
| 35 | + SET normalized_name = normalize_pep426_name(name) |
| 36 | + """ |
| 37 | + ) |
| 38 | + op.alter_column("organizations", "normalized_name", nullable=False) |
| 39 | + op.create_unique_constraint(None, "organizations", ["normalized_name"]) |
| 40 | + |
| 41 | + op.execute( |
| 42 | + """ CREATE OR REPLACE FUNCTION maintain_organizations_normalized_name() |
| 43 | + RETURNS TRIGGER AS $$ |
| 44 | + BEGIN |
| 45 | + NEW.normalized_name := normalize_pep426_name(NEW.name); |
| 46 | + RETURN NEW; |
| 47 | + END; |
| 48 | + $$ |
| 49 | + LANGUAGE plpgsql |
| 50 | + """ |
| 51 | + ) |
| 52 | + |
| 53 | + op.execute( |
| 54 | + """ CREATE TRIGGER organizations_update_normalized_name |
| 55 | + BEFORE INSERT OR UPDATE OF name ON organizations |
| 56 | + FOR EACH ROW |
| 57 | + EXECUTE PROCEDURE maintain_organizations_normalized_name() |
| 58 | + """ |
| 59 | + ) |
| 60 | + |
| 61 | + |
| 62 | +def downgrade(): |
| 63 | + op.drop_constraint(None, "organizations", type_="unique") |
| 64 | + op.drop_column("organizations", "normalized_name") |
0 commit comments