This commit is contained in:
2024-11-05 12:10:06 +08:00
commit 6b687feee2
3995 changed files with 418583 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+381
View File
@@ -0,0 +1,381 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Str;
class MySqlGrammar extends Grammar
{
/**
* The grammar specific operators.
*
* @var string[]
*/
protected $operators = ['sounds like'];
/**
* Add a "where null" clause to the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereNull(Builder $query, $where)
{
if ($this->isJsonSelector($where['column'])) {
[$field, $path] = $this->wrapJsonFieldAndPath($where['column']);
return '(json_extract('.$field.$path.') is null OR json_type(json_extract('.$field.$path.')) = \'NULL\')';
}
return parent::whereNull($query, $where);
}
/**
* Add a "where not null" clause to the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereNotNull(Builder $query, $where)
{
if ($this->isJsonSelector($where['column'])) {
[$field, $path] = $this->wrapJsonFieldAndPath($where['column']);
return '(json_extract('.$field.$path.') is not null AND json_type(json_extract('.$field.$path.')) != \'NULL\')';
}
return parent::whereNotNull($query, $where);
}
/**
* Compile a "where fulltext" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
public function whereFullText(Builder $query, $where)
{
$columns = $this->columnize($where['columns']);
$value = $this->parameter($where['value']);
$mode = ($where['options']['mode'] ?? []) === 'boolean'
? ' in boolean mode'
: ' in natural language mode';
$expanded = ($where['options']['expanded'] ?? []) && ($where['options']['mode'] ?? []) !== 'boolean'
? ' with query expansion'
: '';
return "match ({$columns}) against (".$value."{$mode}{$expanded})";
}
/**
* Compile the index hints for the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param \Illuminate\Database\Query\IndexHint $indexHint
* @return string
*/
protected function compileIndexHint(Builder $query, $indexHint)
{
return match ($indexHint->type) {
'hint' => "use index ({$indexHint->index})",
'force' => "force index ({$indexHint->index})",
default => "ignore index ({$indexHint->index})",
};
}
/**
* Compile an insert ignore statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
public function compileInsertOrIgnore(Builder $query, array $values)
{
return Str::replaceFirst('insert', 'insert ignore', $this->compileInsert($query, $values));
}
/**
* Compile a "JSON contains" statement into SQL.
*
* @param string $column
* @param string $value
* @return string
*/
protected function compileJsonContains($column, $value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return 'json_contains('.$field.', '.$value.$path.')';
}
/**
* Compile a "JSON contains key" statement into SQL.
*
* @param string $column
* @return string
*/
protected function compileJsonContainsKey($column)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return 'ifnull(json_contains_path('.$field.', \'one\''.$path.'), 0)';
}
/**
* Compile a "JSON length" statement into SQL.
*
* @param string $column
* @param string $operator
* @param string $value
* @return string
*/
protected function compileJsonLength($column, $operator, $value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return 'json_length('.$field.$path.') '.$operator.' '.$value;
}
/**
* Compile a "JSON value cast" statement into SQL.
*
* @param string $value
* @return string
*/
public function compileJsonValueCast($value)
{
return 'cast('.$value.' as json)';
}
/**
* Compile the random statement into SQL.
*
* @param string|int $seed
* @return string
*/
public function compileRandom($seed)
{
return 'RAND('.$seed.')';
}
/**
* Compile the lock into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param bool|string $value
* @return string
*/
protected function compileLock(Builder $query, $value)
{
if (! is_string($value)) {
return $value ? 'for update' : 'lock in share mode';
}
return $value;
}
/**
* Compile an insert statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
public function compileInsert(Builder $query, array $values)
{
if (empty($values)) {
$values = [[]];
}
return parent::compileInsert($query, $values);
}
/**
* Compile the columns for an update statement.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
protected function compileUpdateColumns(Builder $query, array $values)
{
return collect($values)->map(function ($value, $key) {
if ($this->isJsonSelector($key)) {
return $this->compileJsonUpdateColumn($key, $value);
}
return $this->wrap($key).' = '.$this->parameter($value);
})->implode(', ');
}
/**
* Compile an "upsert" statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param array $uniqueBy
* @param array $update
* @return string
*/
public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update)
{
$useUpsertAlias = $query->connection->getConfig('use_upsert_alias');
$sql = $this->compileInsert($query, $values);
if ($useUpsertAlias) {
$sql .= ' as laravel_upsert_alias';
}
$sql .= ' on duplicate key update ';
$columns = collect($update)->map(function ($value, $key) use ($useUpsertAlias) {
if (! is_numeric($key)) {
return $this->wrap($key).' = '.$this->parameter($value);
}
return $useUpsertAlias
? $this->wrap($value).' = '.$this->wrap('laravel_upsert_alias').'.'.$this->wrap($value)
: $this->wrap($value).' = values('.$this->wrap($value).')';
})->implode(', ');
return $sql.$columns;
}
/**
* Prepare a JSON column being updated using the JSON_SET function.
*
* @param string $key
* @param mixed $value
* @return string
*/
protected function compileJsonUpdateColumn($key, $value)
{
if (is_bool($value)) {
$value = $value ? 'true' : 'false';
} elseif (is_array($value)) {
$value = 'cast(? as json)';
} else {
$value = $this->parameter($value);
}
[$field, $path] = $this->wrapJsonFieldAndPath($key);
return "{$field} = json_set({$field}{$path}, {$value})";
}
/**
* Compile an update statement without joins into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $table
* @param string $columns
* @param string $where
* @return string
*/
protected function compileUpdateWithoutJoins(Builder $query, $table, $columns, $where)
{
$sql = parent::compileUpdateWithoutJoins($query, $table, $columns, $where);
if (! empty($query->orders)) {
$sql .= ' '.$this->compileOrders($query, $query->orders);
}
if (isset($query->limit)) {
$sql .= ' '.$this->compileLimit($query, $query->limit);
}
return $sql;
}
/**
* Prepare the bindings for an update statement.
*
* Booleans, integers, and doubles are inserted into JSON updates as raw values.
*
* @param array $bindings
* @param array $values
* @return array
*/
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$values = collect($values)->reject(function ($value, $column) {
return $this->isJsonSelector($column) && is_bool($value);
})->map(function ($value) {
return is_array($value) ? json_encode($value) : $value;
})->all();
return parent::prepareBindingsForUpdate($bindings, $values);
}
/**
* Compile a delete query that does not use joins.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $table
* @param string $where
* @return string
*/
protected function compileDeleteWithoutJoins(Builder $query, $table, $where)
{
$sql = parent::compileDeleteWithoutJoins($query, $table, $where);
// When using MySQL, delete statements may contain order by statements and limits
// so we will compile both of those here. Once we have finished compiling this
// we will return the completed SQL statement so it will be executed for us.
if (! empty($query->orders)) {
$sql .= ' '.$this->compileOrders($query, $query->orders);
}
if (isset($query->limit)) {
$sql .= ' '.$this->compileLimit($query, $query->limit);
}
return $sql;
}
/**
* Wrap a single string in keyword identifiers.
*
* @param string $value
* @return string
*/
protected function wrapValue($value)
{
return $value === '*' ? $value : '`'.str_replace('`', '``', $value).'`';
}
/**
* Wrap the given JSON selector.
*
* @param string $value
* @return string
*/
protected function wrapJsonSelector($value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($value);
return 'json_unquote(json_extract('.$field.$path.'))';
}
/**
* Wrap the given JSON selector for boolean values.
*
* @param string $value
* @return string
*/
protected function wrapJsonBooleanSelector($value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($value);
return 'json_extract('.$field.$path.')';
}
}
+701
View File
@@ -0,0 +1,701 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class PostgresGrammar extends Grammar
{
/**
* All of the available clause operators.
*
* @var string[]
*/
protected $operators = [
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike', 'not ilike',
'~', '&', '|', '#', '<<', '>>', '<<=', '>>=',
'&&', '@>', '<@', '?', '?|', '?&', '||', '-', '@?', '@@', '#-',
'is distinct from', 'is not distinct from',
];
/**
* The grammar specific bitwise operators.
*
* @var array
*/
protected $bitwiseOperators = [
'~', '&', '|', '#', '<<', '>>', '<<=', '>>=',
];
/**
* Compile a basic where clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereBasic(Builder $query, $where)
{
if (str_contains(strtolower($where['operator']), 'like')) {
return sprintf(
'%s::text %s %s',
$this->wrap($where['column']),
$where['operator'],
$this->parameter($where['value'])
);
}
return parent::whereBasic($query, $where);
}
/**
* Compile a bitwise operator where clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereBitwise(Builder $query, $where)
{
$value = $this->parameter($where['value']);
$operator = str_replace('?', '??', $where['operator']);
return '('.$this->wrap($where['column']).' '.$operator.' '.$value.')::bool';
}
/**
* Compile a "where date" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereDate(Builder $query, $where)
{
$value = $this->parameter($where['value']);
return $this->wrap($where['column']).'::date '.$where['operator'].' '.$value;
}
/**
* Compile a "where time" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereTime(Builder $query, $where)
{
$value = $this->parameter($where['value']);
return $this->wrap($where['column']).'::time '.$where['operator'].' '.$value;
}
/**
* Compile a date based where clause.
*
* @param string $type
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function dateBasedWhere($type, Builder $query, $where)
{
$value = $this->parameter($where['value']);
return 'extract('.$type.' from '.$this->wrap($where['column']).') '.$where['operator'].' '.$value;
}
/**
* Compile a "where fulltext" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
public function whereFullText(Builder $query, $where)
{
$language = $where['options']['language'] ?? 'english';
if (! in_array($language, $this->validFullTextLanguages())) {
$language = 'english';
}
$columns = collect($where['columns'])->map(function ($column) use ($language) {
return "to_tsvector('{$language}', {$this->wrap($column)})";
})->implode(' || ');
$mode = 'plainto_tsquery';
if (($where['options']['mode'] ?? []) === 'phrase') {
$mode = 'phraseto_tsquery';
}
if (($where['options']['mode'] ?? []) === 'websearch') {
$mode = 'websearch_to_tsquery';
}
return "({$columns}) @@ {$mode}('{$language}', {$this->parameter($where['value'])})";
}
/**
* Get an array of valid full text languages.
*
* @return array
*/
protected function validFullTextLanguages()
{
return [
'simple',
'arabic',
'danish',
'dutch',
'english',
'finnish',
'french',
'german',
'hungarian',
'indonesian',
'irish',
'italian',
'lithuanian',
'nepali',
'norwegian',
'portuguese',
'romanian',
'russian',
'spanish',
'swedish',
'tamil',
'turkish',
];
}
/**
* Compile the "select *" portion of the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $columns
* @return string|null
*/
protected function compileColumns(Builder $query, $columns)
{
// If the query is actually performing an aggregating select, we will let that
// compiler handle the building of the select clauses, as it will need some
// more syntax that is best handled by that function to keep things neat.
if (! is_null($query->aggregate)) {
return;
}
if (is_array($query->distinct)) {
$select = 'select distinct on ('.$this->columnize($query->distinct).') ';
} elseif ($query->distinct) {
$select = 'select distinct ';
} else {
$select = 'select ';
}
return $select.$this->columnize($columns);
}
/**
* Compile a "JSON contains" statement into SQL.
*
* @param string $column
* @param string $value
* @return string
*/
protected function compileJsonContains($column, $value)
{
$column = str_replace('->>', '->', $this->wrap($column));
return '('.$column.')::jsonb @> '.$value;
}
/**
* Compile a "JSON contains key" statement into SQL.
*
* @param string $column
* @return string
*/
protected function compileJsonContainsKey($column)
{
$segments = explode('->', $column);
$lastSegment = array_pop($segments);
if (filter_var($lastSegment, FILTER_VALIDATE_INT) !== false) {
$i = $lastSegment;
} elseif (preg_match('/\[(-?[0-9]+)\]$/', $lastSegment, $matches)) {
$segments[] = Str::beforeLast($lastSegment, $matches[0]);
$i = $matches[1];
}
$column = str_replace('->>', '->', $this->wrap(implode('->', $segments)));
if (isset($i)) {
return vsprintf('case when %s then %s else false end', [
'jsonb_typeof(('.$column.")::jsonb) = 'array'",
'jsonb_array_length(('.$column.')::jsonb) >= '.($i < 0 ? abs($i) : $i + 1),
]);
}
$key = "'".str_replace("'", "''", $lastSegment)."'";
return 'coalesce(('.$column.')::jsonb ?? '.$key.', false)';
}
/**
* Compile a "JSON length" statement into SQL.
*
* @param string $column
* @param string $operator
* @param string $value
* @return string
*/
protected function compileJsonLength($column, $operator, $value)
{
$column = str_replace('->>', '->', $this->wrap($column));
return 'jsonb_array_length(('.$column.')::jsonb) '.$operator.' '.$value;
}
/**
* Compile a single having clause.
*
* @param array $having
* @return string
*/
protected function compileHaving(array $having)
{
if ($having['type'] === 'Bitwise') {
return $this->compileHavingBitwise($having);
}
return parent::compileHaving($having);
}
/**
* Compile a having clause involving a bitwise operator.
*
* @param array $having
* @return string
*/
protected function compileHavingBitwise($having)
{
$column = $this->wrap($having['column']);
$parameter = $this->parameter($having['value']);
return '('.$column.' '.$having['operator'].' '.$parameter.')::bool';
}
/**
* Compile the lock into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param bool|string $value
* @return string
*/
protected function compileLock(Builder $query, $value)
{
if (! is_string($value)) {
return $value ? 'for update' : 'for share';
}
return $value;
}
/**
* Compile an insert ignore statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
public function compileInsertOrIgnore(Builder $query, array $values)
{
return $this->compileInsert($query, $values).' on conflict do nothing';
}
/**
* Compile an insert and get ID statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param string $sequence
* @return string
*/
public function compileInsertGetId(Builder $query, $values, $sequence)
{
return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence ?: 'id');
}
/**
* Compile an update statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
public function compileUpdate(Builder $query, array $values)
{
if (isset($query->joins) || isset($query->limit)) {
return $this->compileUpdateWithJoinsOrLimit($query, $values);
}
return parent::compileUpdate($query, $values);
}
/**
* Compile the columns for an update statement.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
protected function compileUpdateColumns(Builder $query, array $values)
{
return collect($values)->map(function ($value, $key) {
$column = last(explode('.', $key));
if ($this->isJsonSelector($key)) {
return $this->compileJsonUpdateColumn($column, $value);
}
return $this->wrap($column).' = '.$this->parameter($value);
})->implode(', ');
}
/**
* Compile an "upsert" statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param array $uniqueBy
* @param array $update
* @return string
*/
public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update)
{
$sql = $this->compileInsert($query, $values);
$sql .= ' on conflict ('.$this->columnize($uniqueBy).') do update set ';
$columns = collect($update)->map(function ($value, $key) {
return is_numeric($key)
? $this->wrap($value).' = '.$this->wrapValue('excluded').'.'.$this->wrap($value)
: $this->wrap($key).' = '.$this->parameter($value);
})->implode(', ');
return $sql.$columns;
}
/**
* Prepares a JSON column being updated using the JSONB_SET function.
*
* @param string $key
* @param mixed $value
* @return string
*/
protected function compileJsonUpdateColumn($key, $value)
{
$segments = explode('->', $key);
$field = $this->wrap(array_shift($segments));
$path = "'{".implode(',', $this->wrapJsonPathAttributes($segments, '"'))."}'";
return "{$field} = jsonb_set({$field}::jsonb, {$path}, {$this->parameter($value)})";
}
/**
* Compile an update from statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
public function compileUpdateFrom(Builder $query, $values)
{
$table = $this->wrapTable($query->from);
// Each one of the columns in the update statements needs to be wrapped in the
// keyword identifiers, also a place-holder needs to be created for each of
// the values in the list of bindings so we can make the sets statements.
$columns = $this->compileUpdateColumns($query, $values);
$from = '';
if (isset($query->joins)) {
// When using Postgres, updates with joins list the joined tables in the from
// clause, which is different than other systems like MySQL. Here, we will
// compile out the tables that are joined and add them to a from clause.
$froms = collect($query->joins)->map(function ($join) {
return $this->wrapTable($join->table);
})->all();
if (count($froms) > 0) {
$from = ' from '.implode(', ', $froms);
}
}
$where = $this->compileUpdateWheres($query);
return trim("update {$table} set {$columns}{$from} {$where}");
}
/**
* Compile the additional where clauses for updates with joins.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileUpdateWheres(Builder $query)
{
$baseWheres = $this->compileWheres($query);
if (! isset($query->joins)) {
return $baseWheres;
}
// Once we compile the join constraints, we will either use them as the where
// clause or append them to the existing base where clauses. If we need to
// strip the leading boolean we will do so when using as the only where.
$joinWheres = $this->compileUpdateJoinWheres($query);
if (trim($baseWheres) == '') {
return 'where '.$this->removeLeadingBoolean($joinWheres);
}
return $baseWheres.' '.$joinWheres;
}
/**
* Compile the "join" clause where clauses for an update.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileUpdateJoinWheres(Builder $query)
{
$joinWheres = [];
// Here we will just loop through all of the join constraints and compile them
// all out then implode them. This should give us "where" like syntax after
// everything has been built and then we will join it to the real wheres.
foreach ($query->joins as $join) {
foreach ($join->wheres as $where) {
$method = "where{$where['type']}";
$joinWheres[] = $where['boolean'].' '.$this->$method($query, $where);
}
}
return implode(' ', $joinWheres);
}
/**
* Prepare the bindings for an update statement.
*
* @param array $bindings
* @param array $values
* @return array
*/
public function prepareBindingsForUpdateFrom(array $bindings, array $values)
{
$values = collect($values)->map(function ($value, $column) {
return is_array($value) || ($this->isJsonSelector($column) && ! $this->isExpression($value))
? json_encode($value)
: $value;
})->all();
$bindingsWithoutWhere = Arr::except($bindings, ['select', 'where']);
return array_values(
array_merge($values, $bindings['where'], Arr::flatten($bindingsWithoutWhere))
);
}
/**
* Compile an update statement with joins or limit into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
protected function compileUpdateWithJoinsOrLimit(Builder $query, array $values)
{
$table = $this->wrapTable($query->from);
$columns = $this->compileUpdateColumns($query, $values);
$alias = last(preg_split('/\s+as\s+/i', $query->from));
$selectSql = $this->compileSelect($query->select($alias.'.ctid'));
return "update {$table} set {$columns} where {$this->wrap('ctid')} in ({$selectSql})";
}
/**
* Prepare the bindings for an update statement.
*
* @param array $bindings
* @param array $values
* @return array
*/
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$values = collect($values)->map(function ($value, $column) {
return is_array($value) || ($this->isJsonSelector($column) && ! $this->isExpression($value))
? json_encode($value)
: $value;
})->all();
$cleanBindings = Arr::except($bindings, 'select');
return array_values(
array_merge($values, Arr::flatten($cleanBindings))
);
}
/**
* Compile a delete statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
public function compileDelete(Builder $query)
{
if (isset($query->joins) || isset($query->limit)) {
return $this->compileDeleteWithJoinsOrLimit($query);
}
return parent::compileDelete($query);
}
/**
* Compile a delete statement with joins or limit into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileDeleteWithJoinsOrLimit(Builder $query)
{
$table = $this->wrapTable($query->from);
$alias = last(preg_split('/\s+as\s+/i', $query->from));
$selectSql = $this->compileSelect($query->select($alias.'.ctid'));
return "delete from {$table} where {$this->wrap('ctid')} in ({$selectSql})";
}
/**
* Compile a truncate table statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return array
*/
public function compileTruncate(Builder $query)
{
return ['truncate '.$this->wrapTable($query->from).' restart identity cascade' => []];
}
/**
* Wrap the given JSON selector.
*
* @param string $value
* @return string
*/
protected function wrapJsonSelector($value)
{
$path = explode('->', $value);
$field = $this->wrapSegments(explode('.', array_shift($path)));
$wrappedPath = $this->wrapJsonPathAttributes($path);
$attribute = array_pop($wrappedPath);
if (! empty($wrappedPath)) {
return $field.'->'.implode('->', $wrappedPath).'->>'.$attribute;
}
return $field.'->>'.$attribute;
}
/**
* Wrap the given JSON selector for boolean values.
*
* @param string $value
* @return string
*/
protected function wrapJsonBooleanSelector($value)
{
$selector = str_replace(
'->>', '->',
$this->wrapJsonSelector($value)
);
return '('.$selector.')::jsonb';
}
/**
* Wrap the given JSON boolean value.
*
* @param string $value
* @return string
*/
protected function wrapJsonBooleanValue($value)
{
return "'".$value."'::jsonb";
}
/**
* Wrap the attributes of the given JSON path.
*
* @param array $path
* @return array
*/
protected function wrapJsonPathAttributes($path)
{
$quote = func_num_args() === 2 ? func_get_arg(1) : "'";
return collect($path)->map(function ($attribute) {
return $this->parseJsonPathArrayKeys($attribute);
})->collapse()->map(function ($attribute) use ($quote) {
return filter_var($attribute, FILTER_VALIDATE_INT) !== false
? $attribute
: $quote.$attribute.$quote;
})->all();
}
/**
* Parse the given JSON path attribute for array keys.
*
* @param string $attribute
* @return array
*/
protected function parseJsonPathArrayKeys($attribute)
{
if (preg_match('/(\[[^\]]+\])+$/', $attribute, $parts)) {
$key = Str::beforeLast($attribute, $parts[0]);
preg_match_all('/\[([^\]]+)\]/', $parts[0], $keys);
return collect([$key])
->merge($keys[1])
->diff('')
->values()
->all();
}
return [$attribute];
}
}
+369
View File
@@ -0,0 +1,369 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class SQLiteGrammar extends Grammar
{
/**
* All of the available clause operators.
*
* @var string[]
*/
protected $operators = [
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'ilike',
'&', '|', '<<', '>>',
];
/**
* Compile the lock into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param bool|string $value
* @return string
*/
protected function compileLock(Builder $query, $value)
{
return '';
}
/**
* Wrap a union subquery in parentheses.
*
* @param string $sql
* @return string
*/
protected function wrapUnion($sql)
{
return 'select * from ('.$sql.')';
}
/**
* Compile a "where date" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereDate(Builder $query, $where)
{
return $this->dateBasedWhere('%Y-%m-%d', $query, $where);
}
/**
* Compile a "where day" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereDay(Builder $query, $where)
{
return $this->dateBasedWhere('%d', $query, $where);
}
/**
* Compile a "where month" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereMonth(Builder $query, $where)
{
return $this->dateBasedWhere('%m', $query, $where);
}
/**
* Compile a "where year" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereYear(Builder $query, $where)
{
return $this->dateBasedWhere('%Y', $query, $where);
}
/**
* Compile a "where time" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereTime(Builder $query, $where)
{
return $this->dateBasedWhere('%H:%M:%S', $query, $where);
}
/**
* Compile a date based where clause.
*
* @param string $type
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function dateBasedWhere($type, Builder $query, $where)
{
$value = $this->parameter($where['value']);
return "strftime('{$type}', {$this->wrap($where['column'])}) {$where['operator']} cast({$value} as text)";
}
/**
* Compile the index hints for the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param \Illuminate\Database\Query\IndexHint $indexHint
* @return string
*/
protected function compileIndexHint(Builder $query, $indexHint)
{
return $indexHint->type === 'force'
? "indexed by {$indexHint->index}"
: '';
}
/**
* Compile a "JSON length" statement into SQL.
*
* @param string $column
* @param string $operator
* @param string $value
* @return string
*/
protected function compileJsonLength($column, $operator, $value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return 'json_array_length('.$field.$path.') '.$operator.' '.$value;
}
/**
* Compile a "JSON contains key" statement into SQL.
*
* @param string $column
* @return string
*/
protected function compileJsonContainsKey($column)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return 'json_type('.$field.$path.') is not null';
}
/**
* Compile an update statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
public function compileUpdate(Builder $query, array $values)
{
if (isset($query->joins) || isset($query->limit)) {
return $this->compileUpdateWithJoinsOrLimit($query, $values);
}
return parent::compileUpdate($query, $values);
}
/**
* Compile an insert ignore statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
public function compileInsertOrIgnore(Builder $query, array $values)
{
return Str::replaceFirst('insert', 'insert or ignore', $this->compileInsert($query, $values));
}
/**
* Compile the columns for an update statement.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
protected function compileUpdateColumns(Builder $query, array $values)
{
$jsonGroups = $this->groupJsonColumnsForUpdate($values);
return collect($values)->reject(function ($value, $key) {
return $this->isJsonSelector($key);
})->merge($jsonGroups)->map(function ($value, $key) use ($jsonGroups) {
$column = last(explode('.', $key));
$value = isset($jsonGroups[$key]) ? $this->compileJsonPatch($column, $value) : $this->parameter($value);
return $this->wrap($column).' = '.$value;
})->implode(', ');
}
/**
* Compile an "upsert" statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param array $uniqueBy
* @param array $update
* @return string
*/
public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update)
{
$sql = $this->compileInsert($query, $values);
$sql .= ' on conflict ('.$this->columnize($uniqueBy).') do update set ';
$columns = collect($update)->map(function ($value, $key) {
return is_numeric($key)
? $this->wrap($value).' = '.$this->wrapValue('excluded').'.'.$this->wrap($value)
: $this->wrap($key).' = '.$this->parameter($value);
})->implode(', ');
return $sql.$columns;
}
/**
* Group the nested JSON columns.
*
* @param array $values
* @return array
*/
protected function groupJsonColumnsForUpdate(array $values)
{
$groups = [];
foreach ($values as $key => $value) {
if ($this->isJsonSelector($key)) {
Arr::set($groups, str_replace('->', '.', Str::after($key, '.')), $value);
}
}
return $groups;
}
/**
* Compile a "JSON" patch statement into SQL.
*
* @param string $column
* @param mixed $value
* @return string
*/
protected function compileJsonPatch($column, $value)
{
return "json_patch(ifnull({$this->wrap($column)}, json('{}')), json({$this->parameter($value)}))";
}
/**
* Compile an update statement with joins or limit into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @return string
*/
protected function compileUpdateWithJoinsOrLimit(Builder $query, array $values)
{
$table = $this->wrapTable($query->from);
$columns = $this->compileUpdateColumns($query, $values);
$alias = last(preg_split('/\s+as\s+/i', $query->from));
$selectSql = $this->compileSelect($query->select($alias.'.rowid'));
return "update {$table} set {$columns} where {$this->wrap('rowid')} in ({$selectSql})";
}
/**
* Prepare the bindings for an update statement.
*
* @param array $bindings
* @param array $values
* @return array
*/
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$groups = $this->groupJsonColumnsForUpdate($values);
$values = collect($values)->reject(function ($value, $key) {
return $this->isJsonSelector($key);
})->merge($groups)->map(function ($value) {
return is_array($value) ? json_encode($value) : $value;
})->all();
$cleanBindings = Arr::except($bindings, 'select');
return array_values(
array_merge($values, Arr::flatten($cleanBindings))
);
}
/**
* Compile a delete statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
public function compileDelete(Builder $query)
{
if (isset($query->joins) || isset($query->limit)) {
return $this->compileDeleteWithJoinsOrLimit($query);
}
return parent::compileDelete($query);
}
/**
* Compile a delete statement with joins or limit into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileDeleteWithJoinsOrLimit(Builder $query)
{
$table = $this->wrapTable($query->from);
$alias = last(preg_split('/\s+as\s+/i', $query->from));
$selectSql = $this->compileSelect($query->select($alias.'.rowid'));
return "delete from {$table} where {$this->wrap('rowid')} in ({$selectSql})";
}
/**
* Compile a truncate table statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return array
*/
public function compileTruncate(Builder $query)
{
return [
'delete from sqlite_sequence where name = ?' => [$query->from],
'delete from '.$this->wrapTable($query->from) => [],
];
}
/**
* Wrap the given JSON selector.
*
* @param string $value
* @return string
*/
protected function wrapJsonSelector($value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($value);
return 'json_extract('.$field.$path.')';
}
}
+634
View File
@@ -0,0 +1,634 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class SqlServerGrammar extends Grammar
{
/**
* All of the available clause operators.
*
* @var string[]
*/
protected $operators = [
'=', '<', '>', '<=', '>=', '!<', '!>', '<>', '!=',
'like', 'not like', 'ilike',
'&', '&=', '|', '|=', '^', '^=',
];
/**
* Compile a select query into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
public function compileSelect(Builder $query)
{
if (! $query->offset) {
return parent::compileSelect($query);
}
if (is_null($query->columns)) {
$query->columns = ['*'];
}
$components = $this->compileComponents($query);
if (! empty($components['orders'])) {
return parent::compileSelect($query)." offset {$query->offset} rows fetch next {$query->limit} rows only";
}
// If an offset is present on the query, we will need to wrap the query in
// a big "ANSI" offset syntax block. This is very nasty compared to the
// other database systems but is necessary for implementing features.
return $this->compileAnsiOffset(
$query, $components
);
}
/**
* Compile the "select *" portion of the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $columns
* @return string|null
*/
protected function compileColumns(Builder $query, $columns)
{
if (! is_null($query->aggregate)) {
return;
}
$select = $query->distinct ? 'select distinct ' : 'select ';
// If there is a limit on the query, but not an offset, we will add the top
// clause to the query, which serves as a "limit" type clause within the
// SQL Server system similar to the limit keywords available in MySQL.
if (is_numeric($query->limit) && $query->limit > 0 && $query->offset <= 0) {
$select .= 'top '.((int) $query->limit).' ';
}
return $select.$this->columnize($columns);
}
/**
* Compile the "from" portion of the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $table
* @return string
*/
protected function compileFrom(Builder $query, $table)
{
$from = parent::compileFrom($query, $table);
if (is_string($query->lock)) {
return $from.' '.$query->lock;
}
if (! is_null($query->lock)) {
return $from.' with(rowlock,'.($query->lock ? 'updlock,' : '').'holdlock)';
}
return $from;
}
/**
* Compile the index hints for the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param \Illuminate\Database\Query\IndexHint $indexHint
* @return string
*/
protected function compileIndexHint(Builder $query, $indexHint)
{
return $indexHint->type === 'force'
? "with (index({$indexHint->index}))"
: '';
}
/**
* {@inheritdoc}
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereBitwise(Builder $query, $where)
{
$value = $this->parameter($where['value']);
$operator = str_replace('?', '??', $where['operator']);
return '('.$this->wrap($where['column']).' '.$operator.' '.$value.') != 0';
}
/**
* Compile a "where date" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereDate(Builder $query, $where)
{
$value = $this->parameter($where['value']);
return 'cast('.$this->wrap($where['column']).' as date) '.$where['operator'].' '.$value;
}
/**
* Compile a "where time" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereTime(Builder $query, $where)
{
$value = $this->parameter($where['value']);
return 'cast('.$this->wrap($where['column']).' as time) '.$where['operator'].' '.$value;
}
/**
* Compile a "JSON contains" statement into SQL.
*
* @param string $column
* @param string $value
* @return string
*/
protected function compileJsonContains($column, $value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return $value.' in (select [value] from openjson('.$field.$path.'))';
}
/**
* Prepare the binding for a "JSON contains" statement.
*
* @param mixed $binding
* @return string
*/
public function prepareBindingForJsonContains($binding)
{
return is_bool($binding) ? json_encode($binding) : $binding;
}
/**
* Compile a "JSON contains key" statement into SQL.
*
* @param string $column
* @return string
*/
protected function compileJsonContainsKey($column)
{
$segments = explode('->', $column);
$lastSegment = array_pop($segments);
if (preg_match('/\[([0-9]+)\]$/', $lastSegment, $matches)) {
$segments[] = Str::beforeLast($lastSegment, $matches[0]);
$key = $matches[1];
} else {
$key = "'".str_replace("'", "''", $lastSegment)."'";
}
[$field, $path] = $this->wrapJsonFieldAndPath(implode('->', $segments));
return $key.' in (select [key] from openjson('.$field.$path.'))';
}
/**
* Compile a "JSON length" statement into SQL.
*
* @param string $column
* @param string $operator
* @param string $value
* @return string
*/
protected function compileJsonLength($column, $operator, $value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return '(select count(*) from openjson('.$field.$path.')) '.$operator.' '.$value;
}
/**
* Compile a "JSON value cast" statement into SQL.
*
* @param string $value
* @return string
*/
public function compileJsonValueCast($value)
{
return 'json_query('.$value.')';
}
/**
* Compile a single having clause.
*
* @param array $having
* @return string
*/
protected function compileHaving(array $having)
{
if ($having['type'] === 'Bitwise') {
return $this->compileHavingBitwise($having);
}
return parent::compileHaving($having);
}
/**
* Compile a having clause involving a bitwise operator.
*
* @param array $having
* @return string
*/
protected function compileHavingBitwise($having)
{
$column = $this->wrap($having['column']);
$parameter = $this->parameter($having['value']);
return '('.$column.' '.$having['operator'].' '.$parameter.') != 0';
}
/**
* Create a full ANSI offset clause for the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $components
* @return string
*/
protected function compileAnsiOffset(Builder $query, $components)
{
// An ORDER BY clause is required to make this offset query work, so if one does
// not exist we'll just create a dummy clause to trick the database and so it
// does not complain about the queries for not having an "order by" clause.
if (empty($components['orders'])) {
$components['orders'] = 'order by (select 0)';
}
// We need to add the row number to the query so we can compare it to the offset
// and limit values given for the statements. So we will add an expression to
// the "select" that will give back the row numbers on each of the records.
$components['columns'] .= $this->compileOver($components['orders']);
unset($components['orders']);
if ($this->queryOrderContainsSubquery($query)) {
$query->bindings = $this->sortBindingsForSubqueryOrderBy($query);
}
// Next we need to calculate the constraints that should be placed on the query
// to get the right offset and limit from our query but if there is no limit
// set we will just handle the offset only since that is all that matters.
$sql = $this->concatenate($components);
return $this->compileTableExpression($sql, $query);
}
/**
* Compile the over statement for a table expression.
*
* @param string $orderings
* @return string
*/
protected function compileOver($orderings)
{
return ", row_number() over ({$orderings}) as row_num";
}
/**
* Determine if the query's order by clauses contain a subquery.
*
* @param \Illuminate\Database\Query\Builder $query
* @return bool
*/
protected function queryOrderContainsSubquery($query)
{
if (! is_array($query->orders)) {
return false;
}
return Arr::first($query->orders, function ($value) {
return $this->isExpression($value['column'] ?? null);
}, false) !== false;
}
/**
* Move the order bindings to be after the "select" statement to account for an order by subquery.
*
* @param \Illuminate\Database\Query\Builder $query
* @return array
*/
protected function sortBindingsForSubqueryOrderBy($query)
{
return Arr::sort($query->bindings, function ($bindings, $key) {
return array_search($key, ['select', 'order', 'from', 'join', 'where', 'groupBy', 'having', 'union', 'unionOrder']);
});
}
/**
* Compile a common table expression for a query.
*
* @param string $sql
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileTableExpression($sql, $query)
{
$constraint = $this->compileRowConstraint($query);
return "select * from ({$sql}) as temp_table where row_num {$constraint} order by row_num";
}
/**
* Compile the limit / offset row constraint for a query.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileRowConstraint($query)
{
$start = (int) $query->offset + 1;
if ($query->limit > 0) {
$finish = (int) $query->offset + (int) $query->limit;
return "between {$start} and {$finish}";
}
return ">= {$start}";
}
/**
* Compile a delete statement without joins into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $table
* @param string $where
* @return string
*/
protected function compileDeleteWithoutJoins(Builder $query, $table, $where)
{
$sql = parent::compileDeleteWithoutJoins($query, $table, $where);
return ! is_null($query->limit) && $query->limit > 0 && $query->offset <= 0
? Str::replaceFirst('delete', 'delete top ('.$query->limit.')', $sql)
: $sql;
}
/**
* Compile the random statement into SQL.
*
* @param string|int $seed
* @return string
*/
public function compileRandom($seed)
{
return 'NEWID()';
}
/**
* Compile the "limit" portions of the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param int $limit
* @return string
*/
protected function compileLimit(Builder $query, $limit)
{
return '';
}
/**
* Compile the "offset" portions of the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param int $offset
* @return string
*/
protected function compileOffset(Builder $query, $offset)
{
return '';
}
/**
* Compile the lock into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param bool|string $value
* @return string
*/
protected function compileLock(Builder $query, $value)
{
return '';
}
/**
* Wrap a union subquery in parentheses.
*
* @param string $sql
* @return string
*/
protected function wrapUnion($sql)
{
return 'select * from ('.$sql.') as '.$this->wrapTable('temp_table');
}
/**
* Compile an exists statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
public function compileExists(Builder $query)
{
$existsQuery = clone $query;
$existsQuery->columns = [];
return $this->compileSelect($existsQuery->selectRaw('1 [exists]')->limit(1));
}
/**
* Compile an update statement with joins into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $table
* @param string $columns
* @param string $where
* @return string
*/
protected function compileUpdateWithJoins(Builder $query, $table, $columns, $where)
{
$alias = last(explode(' as ', $table));
$joins = $this->compileJoins($query, $query->joins);
return "update {$alias} set {$columns} from {$table} {$joins} {$where}";
}
/**
* Compile an "upsert" statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param array $uniqueBy
* @param array $update
* @return string
*/
public function compileUpsert(Builder $query, array $values, array $uniqueBy, array $update)
{
$columns = $this->columnize(array_keys(reset($values)));
$sql = 'merge '.$this->wrapTable($query->from).' ';
$parameters = collect($values)->map(function ($record) {
return '('.$this->parameterize($record).')';
})->implode(', ');
$sql .= 'using (values '.$parameters.') '.$this->wrapTable('laravel_source').' ('.$columns.') ';
$on = collect($uniqueBy)->map(function ($column) use ($query) {
return $this->wrap('laravel_source.'.$column).' = '.$this->wrap($query->from.'.'.$column);
})->implode(' and ');
$sql .= 'on '.$on.' ';
if ($update) {
$update = collect($update)->map(function ($value, $key) {
return is_numeric($key)
? $this->wrap($value).' = '.$this->wrap('laravel_source.'.$value)
: $this->wrap($key).' = '.$this->parameter($value);
})->implode(', ');
$sql .= 'when matched then update set '.$update.' ';
}
$sql .= 'when not matched then insert ('.$columns.') values ('.$columns.');';
return $sql;
}
/**
* Prepare the bindings for an update statement.
*
* @param array $bindings
* @param array $values
* @return array
*/
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$cleanBindings = Arr::except($bindings, 'select');
return array_values(
array_merge($values, Arr::flatten($cleanBindings))
);
}
/**
* Compile the SQL statement to define a savepoint.
*
* @param string $name
* @return string
*/
public function compileSavepoint($name)
{
return 'SAVE TRANSACTION '.$name;
}
/**
* Compile the SQL statement to execute a savepoint rollback.
*
* @param string $name
* @return string
*/
public function compileSavepointRollBack($name)
{
return 'ROLLBACK TRANSACTION '.$name;
}
/**
* Get the format for database stored dates.
*
* @return string
*/
public function getDateFormat()
{
return 'Y-m-d H:i:s.v';
}
/**
* Wrap a single string in keyword identifiers.
*
* @param string $value
* @return string
*/
protected function wrapValue($value)
{
return $value === '*' ? $value : '['.str_replace(']', ']]', $value).']';
}
/**
* Wrap the given JSON selector.
*
* @param string $value
* @return string
*/
protected function wrapJsonSelector($value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($value);
return 'json_value('.$field.$path.')';
}
/**
* Wrap the given JSON boolean value.
*
* @param string $value
* @return string
*/
protected function wrapJsonBooleanValue($value)
{
return "'".$value."'";
}
/**
* Wrap a table in keyword identifiers.
*
* @param \Illuminate\Database\Query\Expression|string $table
* @return string
*/
public function wrapTable($table)
{
if (! $this->isExpression($table)) {
return $this->wrapTableValuedFunction(parent::wrapTable($table));
}
return $this->getValue($table);
}
/**
* Wrap a table in keyword identifiers.
*
* @param string $table
* @return string
*/
protected function wrapTableValuedFunction($table)
{
if (preg_match('/^(.+?)(\(.*?\))]$/', $table, $matches) === 1) {
$table = $matches[1].']'.$matches[2];
}
return $table;
}
}