This commit is contained in:
2026-05-01 23:40:14 +08:00
commit b8f599a617
3867 changed files with 478663 additions and 0 deletions
+4939
View File
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Illuminate\Database\Query;
use Illuminate\Contracts\Database\Query\Expression as ExpressionContract;
use Illuminate\Database\Grammar;
/**
* @template TValue of literal-string|int|float
*/
class Expression implements ExpressionContract
{
/**
* Create a new raw query expression.
*
* @param TValue $value
*/
public function __construct(
protected $value,
) {
}
/**
* Get the value of the expression.
*
* @param \Illuminate\Database\Grammar $grammar
* @return TValue
*/
public function getValue(Grammar $grammar)
{
return $this->value;
}
}
File diff suppressed because it is too large Load Diff
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\JoinLateralClause;
use RuntimeException;
class MariaDbGrammar extends MySqlGrammar
{
/**
* Compile a "lateral join" clause.
*
* @param \Illuminate\Database\Query\JoinLateralClause $join
* @param string $expression
* @return string
*
* @throws \RuntimeException
*/
public function compileJoinLateral(JoinLateralClause $join, string $expression): string
{
throw new RuntimeException('This database engine does not support lateral joins.');
}
/**
* Compile a "JSON value cast" statement into SQL.
*
* @param string $value
* @return string
*/
public function compileJsonValueCast($value)
{
return "json_query({$value}, '$')";
}
/**
* Compile a query to get the number of open connections for a database.
*
* @return string
*/
public function compileThreadCount()
{
return 'select variable_value as `Value` from information_schema.global_status where variable_name = \'THREADS_CONNECTED\'';
}
/**
* Determine whether to use a legacy group limit clause for MySQL < 8.0.
*
* @param \Illuminate\Database\Query\Builder $query
* @return bool
*/
public function useLegacyGroupLimit(Builder $query)
{
return false;
}
/**
* Wrap the given JSON selector.
*
* @param string $value
* @return string
*/
protected function wrapJsonSelector($value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($value);
return 'json_value('.$field.$path.')';
}
}
+619
View File
@@ -0,0 +1,619 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\JoinLateralClause;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;
class MySqlGrammar extends Grammar
{
/**
* The grammar specific operators.
*
* @var string[]
*/
protected $operators = ['sounds like'];
/**
* Compile a select query into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
public function compileSelect(Builder $query)
{
$sql = parent::compileSelect($query);
if ($query->timeout === null) {
return $sql;
}
$milliseconds = $query->timeout * 1000;
return preg_replace(
'/^select\b/i',
'select /*+ MAX_EXECUTION_TIME('.$milliseconds.') */',
$sql,
1
);
}
/**
* Compile a "where like" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereLike(Builder $query, $where)
{
$where['operator'] = $where['not'] ? 'not ' : '';
$where['operator'] .= $where['caseSensitive'] ? 'like binary' : 'like';
return $this->whereBasic($query, $where);
}
/**
* Compile a "where null safe equals" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereNullSafeEquals(Builder $query, $where)
{
return $this->wrap($where['column']).' <=> '.$this->parameter($where['value']);
}
/**
* 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)
{
$columnValue = (string) $this->getValue($where['column']);
if ($this->isJsonSelector($columnValue)) {
[$field, $path] = $this->wrapJsonFieldAndPath($columnValue);
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)
{
$columnValue = (string) $this->getValue($where['column']);
if ($this->isJsonSelector($columnValue)) {
[$field, $path] = $this->wrapJsonFieldAndPath($columnValue);
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
*
* @throws \InvalidArgumentException
*/
protected function compileIndexHint(Builder $query, $indexHint)
{
$index = $indexHint->index;
$indexes = array_map('trim', explode(',', $index));
foreach ($indexes as $i) {
if (! preg_match('/^[a-zA-Z0-9_$]+$/', $i)) {
throw new InvalidArgumentException('Index name contains invalid characters.');
}
}
return match ($indexHint->type) {
'hint' => "use index ({$index})",
'force' => "force index ({$index})",
default => "ignore index ({$index})",
};
}
/**
* Compile a group limit clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileGroupLimit(Builder $query)
{
return $this->useLegacyGroupLimit($query)
? $this->compileLegacyGroupLimit($query)
: parent::compileGroupLimit($query);
}
/**
* Determine whether to use a legacy group limit clause for MySQL < 8.0.
*
* @param \Illuminate\Database\Query\Builder $query
* @return bool
*/
public function useLegacyGroupLimit(Builder $query)
{
$version = $query->getConnection()->getServerVersion();
return ! $query->getConnection()->isMaria() && version_compare($version, '8.0.11', '<');
}
/**
* Compile a group limit clause for MySQL < 8.0.
*
* Derived from https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileLegacyGroupLimit(Builder $query)
{
$limit = (int) $query->groupLimit['value'];
$offset = $query->offset;
if (isset($offset)) {
$offset = (int) $offset;
$limit += $offset;
$query->offset = null;
}
$column = last(explode('.', $query->groupLimit['column']));
$column = $this->wrap($column);
$partition = ', @laravel_row := if(@laravel_group = '.$column.', @laravel_row + 1, 1) as `laravel_row`';
$partition .= ', @laravel_group := '.$column;
$orders = (array) $query->orders;
array_unshift($orders, [
'column' => $query->groupLimit['column'],
'direction' => 'asc',
]);
$query->orders = $orders;
$components = $this->compileComponents($query);
$sql = $this->concatenate($components);
$from = '(select @laravel_row := 0, @laravel_group := 0) as `laravel_vars`, ('.$sql.') as `laravel_table`';
$sql = 'select `laravel_table`.*'.$partition.' from '.$from.' having `laravel_row` <= '.$limit;
if (isset($offset)) {
$sql .= ' and `laravel_row` > '.$offset;
}
return $sql.' order by `laravel_row`';
}
/**
* 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 an insert ignore statement using a subquery into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $columns
* @param string $sql
* @return string
*/
public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql)
{
return Str::replaceFirst('insert', 'insert ignore', $this->compileInsertUsing($query, $columns, $sql));
}
/**
* 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 overlaps" statement into SQL.
*
* @param string $column
* @param string $value
* @return string
*/
protected function compileJsonOverlaps($column, $value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return 'json_overlaps('.$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
*
* @throws \InvalidArgumentException
*/
public function compileRandom($seed)
{
if ($seed === '' || $seed === null) {
return 'RAND()';
}
if (! is_numeric($seed)) {
throw new InvalidArgumentException('The seed value must be numeric.');
}
return 'RAND('.(int) $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 (new Collection($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 = (new Collection($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;
}
/**
* Compile a "lateral join" clause.
*
* @param \Illuminate\Database\Query\JoinLateralClause $join
* @param string $expression
* @return string
*/
public function compileJoinLateral(JoinLateralClause $join, string $expression): string
{
return trim("{$join->type} join lateral {$expression} on true");
}
/**
* {@inheritdoc}
*/
protected function supportsStraightJoins()
{
return true;
}
/**
* 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
*/
#[\Override]
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$values = (new Collection($values))
->reject(fn ($value, $column) => $this->isJsonSelector($column) && is_bool($value))
->map(fn ($value) => is_array($value) ? json_encode($value) : $value)
->all();
return parent::prepareBindingsForUpdate($bindings, $values);
}
/**
* 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);
if (! empty($query->orders)) {
$sql .= ' '.$this->compileOrders($query, $query->orders);
}
if (isset($query->limit)) {
$sql .= ' '.$this->compileLimit($query, $query->limit);
}
return $sql;
}
/**
* Compile a delete statement with joins into SQL.
*
* Adds ORDER BY and LIMIT if present, for platforms that allow them (e.g., PlanetScale).
*
* Standard MySQL does not support ORDER BY or LIMIT with joined deletes and will throw a syntax error.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $table
* @param string $where
* @return string
*/
protected function compileDeleteWithJoins(Builder $query, $table, $where)
{
$sql = parent::compileDeleteWithJoins($query, $table, $where);
if (! empty($query->orders)) {
$sql .= ' '.$this->compileOrders($query, $query->orders);
}
if (isset($query->limit)) {
$sql .= ' '.$this->compileLimit($query, $query->limit);
}
return $sql;
}
/**
* Compile a query to get the number of open connections for a database.
*
* @return string
*/
public function compileThreadCount()
{
return 'select variable_value as `Value` from performance_schema.session_status where variable_name = \'threads_connected\'';
}
/**
* 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.')';
}
}
+876
View File
@@ -0,0 +1,876 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\JoinLateralClause;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
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 Postgres grammar specific custom operators.
*
* @var array
*/
protected static $customOperators = [];
/**
* The grammar specific bitwise operators.
*
* @var array
*/
protected $bitwiseOperators = [
'~', '&', '|', '#', '<<', '>>', '<<=', '>>=',
];
/**
* Indicates if the cascade option should be used when truncating.
*
* @var bool
*/
protected static $cascadeTruncate = true;
/**
* 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 like" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereLike(Builder $query, $where)
{
$where['operator'] = $where['not'] ? 'not ' : '';
$where['operator'] .= $where['caseSensitive'] ? 'like' : 'ilike';
return $this->whereBasic($query, $where);
}
/**
* Compile a "where date" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereDate(Builder $query, $where)
{
$column = $this->wrap($where['column']);
$value = $this->parameter($where['value']);
if ($this->isJsonSelector($where['column'])) {
$column = '('.$column.')';
}
return $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)
{
$column = $this->wrap($where['column']);
$value = $this->parameter($where['value']);
if ($this->isJsonSelector($where['column'])) {
$column = '('.$column.')';
}
return $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';
}
$isVector = $where['options']['vector'] ?? false;
$columns = (new Collection($where['columns']))
->map(fn ($column) => $isVector
? $this->wrap($column)
: "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';
}
if (($where['options']['mode'] ?? []) === 'raw') {
$mode = '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 or ignore statement with a returning clause into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param array $returning
* @param array|null $uniqueBy
* @return string
*/
public function compileInsertOrIgnoreReturning(Builder $query, array $values, array $returning, ?array $uniqueBy)
{
$insert = $this->compileInsert($query, $values);
return match ($uniqueBy) {
null => "{$insert} on conflict do nothing returning {$this->columnize($returning)}",
default => "{$insert} on conflict ({$this->columnize($uniqueBy)}) do nothing returning {$this->columnize($returning)}",
};
}
/**
* Compile an insert ignore statement using a subquery into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $columns
* @param string $sql
* @return string
*/
public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql)
{
return $this->compileInsertUsing($query, $columns, $sql).' on conflict do nothing';
}
/**
* Compile an insert and get ID statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param string|null $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 (new Collection($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 = (new Collection($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;
}
/**
* Compile a "lateral join" clause.
*
* @param \Illuminate\Database\Query\JoinLateralClause $join
* @param string $expression
* @return string
*/
public function compileJoinLateral(JoinLateralClause $join, string $expression): string
{
return trim("{$join->type} join lateral {$expression} on true");
}
/**
* 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 = (new Collection($query->joins))
->map(fn ($join) => $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 = (new Collection($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
*/
#[\Override]
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$values = (new Collection($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');
$values = Arr::flatten(array_map(fn ($value) => value($value), $values));
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'.(static::$cascadeTruncate ? ' cascade' : '') => []];
}
/**
* Compile a query to get the number of open connections for a database.
*
* @return string
*/
public function compileThreadCount()
{
return 'select count(*) as "Value" from pg_stat_activity';
}
/**
* 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 (new Collection($path))
->map(fn ($attribute) => $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 (new Collection([$key]))
->merge($keys[1])
->diff('')
->values()
->all();
}
return [$attribute];
}
/**
* Substitute the given bindings into the given raw SQL query.
*
* @param string $sql
* @param array $bindings
* @return string
*/
public function substituteBindingsIntoRawSql($sql, $bindings)
{
$query = parent::substituteBindingsIntoRawSql($sql, $bindings);
foreach ($this->operators as $operator) {
if (! str_contains($operator, '?')) {
continue;
}
$query = str_replace(str_replace('?', '??', $operator), $operator, $query);
}
return $query;
}
/**
* Get the Postgres grammar specific operators.
*
* @return array
*/
public function getOperators()
{
return array_values(array_unique(array_merge(parent::getOperators(), static::$customOperators)));
}
/**
* Set any Postgres grammar specific custom operators.
*
* @param array $operators
* @return void
*/
public static function customOperators(array $operators)
{
static::$customOperators = array_values(
array_merge(static::$customOperators, array_filter(array_filter($operators, 'is_string')))
);
}
/**
* Enable or disable the "cascade" option when compiling the truncate statement.
*
* @param bool $value
* @return void
*/
public static function cascadeOnTruncate(bool $value = true)
{
static::$cascadeTruncate = $value;
}
/**
* @deprecated use cascadeOnTruncate
*/
public static function cascadeOnTrucate(bool $value = true)
{
self::cascadeOnTruncate($value);
}
}
+511
View File
@@ -0,0 +1,511 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;
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 like" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereLike(Builder $query, $where)
{
if ($where['caseSensitive'] == false) {
return parent::whereLike($query, $where);
}
$where['operator'] = $where['not'] ? 'not glob' : 'glob';
return $this->whereBasic($query, $where);
}
/**
* Convert a LIKE pattern to a GLOB pattern using simple string replacement.
*
* @param string $value
* @param bool $caseSensitive
* @return string
*/
public function prepareWhereLikeBinding($value, $caseSensitive)
{
return $caseSensitive === false ? $value : str_replace(
['*', '?', '%', '_'],
['[*]', '[?]', '*', '?'],
$value
);
}
/**
* Compile a "where null safe equals" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereNullSafeEquals(Builder $query, $where)
{
return $this->wrap($where['column']).' is '.$this->parameter($where['value']);
}
/**
* 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
*
* @throws \InvalidArgumentException
*/
protected function compileIndexHint(Builder $query, $indexHint)
{
if ($indexHint->type !== 'force') {
return '';
}
$index = $indexHint->index;
if (! preg_match('/^[a-zA-Z0-9_$]+$/', $index)) {
throw new InvalidArgumentException('Index name contains invalid characters.');
}
return "indexed by {$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" statement into SQL.
*
* @param string $column
* @param mixed $value
* @return string
*/
protected function compileJsonContains($column, $value)
{
[$field, $path] = $this->wrapJsonFieldAndPath($column);
return 'exists (select 1 from json_each('.$field.$path.') where '.$this->wrap('json_each.value').' is '.$value.')';
}
/**
* Prepare the binding for a "JSON contains" statement.
*
* @param mixed $binding
* @return mixed
*/
public function prepareBindingForJsonContains($binding)
{
return $binding;
}
/**
* 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 a group limit clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
protected function compileGroupLimit(Builder $query)
{
$version = $query->getConnection()->getServerVersion();
if (version_compare($version, '3.25.0', '>=')) {
return parent::compileGroupLimit($query);
}
$query->groupLimit = null;
return $this->compileSelect($query);
}
/**
* 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 an insert or ignore statement with a returning clause into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $values
* @param array $returning
* @param array|null $uniqueBy
* @return string
*/
public function compileInsertOrIgnoreReturning(Builder $query, array $values, array $returning, ?array $uniqueBy)
{
$insert = $this->compileInsert($query, $values);
return match ($uniqueBy) {
null => "{$insert} on conflict do nothing returning {$this->columnize($returning)}",
default => "{$insert} on conflict ({$this->columnize($uniqueBy)}) do nothing returning {$this->columnize($returning)}",
};
}
/**
* Compile an insert ignore statement using a subquery into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $columns
* @param string $sql
* @return string
*/
public function compileInsertOrIgnoreUsing(Builder $query, array $columns, string $sql)
{
return Str::replaceFirst('insert', 'insert or ignore', $this->compileInsertUsing($query, $columns, $sql));
}
/**
* 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 (new Collection($values))
->reject(fn ($value, $key) => $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 = (new Collection($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
*/
#[\Override]
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$groups = $this->groupJsonColumnsForUpdate($values);
$values = (new Collection($values))
->reject(fn ($value, $key) => $this->isJsonSelector($key))
->merge($groups)
->map(fn ($value) => is_array($value) ? json_encode($value) : $value)
->all();
$cleanBindings = Arr::except($bindings, 'select');
$values = Arr::flatten(array_map(fn ($value) => value($value), $values));
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)
{
[$schema, $table] = $query->getConnection()->getSchemaBuilder()->parseSchemaAndTable($query->from);
$schema = $schema ? $this->wrapValue($schema).'.' : '';
return [
'delete from '.$schema.'sqlite_sequence where name = ?' => [$query->getConnection()->getTablePrefix().$table],
'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.')';
}
}
+612
View File
@@ -0,0 +1,612 @@
<?php
namespace Illuminate\Database\Query\Grammars;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\JoinLateralClause;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;
class SqlServerGrammar extends Grammar
{
/**
* All of the available clause operators.
*
* @var string[]
*/
protected $operators = [
'=', '<', '>', '<=', '>=', '!<', '!>', '<>', '!=',
'like', 'not like', 'ilike',
'&', '&=', '|', '|=', '^', '^=',
];
/**
* The components that make up a select clause.
*
* @var string[]
*/
protected $selectComponents = [
'aggregate',
'columns',
'from',
'indexHint',
'joins',
'wheres',
'groups',
'havings',
'orders',
'offset',
'limit',
'lock',
];
/**
* Compile a select query into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
public function compileSelect(Builder $query)
{
// An order by clause is required for SQL Server offset to function...
if ($query->offset && empty($query->orders)) {
$query->orders[] = ['sql' => '(SELECT 0)'];
}
return parent::compileSelect($query);
}
/**
* 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
*
* @throws \InvalidArgumentException
*/
protected function compileIndexHint(Builder $query, $indexHint)
{
if ($indexHint->type !== 'force') {
return '';
}
$index = $indexHint->index;
if (! preg_match('/^[a-zA-Z0-9_$]+$/', $index)) {
throw new InvalidArgumentException('Index name contains invalid characters.');
}
return "with (index([{$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 null safe equals" clause.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $where
* @return string
*/
protected function whereNullSafeEquals(Builder $query, $where)
{
return 'exists (select '.$this->wrap($where['column']).' intersect select '.$this->parameter($where['value']).')';
}
/**
* 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';
}
/**
* 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)
{
$limit = (int) $limit;
if ($limit && $query->offset > 0) {
return "fetch next {$limit} rows only";
}
return '';
}
/**
* Compile a row number clause.
*
* @param string $partition
* @param string $orders
* @return string
*/
protected function compileRowNumber($partition, $orders)
{
if (empty($orders)) {
$orders = 'order by (select 0)';
}
return parent::compileRowNumber($partition, $orders);
}
/**
* Compile the "offset" portions of the query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param int $offset
* @return string
*/
protected function compileOffset(Builder $query, $offset)
{
$offset = (int) $offset;
if ($offset) {
return "offset {$offset} rows";
}
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(array_first($values)));
$sql = 'merge '.$this->wrapTable($query->from).' ';
$parameters = (new Collection($values))
->map(fn ($record) => '('.$this->parameterize($record).')')
->implode(', ');
$sql .= 'using (values '.$parameters.') '.$this->wrapTable('laravel_source').' ('.$columns.') ';
$on = (new Collection($uniqueBy))
->map(fn ($column) => $this->wrap('laravel_source.'.$column).' = '.$this->wrap($query->from.'.'.$column))
->implode(' and ');
$sql .= 'on '.$on.' ';
if ($update) {
$update = (new Collection($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
*/
#[\Override]
public function prepareBindingsForUpdate(array $bindings, array $values)
{
$cleanBindings = Arr::except($bindings, 'select');
$values = Arr::flatten(array_map(fn ($value) => value($value), $values));
return array_values(
array_merge($values, Arr::flatten($cleanBindings))
);
}
/**
* Compile a "lateral join" clause.
*
* @param \Illuminate\Database\Query\JoinLateralClause $join
* @param string $expression
* @return string
*/
public function compileJoinLateral(JoinLateralClause $join, string $expression): string
{
$type = $join->type == 'left' ? 'outer' : 'cross';
return trim("{$type} apply {$expression}");
}
/**
* 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;
}
/**
* Compile a query to get the number of open connections for a database.
*
* @return string
*/
public function compileThreadCount()
{
return 'select count(*) Value from sys.dm_exec_sessions where status = N\'running\'';
}
/**
* 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\Contracts\Database\Query\Expression|string $table
* @param string|null $prefix
* @return string
*/
public function wrapTable($table, $prefix = null)
{
if (! $this->isExpression($table)) {
return $this->wrapTableValuedFunction(parent::wrapTable($table, $prefix));
}
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;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Illuminate\Database\Query;
class IndexHint
{
/**
* The type of query hint.
*
* @var string
*/
public $type;
/**
* The name of the index.
*
* @var string
*/
public $index;
/**
* Create a new index hint instance.
*
* @param string $type
* @param string $index
*/
public function __construct($type, $index)
{
$this->type = $type;
$this->index = $index;
}
}
+145
View File
@@ -0,0 +1,145 @@
<?php
namespace Illuminate\Database\Query;
use Closure;
class JoinClause extends Builder
{
/**
* The type of join being performed.
*
* @var string
*/
public $type;
/**
* The table the join clause is joining to.
*
* @var \Illuminate\Contracts\Database\Query\Expression|string
*/
public $table;
/**
* The connection of the parent query builder.
*
* @var \Illuminate\Database\ConnectionInterface
*/
protected $parentConnection;
/**
* The grammar of the parent query builder.
*
* @var \Illuminate\Database\Query\Grammars\Grammar
*/
protected $parentGrammar;
/**
* The processor of the parent query builder.
*
* @var \Illuminate\Database\Query\Processors\Processor
*/
protected $parentProcessor;
/**
* The class name of the parent query builder.
*
* @var string
*/
protected $parentClass;
/**
* Create a new join clause instance.
*
* @param \Illuminate\Database\Query\Builder $parentQuery
* @param string $type
* @param string $table
*/
public function __construct(Builder $parentQuery, $type, $table)
{
$this->type = $type;
$this->table = $table;
$this->parentClass = get_class($parentQuery);
$this->parentGrammar = $parentQuery->getGrammar();
$this->parentProcessor = $parentQuery->getProcessor();
$this->parentConnection = $parentQuery->getConnection();
parent::__construct(
$this->parentConnection, $this->parentGrammar, $this->parentProcessor
);
}
/**
* Add an "on" clause to the join.
*
* On clauses can be chained, e.g.
*
* $join->on('contacts.user_id', '=', 'users.id')
* ->on('contacts.info_id', '=', 'info.id')
*
* will produce the following SQL:
*
* on `contacts`.`user_id` = `users`.`id` and `contacts`.`info_id` = `info`.`id`
*
* @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
* @param string|null $operator
* @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
* @param string $boolean
* @return $this
*
* @throws \InvalidArgumentException
*/
public function on($first, $operator = null, $second = null, $boolean = 'and')
{
if ($first instanceof Closure) {
return $this->whereNested($first, $boolean);
}
return $this->whereColumn($first, $operator, $second, $boolean);
}
/**
* Add an "or on" clause to the join.
*
* @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
* @param string|null $operator
* @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
* @return \Illuminate\Database\Query\JoinClause
*/
public function orOn($first, $operator = null, $second = null)
{
return $this->on($first, $operator, $second, 'or');
}
/**
* Get a new instance of the join clause builder.
*
* @return \Illuminate\Database\Query\JoinClause
*/
public function newQuery()
{
return new static($this->newParentQuery(), $this->type, $this->table);
}
/**
* Create a new query instance for sub-query.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function forSubQuery()
{
return $this->newParentQuery()->newQuery();
}
/**
* Create a new parent query instance.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function newParentQuery()
{
$class = $this->parentClass;
return new $class($this->parentConnection, $this->parentGrammar, $this->parentProcessor);
}
}
@@ -0,0 +1,8 @@
<?php
namespace Illuminate\Database\Query;
class JoinLateralClause extends JoinClause
{
//
}
@@ -0,0 +1,8 @@
<?php
namespace Illuminate\Database\Query\Processors;
class MariaDbProcessor extends MySqlProcessor
{
//
}
@@ -0,0 +1,102 @@
<?php
namespace Illuminate\Database\Query\Processors;
use Illuminate\Database\Query\Builder;
class MySqlProcessor extends Processor
{
/**
* Process the results of a column listing query.
*
* @deprecated Will be removed in a future Laravel version.
*
* @param array $results
* @return array
*/
public function processColumnListing($results)
{
return array_map(function ($result) {
return ((object) $result)->column_name;
}, $results);
}
/**
* Process an "insert get ID" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $sql
* @param array $values
* @param string|null $sequence
* @return int
*/
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
{
$query->getConnection()->insert($sql, $values, $sequence);
$id = $query->getConnection()->getLastInsertId();
return is_numeric($id) ? (int) $id : $id;
}
/** @inheritDoc */
public function processColumns($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'type_name' => $result->type_name,
'type' => $result->type,
'collation' => $result->collation,
'nullable' => $result->nullable === 'YES',
'default' => $result->default,
'auto_increment' => $result->extra === 'auto_increment',
'comment' => $result->comment ?: null,
'generation' => $result->expression ? [
'type' => match ($result->extra) {
'STORED GENERATED' => 'stored',
'VIRTUAL GENERATED' => 'virtual',
default => null,
},
'expression' => $result->expression,
] : null,
];
}, $results);
}
/** @inheritDoc */
public function processIndexes($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $name = strtolower($result->name),
'columns' => $result->columns ? explode(',', $result->columns) : [],
'type' => strtolower($result->type),
'unique' => (bool) $result->unique,
'primary' => $name === 'primary',
];
}, $results);
}
/** @inheritDoc */
public function processForeignKeys($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'columns' => explode(',', $result->columns),
'foreign_schema' => $result->foreign_schema,
'foreign_table' => $result->foreign_table,
'foreign_columns' => explode(',', $result->foreign_columns),
'on_update' => strtolower($result->on_update),
'on_delete' => strtolower($result->on_delete),
];
}, $results);
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
namespace Illuminate\Database\Query\Processors;
use Illuminate\Database\Query\Builder;
class PostgresProcessor extends Processor
{
/**
* Process an "insert get ID" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $sql
* @param array $values
* @param string|null $sequence
* @return int
*/
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
{
$connection = $query->getConnection();
$connection->recordsHaveBeenModified();
$result = $connection->selectFromWriteConnection($sql, $values)[0];
$sequence = $sequence ?: 'id';
$id = is_object($result) ? $result->{$sequence} : $result[$sequence];
return is_numeric($id) ? (int) $id : $id;
}
/** @inheritDoc */
public function processTypes($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'schema' => $result->schema,
'schema_qualified_name' => $result->schema.'.'.$result->name,
'implicit' => (bool) $result->implicit,
'type' => match (strtolower($result->type)) {
'b' => 'base',
'c' => 'composite',
'd' => 'domain',
'e' => 'enum',
'p' => 'pseudo',
'r' => 'range',
'm' => 'multirange',
default => null,
},
'category' => match (strtolower($result->category)) {
'a' => 'array',
'b' => 'boolean',
'c' => 'composite',
'd' => 'date_time',
'e' => 'enum',
'g' => 'geometric',
'i' => 'network_address',
'n' => 'numeric',
'p' => 'pseudo',
'r' => 'range',
's' => 'string',
't' => 'timespan',
'u' => 'user_defined',
'v' => 'bit_string',
'x' => 'unknown',
'z' => 'internal_use',
default => null,
},
];
}, $results);
}
/** @inheritDoc */
public function processColumns($results)
{
return array_map(function ($result) {
$result = (object) $result;
$autoincrement = $result->default !== null && str_starts_with($result->default, 'nextval(');
return [
'name' => $result->name,
'type_name' => $result->type_name,
'type' => $result->type,
'collation' => $result->collation,
'nullable' => (bool) $result->nullable,
'default' => $result->generated ? null : $result->default,
'auto_increment' => $autoincrement,
'comment' => $result->comment,
'generation' => $result->generated ? [
'type' => match ($result->generated) {
's' => 'stored',
'v' => 'virtual',
default => null,
},
'expression' => $result->default,
] : null,
];
}, $results);
}
/** @inheritDoc */
public function processIndexes($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => strtolower($result->name),
'columns' => $result->columns ? explode(',', $result->columns) : [],
'type' => strtolower($result->type),
'unique' => (bool) $result->unique,
'primary' => (bool) $result->primary,
];
}, $results);
}
/** @inheritDoc */
public function processForeignKeys($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'columns' => explode(',', $result->columns),
'foreign_schema' => $result->foreign_schema,
'foreign_table' => $result->foreign_table,
'foreign_columns' => explode(',', $result->foreign_columns),
'on_update' => match (strtolower($result->on_update)) {
'a' => 'no action',
'r' => 'restrict',
'c' => 'cascade',
'n' => 'set null',
'd' => 'set default',
default => null,
},
'on_delete' => match (strtolower($result->on_delete)) {
'a' => 'no action',
'r' => 'restrict',
'c' => 'cascade',
'n' => 'set null',
'd' => 'set default',
default => null,
},
];
}, $results);
}
}
+144
View File
@@ -0,0 +1,144 @@
<?php
namespace Illuminate\Database\Query\Processors;
use Illuminate\Database\Query\Builder;
class Processor
{
/**
* Process the results of a "select" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $results
* @return array
*/
public function processSelect(Builder $query, $results)
{
return $results;
}
/**
* Process an "insert get ID" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $sql
* @param array $values
* @param string|null $sequence
* @return int
*/
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
{
$query->getConnection()->insert($sql, $values);
$id = $query->getConnection()->getPdo()->lastInsertId($sequence);
return is_numeric($id) ? (int) $id : $id;
}
/**
* Process the results of a schemas query.
*
* @param list<array<string, mixed>> $results
* @return list<array{name: string, path: string|null, default: bool}>
*/
public function processSchemas($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'path' => $result->path ?? null, // SQLite Only...
'default' => (bool) $result->default,
];
}, $results);
}
/**
* Process the results of a tables query.
*
* @param list<array<string, mixed>> $results
* @return list<array{name: string, schema: string|null, schema_qualified_name: string, size: int|null, comment: string|null, collation: string|null, engine: string|null}>
*/
public function processTables($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'schema' => $result->schema ?? null,
'schema_qualified_name' => isset($result->schema) ? $result->schema.'.'.$result->name : $result->name,
'size' => isset($result->size) ? (int) $result->size : null,
'comment' => $result->comment ?? null, // MySQL and PostgreSQL
'collation' => $result->collation ?? null, // MySQL only
'engine' => $result->engine ?? null, // MySQL only
];
}, $results);
}
/**
* Process the results of a views query.
*
* @param list<array<string, mixed>> $results
* @return list<array{name: string, schema: string, schema_qualified_name: string, definition: string}>
*/
public function processViews($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'schema' => $result->schema ?? null,
'schema_qualified_name' => isset($result->schema) ? $result->schema.'.'.$result->name : $result->name,
'definition' => $result->definition,
];
}, $results);
}
/**
* Process the results of a types query.
*
* @param list<array<string, mixed>> $results
* @return list<array{name: string, schema: string, type: string, type: string, category: string, implicit: bool}>
*/
public function processTypes($results)
{
return $results;
}
/**
* Process the results of a columns query.
*
* @param list<array<string, mixed>> $results
* @return list<array{name: string, type: string, type_name: string, nullable: bool, default: mixed, auto_increment: bool, comment: string|null, generation: array{type: string, expression: string|null}|null}>
*/
public function processColumns($results)
{
return $results;
}
/**
* Process the results of an indexes query.
*
* @param list<array<string, mixed>> $results
* @return list<array{name: string, columns: list<string>, type: string, unique: bool, primary: bool}>
*/
public function processIndexes($results)
{
return $results;
}
/**
* Process the results of a foreign keys query.
*
* @param list<array<string, mixed>> $results
* @return list<array{name: string, columns: list<string>, foreign_schema: string, foreign_table: string, foreign_columns: list<string>, on_update: string, on_delete: string}>
*/
public function processForeignKeys($results)
{
return $results;
}
}
@@ -0,0 +1,99 @@
<?php
namespace Illuminate\Database\Query\Processors;
class SQLiteProcessor extends Processor
{
/** @inheritDoc */
public function processColumns($results, $sql = '')
{
$hasPrimaryKey = array_sum(array_column($results, 'primary')) === 1;
return array_map(function ($result) use ($hasPrimaryKey, $sql) {
$result = (object) $result;
$type = strtolower($result->type);
$safeName = preg_quote($result->name, '/');
$collation = preg_match(
'/\b'.$safeName.'\b[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:default|check|as)\s*(?:\(.*?\))?[^,]*)*collate\s+["\'`]?(\w+)/i',
$sql,
$matches
) === 1 ? strtolower($matches[1]) : null;
$isGenerated = in_array($result->extra, [2, 3]);
$expression = $isGenerated && preg_match(
'/\b'.$safeName.'\b[^,]+\s+as\s+\(((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/i',
$sql,
$matches
) === 1 ? $matches[1] : null;
return [
'name' => $result->name,
'type_name' => strtok($type, '(') ?: '',
'type' => $type,
'collation' => $collation,
'nullable' => (bool) $result->nullable,
'default' => $result->default,
'auto_increment' => $hasPrimaryKey && $result->primary && $type === 'integer',
'comment' => null,
'generation' => $isGenerated ? [
'type' => match ((int) $result->extra) {
3 => 'stored',
2 => 'virtual',
default => null,
},
'expression' => $expression,
] : null,
];
}, $results);
}
/** @inheritDoc */
public function processIndexes($results)
{
$primaryCount = 0;
$indexes = array_map(function ($result) use (&$primaryCount) {
$result = (object) $result;
if ($isPrimary = (bool) $result->primary) {
$primaryCount += 1;
}
return [
'name' => strtolower($result->name),
'columns' => $result->columns ? explode(',', $result->columns) : [],
'type' => null,
'unique' => (bool) $result->unique,
'primary' => $isPrimary,
];
}, $results);
if ($primaryCount > 1) {
$indexes = array_filter($indexes, fn ($index) => $index['name'] !== 'primary');
}
return $indexes;
}
/** @inheritDoc */
public function processForeignKeys($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => null,
'columns' => explode(',', $result->columns),
'foreign_schema' => $result->foreign_schema,
'foreign_table' => $result->foreign_table,
'foreign_columns' => explode(',', $result->foreign_columns),
'on_update' => strtolower($result->on_update),
'on_delete' => strtolower($result->on_delete),
];
}, $results);
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
namespace Illuminate\Database\Query\Processors;
use Exception;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Builder;
class SqlServerProcessor extends Processor
{
/**
* Process an "insert get ID" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $sql
* @param array $values
* @param string|null $sequence
* @return int
*/
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
{
$connection = $query->getConnection();
$connection->insert($sql, $values);
if ($connection->getConfig('odbc') === true) {
$id = $this->processInsertGetIdForOdbc($connection);
} else {
$id = $connection->getPdo()->lastInsertId();
}
return is_numeric($id) ? (int) $id : $id;
}
/**
* Process an "insert get ID" query for ODBC.
*
* @param \Illuminate\Database\Connection $connection
* @return int
*
* @throws \Exception
*/
protected function processInsertGetIdForOdbc(Connection $connection)
{
$result = $connection->selectFromWriteConnection(
'SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid'
);
if (! $result) {
throw new Exception('Unable to retrieve lastInsertID for ODBC.');
}
$row = $result[0];
return is_object($row) ? $row->insertid : $row['insertid'];
}
/** @inheritDoc */
public function processColumns($results)
{
return array_map(function ($result) {
$result = (object) $result;
$type = match ($typeName = $result->type_name) {
'binary', 'varbinary', 'char', 'varchar', 'nchar', 'nvarchar' => $result->length == -1 ? $typeName.'(max)' : $typeName."($result->length)",
'decimal', 'numeric' => $typeName."($result->precision,$result->places)",
'float', 'datetime2', 'datetimeoffset', 'time' => $typeName."($result->precision)",
default => $typeName,
};
return [
'name' => $result->name,
'type_name' => $result->type_name,
'type' => $type,
'collation' => $result->collation,
'nullable' => (bool) $result->nullable,
'default' => $result->default,
'auto_increment' => (bool) $result->autoincrement,
'comment' => $result->comment,
'generation' => $result->expression ? [
'type' => $result->persisted ? 'stored' : 'virtual',
'expression' => $result->expression,
] : null,
];
}, $results);
}
/** @inheritDoc */
public function processIndexes($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => strtolower($result->name),
'columns' => $result->columns ? explode(',', $result->columns) : [],
'type' => strtolower($result->type),
'unique' => (bool) $result->unique,
'primary' => (bool) $result->primary,
];
}, $results);
}
/** @inheritDoc */
public function processForeignKeys($results)
{
return array_map(function ($result) {
$result = (object) $result;
return [
'name' => $result->name,
'columns' => explode(',', $result->columns),
'foreign_schema' => $result->foreign_schema,
'foreign_table' => $result->foreign_table,
'foreign_columns' => explode(',', $result->foreign_columns),
'on_update' => strtolower(str_replace('_', ' ', $result->on_update)),
'on_delete' => strtolower(str_replace('_', ' ', $result->on_delete)),
];
}, $results);
}
}