Skip to content

Commit

Permalink
优化数据库查询构建器:当 where 条件的值为 NULL 时,不使用参数绑定 (#670)
Browse files Browse the repository at this point in the history
* 优化数据库查询构建器:当 where 条件的值为 NULL 时,不使用参数绑定
原因:MySQL 和 PostgreSQL 都不支持 is NULL 的 NULL 使用参数绑定传值

* 优化根据值类型获取PDO数据类型
  • Loading branch information
Yurunsoft authored Jan 5, 2024
1 parent f28f988 commit 9fb44f3
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/Db/Drivers/TPdoStatement.php
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,14 @@ public function valid(): bool
*/
protected function getDataTypeByValue($value): int
{
if (\is_int($value))
{
return \PDO::PARAM_INT;
}
if (\is_string($value))
{
return \PDO::PARAM_STR;
}
if (null === $value)
{
return \PDO::PARAM_NULL;
Expand All @@ -327,10 +335,6 @@ protected function getDataTypeByValue($value): int
{
return \PDO::PARAM_BOOL;
}
if (\is_int($value))
{
return \PDO::PARAM_INT;
}
if (\is_resource($value))
{
return \PDO::PARAM_LOB;
Expand Down
4 changes: 4 additions & 0 deletions src/Db/Query/Where/Where.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ public function toStringWithoutLogic(IQuery $query): string
{
$result .= $thisValues->toString($query);
}
elseif (null === $thisValues)
{
$result .= 'NULL';
}
else
{
$value = $query->getAutoParamName();
Expand Down
7 changes: 7 additions & 0 deletions tests/unit/Component/Tests/Db/QueryCurdBaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -867,4 +867,11 @@ public function testFullTextSearch(): void
$this->assertEquals([':p1' => 'imi', ':p2' => 0], $query->getBinds());
$this->assertEquals(SearchModifier::WITH_QUERY_EXPANSION, $options->getSearchModifier());
}

public function testWhereNull(): void
{
$query = Db::query()->from('test')->where('a', 'is', null);
$this->assertEquals('select * from `test` where `a` is NULL', $query->buildSelectSql());
$this->assertEquals([], $query->getBinds());
}
}

0 comments on commit 9fb44f3

Please sign in to comment.