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

Add db/drop-all-tables command #11288

Merged
merged 4 commits into from
Jun 6, 2022
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions CHANGELOG-WIP.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Added
- Field layouts can now have “Line Break” UI elements. ([#11328](https://github.com/craftcms/cms/discussions/11328))
- Added the `db/drop-all-tables` command. ([#11288](https://github.com/craftcms/cms/pull/11288))
- The `AdminTable` Vue component can now be included into other Vue apps, in addition to being used as a standalone app. ([#11107](https://github.com/craftcms/cms/pull/11107))
- Added a `one()` alias for `first()` to collections. ([#11134](https://github.com/craftcms/cms/discussions/11134))
- Added `craft\base\Element::EVENT_DEFINE_CACHE_TAGS`. ([#11171](https://github.com/craftcms/cms/discussions/11171))
Expand Down Expand Up @@ -30,6 +31,7 @@
- Newly-created entries now get placeholder Post Date set on them, so they get sorted appropriately when querying for entries ordered by `postDate`. ([#11272](https://github.com/craftcms/cms/issues/11272))
- Field layout elements within field layout designers now support double-clicking to open their settings slideout. ([#11277](https://github.com/craftcms/cms/discussions/11277))
- The control panel’s JavaScript queue is now paused when the browser tab isn’t visible. ([#10632](https://github.com/craftcms/cms/issues/10632))
- The `db/restore` command now asks whether the database should be backed up, and whether all existing database tables should be dropped, prior to restoring the backup. ([#11288](https://github.com/craftcms/cms/pull/11288))
- The `users/create` command now asks whether the user should be activated when saved.
- The `maxBackups` config setting now impacts `.sql.zip` files in addition to `.sql` files. ([#11241](https://github.com/craftcms/cms/issues/11241))
- Deprecation messages are now consistently referred to as “deprecation warnings” in the control panel.
Expand Down
121 changes: 118 additions & 3 deletions src/console/controllers/DbController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@
use Craft;
use craft\console\Controller;
use craft\helpers\Console;
use craft\helpers\Db;
use craft\helpers\FileHelper;
use craft\helpers\StringHelper;
use Throwable;
use yii\base\NotSupportedException;
use yii\console\ExitCode;
use yii\db\Exception;
use ZipArchive;

/**
Expand All @@ -34,21 +37,116 @@ class DbController extends Controller
*/
public bool $overwrite = false;

/**
* @var bool Whether to drop all preexisting tables in the database prior to restoring the backup.
* @since 4.1.0
*/
public bool $dropAllTables = false;

/**
* @inheritdoc
*/
public function options($actionID): array
{
$options = parent::options($actionID);

if ($actionID === 'backup') {
$options[] = 'zip';
$options[] = 'overwrite';
switch ($actionID) {
case 'backup':
$options[] = 'zip';
$options[] = 'overwrite';
break;
case 'restore':
$options[] = 'dropAllTables';
break;
}

return $options;
}

/**
* Drops all tables in the database.
*
* Example:
* ```
* php craft db/drop-all-tables
* ```
*
* @throws \yii\base\NotSupportedException
* @throws \yii\db\Exception
* @since 4.1.0
*/
public function actionDropAllTables(): int
{
if (!$this->_tablesExist()) {
$this->stdout('No existing database tables found.' . PHP_EOL, Console::FG_YELLOW);
return ExitCode::OK;
}

if (!$this->confirm('Are you sure you want to drop all tables from the database?')) {
$this->stdout('Aborted.' . PHP_EOL, Console::FG_YELLOW);
return ExitCode::OK;
}

$this->_backupPrompt();

try {
$this->_dropAllTables();
} catch (Throwable $e) {
Craft::$app->getErrorHandler()->logException($e);
$this->stderr('error: ' . $e->getMessage() . PHP_EOL, Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}

return ExitCode::OK;
}

/**
* Returns whether any database tables exist currently.
*
* @return bool
*/
private function _tablesExist(): bool
{
return !empty(Craft::$app->getDb()->getSchema()->getTableNames());
}

/**
* Prompts for whether the database should be backed up.
*/
private function _backupPrompt(): void
{
if ($this->interactive && $this->confirm('Backup your database?')) {
$this->runAction('backup');
$this->stdout(PHP_EOL);
}
}

/**
* Drops all tables in the database.
*
* @throws NotSupportedException
* @throws Exception
*/
private function _dropAllTables(): void
{
$tableNames = Craft::$app->getDb()->getSchema()->getTableNames();

$this->stdout('Dropping all database tables ... ' . PHP_EOL);

foreach ($tableNames as $tableName) {
$this->stdout(' - Dropping ');
$this->stdout($tableName, Console::FG_CYAN);
$this->stdout(' ... ');
Db::dropAllForeignKeysToTable($tableName);
Craft::$app->getDb()->createCommand()
->dropTable($tableName)
->execute();
$this->stdout('done' . PHP_EOL, Console::FG_GREEN);
}

$this->stdout('Finished dropping all database tables.' . PHP_EOL . PHP_EOL, Console::FG_GREEN);
}

/**
* Creates a new database backup.
*
Expand Down Expand Up @@ -171,6 +269,23 @@ public function actionRestore(?string $path = null): int
$path = reset($files);
}

if ($this->_tablesExist()) {
$this->_backupPrompt();

if (
$this->dropAllTables ||
($this->interactive && $this->confirm('Drop all tables from the database first?'))
) {
try {
$this->_dropAllTables();
} catch (Throwable $e) {
Craft::$app->getErrorHandler()->logException($e);
$this->stderr('error: ' . $e->getMessage() . PHP_EOL, Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
}
}

$this->stdout('Restoring database backup ... ');

try {
Expand Down