Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix enum migration for Postgres #327

Merged
merged 3 commits into from
Jun 21, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,41 @@ class AddMultipleGendersChoices extends Migration
*/
public function up()
{
DB::statement("ALTER TABLE contacts CHANGE COLUMN gender gender ENUM('male', 'female', 'none')");
DB::statement("ALTER TABLE significant_others CHANGE COLUMN gender gender ENUM('male', 'female', 'none')");
DB::statement("ALTER TABLE kids CHANGE COLUMN gender gender ENUM('male', 'female', 'none')");
$driverName = DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);
switch($driverName)
{
case 'mysql':
DB::statement("ALTER TABLE contacts CHANGE COLUMN gender gender ENUM('male', 'female', 'none')");
DB::statement("ALTER TABLE significant_others CHANGE COLUMN gender gender ENUM('male', 'female', 'none')");
DB::statement("ALTER TABLE kids CHANGE COLUMN gender gender ENUM('male', 'female', 'none')");
break;
case 'pgsql':
$this->alterEnum('contacts', 'gender', ['male', 'female', 'none']);
$this->alterEnum('significant_others', 'gender', ['male', 'female', 'none']);
$this->alterEnum('kids', 'gender', ['male', 'female', 'none']);
break;
default:
throw new \Exception("Driver {$driverName} not supported.");
break;
}
}

/**
* Alter an enum field constraints. Source: https://stackoverflow.com/a/36198549
* @param $table
* @param $field
* @param array $options
*/
protected function alterEnum($table, $field, array $options) {
$check = "${table}_${field}_check";
$enumList = [];
foreach($options as $option) {
$enumList[] = sprintf("'%s'::CHARACTER VARYING", $option);
}
$enumString = implode(", ", $enumList);
DB::transaction(function () use ($table, $field, $check, $options, $enumString) {
DB::statement(sprintf('ALTER TABLE %s DROP CONSTRAINT %s;', $table, $check));
DB::statement(sprintf('ALTER TABLE %s ADD CONSTRAINT %s CHECK (%s::TEXT = ANY (ARRAY[%s]::TEXT[]))', $table, $check, $field, $enumString));
});
}
}