1
0
Fork 0
mirror of https://we.phorge.it/source/phorge.git synced 2024-11-15 11:22:40 +01:00
phorge-phorge/resources/sql/autopatches/20180418.almanac.network.unique.php
Austin McKinley 0a83f253ed Add unique constraint for Almanac network names
Summary:
The name of networks should be unique.

Also adds support for exact-name queries for AlamanacNetworks.

Test Plan: Applied migration with existing duplicates, saw networks renamed, attempted to add duplicates, got a nice error message.

Reviewers: epriestley

Reviewed By: epriestley

Subscribers: Korvin, PHID-OPKG-gm6ozazyms6q6i22gyam

Differential Revision: https://secure.phabricator.com/D19379
2018-04-19 13:41:15 -07:00

46 lines
955 B
PHP

<?php
$table = new AlmanacNetwork();
$conn = $table->establishConnection('w');
queryfx(
$conn,
'LOCK TABLES %T WRITE',
$table->getTableName());
$seen = array();
foreach (new LiskMigrationIterator($table) as $network) {
$name = $network->getName();
// If this is the first copy of this row we've seen, mark it as seen and
// move on.
if (empty($seen[$name])) {
$seen[$name] = 1;
continue;
}
// Otherwise, rename this row.
while (true) {
$new_name = $name.'-'.$seen[$name];
if (empty($seen[$new_name])) {
$network->setName($new_name);
try {
$network->save();
break;
} catch (AphrontDuplicateKeyQueryException $ex) {
// New name is a dupe of a network we haven't seen yet.
}
}
$seen[$name]++;
}
$seen[$new_name] = 1;
}
queryfx(
$conn,
'ALTER TABLE %T ADD UNIQUE KEY `key_name` (name)',
$table->getTableName());
queryfx(
$conn,
'UNLOCK TABLES');