Skip to content

Commit

Permalink
Add support for commenting multiple database connections (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexthekiwi authored Jul 11, 2023
1 parent 38c27f7 commit 38ca774
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
8 changes: 8 additions & 0 deletions config/sql-commenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,12 @@
* the SqlCommenter class and specify your custom class here
*/
'commenter_class' => Spatie\SqlCommenter\SqlCommenter::class,

/**
* The database connections for which you want to add comments.
* Defaults to the default connection defined in config/database.php
*/
'connections' => [
// 'mysql',
],
];
27 changes: 17 additions & 10 deletions src/SqlCommenterServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Spatie\SqlCommenter;

use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
use Spatie\SqlCommenter\Commenters\Commenter;
Expand All @@ -29,18 +30,24 @@ public function packageBooted(): void
return new $commenterClass();
});

$this->app->get('db.connection')
->beforeExecuting(function (
string &$query,
array &$bindings,
Connection $connection,
) {
$sqlCommenter = app(SqlCommenter::class);

$commenters = $this->instanciateCommenters(config('sql-commenter.commenters'));
$connections = config('sql-commenter.connections', []);

$query = $sqlCommenter->commentQuery($query, $connection, $commenters);
});
if (empty($connections)) {
$connections = [config('database.default')];
}

collect($connections)->each(fn (string $conn) => DB::connection($conn)->beforeExecuting(function (
string &$query,
array &$bindings,
Connection $connection,
) {
$sqlCommenter = app(SqlCommenter::class);

$commenters = $this->instanciateCommenters(config('sql-commenter.commenters'));

$query = $sqlCommenter->commentQuery($query, $connection, $commenters);
}));
}

/**
Expand Down

0 comments on commit 38ca774

Please sign in to comment.