Skip to content

Commit

Permalink
Better error handling for migrations. Adding support for uninstall wi…
Browse files Browse the repository at this point in the history
…th keeping tables
  • Loading branch information
gustavs-gutmanis committed May 1, 2019
1 parent 8f2dd12 commit 2de20a7
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 12 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "solspace/craft3-commons",
"description": "Solspace Commons Library for Craft CMS 3 plugins",
"version": "1.0.19",
"version": "1.0.20",
"type": "library",
"license": "MIT",
"require": {
Expand Down
7 changes: 7 additions & 0 deletions src/Migrations/KeepTablesAfterUninstallInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Solspace\Commons\Migrations;

interface KeepTablesAfterUninstallInterface
{
}
36 changes: 25 additions & 11 deletions src/Migrations/StreamlinedInstallMigration.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ final public function safeUp(): bool
}

foreach ($this->defineTableData() as $table) {
if ($this->db->tableExists($table->getDatabaseName())) {
continue;
}

$table->addField('dateCreated', $this->dateTime()->notNull());
$table->addField('dateUpdated', $this->dateTime()->notNull());
$table->addField('uid', $this->uid());
Expand All @@ -34,15 +38,19 @@ final public function safeUp(): bool

foreach ($this->defineTableData() as $table) {
foreach ($table->getForeignKeys() as $foreignKey) {
$this->addForeignKey(
$foreignKey->getName(),
$table->getDatabaseName(),
$foreignKey->getColumn(),
$foreignKey->getDatabaseReferenceTableName(),
$foreignKey->getReferenceColumn(),
$foreignKey->getOnDelete(),
$foreignKey->getOnUpdate()
);
try {
$this->addForeignKey(
$foreignKey->getName(),
$table->getDatabaseName(),
$foreignKey->getColumn(),
$foreignKey->getDatabaseReferenceTableName(),
$foreignKey->getReferenceColumn(),
$foreignKey->getOnDelete(),
$foreignKey->getOnUpdate()
);
} catch (\Exception $e) {
\Craft::warning($e->getMessage());
}
}
}

Expand All @@ -58,17 +66,23 @@ final public function safeDown(): bool
return false;
}

if ($this instanceof KeepTablesAfterUninstallInterface) {
return true;
}

$tables = $this->defineTableData();

foreach ($tables as $table) {
if (!\Craft::$app->db->tableExists($table->getDatabaseName())) {
if (!$this->db->tableExists($table->getDatabaseName())) {
continue;
}

foreach ($table->getForeignKeys() as $foreignKey) {
try {
$this->dropForeignKey($foreignKey->getName(), $table->getDatabaseName());
} catch (\Exception $e) {}
} catch (\Exception $e) {
\Craft::warning($e->getMessage());
}
}
}

Expand Down

0 comments on commit 2de20a7

Please sign in to comment.