Skip to content

Reduce binding parameters #412

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

Merged
merged 7 commits into from
Jun 9, 2025
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
- New #397: Realize `Schema::loadResultColumn()` method (@Tigrov)
- New #407: Use `DateTimeColumn` class for datetime column types (@Tigrov)
- New #408, #410: Implement `DMLQueryBuilder::upsertReturning()` method (@Tigrov)
- Enh #412: Reduce binding parameters (@Tigrov)

## 1.3.0 March 21, 2024

Expand Down
22 changes: 9 additions & 13 deletions src/Builder/ArrayExpressionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ private function buildNestedSubquery(QueryInterface $query, string $dbType, int
private function buildNestedValue(iterable $value, string $dbType, ColumnInterface|null $column, int $dimension, array &$params): string
{
$placeholders = [];
$queryBuilder = $this->queryBuilder;
$isTypecastingEnabled = $column !== null && $queryBuilder->isTypecastingEnabled();

if ($dimension > 1) {
/** @var iterable|null $item */
Expand All @@ -93,20 +95,18 @@ private function buildNestedValue(iterable $value, string $dbType, ColumnInterfa
} elseif ($item instanceof ExpressionInterface) {
$placeholders[] = $item instanceof QueryInterface
? $this->buildNestedSubquery($item, $dbType, $dimension - 1, $params)
: $this->queryBuilder->buildExpression($item, $params);
: $queryBuilder->buildExpression($item, $params);
} else {
$placeholders[] = $this->buildNestedValue($item, $dbType, $column, $dimension - 1, $params);
}
}
} else {
$value = $this->dbTypecast($value, $column);
if ($isTypecastingEnabled) {
$value = $this->dbTypecast($value, $column);
}

foreach ($value as $item) {
if ($item instanceof ExpressionInterface) {
$placeholders[] = $this->queryBuilder->buildExpression($item, $params);
} else {
$placeholders[] = $this->queryBuilder->bindParam($item, $params);
}
$placeholders[] = $queryBuilder->buildValue($item, $params);
}
}

Expand Down Expand Up @@ -170,16 +170,12 @@ private function getTypeHint(string $dbType, int $dimension): string
* Converts array values for use in a db query.
*
* @param iterable $value The array or iterable object.
* @param ColumnInterface|null $column The column instance to typecast values.
* @param ColumnInterface $column The column instance to typecast values.
*
* @return iterable Converted values.
*/
private function dbTypecast(iterable $value, ColumnInterface|null $column): iterable
private function dbTypecast(iterable $value, ColumnInterface $column): iterable
{
if ($column === null) {
return $value;
}

if (!is_array($value)) {
$value = iterator_to_array($value, false);
}
Expand Down
12 changes: 5 additions & 7 deletions src/Builder/StructuredExpressionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Exception\NotSupportedException;
use Yiisoft\Db\Expression\AbstractStructuredExpressionBuilder;
use Yiisoft\Db\Expression\ExpressionInterface;
use Yiisoft\Db\Expression\StructuredExpression;
use Yiisoft\Db\Pgsql\Data\StructuredLazyArray;
use Yiisoft\Db\Query\QueryInterface;
Expand Down Expand Up @@ -72,7 +71,10 @@ protected function getLazyArrayValue(LazyArrayInterface $value): array|string
private function buildPlaceholders(array $value, StructuredExpression $expression, array &$params): array
{
$type = $expression->getType();
$columns = $type instanceof AbstractStructuredColumn ? $type->getColumns() : [];
$queryBuilder = $this->queryBuilder;
$columns = $type instanceof AbstractStructuredColumn && $queryBuilder->isTypecastingEnabled()
? $type->getColumns()
: [];

$placeholders = [];

Expand All @@ -82,11 +84,7 @@ private function buildPlaceholders(array $value, StructuredExpression $expressio
$item = $columns[$columnName]->dbTypecast($item);
}

if ($item instanceof ExpressionInterface) {
$placeholders[] = $this->queryBuilder->buildExpression($item, $params);
} else {
$placeholders[] = $this->queryBuilder->bindParam($item, $params);
}
$placeholders[] = $queryBuilder->buildValue($item, $params);
}

return $placeholders;
Expand Down
79 changes: 39 additions & 40 deletions tests/ArrayExpressionBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use Yiisoft\Db\Schema\Column\ColumnInterface;
use Yiisoft\Db\Schema\Data\JsonLazyArray;
use Yiisoft\Db\Schema\Data\LazyArrayInterface;
use Yiisoft\Db\Tests\Support\Assert;

/**
* @group pgsql
Expand All @@ -34,41 +35,45 @@ final class ArrayExpressionBuilderTest extends TestCase
public static function buildProvider(): array
{
return [
[null, null, 'NULL', []],
[[], null, 'ARRAY[]', []],
[[1, 2, 3], null, 'ARRAY[:qp0,:qp1,:qp2]', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]],
[
'null' => [null, null, 'NULL', []],
'empty' => [[], null, 'ARRAY[]', []],
'list' => [[1, 2, 3], null, 'ARRAY[1,2,3]', []],
'ArrayIterator' => [
new ArrayIterator(['a', 'b', 'c']),
'varchar',
'ARRAY[:qp0,:qp1,:qp2]::varchar[]',
[':qp0' => 'a', ':qp1' => 'b', ':qp2' => 'c'],
[
':qp0' => new Param('a', DataType::STRING),
':qp1' => new Param('b', DataType::STRING),
':qp2' => new Param('c', DataType::STRING),
],
],
[
'LazyArray' => [
new LazyArray('{1,2,3}'),
'int[]',
':qp0::int[]',
[':qp0' => new Param('{1,2,3}', DataType::STRING)],
],
[
'LazyArray external' => [
new \Yiisoft\Db\Schema\Data\LazyArray('[1,2,3]'),
ColumnBuilder::integer(),
'ARRAY[:qp0,:qp1,:qp2]::integer[]',
[':qp0' => 1, ':qp1' => 2, ':qp2' => 3],
'ARRAY[1,2,3]::integer[]',
[],
],
[
'StructuredLazyArray' => [
new StructuredLazyArray('(1,2,3)'),
'int',
'ARRAY[:qp0,:qp1,:qp2]::int[]',
[':qp0' => 1, ':qp1' => 2, ':qp2' => 3],
'ARRAY[1,2,3]::int[]',
[],
],
[
'JsonLazyArray' => [
new JsonLazyArray('[1,2,3]'),
ColumnBuilder::array(ColumnBuilder::integer()),
'ARRAY[:qp0,:qp1,:qp2]::integer[]',
[':qp0' => 1, ':qp1' => 2, ':qp2' => 3],
'ARRAY[1,2,3]::integer[]',
[],
],
[[new Expression('now()')], null, 'ARRAY[now()]', []],
[
'Expression' => [[new Expression('now()')], null, 'ARRAY[now()]', []],
'JsonExpression w/o type' => [
[new JsonExpression(['a' => null, 'b' => 123, 'c' => [4, 5]]), new JsonExpression([true])],
null,
'ARRAY[:qp0,:qp1]',
Expand All @@ -77,7 +82,7 @@ public static function buildProvider(): array
':qp1' => new Param('[true]', DataType::STRING),
],
],
[
'JsonExpression' => [
[new JsonExpression(['a' => null, 'b' => 123, 'c' => [4, 5]]), new JsonExpression([true])],
'jsonb',
'ARRAY[:qp0,:qp1]::jsonb[]',
Expand All @@ -86,57 +91,51 @@ public static function buildProvider(): array
':qp1' => new Param('[true]', DataType::STRING),
],
],
[
'StructuredExpression' => [
[
null,
new StructuredExpression(['value' => 11.11, 'currency_code' => 'USD']),
new StructuredExpression(['value' => null, 'currency_code' => null]),
],
null,
'ARRAY[:qp0,ROW(:qp1,:qp2),ROW(:qp3,:qp4)]',
[':qp0' => null, ':qp1' => 11.11, ':qp2' => 'USD', ':qp3' => null, ':qp4' => null],
'ARRAY[NULL,ROW(11.11,:qp0),ROW(NULL,NULL)]',
[':qp0' => new Param('USD', DataType::STRING)],
],
[
'Query w/o type' => [
(new Query(self::getDb()))->select('id')->from('users')->where(['active' => 1]),
null,
'ARRAY(SELECT "id" FROM "users" WHERE "active"=:qp0)',
[':qp0' => 1],
],
[
'Query' => [
[(new Query(self::getDb()))->select('id')->from('users')->where(['active' => 1])],
'integer[][]',
'ARRAY[ARRAY(SELECT "id" FROM "users" WHERE "active"=:qp0)::integer[]]::integer[][]',
[':qp0' => 1],
],
[
'bool' => [
[[[true], [false, null]], [['t', 'f'], null], null],
'bool[][][]',
'ARRAY[ARRAY[ARRAY[:qp0]::bool[],ARRAY[:qp1,:qp2]::bool[]]::bool[][],ARRAY[ARRAY[:qp3,:qp4]::bool[],NULL]::bool[][],NULL]::bool[][][]',
[
':qp0' => true,
':qp1' => false,
':qp2' => null,
':qp3' => 't',
':qp4' => 'f',
],
'ARRAY[ARRAY[ARRAY[TRUE]::bool[],ARRAY[FALSE,NULL]::bool[]]::bool[][],ARRAY[ARRAY[TRUE,TRUE]::bool[],NULL]::bool[][],NULL]::bool[][][]',
[],
],
[
'associative' => [
['a' => '1', 'b' => null],
ColumnType::STRING,
'ARRAY[:qp0,:qp1]::varchar(255)[]',
[':qp0' => '1', ':qp1' => null],
'ARRAY[:qp0,NULL]::varchar(255)[]',
[':qp0' => new Param('1', DataType::STRING)],
],
[
'string' => [
'{1,2,3}',
'string[]',
':qp0::varchar(255)[]',
[':qp0' => new Param('{1,2,3}', DataType::STRING)],
],
[
'null multi-level' => [
[[1, null], null],
'int[][]',
'ARRAY[ARRAY[:qp0,:qp1]::int[],NULL]::int[][]',
[':qp0' => '1', ':qp1' => null],
'ARRAY[ARRAY[1,NULL]::int[],NULL]::int[][]',
[],
],
];
}
Expand All @@ -156,6 +155,6 @@ public function testBuild(
$expression = new ArrayExpression($value, $type);

$this->assertSame($expected, $builder->build($expression, $params));
$this->assertEquals($expectedParams, $params);
Assert::arraysEquals($expectedParams, $params);
}
}
12 changes: 1 addition & 11 deletions tests/ColumnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@
use DateTimeImmutable;
use DateTimeZone;
use PHPUnit\Framework\Attributes\DataProviderExternal;
use Throwable;
use Yiisoft\Db\Constant\ColumnType;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Expression\ArrayExpression;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Expression\JsonExpression;
Expand Down Expand Up @@ -38,8 +35,6 @@

/**
* @group pgsql
*
* @psalm-suppress PropertyNotSetInConstructor
*/
final class ColumnTest extends CommonColumnTest
{
Expand Down Expand Up @@ -91,7 +86,7 @@ private function assertTypecastedValues(array $result): void
$this->assertSame(['', 'some text', '""', '\\\\', '[",","null",true,"false","f"]', null], $result['varchararray_col']);
$this->assertNull($result['textarray2_col']);
$this->assertSame([['a' => 1, 'b' => null, 'c' => [1, 3, 5]]], $result['json_col']);
$this->assertSame(['1', '2', '3'], $result['jsonb_col']);
$this->assertSame([1, 2, 3], $result['jsonb_col']);
$this->assertSame([[[',', 'null', true, 'false', 'f']]], $result['jsonarray_col']);
}

Expand Down Expand Up @@ -193,11 +188,6 @@ public function testSelectWithPhpTypecasting(): void
$db->close();
}

/**
* @throws Exception
* @throws InvalidConfigException
* @throws Throwable
*/
public function testPhpTypeCast(): void
{
$db = $this->getConnection(true);
Expand Down
Loading