Skip to content

Commit

Permalink
fix(QueryBuilder): 参数传入 null 时生成 SQL 错误
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed Jan 31, 2023
1 parent 4cc7fed commit c902a97
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
22 changes: 15 additions & 7 deletions lib/Db/QueryBuilderTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -1056,7 +1056,11 @@ protected function where($column = null, $operator = null, $value = null): self
*/
protected function whereRaw($expression, $params = null): self
{
return $this->where($this->raw($expression), null, $params);
$args = [$this->raw($expression), null];
if (func_num_args() > 1) {
$args[] = $params;
}
return $this->addWhere(...$args);
}

/**
Expand Down Expand Up @@ -1590,7 +1594,8 @@ protected function addWhere(
string $condition = 'AND',
string $type = null
): self {
if ($column instanceof Closure) {
$isClosure = $column instanceof Closure;
if ($isClosure) {
/** @phpstan-ignore-next-line Allow new static */
$query = new static([
'wei' => $this->wei,
Expand All @@ -1602,15 +1607,18 @@ protected function addWhere(
$this->addQueryParams($query->getQueryParams());
}

if (null === $value) {
$operator = 'NOT NULL' === $operator ? $operator : 'NULL';
} elseif (is_array($value) && !in_array($operator, ['BETWEEN', 'NOT BETWEEN'], true)) {
if (is_array($value) && !in_array($operator, ['BETWEEN', 'NOT BETWEEN'], true)) {
$operator = 'NOT IN' === $operator ? $operator : 'IN';
}

$this->addQueryPart('where', compact('column', 'operator', 'value', 'condition', 'type'), true);
if (null !== $value) {
$this->addQueryParam($value);

// Ignore params when
// 1. query is closure
// 2. operator is NULL or NOT NULL
// 3. params are not passed
if (!$isClosure && !in_array($operator, ['NULL', 'NOT NULL'], true) && func_num_args() > 2) {
$this->addQueryParam(null === $value ? [null] : $value);
}

return $this;
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,24 @@ public function testWhereNot()
$this->assertEquals('test', $qb->fetch()['name']);
}

public function testWhereNotNullValue()
{
$this->initFixtures();

$qb = Qb::table('test_users')->whereNot('id', null);
$this->assertEquals('SELECT * FROM `p_test_users` WHERE `id` != NULL', $qb->getRawSql());
$this->assertNull($qb->fetch());
}

public function testWhereGtNullValue()
{
$this->initFixtures();

$qb = Qb::table('test_users')->where('id', '>', null);
$this->assertEquals('SELECT * FROM `p_test_users` WHERE `id` > NULL', $qb->getRawSql());
$this->assertNull($qb->fetch());
}

public function testOrWhere()
{
$sql = Qb::table('test_users')
Expand Down

0 comments on commit c902a97

Please sign in to comment.