diff --git a/src/Command/AbstractCommand.php b/src/Command/AbstractCommand.php index 82584dcc0..fda46e9d7 100644 --- a/src/Command/AbstractCommand.php +++ b/src/Command/AbstractCommand.php @@ -6,6 +6,7 @@ use Closure; use Throwable; +use Yiisoft\Db\Connection\ConnectionInterface; use Yiisoft\Db\Exception\Exception; use Yiisoft\Db\Query\DataReaderInterface; use Yiisoft\Db\Query\QueryInterface; @@ -201,22 +202,26 @@ public function alterColumn(string $table, string $column, ColumnInterface|strin * * @deprecated Use {@see insertBatch()} instead. It will be removed in version 3.0.0. */ - public function batchInsert(string $table, array $columns, iterable $rows): static + public function batchInsert(string $table, array $columns, iterable $rows): BatchCommand { return $this->insertBatch($table, $rows, $columns); } - public function insertBatch(string $table, iterable $rows, array $columns = []): static + public function insertBatch(string $table, iterable $rows, array $columns = [], int $rowsAtOnceLimit = 0): BatchCommand { $table = $this->getQueryBuilder()->getQuoter()->getRawTableName($table); + $db = $this->getConnection(); - $params = []; - $sql = $this->getQueryBuilder()->insertBatch($table, $rows, $columns, $params); - - $this->setRawSql($sql); - $this->bindValues($params); + $statements = $this->getQueryBuilder()->insertBatch($table, $rows, $columns, $rowsAtOnceLimit); + $commands = []; + foreach ($statements as $statement) { + $command = $db->createCommand(); + $command->setRawSql($statement->sql); + $command->bindValues($statement->params); - return $this; + $commands[] = $command; + } + return new BatchCommand($commands); } abstract public function bindValue(int|string $name, mixed $value, ?int $dataType = null): static; @@ -521,6 +526,11 @@ public function upsert( return $this->setSql($sql)->bindValues($params); } + /** + * @return ConnectionInterface The query builder instance. + */ + abstract protected function getConnection(): ConnectionInterface; + /** * @return QueryBuilderInterface The query builder instance. */ diff --git a/src/Command/BatchCommand.php b/src/Command/BatchCommand.php new file mode 100644 index 000000000..409da0dfb --- /dev/null +++ b/src/Command/BatchCommand.php @@ -0,0 +1,44 @@ +commands); + } + + public function getCommands(): array + { + return $this->commands; + } + + /** + * @throws \Throwable + * @throws Exception + */ + public function execute(): int + { + $total = 0; + foreach ($this->commands as $command) { + $total += $command->execute(); + } + + return $total; + } +} diff --git a/src/Command/CommandInterface.php b/src/Command/CommandInterface.php index d55758b0d..1695c3df5 100644 --- a/src/Command/CommandInterface.php +++ b/src/Command/CommandInterface.php @@ -193,6 +193,8 @@ public function alterColumn(string $table, string $column, ColumnInterface|strin * @param string $table The name of the table to insert new rows into. * @param iterable $rows The rows to be batch inserted into the table. * @param string[] $columns The column names. + * @param int $rowsAtOnceLimit Limit number of rows inserted at once. Default 0 - means maximum allowed by DBMS. If + * provided value is greater, than supported by DBMS, then DBMS maximum value will be used. * * @throws Exception * @throws InvalidArgumentException @@ -201,7 +203,7 @@ public function alterColumn(string $table, string $column, ColumnInterface|strin * * Note: The method will quote the `table` and `column` parameters before using them in the generated SQL. */ - public function insertBatch(string $table, iterable $rows, array $columns = []): static; + public function insertBatch(string $table, iterable $rows, array $columns = [], int $rowsAtOnceLimit = 0): BatchCommand; /** * Binds a parameter to the SQL statement to be executed. diff --git a/src/Command/QueryStatement.php b/src/Command/QueryStatement.php new file mode 100644 index 000000000..eccb5cc98 --- /dev/null +++ b/src/Command/QueryStatement.php @@ -0,0 +1,19 @@ +getDriverName() === 'pgsql') { + return 65535; + } + return 0; + } } diff --git a/src/Connection/ConnectionInterface.php b/src/Connection/ConnectionInterface.php index de1a47ac6..fdc37a239 100644 --- a/src/Connection/ConnectionInterface.php +++ b/src/Connection/ConnectionInterface.php @@ -227,4 +227,10 @@ public function setTablePrefix(string $value): void; * @psalm-param Closure(ConnectionInterface):mixed|Closure(ConnectionInterface):void $closure */ public function transaction(Closure $closure, ?string $isolationLevel = null): mixed; + + /** + * Returns maximum number of bound parameters for a DBMS. Default is 0 which means unlimited. + * @return int + */ + public function getParametersLimit(): int; } diff --git a/src/Debug/CommandInterfaceProxy.php b/src/Debug/CommandInterfaceProxy.php index 98478b43e..6f8e87332 100644 --- a/src/Debug/CommandInterfaceProxy.php +++ b/src/Debug/CommandInterfaceProxy.php @@ -6,6 +6,7 @@ use Closure; use Throwable; +use Yiisoft\Db\Command\BatchCommand; use Yiisoft\Db\Command\CommandInterface; use Yiisoft\Db\Query\DataReaderInterface; use Yiisoft\Db\Query\QueryInterface; @@ -99,11 +100,11 @@ public function alterColumn(string $table, string $column, ColumnInterface|strin } /** - * @psalm-suppress MixedArgument + * @psalm-suppress MixedReturnStatement */ - public function insertBatch(string $table, iterable $rows, array $columns = []): static + public function insertBatch(string $table, iterable $rows, array $columns = [], int $rowsAtOnceLimit = 0): BatchCommand { - return new self($this->decorated->{__FUNCTION__}(...func_get_args()), $this->collector); + return $this->decorated->{__FUNCTION__}(...func_get_args()); } /** diff --git a/src/Debug/ConnectionInterfaceProxy.php b/src/Debug/ConnectionInterfaceProxy.php index 6e9d35b73..542e461d8 100644 --- a/src/Debug/ConnectionInterfaceProxy.php +++ b/src/Debug/ConnectionInterfaceProxy.php @@ -163,4 +163,9 @@ public function getDriverName(): string { return $this->connection->getDriverName(); } + + public function getParametersLimit(): int + { + return $this->connection->getParametersLimit(); + } } diff --git a/src/Driver/Pdo/AbstractPdoCommand.php b/src/Driver/Pdo/AbstractPdoCommand.php index 7f8df4ad0..5fd8fe7b4 100644 --- a/src/Driver/Pdo/AbstractPdoCommand.php +++ b/src/Driver/Pdo/AbstractPdoCommand.php @@ -14,6 +14,7 @@ use Yiisoft\Db\Command\AbstractCommand; use Yiisoft\Db\Command\Param; use Yiisoft\Db\Command\ParamInterface; +use Yiisoft\Db\Connection\ConnectionInterface; use Yiisoft\Db\Exception\ConvertException; use Yiisoft\Db\Exception\Exception; use Yiisoft\Db\Exception\InvalidParamException; @@ -165,6 +166,11 @@ protected function bindPendingParams(): void } } + protected function getConnection(): ConnectionInterface + { + return $this->db; + } + protected function getQueryBuilder(): QueryBuilderInterface { return $this->db->getQueryBuilder(); diff --git a/src/QueryBuilder/AbstractDMLQueryBuilder.php b/src/QueryBuilder/AbstractDMLQueryBuilder.php index c28368ed4..f8a96d69a 100644 --- a/src/QueryBuilder/AbstractDMLQueryBuilder.php +++ b/src/QueryBuilder/AbstractDMLQueryBuilder.php @@ -8,6 +8,7 @@ use IteratorAggregate; use JsonException; use Traversable; +use Yiisoft\Db\Command\QueryStatement; use Yiisoft\Db\Connection\ConnectionInterface; use Yiisoft\Db\Constraint\Constraint; use Yiisoft\Db\Exception\Exception; @@ -16,6 +17,7 @@ use Yiisoft\Db\Exception\NotSupportedException; use Yiisoft\Db\Expression\ExpressionInterface; use Yiisoft\Db\Query\QueryInterface; +use Yiisoft\Db\Schema\Column\ColumnInterface; use Yiisoft\Db\Schema\QuoterInterface; use Yiisoft\Db\Schema\SchemaInterface; @@ -70,23 +72,26 @@ public function __construct( * * @deprecated Use {@see insertBatch()} instead. It will be removed in version 3.0.0. */ - public function batchInsert(string $table, array $columns, iterable $rows, array &$params = []): string + public function batchInsert(string $table, array $columns, iterable $rows): array { - return $this->insertBatch($table, $rows, $columns, $params); + return $this->insertBatch($table, $rows, $columns); } - public function insertBatch(string $table, iterable $rows, array $columns = [], array &$params = []): string + public function insertBatch(string $table, iterable $rows, array $columns = [], int $rowsAtOnceLimit = 0): array { if (!is_array($rows)) { $rows = $this->prepareTraversable($rows); } if (empty($rows)) { - return ''; + return []; } + $statements = []; + $columns = $this->extractColumnNames($rows, $columns); - $values = $this->prepareBatchInsertValues($table, $rows, $columns, $params); + + $parameters = $this->prepareBatchInsertValues($table, $rows, $columns, $rowsAtOnceLimit); $query = 'INSERT INTO ' . $this->quoter->quoteTableName($table); @@ -96,7 +101,16 @@ public function insertBatch(string $table, iterable $rows, array $columns = [], $query .= ' (' . implode(', ', $quotedColumnNames) . ')'; } - return $query . ' VALUES (' . implode('), (', $values) . ')'; + foreach ($parameters as $parameter) { + $values = $parameter['values']; + $params = $parameter['params']; + $statements[] = new QueryStatement( + $query . ' VALUES (' . implode('), (', $values) . ')', + $params + ); + } + + return $statements; } public function delete(string $table, array|string $condition, array &$params): string @@ -152,7 +166,7 @@ public function upsert( * * @return array|Iterator The prepared rows. * - * @psalm-return Iterator|array> + * @psalm-return Iterator>|array{} */ final protected function prepareTraversable(Traversable $rows): Iterator|array { @@ -160,7 +174,7 @@ final protected function prepareTraversable(Traversable $rows): Iterator|array $rows = $rows->getIterator(); } - /** @var Iterator $rows */ + /** @var Iterator> $rows */ if (!$rows->valid()) { return []; } @@ -174,45 +188,120 @@ final protected function prepareTraversable(Traversable $rows): Iterator|array * @param string $table The table name. * @param iterable $rows The rows to be batch inserted into the table. * @param string[] $columnNames The column names. - * @param array $params The binding parameters that will be generated by this method. + * @param int $rowsAtOnceLimit The limit of rows inserted at once. * - * @return string[] The values. + * @return array The values. * + * @psalm-param BatchValues $rows * @psalm-param ParamsType $params + * @psalm-return array, + * }> */ - protected function prepareBatchInsertValues(string $table, iterable $rows, array $columnNames, array &$params): array - { - $values = []; - /** @var string[] $names */ + protected function prepareBatchInsertValues( + string $table, + iterable $rows, + array $columnNames, + int $rowsAtOnceLimit = 0 + ): array { + $queryStatementParameters = []; $names = array_values($columnNames); $keys = array_fill_keys($names, false); $columns = $this->schema->getTableSchema($table)?->getColumns() ?? []; + $statementParameters = ['values' => []]; + $maxParametersLimit = $this->queryBuilder->getParametersLimit(); + + $currentStatementParams = []; + $insertedRowsCount = 0; foreach ($rows as $row) { - $i = 0; - $placeholders = $keys; + $statementParameters['params'] = $currentStatementParams; + + $placeholders = $this->prepareRowBatchInsertValues( + $row, + $columnNames, + $keys, + $names, + $columns, + $currentStatementParams + ); - /** @var int|string $key */ - foreach ($row as $key => $value) { - $columnName = $columnNames[$key] ?? (isset($keys[$key]) ? $key : $names[$i] ?? $i); + $insertedRowsCount++; + if ((!empty($rowsAtOnceLimit) && $insertedRowsCount > $rowsAtOnceLimit) || + (!empty($maxParametersLimit) && count($currentStatementParams) > $maxParametersLimit)) { + $queryStatementParameters[] = $statementParameters; + $statementParameters = ['values' => []]; + $insertedRowsCount = 1; + $currentStatementParams = []; + + $placeholders = $this->prepareRowBatchInsertValues( + $row, + $columnNames, + $keys, + $names, + $columns, + $currentStatementParams + ); + } - if (isset($columns[$columnName])) { - $value = $columns[$columnName]->dbTypecast($value); - } + $statementParameters['values'][] = implode(', ', $placeholders); + } - if ($value instanceof ExpressionInterface) { - $placeholders[$columnName] = $this->queryBuilder->buildExpression($value, $params); - } else { - $placeholders[$columnName] = $this->queryBuilder->bindParam($value, $params); - } + $statementParameters['params'] = $currentStatementParams; + $queryStatementParameters[] = $statementParameters; - ++$i; + return $queryStatementParameters; + } + + /** + * Prepare values for batch insert for a single row. + * + * @param iterable|object $row The rows to be batch inserted into the table. + * @param string[] $columnNames The column names. + * @param array $keys The column names. + * @param string[] $names The column names. + * @param ColumnInterface[] $columns The table columns. + * @param array $currentStatementParams The binding parameters that will be generated by this method. + * + * @return array The placeholder for a row. + * + * @psalm-param iterable|object $row + * @psalm-param array $keys + * @psalm-param ParamsType $params + * @psalm-return array + */ + protected function prepareRowBatchInsertValues( + mixed $row, + array $columnNames, + array $keys, + array $names, + array $columns, + array &$currentStatementParams + ): array { + $i = 0; + $placeholders = $keys; + + /** + * @var string $key + */ + foreach ($row as $key => $value) { + $columnName = $columnNames[$key] ?? (isset($keys[$key]) ? $key : $names[$i] ?? $i); + + if (isset($columns[$columnName])) { + $value = $columns[$columnName]->dbTypecast($value); + } + + if ($value instanceof ExpressionInterface) { + $placeholders[$columnName] = $this->queryBuilder->buildExpression($value, $currentStatementParams); + } else { + $placeholders[$columnName] = $this->queryBuilder->bindParam($value, $currentStatementParams); } - $values[] = implode(', ', $placeholders); + ++$i; } - return $values; + return $placeholders; } /** @@ -225,7 +314,7 @@ protected function prepareBatchInsertValues(string $table, iterable $rows, array * * @psalm-param Iterator|non-empty-array> $rows */ - protected function extractColumnNames(array|Iterator $rows, array $columns): array + final protected function extractColumnNames(array|Iterator $rows, array $columns): array { $columns = $this->getNormalizeColumnNames($columns); diff --git a/src/QueryBuilder/AbstractQueryBuilder.php b/src/QueryBuilder/AbstractQueryBuilder.php index c3bffadca..26900cddf 100644 --- a/src/QueryBuilder/AbstractQueryBuilder.php +++ b/src/QueryBuilder/AbstractQueryBuilder.php @@ -139,14 +139,14 @@ public function alterColumn(string $table, string $column, ColumnInterface|strin * * @deprecated Use {@see insertBatch()} instead. It will be removed in version 3.0.0. */ - public function batchInsert(string $table, array $columns, iterable $rows, array &$params = []): string + public function batchInsert(string $table, array $columns, iterable $rows): array { - return $this->dmlBuilder->insertBatch($table, $rows, $columns, $params); + return $this->dmlBuilder->insertBatch($table, $rows, $columns); } - public function insertBatch(string $table, iterable $rows, array $columns = [], array &$params = []): string + public function insertBatch(string $table, iterable $rows, array $columns = [], int $rowsAtOnceLimit = 0): array { - return $this->dmlBuilder->insertBatch($table, $rows, $columns, $params); + return $this->dmlBuilder->insertBatch($table, $rows, $columns, $rowsAtOnceLimit); } public function bindParam(mixed $value, array &$params = []): string @@ -495,4 +495,9 @@ protected function prepareBinary(string $binary): string { return '0x' . bin2hex($binary); } + + public function getParametersLimit(): int + { + return $this->db->getParametersLimit(); + } } diff --git a/src/QueryBuilder/DMLQueryBuilderInterface.php b/src/QueryBuilder/DMLQueryBuilderInterface.php index 463d7ccd9..dafb26fce 100644 --- a/src/QueryBuilder/DMLQueryBuilderInterface.php +++ b/src/QueryBuilder/DMLQueryBuilderInterface.php @@ -5,6 +5,7 @@ namespace Yiisoft\Db\QueryBuilder; use JsonException; +use Yiisoft\Db\Command\QueryStatement; use Yiisoft\Db\Connection\ConnectionInterface; use Yiisoft\Db\Exception\Exception; use Yiisoft\Db\Exception\InvalidArgumentException; @@ -48,12 +49,12 @@ interface DMLQueryBuilderInterface * @param string $table The table to insert new rows into. * @param iterable $rows The rows to batch-insert into the table. * @param string[] $columns The column names of the table. - * @param array $params The binding parameters. This parameter exists. + * @param int $rowsAtOnceLimit The limit of rows inserted at once. * * @throws Exception * @throws InvalidArgumentException * - * @return string The batch INSERT SQL statement. + * @return QueryStatement[] Array of batch INSERT SQL statements. * * @psalm-param BatchValues $rows * @psalm-param ParamsType $params @@ -62,7 +63,7 @@ interface DMLQueryBuilderInterface * - That the values in each row must match the corresponding column names. * - The method will escape the column names, and quote the values to insert. */ - public function insertBatch(string $table, iterable $rows, array $columns = [], array &$params = []): string; + public function insertBatch(string $table, iterable $rows, array $columns = [], int $rowsAtOnceLimit = 0): array; /** * Creates a `DELETE` SQL statement. diff --git a/src/QueryBuilder/QueryBuilderInterface.php b/src/QueryBuilder/QueryBuilderInterface.php index 661b52c0e..cfae40e79 100644 --- a/src/QueryBuilder/QueryBuilderInterface.php +++ b/src/QueryBuilder/QueryBuilderInterface.php @@ -91,4 +91,10 @@ public function prepareParam(ParamInterface $param): string; * Used when the bind parameter cannot be used in the SQL query. */ public function prepareValue(mixed $value): string; + + /** + * Returns maximum number of parameters for a DBMS. + * @return int + */ + public function getParametersLimit(): int; } diff --git a/tests/AbstractCommandTest.php b/tests/AbstractCommandTest.php index 899e8757f..c0fe22a65 100644 --- a/tests/AbstractCommandTest.php +++ b/tests/AbstractCommandTest.php @@ -9,11 +9,13 @@ use Yiisoft\Db\Command\Param; use Yiisoft\Db\Command\ParamInterface; use Yiisoft\Db\Exception\Exception; +use Yiisoft\Db\Exception\InvalidArgumentException; use Yiisoft\Db\Exception\InvalidConfigException; use Yiisoft\Db\Exception\NotSupportedException; use Yiisoft\Db\Profiler\Context\CommandContext; use Yiisoft\Db\Profiler\ContextInterface; use Yiisoft\Db\Profiler\ProfilerInterface; +use Yiisoft\Db\Schema\Column\ColumnBuilder; use Yiisoft\Db\Tests\Support\DbHelper; use Yiisoft\Db\Tests\Support\TestTrait; @@ -48,6 +50,7 @@ public function testAutoQuoting(): void ), $command->getSql(), ); + $db->close(); } /** @@ -69,6 +72,7 @@ public function testConstruct(): void $this->assertSame($sql, $command->getSql()); $this->assertSame([':name' => 'John Doe'], $command->getParams()); + $db->close(); } /** @@ -106,6 +110,7 @@ public function testGetParams(): void $this->assertContainsOnlyInstancesOf(ParamInterface::class, $bindedValues); $this->assertCount(3, $bindedValues); $this->assertEquals($param, $bindedValues['int']); + $db->close(); } /** @@ -127,6 +132,7 @@ public function testGetRawSql(string $sql, array $params, string $expectedRawSql $command = $db->createCommand($sql, $params); $this->assertSame($expectedRawSql, $command->getRawSql()); + $db->close(); } /** @@ -148,6 +154,7 @@ public function testGetSetSql(): void SQL; $command->setSql($sql2); $this->assertSame($sql2, $command->getSql()); + $db->close(); } /** @@ -174,6 +181,7 @@ public function testPrepareCancel(): void $command->cancel(); $this->assertNull($command->getPdoStatement()); + $db->close(); } /** @@ -193,6 +201,7 @@ public function testSetRawSql(): void ); $this->assertSame('SELECT 123', $command->getRawSql()); + $db->close(); } /** @@ -211,6 +220,7 @@ public function testSetSql(): void ); $this->assertSame('SELECT 123', $command->getSql()); + $db->close(); } /** @@ -236,6 +246,7 @@ public function testProfiler(?string $sql = null): void $db->setProfiler($profiler); $db->createCommand($sql)->execute(); + $db->close(); } /** @@ -276,5 +287,125 @@ public function end(string $token, ContextInterface|array $context = []): void $db->setProfiler($profiler); $db->createCommand($sql)->execute(); + $db->close(); + } + + public function testBatchInsertEmptyRows(): void + { + $db = $this->getConnection(); + + $command = $db->createCommand(); + $batchCommands = $command->insertBatch('table', [], ['column1', 'column2']); + + $this->assertSame(0, $batchCommands->count()); + + $db->close(); + } + + /** + * @throws InvalidArgumentException + * @throws NotSupportedException + * @throws Exception + * @throws Throwable + * @throws InvalidConfigException + */ + public function testBindParamsOverflowIssue(): void + { + $db = $this->getConnection(); + + if ($db->getDriverName() !== 'pgsql') { + $this->markTestSkipped('Test is intended for use with pgsql database.'); + } + + $tempTableName = 'testTempTable'; + $db->createCommand()->createTable($tempTableName, [ + 'id' => ColumnBuilder::primaryKey(), + 'first_name' => ColumnBuilder::string()->notNull(), + 'last_name' => ColumnBuilder::string()->notNull(), + 'birth_date' => ColumnBuilder::date(), + 'country' => ColumnBuilder::string(), + 'city' => ColumnBuilder::string(), + 'address' => ColumnBuilder::string(), + ])->execute(); + + $personData = [ + 'first_name' => 'IVAN', + 'last_name' => 'PUPKIN', + 'birth_date' => '1983-08-08', + 'country' => 'Kazakhstan', + 'city' => 'Almaty', + 'address' => '7, Gagarin street, apartment 10', + ]; + + //generate 66 000 params (6 fields x 11000 lines) + $generateRowsCount = 11000; + $insertData = []; + for ($i = 0; $i < $generateRowsCount; $i++) { + $insertData[] = $personData; + } + + $batchCommand = $db->createCommand()->insertBatch($tempTableName, $insertData); + $insertedRowsCount = $batchCommand->execute(); + + $countSql = 'SELECT COUNT(*) FROM ' . $db->getQuoter()->quoteTableName($tempTableName); + $this->assertEquals($insertedRowsCount, $insertedRowsCount); + $this->assertEquals($generateRowsCount, $db->createCommand($countSql)->queryScalar()); + $db->createCommand()->dropTable($tempTableName)->execute(); + $db->close(); + } + + /** + * @throws InvalidArgumentException + * @throws NotSupportedException + * @throws Exception + * @throws Throwable + * @throws InvalidConfigException + */ + public function testBindParamsCustomRowsAtOnce(): void + { + $db = $this->getConnection(); + + if ($db->getDriverName() !== 'pgsql') { + $this->markTestSkipped('Test is intended for use with pgsql database.'); + } + + $tempTableName = 'testTempTable'; + $db->createCommand()->createTable($tempTableName, [ + 'id' => ColumnBuilder::primaryKey(), + 'first_name' => ColumnBuilder::string()->notNull(), + 'last_name' => ColumnBuilder::string()->notNull(), + 'birth_date' => ColumnBuilder::date(), + 'country' => ColumnBuilder::string(), + 'city' => ColumnBuilder::string(), + 'address' => ColumnBuilder::string(), + ])->execute(); + + $personData = [ + 'first_name' => 'IVAN', + 'last_name' => 'PUPKIN', + 'birth_date' => '1983-08-08', + 'country' => 'Kazakhstan', + 'city' => 'Almaty', + 'address' => '7, Gagarin street, apartment 10', + ]; + + //generate 66 000 params (6 fields x 11000 lines) + $generateRowsCount = 11000; + $insertData = []; + for ($i = 0; $i < $generateRowsCount; $i++) { + $insertData[] = $personData; + } + + $rowsAtOnceLimit = 1000; + $batchCommand = $db->createCommand()->insertBatch($tempTableName, $insertData, [], $rowsAtOnceLimit); + $this->assertEquals($generateRowsCount / $rowsAtOnceLimit, $batchCommand->count()); + + $insertedRowsCount = $batchCommand->execute(); + + $countSql = 'SELECT COUNT(*) FROM ' . $db->getQuoter()->quoteTableName($tempTableName); + $this->assertEquals($insertedRowsCount, $insertedRowsCount); + $this->assertEquals($generateRowsCount, $db->createCommand($countSql)->queryScalar()); + $db->createCommand()->dropTable($tempTableName)->execute(); + $db->close(); } } diff --git a/tests/AbstractConnectionTest.php b/tests/AbstractConnectionTest.php index 587bf86dc..3fa776b4d 100644 --- a/tests/AbstractConnectionTest.php +++ b/tests/AbstractConnectionTest.php @@ -37,6 +37,7 @@ public function testCreateBatchQueryResult(): void $query = (new Query($db))->from('customer'); $this->assertInstanceOf(BatchQueryResult::class, $db->createBatchQueryResult($query)); + $db->close(); } /** @@ -56,6 +57,7 @@ public function testCreateCommand(): void $this->assertSame($sql, $command->getSql()); $this->assertSame($params, $command->getParams()); + $db->close(); } public function testGetDriverName(): void @@ -63,6 +65,7 @@ public function testGetDriverName(): void $db = $this->getConnection(); $this->assertSame($this->getDriverName(), $db->getDriverName()); + $db->close(); } /** @@ -84,6 +87,7 @@ function (PdoConnectionInterface $db) { $db->beginTransaction(); } ); + $db->close(); } public function testNotProfiler(): void @@ -101,6 +105,7 @@ public function testNotProfiler(): void $db->setProfiler(null); $this->assertNull(Assert::getInaccessibleProperty($db, 'profiler')); + $db->close(); } public function testProfiler(): void @@ -128,6 +133,7 @@ public function end(string $token, ContextInterface|array $context = []): void }; $db->setProfiler($profiler); $db->open(); + $db->close(); } public function testSetTablePrefix(): void @@ -137,6 +143,7 @@ public function testSetTablePrefix(): void $db->setTablePrefix('pre_'); $this->assertSame('pre_', $db->getTablePrefix()); + $db->close(); } public function testSerialized(): void @@ -150,7 +157,8 @@ public function testSerialized(): void $this->assertInstanceOf(PdoConnectionInterface::class, $unserialized); $this->assertNull($unserialized->getPdo()); $this->assertEquals(123, $unserialized->createCommand('SELECT 123')->queryScalar()); - $this->assertNotNull($connection->getPdo()); + $this->assertNotNull($connection->getPDO()); + $connection->close(); } private function getProfiler(): ProfilerInterface diff --git a/tests/AbstractPdoConnectionTest.php b/tests/AbstractPdoConnectionTest.php index bab2f092d..def266464 100644 --- a/tests/AbstractPdoConnectionTest.php +++ b/tests/AbstractPdoConnectionTest.php @@ -26,14 +26,18 @@ public function testClone(): void $this->assertNotSame($db, $db2); $this->assertNull($db2->getTransaction()); - $this->assertNull($db2->getPdo()); + $this->assertNull($db2->getPDO()); + $db->close(); + $db2->close(); } public function testGetDriver(): void { - $driver = $this->getConnection()->getDriver(); + $db = $this->getConnection(); + $driver = $db->getDriver(); $this->assertInstanceOf(PdoDriverInterface::class, $driver); + $db->close(); } public function testGetServerInfo(): void @@ -41,6 +45,7 @@ public function testGetServerInfo(): void $db = $this->getConnection(); $this->assertInstanceOf(PdoServerInfo::class, $db->getServerInfo()); + $db->close(); } /** @@ -72,6 +77,7 @@ public function testOpenClose(): void $this->expectExceptionMessage('could not find driver'); $db->open(); + $db->close(); } /** @@ -107,6 +113,7 @@ public function testOpenCloseWithLogger(): void $this->expectExceptionMessage('could not find driver'); $db->open(); + $db->close(); } public function testQuoteValueNotString(): void @@ -116,6 +123,7 @@ public function testQuoteValueNotString(): void $value = $db->quoteValue(1); $this->assertSame(1, $value); + $db->close(); } public function testSetEmulatePrepare(): void @@ -127,6 +135,7 @@ public function testSetEmulatePrepare(): void $db->setEmulatePrepare(true); $this->assertTrue($db->getEmulatePrepare()); + $db->close(); } protected function getLogger(): LoggerInterface|MockObject diff --git a/tests/AbstractQueryBuilderTest.php b/tests/AbstractQueryBuilderTest.php index c4f18df72..017707dcb 100644 --- a/tests/AbstractQueryBuilderTest.php +++ b/tests/AbstractQueryBuilderTest.php @@ -56,6 +56,7 @@ public function testAddCheck(): void ), $sql, ); + $db->close(); } /** @dataProvider \Yiisoft\Db\Tests\Provider\QueryBuilderProvider::columnTypes */ @@ -75,6 +76,7 @@ public function testAddColumn(ColumnInterface|string $type): void ), $sql, ); + $db->close(); } /** @@ -96,6 +98,7 @@ public function testAddCommentOnColumn(): void ), $sql, ); + $db->close(); } /** @@ -117,6 +120,7 @@ public function testAddCommentOnTable(): void ), $sql, ); + $db->close(); } /** @@ -139,6 +143,7 @@ public function testAddDefaultValue(): void ), $sql, ); + $db->close(); } /** @@ -163,6 +168,7 @@ public function testAddForeignKey( $sql = $qb->addForeignKey($table, $name, $columns, $refTable, $refColumns, $delete, $update); $this->assertSame($expected, $sql); + $db->close(); } /** @@ -176,6 +182,7 @@ public function testAddPrimaryKey(string $name, string $table, array|string $col $sql = $qb->addPrimaryKey($table, $name, $columns); $this->assertSame($expected, $sql); + $db->close(); } /** @@ -189,6 +196,7 @@ public function testAddUnique(string $name, string $table, array|string $columns $sql = $qb->addUnique($table, $name, $columns); $this->assertSame($expected, $sql); + $db->close(); } #[DataProviderExternal(QueryBuilderProvider::class, 'alterColumn')] @@ -217,11 +225,16 @@ public function testBatchInsert( $db = $this->getConnection(true); $qb = $db->getQueryBuilder(); - $params = []; - $sql = $qb->insertBatch($table, $rows, $columns, $params); + $statements = $qb->insertBatch($table, $rows, $columns); - $this->assertSame($expected, $sql); - $this->assertSame($expectedParams, $params); + if (empty($expected)) { + $this->assertCount(0, $statements); + } else { + $this->assertSame($expected, $statements[0]->sql); + $this->assertSame($expectedParams, $statements[0]->params); + } + + $db->close(); } #[DataProviderExternal(QueryBuilderProvider::class, 'buildCondition')] @@ -243,6 +256,7 @@ public function testBuildCondition( $sql ); $this->assertEquals($expectedParams, $params); + $db->close(); } /** @@ -256,6 +270,7 @@ public function testBuildColumnsWithString(): void $qb = $db->getQueryBuilder(); $this->assertSame('(id)', $qb->buildColumns('(id)')); + $db->close(); } /** @@ -272,6 +287,7 @@ public function testBuildColumnsWithArray(): void DbHelper::replaceQuotes('[[id]], [[name]], [[email]], [[address]], [[status]]', $db->getDriverName()), $qb->buildColumns(['id', 'name', 'email', 'address', 'status']), ); + $db->close(); } /** @@ -291,6 +307,7 @@ public function testBuildColumnsWithExpression(): void ), $qb->buildColumns(['id', 'name', 'email', 'address', 'status', new Expression('COUNT(*)')]), ); + $db->close(); } /** @@ -321,6 +338,7 @@ public function testBuildIssue15653(): void $sql, ); $this->assertSame([':qp0' => '1', ':qp1' => '0'], $params); + $db->close(); } /** @@ -347,6 +365,7 @@ public function testBuildFilterCondition(array $condition, string $expected, arr $sql, ); $this->assertSame($expectedParams, $params); + $db->close(); } /** @@ -371,6 +390,7 @@ public function testBuildFrom(): void ), $qb->buildFrom($query->getFrom(), $params), ); + $db->close(); } /** @@ -394,6 +414,7 @@ public function testBuildGroupBy(): void ), $qb->buildGroupBy($query->getGroupBy(), $params), ); + $db->close(); } /** @@ -419,6 +440,7 @@ public function testBuildHaving(): void ), $qb->buildHaving($query->getHaving(), $params), ); + $db->close(); } /** @@ -443,6 +465,7 @@ public function testBuildJoin(): void ), $qb->buildJoin($query->getJoins(), $params), ); + $db->close(); } #[DataProviderExternal(QueryBuilderProvider::class, 'buildLikeCondition')] @@ -473,6 +496,7 @@ public function testBuildLikeCondition( $this->assertSame($expectedParams[$name], $value); } } + $db->close(); } /** @@ -505,6 +529,7 @@ public function testBuildLimit(): void $query = (new Query($db))->from('admin_user')->limit(10); $this->assertSame('LIMIT 10', $qb->buildLimit($query->getLimit(), 0)); + $db->close(); } public function testBuildLimitOffset(): void @@ -515,6 +540,7 @@ public function testBuildLimitOffset(): void $query = (new Query($db))->from('admin_user')->limit(10)->offset(5); $this->assertSame('LIMIT 10 OFFSET 5', $qb->buildLimit($query->getLimit(), $query->getOffset())); + $db->close(); } /** @@ -538,6 +564,7 @@ public function testBuildOrderBy(): void ), $qb->buildOrderBy($query->getOrderBy(), $params), ); + $db->close(); } /** @@ -574,6 +601,7 @@ public function testBuildOrderByAndLimit(): void $query->getOffset(), ), ); + $db->close(); } /** @@ -599,6 +627,7 @@ public function testBuildSelect(): void ), $qb->buildSelect($query->getSelect(), $params), ); + $db->close(); } /** @@ -623,6 +652,7 @@ public function testBuildSelectWithAlias(): void ), $qb->buildSelect(['id as a'], $params), ); + $db->close(); } /** @@ -648,6 +678,7 @@ public function testBuildSelectWithDistinct(): void ), $qb->buildSelect($query->getSelect(), $params, true), ); + $db->close(); } /** @@ -673,6 +704,7 @@ public function testBuildUnion(): void ), $qb->buildUnion($query->getUnions(), $params), ); + $db->close(); } /** @@ -698,6 +730,7 @@ public function testBuildWithQueries(): void ), $qb->buildWithQueries($query->getWithQueries(), $params), ); + $db->close(); } /** @@ -745,6 +778,7 @@ public function testBuildWithComplexSelect(): void $sql, ); $this->assertEmpty($params); + $db->close(); } /** @@ -769,6 +803,7 @@ public function testBuildWithFrom( $this->assertSame($expectedSql, $sql); $this->assertSame($expectedParams, $params); + $db->close(); } /** @@ -797,6 +832,7 @@ public function testBuildWithFromAliasesNoExist(): void ); $this->assertSame([], $params); + $db->close(); } /** @@ -845,6 +881,7 @@ public function testBuildWithFromIndexHint(): void ); $this->assertEmpty($params); + $db->close(); } /** @@ -912,6 +949,7 @@ public function testBuildWithFromSubquery(): void $sql, ); $this->assertEmpty($params); + $db->close(); } /** @@ -996,6 +1034,7 @@ public function testBuildWithGroupBy(): void $sql, ); $this->assertSame([':to' => 4], $params); + $db->close(); } /** @@ -1021,6 +1060,7 @@ public function testBuildWithLimit(): void ); $this->assertSame([], $params); + $db->close(); } /** @@ -1045,6 +1085,7 @@ public function testBuildWithOffset(): void $sql, ); $this->assertSame([], $params); + $db->close(); } /** @@ -1129,6 +1170,7 @@ public function testBuildWithOrderBy(): void $sql, ); $this->assertSame([':to' => 4], $params); + $db->close(); } /** @@ -1163,6 +1205,7 @@ public function testBuildWithQuery(): void ); $this->assertSame([], $params); + $db->close(); } /** @@ -1194,6 +1237,7 @@ public function testBuildWithQueryRecursive(): void $this->assertSame($expected, $sql); $this->assertSame([], $params); + $db->close(); } /** @dataProvider \Yiisoft\Db\Tests\Provider\QueryBuilderProvider::cteAliases */ @@ -1216,6 +1260,7 @@ public function testBuildWithQueryAlias($alias, $expected) $this->assertSame($expectedSql, $sql); $this->assertSame([], $params); + $db->close(); } /** @@ -1279,6 +1324,7 @@ public function testBuildWithSelectExpression(): void $sql, ); $this->assertSame([':len' => 4], $params); + $db->close(); } /** @@ -1307,6 +1353,7 @@ public function testBuildWithSelectSubquery(): void $sql, ); $this->assertEmpty($params); + $db->close(); } /** @@ -1332,6 +1379,7 @@ public function testBuildWithSelectOption(): void $this->assertSame($expected, $sql); $this->assertSame([], $params); + $db->close(); } /** @@ -1374,6 +1422,7 @@ public function testBuildWithSetSeparator(): void $sql, ); $this->assertEmpty($params); + $db->close(); } /** @@ -1409,6 +1458,7 @@ public function testBuildWithUnion(): void $sql, ); $this->assertSame([], $params); + $db->close(); } /** @@ -1434,6 +1484,7 @@ public function testBuildWithWhereExists(string $cond, string $expectedQuerySql) $this->assertSame($expectedQuerySql, $actualQuerySql); $this->assertSame($expectedQueryParams, $actualQueryParams); + $db->close(); } /** @@ -1470,6 +1521,7 @@ public function testBuildWithWhereExistsArrayParameters(): void $sql, ); $this->assertSame([':qp0' => 6, ':qp1' => 210, ':qp2' => 'asd'], $params); + $db->close(); } /** @@ -1506,6 +1558,7 @@ public function testBuildWithWhereExistsWithParameters(): void $sql, ); $this->assertSame([':some_value' => 'asd', ':merchant_id' => 6], $params); + $db->close(); } /** @@ -1555,6 +1608,7 @@ public function testsCreateConditionFromArray(): void ['a = 1', ['or', 'b = 2', ['and', 'c = 3', ['or', 'd = 4', 'e = 5']]]], $condition->getExpressions(), ); + $db->close(); } public function testCreateOverlapsConditionFromArray(): void @@ -1573,6 +1627,7 @@ public function testCreateOverlapsConditionFromArray(): void $this->assertInstanceOf(JsonOverlapsCondition::class, $condition); $this->assertSame('column', $condition->getColumn()); $this->assertSame([1, 2, 3], $condition->getValues()); + $db->close(); } public function testCreateOverlapsConditionFromArrayWithInvalidOperandsCount(): void @@ -1584,6 +1639,7 @@ public function testCreateOverlapsConditionFromArrayWithInvalidOperandsCount(): $this->expectExceptionMessage('Operator "JSON OVERLAPS" requires two operands.'); $qb->createConditionFromArray(['json overlaps', 'column']); + $db->close(); } public function testCreateOverlapsConditionFromArrayWithInvalidColumn(): void @@ -1595,6 +1651,7 @@ public function testCreateOverlapsConditionFromArrayWithInvalidColumn(): void $this->expectExceptionMessage('Operator "JSON OVERLAPS" requires column to be string or ExpressionInterface.'); $qb->createConditionFromArray(['json overlaps', ['column'], [1, 2, 3]]); + $db->close(); } public function testCreateOverlapsConditionFromArrayWithInvalidValues(): void @@ -1606,6 +1663,7 @@ public function testCreateOverlapsConditionFromArrayWithInvalidValues(): void $this->expectExceptionMessage('Operator "JSON OVERLAPS" requires values to be iterable or ExpressionInterface.'); $qb->createConditionFromArray(['json overlaps', 'column', 1]); + $db->close(); } /** @@ -1618,6 +1676,7 @@ public function testCreateIndex(string $sql, Closure $builder): void $qb = $db->getQueryBuilder(); $this->assertSame($db->getQuoter()->quoteSql($sql), $builder($qb)); + $db->close(); } /** @@ -1640,6 +1699,7 @@ public function testCreateView(): void DbHelper::replaceQuotes($expected, $db->getDriverName()), $qb->createView('animal_view', (new Query($db))->select('1')), ); + $db->close(); } /** @@ -1658,6 +1718,7 @@ public function testDelete(string $table, array|string $condition, string $expec $this->assertSame($expectedSQL, $actualSQL); $this->assertSame($expectedParams, $actualParams); + $db->close(); } public function testDropCheck(): void @@ -1675,6 +1736,7 @@ public function testDropCheck(): void ), $qb->dropCheck('T_constraints_1', 'CN_check'), ); + $db->close(); } public function testDropColumn(): void @@ -1692,6 +1754,7 @@ public function testDropColumn(): void ), $qb->dropColumn('customer', 'id'), ); + $db->close(); } public function testDropCommentFromColumn(): void @@ -1709,6 +1772,7 @@ public function testDropCommentFromColumn(): void ), $qb->dropCommentFromColumn('customer', 'id'), ); + $db->close(); } public function testDropCommentFromTable(): void @@ -1726,6 +1790,7 @@ public function testDropCommentFromTable(): void ), $qb->dropCommentFromTable('customer'), ); + $db->close(); } /** @@ -1747,6 +1812,7 @@ public function testDropDefaultValue(): void ), $qb->dropDefaultValue('T_constraints_1', 'CN_pk'), ); + $db->close(); } public function testDropForeignKey(): void @@ -1764,6 +1830,7 @@ public function testDropForeignKey(): void ), $qb->dropForeignKey('T_constraints_3', 'CN_constraints_3'), ); + $db->close(); } public function testDropIndex(): void @@ -1781,6 +1848,7 @@ public function testDropIndex(): void ), $qb->dropIndex('T_constraints_2', 'CN_constraints_2_single'), ); + $db->close(); } public function testDropPrimaryKey(): void @@ -1798,6 +1866,7 @@ public function testDropPrimaryKey(): void ), $qb->dropPrimaryKey('T_constraints_1', 'CN_pk'), ); + $db->close(); } public static function dataDropTable(): iterable @@ -1832,6 +1901,7 @@ public function testDropTable(string $expected, ?bool $ifExists, ?bool $cascade) $expectedSql = DbHelper::replaceQuotes($expected, $db->getDriverName()); $this->assertSame($expectedSql, $sql); + $db->close(); } public function testDropUnique(): void @@ -1849,6 +1919,7 @@ public function testDropUnique(): void ), $qb->dropUnique('test_uq', 'test_uq_constraint'), ); + $db->close(); } public function testDropView(): void @@ -1866,6 +1937,7 @@ public function testDropView(): void ), $qb->dropview('animal_view'), ); + $db->close(); } /** @@ -1883,6 +1955,7 @@ public function testGetExpressionBuilder(): void ExpressionBuilderInterface::class, $qb->getExpressionBuilder($simpleCondition), ); + $db->close(); } /** @@ -1906,6 +1979,7 @@ public function testInsert( $this->assertSame($expectedSQL, $qb->insert($table, $columns, $params)); $this->assertEquals($expectedParams, $params); + $db->close(); } /** @@ -1924,6 +1998,7 @@ public function testInsertWithReturningPks( $this->assertSame($expectedSQL, $qb->insertWithReturningPks($table, $columns, $params)); $this->assertSame($expectedParams, $params); + $db->close(); } public function testQuoter(): void @@ -1933,6 +2008,7 @@ public function testQuoter(): void $qb = $db->getQueryBuilder(); $this->assertInstanceOf(QuoterInterface::class, $qb->getQuoter()); + $db->close(); } public function testRenameColumn(): void @@ -1951,6 +2027,7 @@ public function testRenameColumn(): void ), $sql, ); + $db->close(); } public function testRenameTable(): void @@ -1969,6 +2046,7 @@ public function testRenameTable(): void ), $sql, ); + $db->close(); } /** @@ -1994,6 +2072,7 @@ public function testResetSequence(): void SQL, $qb->resetSequence('item', 3), ); + $db->close(); } /** @@ -2018,6 +2097,7 @@ public function testResetSequenceNoAssociatedException(): void } $qb->resetSequence('type'); + $db->close(); } /** @@ -2040,6 +2120,7 @@ public function testResetSequenceTableNoExistException(): void } $qb->resetSequence('noExist', 1); + $db->close(); } /** @@ -2053,6 +2134,7 @@ public function testSelectExists(string $sql, string $expected): void $sqlSelectExist = $qb->selectExists($sql); $this->assertSame($expected, $sqlSelectExist); + $db->close(); } /** @@ -2113,6 +2195,7 @@ public function testSelectExpression(): void $this->assertSame($expected, $sql); $this->assertSame([':len' => 4], $params); + $db->close(); } /** @@ -2139,6 +2222,7 @@ public function testSelectSubquery(): void $this->assertSame($expected, $sql); $this->assertEmpty($params); + $db->close(); } /** @dataProvider \Yiisoft\Db\Tests\Provider\QueryBuilderProvider::selectScalar */ @@ -2157,6 +2241,7 @@ public function testSelectScalar(array|bool|float|int|string $columns, string $e $this->assertSame($expected, $sql); $this->assertEmpty($params); + $db->close(); } public function testSetConditionClasses(): void @@ -2169,6 +2254,7 @@ public function testSetConditionClasses(): void $conditionClasses = Assert::getInaccessibleProperty($dqlBuilder, 'conditionClasses'); $this->assertSame(stdClass::class, $conditionClasses['stdClass']); + $db->close(); } public function testSetExpressionBuilder(): void @@ -2181,6 +2267,7 @@ public function testSetExpressionBuilder(): void $expressionBuilders = Assert::getInaccessibleProperty($dqlBuilder, 'expressionBuilders'); $this->assertSame(stdClass::class, $expressionBuilders['stdClass']); + $db->close(); } /** @@ -2222,6 +2309,7 @@ public function testSetSeparator(): void $sql, ); $this->assertEmpty($params); + $db->close(); } public function testTruncateTable(): void @@ -2252,6 +2340,7 @@ public function testTruncateTable(): void ), $sql, ); + $db->close(); } /** @@ -2276,6 +2365,7 @@ public function testUpdate( $this->assertSame($expectedSql, $sql); $this->assertEquals($expectedParams, $params); + $db->close(); } /** @@ -2301,6 +2391,7 @@ public function testUpsert( $this->assertSame($expectedSQL, $actualSQL); $this->assertSame($expectedParams, $actualParams); + $db->close(); } /** @@ -2335,6 +2426,7 @@ public function testUpsertExecute( $command = $db->createCommand($actualSQL, $actualParams); $command->execute(); + $db->close(); } /** @@ -2366,6 +2458,7 @@ public function testOverrideParameters1(): void ), $command->getRawSql() ); + $db->close(); } /** @@ -2397,6 +2490,7 @@ public function testOverrideParameters2(): void ), $command->getRawSql() ); + $db->close(); } #[DataProviderExternal(QueryBuilderProvider::class, 'buildColumnDefinition')] @@ -2418,6 +2512,7 @@ public function testPrepareParam(string $expected, mixed $value, int $type): voi $param = new Param($value, $type); $this->assertSame($expected, $qb->prepareParam($param)); + $db->close(); } #[DataProviderExternal(QueryBuilderProvider::class, 'prepareValue')] @@ -2427,5 +2522,6 @@ public function testPrepareValue(string $expected, mixed $value): void $qb = $db->getQueryBuilder(); $this->assertSame($expected, $qb->prepareValue($value)); + $db->close(); } } diff --git a/tests/AbstractQueryGetTableAliasTest.php b/tests/AbstractQueryGetTableAliasTest.php index 169b616f0..59067f535 100644 --- a/tests/AbstractQueryGetTableAliasTest.php +++ b/tests/AbstractQueryGetTableAliasTest.php @@ -36,6 +36,7 @@ public function testAliasesFromString(): void ], $tables, ); + $db->close(); } /** @@ -53,6 +54,7 @@ public function testGetTableNamesIsFromAliasedSubquery(): void $tables = $query->getTablesUsedInFrom(); $this->assertSame($expected, $tables); + $db->close(); } /** @@ -68,6 +70,7 @@ public function testNamesIsFromAliasedArrayWithExpression(): void $tables = $query->getTablesUsedInFrom(); $this->assertSame(['{{x}}' => $expression], $tables); + $db->close(); } public function testNamesIsFromAliasedExpression(): void @@ -84,6 +87,7 @@ public function testNamesIsFromAliasedExpression(): void $tables = $query->getTablesUsedInFrom(); $this->assertSame(['{{x}}' => $expression], $tables); + $db->close(); } /** @@ -102,6 +106,7 @@ public function testNamesIsFromArrayWithAlias(): void ['{{prf}}' => '{{profile}}', '{{usr}}' => '{{user}}', '{{a b}}' => '{{c d}}', '{{p}}' => '{{post}}'], $tables, ); + $db->close(); } /** @@ -116,6 +121,7 @@ public function testNamesIsFromArrayWithoutAlias(): void $tables = $query->getTablesUsedInFrom(); $this->assertSame(['{{profile}}' => '{{profile}}', '{{user}}' => '{{user}}'], $tables); + $db->close(); } /** @@ -132,6 +138,7 @@ public function testNamesIsFromPrefixedTableName(): void $tables = $query->getTablesUsedInFrom(); $this->assertSame(['{{%order_item}}' => '{{%order_item}}'], $tables); + $db->close(); } /** @@ -155,6 +162,7 @@ public function testNamesIsFromString(): void ], $tables, ); + $db->close(); } /** @@ -171,5 +179,6 @@ public function testNamesIsFromTableNameWithDatabase(): void $tables = $query->getTablesUsedInFrom(); $this->assertSame(['{{tickets.workflows}}' => '{{tickets.workflows}}'], $tables); + $db->close(); } } diff --git a/tests/AbstractQueryTest.php b/tests/AbstractQueryTest.php index dd96344e8..75698df10 100644 --- a/tests/AbstractQueryTest.php +++ b/tests/AbstractQueryTest.php @@ -29,6 +29,7 @@ public function testAddGroupByExpression(): void $query->addGroupBy($expression); $this->assertSame([$expression], $query->getGroupBy()); + $db->close(); } public function testAddOrderByEmpty(): void @@ -39,6 +40,7 @@ public function testAddOrderByEmpty(): void $query->addOrderBy([]); $this->assertSame([], $query->getOrderBy()); + $db->close(); } public function testAddParamsWithNameInt(): void @@ -50,6 +52,7 @@ public function testAddParamsWithNameInt(): void $query->addParams([2 => 'test']); $this->assertSame([1 => 'value', 2 => 'test'], $query->getParams()); + $db->close(); } /** @@ -91,6 +94,7 @@ public function testAndFilterCompare(): void $query->andFilterCompare('value', '<=100'); $this->assertSame($condition, $query->getWhere()); + $db->close(); } /** @@ -109,6 +113,7 @@ public function testAndFilterHaving(): void $query->andFilterHaving(['>', 'id', 2]); $this->assertSame(['and', ['>', 'id', 1], ['>', 'id', 2]], $query->getHaving()); + $db->close(); } /** @@ -123,6 +128,7 @@ public function testAndFilterHavingWithHashFormat(): void $this->assertInstanceOf(QueryInterface::class, $result); $this->assertSame(['status' => 1], $query->getHaving()); + $db->close(); } /** @@ -158,6 +164,7 @@ public function testCount(): void $count = (new Query($db))->from('customer')->orderBy('id')->limit(1)->count(); $this->assertEquals(3, $count); + $db->close(); } /** @@ -207,6 +214,7 @@ public function testEmulateExecution(): void $column = (new Query($db))->select(['id'])->from('customer')->emulateExecution()->column(); $this->assertSame([], $column); + $db->close(); } /** @@ -228,6 +236,7 @@ public function testFilterHavingWithHashFormat(): void $query->orFilterHaving(['name' => '']); $this->assertSame(['id' => 0], $query->getHaving()); + $db->close(); } /** @@ -278,6 +287,7 @@ public function testFilterHavingWithOperatorFormat(): void $query->andFilterHaving(['or', ['eq', 'id', null], ['eq', 'id', []]]); $this->assertSame($condition, $query->getHaving()); + $db->close(); } /** @@ -293,6 +303,7 @@ public function testFilterRecursively(): void ); $this->assertSame(['and', ['id' => 1]], $query->getWhere()); + $db->close(); } /** @@ -314,6 +325,7 @@ public function testFilterWhereWithHashFormat(): void $query->orFilterWhere(['name' => '']); $this->assertSame(['id' => 0], $query->getWhere()); + $db->close(); } /** @@ -364,6 +376,7 @@ public function testFilterWhereWithOperatorFormat(): void $query->andFilterWhere(['or', ['eq', 'id', null], ['eq', 'id', []]]); $this->assertSame($condition, $query->getWhere()); + $db->close(); } public function testFrom(): void @@ -374,6 +387,7 @@ public function testFrom(): void $query->from('user'); $this->assertSame(['user'], $query->getFrom()); + $db->close(); } public function testFromTableIsArrayWithExpression(): void @@ -387,6 +401,7 @@ public function testFromTableIsArrayWithExpression(): void $this->assertIsArray($from); $this->assertInstanceOf(ExpressionInterface::class, $from[0]); + $db->close(); } public function testGroup(): void @@ -405,6 +420,7 @@ public function testGroup(): void $query->addGroupBy('age'); $this->assertSame(['team', 'company', 'age'], $query->getGroupBy()); + $db->close(); } public function testHaving(): void @@ -424,6 +440,7 @@ public function testHaving(): void $query->orHaving('age = :age', [':age' => '30']); $this->assertSame(['or', ['and', 'id = :id', 'name = :name'], 'age = :age'], $query->getHaving()); $this->assertSame([':id' => 1, ':name' => 'something', ':age' => '30'], $query->getParams()); + $db->close(); } public function testJoin(): void @@ -441,6 +458,7 @@ public function testJoin(): void [['INNER JOIN', 'profile', 'user.id = profile.user_id'], ['LEFT JOIN', 'order', 'user.id = order.user_id']], $query->getJoins() ); + $db->close(); } public function testLimitOffset(): void @@ -452,6 +470,7 @@ public function testLimitOffset(): void $this->assertSame(10, $query->getLimit()); $this->assertSame(5, $query->getOffset()); + $db->close(); } /** @@ -465,6 +484,7 @@ public function testOrFilterHavingHashFormat(): void $query->orFilterHaving(['status' => 1]); $this->assertSame(['status' => 1], $query->getHaving()); + $db->close(); } /** @@ -478,6 +498,7 @@ public function testOrFilterWhereHashFormat(): void $query->orFilterWhere(['status' => 1]); $this->assertSame(['status' => 1], $query->getWhere()); + $db->close(); } public function testOrder(): void @@ -516,6 +537,7 @@ public function testOrder(): void $query->addOrderBy($expression2); $this->assertSame([$expression1, $expression2], $query->getOrderBy()); + $db->close(); } public function testRightJoin(): void @@ -526,6 +548,7 @@ public function testRightJoin(): void $query->rightJoin('profile', 'user.id = profile.user_id'); $this->assertSame([['RIGHT JOIN', 'profile', 'user.id = profile.user_id']], $query->getJoins()); + $db->close(); } public function testSelect(): void @@ -669,6 +692,7 @@ public function testSelect(): void $query->addSelect(['float' => 12.34]); $this->assertSame([1, true, 'float' => 12.34], $query->getSelect()); + $db->close(); } public function testSetJoin(): void @@ -688,6 +712,7 @@ public function testSetJoin(): void ], $query->getJoins() ); + $db->close(); } public function testSetUnion(): void @@ -698,6 +723,7 @@ public function testSetUnion(): void $query->setUnions(['SELECT * FROM table1', 'SELECT * FROM table2']); $this->assertSame(['SELECT * FROM table1', 'SELECT * FROM table2'], $query->getUnions()); + $db->close(); } public function testShouldEmulateExecution(): void @@ -711,6 +737,7 @@ public function testShouldEmulateExecution(): void $query->emulateExecution(); $this->assertTrue($query->shouldEmulateExecution()); + $db->close(); } public function testWhere(): void @@ -732,6 +759,7 @@ public function testWhere(): void $this->assertSame(['or', ['and', 'id = :id', 'name = :name'], 'age = :age'], $query->getWhere()); $this->assertSame([':id' => 1, ':name' => 'something', ':age' => '30'], $query->getParams()); + $db->close(); } public function testWithQueries(): void @@ -742,6 +770,7 @@ public function testWithQueries(): void $query->withQueries(['query1', 'query2']); $this->assertSame(['query1', 'query2'], $query->getWithQueries()); + $db->close(); } public function testColumnWithIndexBy(): void @@ -774,6 +803,7 @@ public function testColumnWithIndexBy(): void ->where(['id' => null]); $this->assertSame([], $query->column()); + $db->close(); } /** @@ -781,11 +811,13 @@ public function testColumnWithIndexBy(): void */ public function testFilterCondition(array|string $condition, array|string|null $expected): void { - $query = (new Query($this->getConnection())); + $db = $this->getConnection(); + $query = (new Query($db)); $this->assertNull($query->getWhere()); $query->filterWhere($condition); $this->assertEquals($expected, $query->getWhere()); + $db->close(); } /** @@ -793,11 +825,13 @@ public function testFilterCondition(array|string $condition, array|string|null $ */ public function testNormalizeOrderBy(array|string|Expression $columns, array|string $expected): void { - $query = (new Query($this->getConnection())); + $db = $this->getConnection(); + $query = (new Query($db)); $this->assertEquals([], $query->getOrderBy()); $query->orderBy($columns); $this->assertEquals($expected, $query->getOrderBy()); + $db->close(); } /** @@ -805,17 +839,20 @@ public function testNormalizeOrderBy(array|string|Expression $columns, array|str */ public function testNormalizeSelect(array|bool|float|int|string|ExpressionInterface $columns, array|string $expected): void { - $query = (new Query($this->getConnection())); + $db = $this->getConnection(); + $query = (new Query($db)); $this->assertEquals([], $query->getSelect()); $query->select($columns); $this->assertEquals($expected, $query->getSelect()); + $db->close(); } public function testCountGreaterThanPhpIntMax(): void { + $db = $this->getConnection(); $query = $this->getMockBuilder(Query::class) - ->setConstructorArgs([$this->getConnection()]) + ->setConstructorArgs([$db]) ->onlyMethods(['queryScalar']) ->getMock(); @@ -824,6 +861,7 @@ public function testCountGreaterThanPhpIntMax(): void ->willReturn('12345678901234567890'); $this->assertSame('12345678901234567890', $query->count()); + $db->close(); } public function testResultCallback(): void diff --git a/tests/AbstractQuoterTest.php b/tests/AbstractQuoterTest.php index e98a3ab07..0c731b373 100644 --- a/tests/AbstractQuoterTest.php +++ b/tests/AbstractQuoterTest.php @@ -19,6 +19,7 @@ public function testEnsureColumnName(string $columnName, string $expected): void $db = $this->getConnection(); $this->assertSame($expected, $db->getQuoter()->ensureColumnName($columnName)); + $db->close(); } /** @@ -29,6 +30,7 @@ public function testEnsureNameQuoted(string $name, string $expected): void $db = $this->getConnection(); $this->assertSame($expected, $db->getQuoter()->ensureNameQuoted($name)); + $db->close(); } /** @@ -41,6 +43,7 @@ public function testGetRawTableName(string $tableName, string $expected, string $db->setTablePrefix($tablePrefix); $this->assertSame($expected, $db->getQuoter()->getRawTableName($tableName)); + $db->close(); } /** @@ -51,6 +54,7 @@ public function testGetTableNameParts(string $tableName, string ...$expected): v $db = $this->getConnection(); $this->assertSame($expected, array_reverse($db->getQuoter()->getTableNameParts($tableName))); + $db->close(); } /** @@ -61,6 +65,7 @@ public function testQuoteColumnName(string $columnName, string $expected): void $db = $this->getConnection(); $this->assertSame($expected, $db->getQuoter()->quoteColumnName($columnName)); + $db->close(); } /** @@ -81,6 +86,7 @@ public function testQuoteSimpleColumnName( $unQuoted = $quoter->unquoteSimpleColumnName($quoted); $this->assertSame($expectedUnQuotedColumnName, $unQuoted); + $db->close(); } /** @@ -98,5 +104,6 @@ public function testQuoteTableName(string $tableName, string $expected): void $unQuoted = $quoter->unquoteSimpleTableName($quoter->quoteTableName($tableName)); $this->assertSame($expected, $unQuoted); + $db->close(); } } diff --git a/tests/AbstractSchemaTest.php b/tests/AbstractSchemaTest.php index db453111e..634ecd5d1 100644 --- a/tests/AbstractSchemaTest.php +++ b/tests/AbstractSchemaTest.php @@ -24,6 +24,7 @@ public function testGetDefaultSchema(): void $schema = $db->getSchema(); $this->assertNull($schema->getDefaultSchema()); + $db->close(); } public function testGetDataType(): void @@ -53,6 +54,7 @@ public function testGetDataType(): void } fclose($fp); + $db->close(); } public function testRefresh(): void @@ -64,5 +66,6 @@ public function testRefresh(): void $this->assertSame([], Assert::getInaccessibleProperty($schema, 'tableMetadata')); $this->assertSame([], Assert::getInaccessibleProperty($schema, 'tableNames')); + $db->close(); } } diff --git a/tests/Common/CommonCommandTest.php b/tests/Common/CommonCommandTest.php index 6071278c7..2e97ba1b1 100644 --- a/tests/Common/CommonCommandTest.php +++ b/tests/Common/CommonCommandTest.php @@ -320,13 +320,17 @@ public function testBatchInsert( $db = $this->getConnection(true); $command = $db->createCommand(); - $command->insertBatch($table, $values, $columns); + $batchCommand = $command->insertBatch($table, $values, $columns); - $this->assertSame($expected, $command->getSql()); - $this->assertSame($expectedParams, $command->getParams()); + $this->assertSame(1, $batchCommand->count()); + $commands = $batchCommand->getCommands(); + $firstCommand = $commands[0]; - $command->prepare(false); - $command->execute(); + $this->assertSame($expected, $firstCommand->getSql()); + $this->assertSame($expectedParams, $firstCommand->getParams()); + + $firstCommand->prepare(false); + $batchCommand->execute(); $this->assertEquals($insertedRow, (new Query($db))->from($table)->count()); @@ -419,13 +423,13 @@ public function testBatchInsertWithDuplicates(): void $db = $this->getConnection(true); $command = $db->createCommand(); - $command->insertBatch( + $batchCommand = $command->insertBatch( '{{customer}}', [['t1@example.com', 'test_name', 'test_address']], ['email', 'name', 'address'], ); - $this->assertSame(1, $command->execute()); + $this->assertSame(1, $batchCommand->execute()); $result = (new Query($db)) ->select(['email', 'name', 'address']) @@ -456,9 +460,9 @@ public function testBatchInsertWithManyData(): void $values[$i] = ['t' . $i . '@any.com', 't' . $i, 't' . $i . ' address']; } - $command->insertBatch('{{customer}}', $values, ['email', 'name', 'address']); + $batchCommand = $command->insertBatch('{{customer}}', $values, ['email', 'name', 'address']); - $this->assertSame($attemptsInsertRows, $command->execute()); + $this->assertSame($attemptsInsertRows, $batchCommand->execute()); $insertedRowsCount = (new Query($db))->from('{{customer}}')->count(); @@ -482,9 +486,9 @@ static function () { } )(); $command = $db->createCommand(); - $command->insertBatch('{{customer}}', $rows, ['email', 'name', 'address']); + $batchCommand = $command->insertBatch('{{customer}}', $rows, ['email', 'name', 'address']); - $this->assertSame(1, $command->execute()); + $this->assertSame(1, $batchCommand->execute()); $db->close(); } @@ -1118,6 +1122,7 @@ public function testExecute(): void $this->expectExceptionMessage($message); $command->execute(); + $db->close(); } /** @@ -1489,6 +1494,7 @@ public function testInsertSelectFailed(array|ExpressionInterface|string $invalid $this->expectExceptionMessage('Expected select query object with enumerated (named) parameters'); $command->insert('{{customer}}', $query)->execute(); + $db->close(); } /** @@ -1543,6 +1549,7 @@ public function testIntegrityViolation(): void ); $command->execute(); $command->execute(); + $db->close(); } /** @@ -1635,6 +1642,7 @@ public function testQuery(): void $this->expectException(Exception::class); $command->query(); + $db->close(); } /** @@ -2064,6 +2072,7 @@ protected function internalExecute(): void }; $command->prepare(); + $db->close(); } /** @@ -2118,6 +2127,7 @@ public function testDecimalValue(): void $phpTypecastValue = $column->phpTypecast($result['total']); $this->assertSame($decimalValue, $phpTypecastValue); + $db->close(); } public function testInsertWithReturningPksEmptyValues() @@ -2132,6 +2142,7 @@ public function testInsertWithReturningPksEmptyValues() }; $this->assertSame($expected, $pkValues); + $db->close(); } public function testInsertWithReturningPksEmptyValuesAndNoPk() @@ -2141,6 +2152,7 @@ public function testInsertWithReturningPksEmptyValuesAndNoPk() $pkValues = $db->createCommand()->insertWithReturningPks('negative_default_values', []); $this->assertSame([], $pkValues); + $db->close(); } public function testUuid(): void @@ -2231,5 +2243,6 @@ public function testJsonTable(): void $value = (new Query($db))->select('json_col')->from('json_table')->where(['id' => 1])->scalar(); $this->assertSame('{"a":1,"b":2}', str_replace(' ', '', $value)); + $db->close(); } } diff --git a/tests/Db/Command/CommandTest.php b/tests/Db/Command/CommandTest.php index 62cbfae36..bcd0c44eb 100644 --- a/tests/Db/Command/CommandTest.php +++ b/tests/Db/Command/CommandTest.php @@ -42,6 +42,7 @@ public function testAddCheck(): void ), $sql, ); + $db->close(); } /** @dataProvider \Yiisoft\Db\Tests\Provider\CommandProvider::columnTypes */ @@ -63,6 +64,7 @@ public function testAddColumn(ColumnInterface|string $type): void ), $sql, ); + $db->close(); } public function testAddCommentOnColumn(): void @@ -81,6 +83,7 @@ public function testAddCommentOnColumn(): void ), $sql, ); + $db->close(); } public function testAddCommentOnTable(): void @@ -99,6 +102,7 @@ public function testAddCommentOnTable(): void ), $sql, ); + $db->close(); } public function testAddDefaultValue(): void @@ -113,6 +117,7 @@ public function testAddDefaultValue(): void ); $command->addDefaultValue('table', 'name', 'column', 'value'); + $db->close(); } /** @@ -135,6 +140,7 @@ public function testAddForeignKeySql( $sql = $command->addForeignKey($tableName, $name, $columns, $referenceTable, $referenceColumns, $delete, $update)->getSql(); $this->assertSame($expected, $sql); + $db->close(); } /** @@ -149,6 +155,7 @@ public function testAddPrimaryKeySql(string $name, string $tableName, array|stri $this->assertSame($expected, $sql); + $db->close(); } /** @@ -162,6 +169,7 @@ public function testAddUniqueSql(string $name, string $tableName, array|string $ $sql = $command->addUnique($tableName, $name, $column)->getSql(); $this->assertSame($expected, $sql); + $db->close(); } public function testAlterColumn(): void @@ -180,6 +188,7 @@ public function testAlterColumn(): void ), $sql, ); + $db->close(); } public function testBatchInsert(): void @@ -187,9 +196,13 @@ public function testBatchInsert(): void $db = $this->getConnection(); $command = $db->createCommand(); - $command->insertBatch('table', [['value1', 'value2'], ['value3', 'value4']], ['column1', 'column2']); + $batchCommand = $command->insertBatch('table', [['value1', 'value2'], ['value3', 'value4']], ['column1', 'column2']); - $this->assertSame('INSERT INTO [table] ([column1], [column2]) VALUES (:qp0, :qp1), (:qp2, :qp3)', $command->getSql()); + $this->assertSame(1, $batchCommand->count()); + $commands = $batchCommand->getCommands(); + + $firstCommand = $commands[0]; + $this->assertSame('INSERT INTO [table] ([column1], [column2]) VALUES (:qp0, :qp1), (:qp2, :qp3)', $firstCommand->getSql()); $this->assertSame( [ ':qp0' => 'value1', @@ -197,8 +210,10 @@ public function testBatchInsert(): void ':qp2' => 'value3', ':qp3' => 'value4', ], - $command->getParams() + $firstCommand->getParams() ); + + $db->close(); } /** @@ -219,6 +234,7 @@ public function testCreateIndexSql( $sql = $command->createIndex($table, $name, $column, $indexType, $indexMethod)->getSql(); $this->assertSame($expected, $sql); + $db->close(); } public function testCheckIntegrity(): void @@ -233,6 +249,7 @@ public function testCheckIntegrity(): void ); $command->checkIntegrity('schema', 'table')->execute(); + $db->close(); } public function testCreateTable(): void @@ -269,6 +286,7 @@ public function testCreateTable(): void $sql = $command->createTable('test_table', $columns, $options)->getSql(); Assert::equalsWithoutLE($expected, $sql); + $db->close(); } public function testCreateView(): void @@ -293,6 +311,7 @@ public function testCreateView(): void ), $sql, ); + $db->close(); } public function testDelete(): void @@ -311,6 +330,7 @@ public function testDelete(): void ), $sql, ); + $db->close(); } public function testDropCheck(): void @@ -329,6 +349,7 @@ public function testDropCheck(): void ), $sql, ); + $db->close(); } public function testDropColumn(): void @@ -347,6 +368,7 @@ public function testDropColumn(): void ), $sql, ); + $db->close(); } public function testDropCommentFromColumn(): void @@ -365,6 +387,7 @@ public function testDropCommentFromColumn(): void ), $sql, ); + $db->close(); } public function testDropCommentFromTable(): void @@ -383,6 +406,7 @@ public function testDropCommentFromTable(): void ), $sql, ); + $db->close(); } public function testDropDefaultValue(): void @@ -397,6 +421,7 @@ public function testDropDefaultValue(): void ); $command->dropDefaultValue('table', 'column'); + $db->close(); } public function testDropForeingKey(): void @@ -415,6 +440,7 @@ public function testDropForeingKey(): void ), $sql, ); + $db->close(); } public function testDropIndex(): void @@ -433,6 +459,7 @@ public function testDropIndex(): void ), $sql, ); + $db->close(); } public function testDropPrimaryKey(): void @@ -451,6 +478,7 @@ public function testDropPrimaryKey(): void ), $sql, ); + $db->close(); } public function testDropView(): void @@ -469,6 +497,7 @@ public function testDropView(): void ), $sql, ); + $db->close(); } #[DataProviderExternal(CommandProvider::class, 'dropTable')] @@ -490,6 +519,7 @@ public function testDropTable(string $expected, ?bool $ifExists, ?bool $cascade) $expectedSql = DbHelper::replaceQuotes($expected, $db->getDriverName()); $this->assertSame($expectedSql, $command->getSql()); + $db->close(); } public function testDropUnique(): void @@ -508,6 +538,7 @@ public function testDropUnique(): void ), $sql, ); + $db->close(); } public function testExecute(): void @@ -522,6 +553,7 @@ public function testExecute(): void ); $command->createTable('customer', ['id' => 'pk'])->execute(); + $db->close(); } public function testInsert(): void @@ -543,6 +575,7 @@ public function testInsert(): void ], $command->getParams(), ); + $db->close(); } public function testQuery(): void @@ -562,6 +595,7 @@ public function testQuery(): void ); $command->query(); + $db->close(); } public function testQueryAll(): void @@ -581,6 +615,7 @@ public function testQueryAll(): void ); $command->queryAll(); + $db->close(); } public function testQueryColumn(): void @@ -600,6 +635,7 @@ public function testQueryColumn(): void ); $command->queryColumn(); + $db->close(); } public function testQueryOne(): void @@ -617,6 +653,7 @@ public function testQueryOne(): void ); $command->setSql($sql)->queryOne(); + $db->close(); } public function testQueryScalar(): void @@ -634,6 +671,7 @@ public function testQueryScalar(): void ); $this->assertEquals(1, $command->setSql($sql)->queryScalar()); + $db->close(); } public function testRenameColumn(): void @@ -651,6 +689,7 @@ public function testRenameColumn(): void ), $sql, ); + $db->close(); } public function testRenameTable(): void @@ -668,6 +707,7 @@ public function testRenameTable(): void ), $sql, ); + $db->close(); } public function testResetSequence(): void @@ -680,6 +720,7 @@ public function testResetSequence(): void ); $db->createCommand()->resetSequence('table', 5); + $db->close(); } public function testSetRetryHandler(): void @@ -691,6 +732,7 @@ public function testSetRetryHandler(): void $command->setRetryHandler($handler); $this->assertSame($handler, Assert::getInaccessibleProperty($command, 'retryHandler')); + $db->close(); } public function testTruncateTable(): void @@ -709,6 +751,7 @@ public function testTruncateTable(): void ), $sql, ); + $db->close(); } public function testUpdate(): void @@ -720,6 +763,7 @@ public function testUpdate(): void $this->assertSame('UPDATE [table] SET [name]=:qp0 WHERE [id]=:qp1', $command->getSql()); $this->assertSame([':qp0' => 'John', ':qp1' => 1], $command->getParams()); + $db->close(); } public function testUpsert(): void @@ -734,6 +778,7 @@ public function testUpsert(): void ); $command->upsert('{{table}}', []); + $db->close(); } public function testProfiler(?string $sql = null): void diff --git a/tests/Db/Connection/ConnectionTest.php b/tests/Db/Connection/ConnectionTest.php index 6a3599292..5f9d07e93 100644 --- a/tests/Db/Connection/ConnectionTest.php +++ b/tests/Db/Connection/ConnectionTest.php @@ -22,6 +22,7 @@ public function testGetTableSchema(): void $db = $this->getConnection(); $this->assertNull($db->getTableSchema('non_existing_table')); + $db->close(); } public function testSerialized(): void @@ -33,4 +34,9 @@ public function testSerialized(): void parent::testSerialized(); } + + public function testGetParametersLimit(): void + { + $this->assertSame(0, $this->getConnection()->getParametersLimit()); + } } diff --git a/tests/Db/Query/QueryTest.php b/tests/Db/Query/QueryTest.php index ca85c071f..0595e68f3 100644 --- a/tests/Db/Query/QueryTest.php +++ b/tests/Db/Query/QueryTest.php @@ -37,6 +37,7 @@ public function testColumn(): void ); (new Query($db))->select('name')->from('customer')->orderBy(['id' => SORT_DESC])->column(); + $db->close(); } /** @@ -54,6 +55,7 @@ public function testCount(): void ); (new Query($db))->from('customer')->count(); + $db->close(); } public function testExists(): void @@ -66,6 +68,7 @@ public function testExists(): void ); (new Query($db))->from('customer')->where(['status' => 2])->exists(); + $db->close(); } /** @@ -86,6 +89,7 @@ public function testLimitOffsetWithExpression(): void ); $query->column(); + $db->close(); } /** @@ -103,6 +107,7 @@ public function testOne(): void ); (new Query($db))->from('customer')->where(['status' => 2])->one(); + $db->close(); } public function testColumnWithIndexBy(): void diff --git a/tests/Db/QueryBuilder/QueryBuilderTest.php b/tests/Db/QueryBuilder/QueryBuilderTest.php index 8ace1896e..7e5a7607b 100644 --- a/tests/Db/QueryBuilder/QueryBuilderTest.php +++ b/tests/Db/QueryBuilder/QueryBuilderTest.php @@ -47,6 +47,7 @@ public function testAddDefaultValue(): void ); $qb->addDefaultValue('table', 'name', 'column', 'value'); + $db->close(); } /** @@ -61,12 +62,21 @@ public function testBatchInsert( ): void { $db = $this->getConnection(); $qb = new QueryBuilder($db); - $params = []; try { - $this->assertSame($expected, $qb->insertBatch($table, $rows, $columns, $params)); - $this->assertSame($expectedParams, $params); + $statements = $qb->insertBatch($table, $rows, $columns); + + if (empty($expected)) { + $this->assertCount(0, $statements); + } else { + $this->assertSame($expected, $statements[0]->sql); + } + if (!empty($statements)) { + $this->assertSame($expectedParams, $statements[0]->params); + } } catch (InvalidArgumentException|Exception) { + } finally { + $db->close(); } } @@ -82,6 +92,7 @@ public function testBuildJoinException(): void $qb = $db->getQueryBuilder(); $params = []; $qb->buildJoin(['admin_profile', 'admin_user.id = admin_profile.user_id'], $params); + $db->close(); } /** @@ -98,6 +109,7 @@ public function testCheckIntegrity(): void $qb = $db->getQueryBuilder(); $qb->checkIntegrity('schema', 'table'); + $db->close(); } public function testCreateTable(): void @@ -132,6 +144,7 @@ public function testCreateTable(): void ], ), ); + $db->close(); } /** @@ -151,6 +164,7 @@ public function testCreateView(): void SQL, $qb->createView('testCreateView', $subQuery) ); + $db->close(); } /** @@ -168,6 +182,7 @@ public function testDropDefaultValue(): void ); $qb->dropDefaultValue('T_constraints_1', 'CN_pk'); + $db->close(); } /** @@ -183,6 +198,7 @@ public function testGetExpressionBuilderException(): void }; $qb = $db->getQueryBuilder(); $qb->getExpressionBuilder($expression); + $db->close(); } /** @@ -202,6 +218,7 @@ public function testInsert( $this->assertSame($expectedSQL, $qb->insert($table, $columns, $params)); $this->assertEquals($expectedParams, $params); + $db->close(); } /** @@ -224,6 +241,7 @@ public function testInsertWithReturningPks( ); $qb->insertWithReturningPks($table, $columns, $params); + $db->close(); } /** @@ -241,6 +259,7 @@ public function testResetSequence(): void ); $qb->resetSequence('T_constraints_1', 'id'); + $db->close(); } /** @@ -264,6 +283,7 @@ public function testUpdate( $this->assertSame($expectedSql, $sql); $this->assertEquals($expectedParams, $params); + $db->close(); } /** @@ -290,6 +310,7 @@ public function testUpsert( ); $db->getQueryBuilder()->upsert($table, $insertColumns, $updateColumns, $actualParams); + $db->close(); } /** @@ -309,6 +330,7 @@ public function testUpsertExecute( $actualParams = []; $actualSQL = $db->getQueryBuilder()->upsert($table, $insertColumns, $updateColumns, $actualParams); + $db->close(); } public function testPrepareValueClosedResource(): void @@ -322,6 +344,7 @@ public function testPrepareValueClosedResource(): void fclose($resource); $qb->prepareValue($resource); + $db->close(); } public function testPrepareValueNonStreamResource(): void @@ -332,6 +355,7 @@ public function testPrepareValueNonStreamResource(): void $this->expectExceptionObject(new InvalidArgumentException('Supported only stream resource type.')); $qb->prepareValue(stream_context_create()); + $db->close(); } public function testGetServerInfo(): void @@ -340,6 +364,7 @@ public function testGetServerInfo(): void $qb = $db->getQueryBuilder(); $this->assertInstanceOf(ServerInfoInterface::class, $qb->getServerInfo()); + $db->close(); } public function testJsonColumn(): void @@ -371,5 +396,6 @@ public function testJsonColumn(): void ), $qb->alterColumn('json_table', 'json_col', $column), ); + $db->close(); } } diff --git a/tests/Db/Schema/SchemaTest.php b/tests/Db/Schema/SchemaTest.php index 60cd54cb0..6d2f05cd6 100644 --- a/tests/Db/Schema/SchemaTest.php +++ b/tests/Db/Schema/SchemaTest.php @@ -42,6 +42,7 @@ public function testFindTableNames(): void $this->expectExceptionMessage('Yiisoft\Db\Tests\Support\Stub\Schema does not support fetching all table names.'); Assert::invokeMethod($schema, 'findTableNames', ['dbo']); + $db->close(); } /** @@ -54,6 +55,7 @@ public function testFindViewNames(): void $schema = $db->getSchema(); $this->assertSame([], Assert::invokeMethod($schema, 'findViewNames', ['dbo'])); + $db->close(); } /** @@ -83,6 +85,7 @@ public function testGetSchemaChecks(): void $this->assertIsArray($checks); $this->assertContainsOnlyInstancesOf(CheckConstraint::class, $checks); } + $db->close(); } /** @@ -112,6 +115,7 @@ public function testGetSchemaDefaultValues(): void $this->assertIsArray($defaultValues); $this->assertContainsOnlyInstancesOf(DefaultValueConstraint::class, $defaultValues); } + $db->close(); } /** @@ -142,6 +146,7 @@ public function testGetSchemaForeignKeys(): void $this->assertIsArray($foreignKeys); $this->assertContainsOnlyInstancesOf(ForeignKeyConstraint::class, $foreignKeys); } + $db->close(); } /** @@ -172,6 +177,7 @@ public function testGetSchemaIndexes(): void $this->assertIsArray($indexes); $this->assertContainsOnlyInstancesOf(IndexConstraint::class, $indexes); } + $db->close(); } public function testGetSchemaNames(): void @@ -186,6 +192,7 @@ public function testGetSchemaNames(): void ); $schema->getSchemaNames(); + $db->close(); } /** @@ -200,6 +207,7 @@ public function testGetSchemaNamesWithSchema(): void Assert::setInaccessibleProperty($schema, 'schemaNames', ['dbo', 'public']); $this->assertSame(['dbo', 'public'], $schema->getSchemaNames()); + $db->close(); } public function testHasSchema(): void @@ -234,6 +242,7 @@ public function testGetSchemaPrimaryKeys(): void $this->assertIsArray($tablePks); $this->assertContainsOnlyInstancesOf(Constraint::class, $tablePks); + $db->close(); } /** @@ -258,6 +267,7 @@ public function testGetSchemaUniques(): void $this->assertIsArray($uniques); $this->assertContainsOnlyInstancesOf(Constraint::class, $uniques); } + $db->close(); } public function getTableSchema(): void @@ -278,6 +288,7 @@ public function getTableSchema(): void $this->assertSame('T_constraints_1', $table->getFullName()); $this->assertSame(['C_id'], $table->getPrimaryKey()); $this->assertSame(['C_id', 'C_not_null', 'C_check', 'C_default', 'C_unique'], $table->getColumnNames()); + $db->close(); } /** @@ -300,6 +311,7 @@ public function testGetTableSchemas(): void foreach ($tables as $table) { $this->assertInstanceOf(TableSchemaInterface::class, $table); } + $db->close(); } public function testGetViewNames(): void @@ -309,6 +321,7 @@ public function testGetViewNames(): void $schema = $db->getSchema(); $this->assertSame([], $schema->getViewNames()); + $db->close(); } public function testRefreshTableSchema(): void @@ -331,6 +344,7 @@ public function testRefreshTableSchema(): void $refreshedTable = $schemaMock->getTableSchema('T_constraints_1'); $this->assertNotSame($noCacheTable, $refreshedTable); + $db->close(); } public function testRefreshTableSchemaWithSchemaCaseDisabled(): void @@ -353,6 +367,7 @@ public function testRefreshTableSchemaWithSchemaCaseDisabled(): void $refreshedTable = $schemaMock->getTableSchema('T_constraints_1'); $this->assertNotSame($noCacheTable, $refreshedTable); + $db->close(); } /** @@ -368,6 +383,7 @@ public function testResolveTableName(): void $this->expectExceptionMessage('Yiisoft\Db\Tests\Support\Stub\Schema does not support resolving table names.'); Assert::invokeMethod($schema, 'resolveTableName', ['customer']); + $db->close(); } /** @@ -388,6 +404,7 @@ public function testSetTableMetadata(): void Assert::invokeMethod($schema, 'setTableMetadata', ['T_constraints_1', 'checks', $checkConstraint]); $this->assertSame($checkConstraint, $schema->getTableChecks('T_constraints_1')); + $db->close(); } private function createTableSchemaStub(): TableSchemaInterface