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

close all defined db connections on temp apps #285

Merged
merged 1 commit into from
Jul 20, 2022
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
41 changes: 34 additions & 7 deletions src/commands/BatchController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use schmunk42\giiant\generators\crud\Generator;
use schmunk42\giiant\generators\model\Generator as ModelGenerator;
use yii\console\Application;
use yii\console\Controller;
use yii\helpers\ArrayHelper;
use yii\helpers\Inflector;
Expand Down Expand Up @@ -463,13 +464,9 @@ public function actionModels()
$route = 'gii/giiant-model';

$app = \Yii::$app;
$temp = new \yii\console\Application($this->appConfig);
$temp = new Application($this->appConfig);
$temp->runAction(ltrim($route, '/'), $params);
if (\Yii::$container->has($this->modelDb)) {
\Yii::$container->get($this->modelDb)->close();
} else {
$temp->get($this->modelDb)->close();
}
$this->closeTempAppConnections($temp);
unset($temp);
\Yii::$app = $app;
\Yii::$app->log->logger->flush(true);
Expand Down Expand Up @@ -536,8 +533,9 @@ public function actionCruds()
];
$route = 'gii/giiant-crud';
$app = \Yii::$app;
$temp = new \yii\console\Application($this->appConfig);
$temp = new Application($this->appConfig);
$temp->runAction(ltrim($route, '/'), $params);
$this->closeTempAppConnections($temp);
unset($temp);
\Yii::$app = $app;
\Yii::$app->log->logger->flush(true);
Expand Down Expand Up @@ -582,5 +580,34 @@ private function createDirectoryFromNamespace($ns)
$dir = \Yii::getAlias('@' . str_replace('\\', '/', ltrim($ns, '\\')));
@mkdir($dir);
}

/**
* close modelDb and all defined yii\db\Connection components to prevent 'too many connections'
*
* @param $app
*
* @return void
* @throws \yii\base\InvalidConfigException
* @throws \yii\di\NotInstantiableException
*/
private function closeTempAppConnections(Application $app)
{
// if modelDb is set via DI - close
if (\Yii::$container->has($this->modelDb)) {
\Yii::$container->get($this->modelDb)->close();
} elseif($app->get($this->modelDb)) {
$app->get($this->modelDb)->close();
}
// and then we close all defined yii\db\Connection components to be on the safe side,
// since we don't know if there are any other than the "known" modelDb
if (isset($app->components)) {
foreach ($app->components as $cid => $component) {
$cObj = $app->get($cid);
if ($cObj instanceof \yii\db\Connection) {
$cObj->close();
}
}
}
}
}