Skip to content

Commit

Permalink
Support whereJsonLength() on SQLite
Browse files Browse the repository at this point in the history
  • Loading branch information
staudenmeir committed Aug 26, 2018
1 parent 3a31c1a commit f149fbd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
15 changes: 15 additions & 0 deletions src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,21 @@ protected function dateBasedWhere($type, Builder $query, $where)
return "strftime('{$type}', {$this->wrap($where['column'])}) {$where['operator']} cast({$value} as text)";
}

/**
* Compile a "JSON length" statement into SQL.
*
* @param string $column
* @param string $operator
* @param string $value
* @return string
*/
protected function compileJsonLength($column, $operator, $value)
{
list($field, $path) = $this->wrapJsonFieldAndPath($column);

return 'json_array_length('.$field.$path.') '.$operator.' '.$value;
}

/**
* Compile an insert statement into SQL.
*
Expand Down
22 changes: 18 additions & 4 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2837,13 +2837,27 @@ public function testWhereJsonLengthPostgres()
$this->assertEquals([1], $builder->getBindings());
}

/**
* @expectedException \RuntimeException
*/
public function testWhereJsonLengthSqlite()
{
$builder = $this->getSQLiteBuilder();
$builder->select('*')->from('users')->whereJsonLength('options', 0)->toSql();
$builder->select('*')->from('users')->whereJsonLength('options', 0);
$this->assertEquals('select * from "users" where json_array_length("options") = ?', $builder->toSql());
$this->assertEquals([0], $builder->getBindings());

$builder = $this->getSQLiteBuilder();
$builder->select('*')->from('users')->whereJsonLength('users.options->languages', '>', 0);
$this->assertEquals('select * from "users" where json_array_length("users"."options", \'$."languages"\') > ?', $builder->toSql());
$this->assertEquals([0], $builder->getBindings());

$builder = $this->getSQLiteBuilder();
$builder->select('*')->from('users')->where('id', '=', 1)->orWhereJsonLength('options->languages', new Raw('0'));
$this->assertEquals('select * from "users" where "id" = ? or json_array_length("options", \'$."languages"\') = 0', $builder->toSql());
$this->assertEquals([1], $builder->getBindings());

$builder = $this->getSQLiteBuilder();
$builder->select('*')->from('users')->where('id', '=', 1)->orWhereJsonLength('options->languages', '>', new Raw('0'));
$this->assertEquals('select * from "users" where "id" = ? or json_array_length("options", \'$."languages"\') > 0', $builder->toSql());
$this->assertEquals([1], $builder->getBindings());
}

public function testWhereJsonLengthSqlServer()
Expand Down

0 comments on commit f149fbd

Please sign in to comment.