table('users') * ->where('active', 1) * ->whereIn('role_id', [1, 2]) * ->orderBy('created_at', 'desc') * ->limit(20) * ->get(); * * Значения всегда уходят параметрами, имена таблиц и колонок сверяются регуляркой: * их параметром не подставить, а склеивать в SQL что попало нельзя. Каждое значение * получает своё имя параметра (p0, p1, …) — MySQL с настоящими подготовленными * выражениями не разрешает использовать один параметр дважды. */ class Builder { /** Сколько вариантов запроса держать под одним своим ключом remember() */ private const REMEMBER_VARIANTS = 50; protected Connection $db; protected string $table; /** @var array */ protected array $columns = ['*']; protected bool $distinct = false; /** @var array */ protected array $wheres = []; /** @var array */ protected array $joins = []; /** @var array */ protected array $groups = []; /** @var array */ protected array $havings = []; /** @var array */ protected array $orders = []; protected ?int $limit = null; protected ?int $offset = null; /** @var array Значения параметров */ protected array $bindings = []; /** Счётчик имён параметров */ protected int $counter = 0; /** На сколько секунд запомнить результат; null — не кэшировать (по умолчанию) */ protected ?int $rememberSeconds = null; /** Свой ключ кэша — без него ключ считается от текста запроса и параметров */ protected ?string $rememberKey = null; public function __construct(Connection $db, string $table) { $this->db = $db; $this->table = $this->name($table); } public function connection(): Connection { return $this->db; } public function from(string $table): static { $this->table = $this->name($table); return $this; } /** * Колонки выборки. Выражения (COUNT(*), a.b AS c) допускаются как есть — * их пишет разработчик, а не пользователь. */ public function select(string ...$columns): static { $this->columns = $columns === [] ? ['*'] : $columns; return $this; } public function addSelect(string $column): static { if ($this->columns === ['*']) { $this->columns = []; } $this->columns[] = $column; return $this; } public function distinct(bool $distinct = true): static { $this->distinct = $distinct; return $this; } /** * Условие. Два аргумента — равенство, три — со своим оператором. * Замыкание — скобка: ->where(function (Builder $q) { … }). */ public function where(string|Closure $column, mixed $operator = null, mixed $value = null, string $boolean = 'AND'): static { if ($column instanceof Closure) { return $this->nested($column, $boolean); } if (func_num_args() === 2) { $value = $operator; $operator = '='; } $operator = strtoupper(trim((string) $operator)); if (!in_array($operator, ['=', '<>', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE'], true)) { throw new DatabaseException('Недопустимый оператор условия: ' . $operator); } if ($value === null) { return $operator === '=' ? $this->whereNull($column, $boolean) : $this->whereNotNull($column, $boolean); } $this->wheres[] = [ 'type' => 'basic', 'sql' => $this->name($column) . ' ' . $operator . ' ' . $this->bind($value), 'boolean' => $boolean, ]; return $this; } public function orWhere(string|Closure $column, mixed $operator = null, mixed $value = null): static { if (func_num_args() === 2) { return $this->where($column, '=', $operator, 'OR'); } return $this->where($column, $operator, $value, 'OR'); } /** * @param array $values */ public function whereIn(string $column, array $values, string $boolean = 'AND', bool $not = false): static { if ($values === []) { // Пустой список: «ни одно значение не подходит» — и это не ошибка, // а нормальный результат фильтра, из которого ничего не выбрали $this->wheres[] = ['type' => 'basic', 'sql' => $not ? '1 = 1' : '1 = 0', 'boolean' => $boolean]; return $this; } $placeholders = array_map(fn (mixed $value): string => $this->bind($value), array_values($values)); $this->wheres[] = [ 'type' => 'basic', 'sql' => $this->name($column) . ($not ? ' NOT IN (' : ' IN (') . implode(', ', $placeholders) . ')', 'boolean' => $boolean, ]; return $this; } /** * @param array $values */ public function whereNotIn(string $column, array $values, string $boolean = 'AND'): static { return $this->whereIn($column, $values, $boolean, true); } public function whereNull(string $column, string $boolean = 'AND'): static { $this->wheres[] = ['type' => 'basic', 'sql' => $this->name($column) . ' IS NULL', 'boolean' => $boolean]; return $this; } public function whereNotNull(string $column, string $boolean = 'AND'): static { $this->wheres[] = ['type' => 'basic', 'sql' => $this->name($column) . ' IS NOT NULL', 'boolean' => $boolean]; return $this; } public function whereBetween(string $column, mixed $from, mixed $to, string $boolean = 'AND'): static { $this->wheres[] = [ 'type' => 'basic', 'sql' => $this->name($column) . ' BETWEEN ' . $this->bind($from) . ' AND ' . $this->bind($to), 'boolean' => $boolean, ]; return $this; } /** * Сравнение по дню, без времени: `->whereDate('created_at', '=', '2026-10-29')` * или с объектом даты. Годится и для dateTime, и для date. * * Через DATE(колонка) не делаем нарочно: функция над колонкой выключает * индекс, и «записи за сегодня» превращаются в обход всей таблицы. Вместо * этого день разворачивается в диапазон [день, следующий день) — индекс * работает, и SQL одинаковый для обеих баз. Границы — голые даты без * времени: в SQLite даты лежат текстом, и '2026-10-29' меньше, чем * '2026-10-29 00:00:00', — граница со временем потеряла бы колонки date. */ public function whereDate(string $column, string $operator, string|DateTimeInterface $date, string $boolean = 'AND'): static { $day = $date instanceof DateTimeInterface ? DateTimeImmutable::createFromInterface($date)->setTime(0, 0) : DateTimeImmutable::createFromFormat('!Y-m-d', $date); if ($day === false || (is_string($date) && $day->format('Y-m-d') !== $date)) { throw new DatabaseException('Дата для whereDate() — в виде ГГГГ-ММ-ДД: ' . (string) (is_string($date) ? $date : '')); } $column = $this->name($column); $from = $day->format('Y-m-d'); $next = $day->modify('+1 day')->format('Y-m-d'); $sql = match (trim($operator)) { '=' => $column . ' >= ' . $this->bind($from) . ' AND ' . $column . ' < ' . $this->bind($next), '<>', '!=' => '(' . $column . ' < ' . $this->bind($from) . ' OR ' . $column . ' >= ' . $this->bind($next) . ')', '<' => $column . ' < ' . $this->bind($from), '<=' => $column . ' < ' . $this->bind($next), '>' => $column . ' >= ' . $this->bind($next), '>=' => $column . ' >= ' . $this->bind($from), default => throw new DatabaseException('Недопустимый оператор для whereDate(): ' . $operator), }; $this->wheres[] = ['type' => 'basic', 'sql' => '(' . $sql . ')', 'boolean' => $boolean]; return $this; } /** * Поиск подстроки. Служебные символы LIKE экранируем: иначе «100%» в поиске * превращается в «что угодно после 100». */ public function whereLike(string $column, string $value, string $boolean = 'AND'): static { // Экранируем восклицательным знаком, а не обратным слэшем: ESCAPE '!' // пишется одинаково в SQLite и MySQL, а «\» в MySQL пришлось бы удваивать // ещё раз. Без ESCAPE поиск по «имя_файла» не нашёл бы ничего. $escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value); $this->wheres[] = [ 'type' => 'basic', 'sql' => $this->name($column) . ' LIKE ' . $this->bind('%' . $escaped . '%') . " ESCAPE '!'", 'boolean' => $boolean, ]; return $this; } /** * Готовое условие со своими параметрами — там, где построителя не хватает. * * @param array $bindings */ public function whereRaw(string $sql, array $bindings = [], string $boolean = 'AND'): static { foreach ($bindings as $key => $value) { $this->bindings[ltrim((string) $key, ':')] = $value; } $this->wheres[] = ['type' => 'raw', 'sql' => $sql, 'boolean' => $boolean]; return $this; } /** * Условие, только если значение чего-то стоит: удобно для фильтров списка. */ public function when(mixed $condition, callable $callback): static { if ($condition !== null && $condition !== '' && $condition !== false && $condition !== []) { $callback($this, $condition); } return $this; } public function join(string $table, string $first, string $operator, string $second, string $type = 'INNER'): static { $type = strtoupper($type); if (!in_array($type, ['INNER', 'LEFT', 'RIGHT'], true)) { throw new DatabaseException('Недопустимый тип соединения: ' . $type); } if (!in_array($operator, ['=', '<', '<=', '>', '>=', '<>'], true)) { throw new DatabaseException('Недопустимый оператор соединения: ' . $operator); } $this->joins[] = $type . ' JOIN ' . $this->name($table) . ' ON ' . $this->name($first) . ' ' . $operator . ' ' . $this->name($second); return $this; } public function leftJoin(string $table, string $first, string $operator, string $second): static { return $this->join($table, $first, $operator, $second, 'LEFT'); } public function groupBy(string ...$columns): static { foreach ($columns as $column) { $this->groups[] = $this->name($column); } return $this; } /** * @param array $bindings */ public function having(string $sql, array $bindings = []): static { foreach ($bindings as $key => $value) { $this->bindings[ltrim((string) $key, ':')] = $value; } $this->havings[] = $sql; return $this; } public function orderBy(string $column, string $direction = 'asc'): static { $direction = strtolower($direction) === 'desc' ? 'DESC' : 'ASC'; $this->orders[] = $this->name($column) . ' ' . $direction; return $this; } public function latest(string $column = 'created_at'): static { return $this->orderBy($column, 'desc'); } public function limit(?int $limit): static { $this->limit = $limit === null ? null : max(0, $limit); return $this; } public function offset(int $offset): static { $this->offset = max(0, $offset); return $this; } /** * Не бить в базу заново, если результат уже есть в кэше (`Support\Cache`): * справочники и тяжёлые сводки незачем считать на каждый показ страницы. * * $roles = Role::query()->remember(300)->get(); * * Без своего `$key` ключ считается от текста запроса и его параметров — * поэтому один и тот же вызов с разными where() не путается сам с собой. * Свой ключ имеет смысл, когда его потом сбрасывают явно: `Cache::forget()` * после изменения данных, из которых результат считался. * * Кэшируются только `get()`, `count()`, `sum()`, `max()` — и то, что вызывает * их внутри (`first()`, `value()`, `pluck()`, `exists()`). Подгрузка связей * через `with()` идёт отдельными запросами и под эту кэш не попадает. * * В самом кэше ключ лежит с суффиксом метода — `query::get`, * `query::count:колонка` и т.д., иначе `get()` и `count()` одного * запроса стали бы одной записью в кэше. Сбрасывая свой ключ вручную, * суффикс нужно дописать тем же способом. Под своим ключом живут все * варианты запроса (страницы paginate(), first() рядом с get()) — forget() * сбрасывает их разом. */ public function remember(int $seconds, ?string $key = null): static { $this->rememberSeconds = $seconds; $this->rememberKey = $key; return $this; } /** * Строки запроса. * * @return array> */ public function get(): array { return $this->cached('get', fn (): array => $this->db->select($this->toSql(), $this->bindings)); } /** * Первая строка или null. * * Тип возврата шире, чем массив: наследник для моделей отдаёт отсюда объект, * а сузить объявленный ?array он бы не смог. * * @return array|object|null */ public function first(): array|object|null { $limit = $this->limit; $this->limit(1); $rows = $this->get(); $this->limit = $limit; return $rows[0] ?? null; } /** * Одно значение первой строки. */ public function value(string $column): mixed { $row = (clone $this)->select($column)->first(); if ($row === null) { return null; } return reset($row); } /** * Плоский список значений колонки, при желании с ключами. * * @return array */ public function pluck(string $column, ?string $key = null): array { $query = clone $this; $rows = $key === null ? $query->select($column)->get() : $query->select($key, $column)->get(); $result = []; foreach ($rows as $row) { $short = $this->shortName($column); if ($key === null) { $result[] = $row[$short] ?? null; continue; } $result[(string) ($row[$this->shortName($key)] ?? '')] = $row[$short] ?? null; } return $result; } public function count(string $column = '*'): int { $query = clone $this; $query->orders = []; $sql = $query->select('COUNT(' . ($column === '*' ? '*' : $this->name($column)) . ') AS aggregate')->toSql(); return (int) $this->cached('count:' . $column, fn (): mixed => $query->db->value($sql, $query->bindings)); } public function sum(string $column): float { $query = clone $this; $query->orders = []; $sql = $query->select('SUM(' . $this->name($column) . ') AS aggregate')->toSql(); return (float) $this->cached('sum:' . $column, fn (): mixed => $query->db->value($sql, $query->bindings)); } public function max(string $column): mixed { $query = clone $this; $query->orders = []; $sql = $query->select('MAX(' . $this->name($column) . ') AS aggregate')->toSql(); return $this->cached('max:' . $column, fn (): mixed => $query->db->value($sql, $query->bindings)); } public function exists(): bool { return (clone $this)->limit(1)->first() !== null; } /** * Страница результатов вместе со счётчиком — для списков в панели. * * @return array{items: array>, total: int, page: int, pages: int, per_page: int} */ public function paginate(int $page = 1, int $perPage = 30): array { $total = $this->count(); $pages = max(1, (int) ceil($total / max(1, $perPage))); $page = max(1, min($page, $pages)); $items = (clone $this)->limit($perPage)->offset(($page - 1) * $perPage)->get(); return [ 'items' => $items, 'total' => $total, 'page' => $page, 'pages' => $pages, 'per_page' => $perPage, ]; } /** * Обходит таблицу порциями — чтобы не поднимать в память миллион строк. * Замыкание вернуло false — обход прекращается. * * Каждая порция — свой запрос (LIMIT/OFFSET): если строки внутри колбэка * удаляются или переставляют сортировку, часть записей может уйти между * страницами незамеченной. Для разового скрипта или консольной команды * это не страшно; там, где меняются как раз обходимые строки, надёжнее * условие по возрастающему id в собственном where(), как у RebuildNoteSlugsJob. * * @param callable(array>): (bool|void) $callback */ public function chunk(int $size, callable $callback): void { $page = 1; do { $rows = (clone $this)->limit($size)->offset(($page - 1) * $size)->get(); if ($rows === []) { return; } if ($callback($rows) === false) { return; } $page++; } while (count($rows) === $size); } /** * То же самое, но одной строкой за раз вместо порций в памяти — для * действительно больших таблиц, которые целиком в память не влезут. * Одна выборка одним запросом, а не постраничные LIMIT/OFFSET: значит, * и от той же нестабильности при изменении строк во время обхода, что * и у chunk(), это тоже не защищает. * * @return Generator> */ public function cursor(): Generator { yield from $this->db->cursor($this->toSql(), $this->bindings); } /** * Вставка. Возвращает id новой записи. * * @param array $data */ public function insert(array $data): int { return $this->db->insert($this->table, $data); } /** * Вставить или обновить: строка с тем же уникальным ключом уже есть — * перезаписываются колонки $update, нет — вставляется новая. Одним * запросом, без гонки «проверил — вставил» между двумя процессами. * * $db->table('counters')->upsert(['name' => 'visits', 'value' => 5], ['name']); * $db->table('rates')->upsert([$row1, $row2], ['pair', 'day'], ['rate']); * * $uniqueBy — колонки, по которым строка считается той же самой. По ним * в таблице обязан быть PRIMARY KEY или UNIQUE: SQLite без него запрос не * примет, а MySQL смотрит не на $uniqueBy, а на любой уникальный ключ * таблицы. $update по умолчанию — все колонки, кроме $uniqueBy; пустой * список — «есть, так не трогать». * * Новое значение берётся из самой вставляемой строки (excluded.* в SQLite, * VALUES() в MySQL), поэтому каждый параметр встречается в запросе один раз. * VALUES() в MySQL 8.0.20+ объявлен устаревшим, но работает, а синтаксис * с псевдонимом строки не знают MySQL до 8.0.19 и MariaDB. * * Возвращает число затронутых строк, и считают его базы по-разному (MySQL * за обновление даёт 2, за неизменившуюся строку — 0) — полагаться на * него, чтобы отличить вставку от обновления, нельзя. * * @param array|array> $values * @param array $uniqueBy * @param array|null $update */ public function upsert(array $values, array $uniqueBy, ?array $update = null): int { if ($values === []) { return 0; } $rows = array_is_list($values) ? $values : [$values]; $columns = array_map(fn (string $column): string => $this->name($column), array_keys($rows[0])); if ($uniqueBy === [] || array_diff($uniqueBy, $columns) !== []) { throw new DatabaseException('upsert(): колонки ключа должны быть среди вставляемых'); } $update ??= array_values(array_diff($columns, $uniqueBy)); // Параметры свои, а не накопленные построителем: условия where() к вставке // отношения не имеют, а лишний параметр MySQL без эмуляции не примет $params = []; $tuples = []; foreach ($rows as $row) { if (array_keys($row) !== array_keys($rows[0])) { throw new DatabaseException('upsert(): у всех строк должны быть одни и те же колонки в одном порядке'); } $placeholders = []; foreach (array_values($row) as $value) { $name = 'u' . count($params); $params[$name] = $value; $placeholders[] = ':' . $name; } $tuples[] = '(' . implode(', ', $placeholders) . ')'; } $sql = 'INSERT INTO ' . $this->table . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $tuples); if ($this->db->isSqlite()) { $set = array_map(fn (string $column): string => $this->name($column) . ' = excluded.' . $this->name($column), $update); $sql .= ' ON CONFLICT (' . implode(', ', array_map($this->name(...), $uniqueBy)) . ')' . ($set === [] ? ' DO NOTHING' : ' DO UPDATE SET ' . implode(', ', $set)); } else { $set = array_map(fn (string $column): string => $this->name($column) . ' = VALUES(' . $this->name($column) . ')', $update); // Обновлять нечего — присваиваем ключ самому себе: так MySQL // молча пропускает дубль, не превращая его в ошибку, как INSERT IGNORE // превратил бы в тишину и все прочие ошибки строки $sql .= ' ON DUPLICATE KEY UPDATE ' . ($set === [] ? $this->name($uniqueBy[0]) . ' = ' . $this->name($uniqueBy[0]) : implode(', ', $set)); } return $this->db->execute($sql, $params); } /** * Обновление по накопленным условиям. * * @param array $data */ public function update(array $data): int { if ($data === []) { return 0; } $set = []; foreach ($data as $column => $value) { $set[] = $this->name($column) . ' = ' . $this->bind($value, 'set'); } $sql = 'UPDATE ' . $this->table . ' SET ' . implode(', ', $set) . $this->whereSql(); return $this->db->execute($sql, $this->bindings); } /** * Увеличить числовую колонку — счётчики просмотров и попыток. */ public function increment(string $column, int $amount = 1): int { $column = $this->name($column); return $this->db->execute( 'UPDATE ' . $this->table . ' SET ' . $column . ' = ' . $column . ' + ' . (int) $amount . $this->whereSql(), $this->bindings ); } /** * Удаление по накопленным условиям. Без условий удалять отказываемся: * «снести всю таблицу» должно писаться явно, а не получаться по забывчивости. */ public function delete(): int { if ($this->wheres === []) { throw new DatabaseException('Удаление без условий запрещено: добавьте where() или зовите truncate()'); } return $this->db->execute('DELETE FROM ' . $this->table . $this->whereSql(), $this->bindings); } /** * Собранный SQL — пригождается в отладке и тестах. */ public function toSql(): string { $sql = 'SELECT ' . ($this->distinct ? 'DISTINCT ' : '') . implode(', ', $this->columns) . ' FROM ' . $this->table; if ($this->joins !== []) { $sql .= ' ' . implode(' ', $this->joins); } $sql .= $this->whereSql(); if ($this->groups !== []) { $sql .= ' GROUP BY ' . implode(', ', $this->groups); } if ($this->havings !== []) { $sql .= ' HAVING ' . implode(' AND ', $this->havings); } if ($this->orders !== []) { $sql .= ' ORDER BY ' . implode(', ', $this->orders); } if ($this->limit !== null) { $sql .= ' LIMIT ' . $this->limit; } if ($this->offset !== null && $this->offset > 0) { // В обеих базах OFFSET без LIMIT не работает — подставляем предел сами $sql .= ($this->limit === null ? ' LIMIT 18446744073709551615' : '') . ' OFFSET ' . $this->offset; } return $sql; } /** * Значения параметров запроса. * * @return array */ public function bindings(): array { return $this->bindings; } protected function whereSql(): string { if ($this->wheres === []) { return ''; } $sql = ''; foreach ($this->wheres as $index => $where) { $sql .= ($index === 0 ? '' : ' ' . $where['boolean'] . ' ') . $where['sql']; } return ' WHERE ' . $sql; } /** * Скобка из замыкания: ->where(function (Builder $q) { $q->where(…)->orWhere(…); }). */ protected function nested(Closure $callback, string $boolean): static { $nested = new self($this->db, $this->table); // Счётчик общий, иначе имена параметров во вложенной части столкнутся с нашими $nested->counter = $this->counter; $callback($nested); $this->counter = $nested->counter; if ($nested->wheres === []) { return $this; } $this->bindings = array_merge($this->bindings, $nested->bindings); $this->wheres[] = [ 'type' => 'nested', 'sql' => '(' . substr($nested->whereSql(), 7) . ')', 'boolean' => $boolean, ]; return $this; } /** * Без remember() — просто зовёт $factory. С ним — заглядывает в кэш сперва. * * @template T * * @param callable(): T $factory * * @return T */ private function cached(string $suffix, callable $factory): mixed { if ($this->rememberSeconds === null) { return $factory(); } // Отпечаток самого запроса — по $this в его текущем состоянии, то есть // с limit/offset: страницы одного запроса — разные записи $variant = md5($this->toSql() . serialize($this->bindings)); $seconds = max(1, $this->rememberSeconds); // Значение лежит обёрнутым: пустой ответ (first() без строк) иначе // не отличить от промаха, и он шёл бы в базу каждый раз if ($this->rememberKey === null) { $key = 'query:' . $variant . ':' . $suffix; $hit = Cache::get($key); if (is_array($hit) && array_key_exists('v', $hit)) { return $hit['v']; } $value = $factory(); Cache::put($key, ['v' => $value], $seconds); return $value; } // Свой ключ — одна запись на все варианты запроса под ним. Раньше ключ // не учитывал сам запрос, и paginate() отдавал первую страницу на любой // номер. Теперь варианты лежат словарём внутри записи, а Cache::forget() // по ключу (как и прежде, 'query::get') сбрасывает их все разом $key = 'query:' . $this->rememberKey . ':' . $suffix; $map = Cache::get($key); $map = is_array($map) ? $map : []; $hit = $map[$variant] ?? null; if (is_array($hit) && array_key_exists('v', $hit) && (int) ($hit['until'] ?? 0) >= time()) { return $hit['v']; } $value = $factory(); unset($map[$variant]); $map[$variant] = ['v' => $value, 'until' => time() + $seconds]; // Страниц у большого списка много — держим последние, а не все подряд if (count($map) > self::REMEMBER_VARIANTS) { $map = array_slice($map, -self::REMEMBER_VARIANTS, null, true); } Cache::put($key, $map, $seconds); return $value; } /** * Кладёт значение в параметры и возвращает его имя для SQL. */ protected function bind(mixed $value, string $prefix = 'p'): string { $name = $prefix . $this->counter++; $this->bindings[$name] = $value; return ':' . $name; } /** * Имя таблицы или колонки. Разрешаем «таблица.колонка» и звёздочку — * всё остальное отвергаем: подставлять в SQL непонятно что нельзя. */ protected function name(string $name): string { $name = trim($name); if (preg_match('/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*|\.\*)?$/', $name) !== 1) { throw new DatabaseException('Недопустимое имя таблицы или колонки: ' . $name); } return $name; } /** * Имя колонки без таблицы: строки из базы приходят с короткими ключами. */ protected function shortName(string $column): string { $dot = strrpos($column, '.'); return $dot === false ? $column : substr($column, $dot + 1); } }