Skip to content

Commit 2de20a7

Browse files
Better error handling for migrations. Adding support for uninstall with keeping tables
1 parent 8f2dd12 commit 2de20a7

File tree

3 files changed

+33
-12
lines changed

3 files changed

+33
-12
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "solspace/craft3-commons",
33
"description": "Solspace Commons Library for Craft CMS 3 plugins",
4-
"version": "1.0.19",
4+
"version": "1.0.20",
55
"type": "library",
66
"license": "MIT",
77
"require": {
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
namespace Solspace\Commons\Migrations;
4+
5+
interface KeepTablesAfterUninstallInterface
6+
{
7+
}

src/Migrations/StreamlinedInstallMigration.php

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ final public function safeUp(): bool
1616
}
1717

1818
foreach ($this->defineTableData() as $table) {
19+
if ($this->db->tableExists($table->getDatabaseName())) {
20+
continue;
21+
}
22+
1923
$table->addField('dateCreated', $this->dateTime()->notNull());
2024
$table->addField('dateUpdated', $this->dateTime()->notNull());
2125
$table->addField('uid', $this->uid());
@@ -34,15 +38,19 @@ final public function safeUp(): bool
3438

3539
foreach ($this->defineTableData() as $table) {
3640
foreach ($table->getForeignKeys() as $foreignKey) {
37-
$this->addForeignKey(
38-
$foreignKey->getName(),
39-
$table->getDatabaseName(),
40-
$foreignKey->getColumn(),
41-
$foreignKey->getDatabaseReferenceTableName(),
42-
$foreignKey->getReferenceColumn(),
43-
$foreignKey->getOnDelete(),
44-
$foreignKey->getOnUpdate()
45-
);
41+
try {
42+
$this->addForeignKey(
43+
$foreignKey->getName(),
44+
$table->getDatabaseName(),
45+
$foreignKey->getColumn(),
46+
$foreignKey->getDatabaseReferenceTableName(),
47+
$foreignKey->getReferenceColumn(),
48+
$foreignKey->getOnDelete(),
49+
$foreignKey->getOnUpdate()
50+
);
51+
} catch (\Exception $e) {
52+
\Craft::warning($e->getMessage());
53+
}
4654
}
4755
}
4856

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

69+
if ($this instanceof KeepTablesAfterUninstallInterface) {
70+
return true;
71+
}
72+
6173
$tables = $this->defineTableData();
6274

6375
foreach ($tables as $table) {
64-
if (!\Craft::$app->db->tableExists($table->getDatabaseName())) {
76+
if (!$this->db->tableExists($table->getDatabaseName())) {
6577
continue;
6678
}
6779

6880
foreach ($table->getForeignKeys() as $foreignKey) {
6981
try {
7082
$this->dropForeignKey($foreignKey->getName(), $table->getDatabaseName());
71-
} catch (\Exception $e) {}
83+
} catch (\Exception $e) {
84+
\Craft::warning($e->getMessage());
85+
}
7286
}
7387
}
7488

0 commit comments

Comments
 (0)