From 67f13fd86c8bc70bb82794e30362131d0419dfc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miloslav=20H=C5=AFla?= Date: Mon, 17 Sep 2018 12:55:47 +0200 Subject: [PATCH] Connection: added config option onConnect (#303) onConnect option is an array of SQL queries run by Connection::query() right after a database connection is established. --- src/Dibi/Connection.php | 10 ++++++++++ tests/dibi/Connection.connect.phpt | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/Dibi/Connection.php b/src/Dibi/Connection.php index 754b60c1c..1415726f6 100644 --- a/src/Dibi/Connection.php +++ b/src/Dibi/Connection.php @@ -47,6 +47,7 @@ class Connection implements IConnection * - run (bool) => enable profiler? * - file => file to log * - substitutes (array) => map of driver specific substitutes (under development) + * - onConnect (array) => list of SQL queries to execute (by Connection::query()) after connection is established * @param array $config connection parameters * @throws Exception */ @@ -90,6 +91,10 @@ public function __construct($config, string $name = null) } } + if (isset($config['onConnect']) && !is_array($config['onConnect'])) { + throw new \InvalidArgumentException("Configuration option 'onConnect' must be array."); + } + if (empty($config['lazy'])) { $this->connect(); } @@ -133,6 +138,11 @@ final public function connect(): void if ($event) { $this->onEvent($event->done()); } + if (isset($this->config['onConnect'])) { + foreach ($this->config['onConnect'] as $sql) { + $this->query($sql); + } + } } catch (DriverException $e) { if ($event) { diff --git a/tests/dibi/Connection.connect.phpt b/tests/dibi/Connection.connect.phpt index 25112d18c..d0ac395ca 100644 --- a/tests/dibi/Connection.connect.phpt +++ b/tests/dibi/Connection.connect.phpt @@ -50,3 +50,27 @@ test(function () use ($config) { $conn->disconnect(); Assert::false($conn->isConnected()); }); + + +test(function () use ($config) { + Assert::exception(function () use ($config) { + new Connection($config + ['onConnect' => '']); + }, InvalidArgumentException::class, "Configuration option 'onConnect' must be array."); + + $e = Assert::exception(function () use ($config) { + new Connection($config + ['onConnect' => ['STOP']]); + }, Dibi\DriverException::class); + Assert::same('STOP', $e->getSql()); + + $e = Assert::exception(function () use ($config) { + new Connection($config + ['onConnect' => [['STOP %i', 123]]]); + }, Dibi\DriverException::class); + Assert::same('STOP 123', $e->getSql()); + + // lazy + $conn = new Connection($config + ['lazy' => true, 'onConnect' => ['STOP']]); + $e = Assert::exception(function () use ($conn) { + $conn->query('SELECT 1'); + }, Dibi\DriverException::class); + Assert::same('STOP', $e->getSql()); +});