3
declare(strict_types=1);
6
* This file is part of CodeIgniter 4 framework.
8
* (c) CodeIgniter Foundation <admin@codeigniter.com>
10
* For the full copyright and license information, please view
11
* the LICENSE file that was distributed with this source code.
14
namespace CodeIgniter\Database\Postgre;
16
use CodeIgniter\Database\BaseBuilder;
17
use CodeIgniter\Database\Exceptions\DatabaseException;
18
use CodeIgniter\Database\RawSql;
19
use InvalidArgumentException;
24
class Builder extends BaseBuilder
27
* ORDER BY random keyword
31
protected $randomKeyword = [
36
* Specifies which sql statements
37
* support the ignore option.
41
protected $supportedIgnoreStatements = [
42
'insert' => 'ON CONFLICT DO NOTHING',
46
* Checks if the ignore option is supported by
47
* the Database Driver for the specific statement.
51
protected function compileIgnore(string $statement)
53
$sql = parent::compileIgnore($statement);
56
$sql = ' ' . trim($sql);
65
* @param string $direction ASC, DESC or RANDOM
69
public function orderBy(string $orderBy, string $direction = '', ?bool $escape = null)
71
$direction = strtoupper(trim($direction));
72
if ($direction === 'RANDOM') {
73
if (ctype_digit($orderBy)) {
74
$orderBy = (float) ($orderBy > 1 ? "0.{$orderBy}" : $orderBy);
77
if (is_float($orderBy)) {
78
$this->db->simpleQuery("SET SEED {$orderBy}");
81
$orderBy = $this->randomKeyword[0];
86
return parent::orderBy($orderBy, $direction, $escape);
90
* Increments a numeric column by the specified value.
94
* @throws DatabaseException
96
public function increment(string $column, int $value = 1)
98
$column = $this->db->protectIdentifiers($column);
100
$sql = $this->_update($this->QBFrom[0], [$column => "to_number({$column}, '9999999') + {$value}"]);
102
if (! $this->testMode) {
105
return $this->db->query($sql, $this->binds, false);
112
* Decrements a numeric column by the specified value.
116
* @throws DatabaseException
118
public function decrement(string $column, int $value = 1)
120
$column = $this->db->protectIdentifiers($column);
122
$sql = $this->_update($this->QBFrom[0], [$column => "to_number({$column}, '9999999') - {$value}"]);
124
if (! $this->testMode) {
127
return $this->db->query($sql, $this->binds, false);
134
* Compiles an replace into string and runs the query.
135
* Because PostgreSQL doesn't support the replace into command,
136
* we simply do a DELETE and an INSERT on the first key/value
137
* combo, assuming that it's either the primary key or a unique key.
139
* @param array|null $set An associative array of insert values
143
* @throws DatabaseException
145
public function replace(?array $set = null)
151
if ($this->QBSet === []) {
152
if ($this->db->DBDebug) {
153
throw new DatabaseException('You must use the "set" method to update an entry.');
156
return false; // @codeCoverageIgnore
159
$table = $this->QBFrom[0];
162
array_walk($set, static function (array &$item): void {
166
$key = array_key_first($set);
169
$builder = $this->db->table($table);
170
$exists = $builder->where($key, $value, true)->get()->getFirstRow();
172
if (empty($exists) && $this->testMode) {
173
$result = $this->getCompiledInsert();
174
} elseif (empty($exists)) {
175
$result = $builder->insert($set);
176
} elseif ($this->testMode) {
177
$result = $this->where($key, $value, true)->getCompiledUpdate();
180
$result = $builder->where($key, $value, true)->update($set);
191
* Generates a platform-specific insert string from the supplied data
193
protected function _insert(string $table, array $keys, array $unescapedKeys): string
195
return trim(sprintf('INSERT INTO %s (%s) VALUES (%s) %s', $table, implode(', ', $keys), implode(', ', $unescapedKeys), $this->compileIgnore('insert')));
199
* Generates a platform-specific insert string from the supplied data.
201
protected function _insertBatch(string $table, array $keys, array $values): string
203
$sql = $this->QBOptions['sql'] ?? '';
205
// if this is the first iteration of batch then we need to build skeleton sql
207
$sql = 'INSERT INTO ' . $table . '(' . implode(', ', $keys) . ")\n{:_table_:}\n";
209
$sql .= $this->compileIgnore('insert');
211
$this->QBOptions['sql'] = $sql;
214
if (isset($this->QBOptions['setQueryAsData'])) {
215
$data = $this->QBOptions['setQueryAsData'];
217
$data = 'VALUES ' . implode(', ', $this->formatValues($values));
220
return str_replace('{:_table_:}', $data, $sql);
224
* Compiles a delete string and runs the query
226
* @param mixed $where
230
* @throws DatabaseException
232
public function delete($where = '', ?int $limit = null, bool $resetData = true)
234
if ($limit !== null && $limit !== 0 || ! empty($this->QBLimit)) {
235
throw new DatabaseException('PostgreSQL does not allow LIMITs on DELETE queries.');
238
return parent::delete($where, $limit, $resetData);
242
* Generates a platform-specific LIMIT clause.
244
protected function _limit(string $sql, bool $offsetIgnore = false): string
246
return $sql . ' LIMIT ' . $this->QBLimit . ($this->QBOffset ? " OFFSET {$this->QBOffset}" : '');
250
* Generates a platform-specific update string from the supplied data
252
* @throws DatabaseException
254
protected function _update(string $table, array $values): string
256
if (! empty($this->QBLimit)) {
257
throw new DatabaseException('Postgres does not support LIMITs with UPDATE queries.');
260
$this->QBOrderBy = [];
262
return parent::_update($table, $values);
266
* Generates a platform-specific delete string from the supplied data
268
protected function _delete(string $table): string
270
$this->QBLimit = false;
272
return parent::_delete($table);
276
* Generates a platform-specific truncate string from the supplied data
278
* If the database does not support the truncate() command,
279
* then this method maps to 'DELETE FROM table'
281
protected function _truncate(string $table): string
283
return 'TRUNCATE ' . $table . ' RESTART IDENTITY';
287
* Platform independent LIKE statement builder.
289
* In PostgreSQL, the ILIKE operator will perform case insensitive
290
* searches according to the current locale.
292
* @see https://www.postgresql.org/docs/9.2/static/functions-matching.html
294
protected function _like_statement(?string $prefix, string $column, ?string $not, string $bind, bool $insensitiveSearch = false): string
296
$op = $insensitiveSearch === true ? 'ILIKE' : 'LIKE';
298
return "{$prefix} {$column} {$not} {$op} :{$bind}:";
302
* Generates the JOIN portion of the query
304
* @param RawSql|string $cond
306
* @return BaseBuilder
308
public function join(string $table, $cond, string $type = '', ?bool $escape = null)
310
if (! in_array('FULL OUTER', $this->joinTypes, true)) {
311
$this->joinTypes = array_merge($this->joinTypes, ['FULL OUTER']);
314
return parent::join($table, $cond, $type, $escape);
318
* Generates a platform-specific batch update string from the supplied data
320
* @used-by batchExecute()
322
* @param string $table Protected table name
323
* @param list<string> $keys QBKeys
324
* @param list<list<int|string>> $values QBSet
326
protected function _updateBatch(string $table, array $keys, array $values): string
328
$sql = $this->QBOptions['sql'] ?? '';
330
// if this is the first iteration of batch then we need to build skeleton sql
332
$constraints = $this->QBOptions['constraints'] ?? [];
334
if ($constraints === []) {
335
if ($this->db->DBDebug) {
336
throw new DatabaseException('You must specify a constraint to match on for batch updates.'); // @codeCoverageIgnore
339
return ''; // @codeCoverageIgnore
342
$updateFields = $this->QBOptions['updateFields'] ??
343
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
346
$alias = $this->QBOptions['alias'] ?? '_u';
348
$sql = 'UPDATE ' . $this->compileIgnore('update') . $table . "\n";
356
static fn ($key, $value) => $key . ($value instanceof RawSql ?
358
' = ' . $that->cast($alias . '.' . $value, $that->getFieldType($table, $key))),
359
array_keys($updateFields),
364
$sql .= "FROM (\n{:_table_:}";
366
$sql .= ') ' . $alias . "\n";
368
$sql .= 'WHERE ' . implode(
371
static function ($key, $value) use ($table, $alias, $that) {
372
if ($value instanceof RawSql && is_string($key)) {
373
return $table . '.' . $key . ' = ' . $value;
376
if ($value instanceof RawSql) {
380
return $table . '.' . $value . ' = '
381
. $that->cast($alias . '.' . $value, $that->getFieldType($table, $value));
383
array_keys($constraints),
388
$this->QBOptions['sql'] = $sql;
391
if (isset($this->QBOptions['setQueryAsData'])) {
392
$data = $this->QBOptions['setQueryAsData'];
397
static fn ($value) => 'SELECT ' . implode(', ', array_map(
398
static fn ($key, $index) => $index . ' ' . $key,
407
return str_replace('{:_table_:}', $data, $sql);
411
* Returns cast expression.
413
* @TODO move this to BaseBuilder in 4.5.0
415
private function cast(string $expression, ?string $type): string
417
return ($type === null) ? $expression : 'CAST(' . $expression . ' AS ' . strtoupper($type) . ')';
421
* Returns the filed type from database meta data.
423
* @param string $table Protected table name.
424
* @param string $fieldName Field name. May be protected.
426
private function getFieldType(string $table, string $fieldName): ?string
428
$fieldName = trim($fieldName, $this->db->escapeChar);
430
if (! isset($this->QBOptions['fieldTypes'][$table])) {
431
$this->QBOptions['fieldTypes'][$table] = [];
433
foreach ($this->db->getFieldData($table) as $field) {
434
$type = $field->type;
436
// If `character` (or `char`) lacks a specifier, it is equivalent
437
// to `character(1)`.
438
// See https://www.postgresql.org/docs/current/datatype-character.html
439
if ($field->type === 'character') {
440
$type = $field->type . '(' . $field->max_length . ')';
443
$this->QBOptions['fieldTypes'][$table][$field->name] = $type;
447
return $this->QBOptions['fieldTypes'][$table][$fieldName] ?? null;
451
* Generates a platform-specific upsertBatch string from the supplied data
453
* @throws DatabaseException
455
protected function _upsertBatch(string $table, array $keys, array $values): string
457
$sql = $this->QBOptions['sql'] ?? '';
459
// if this is the first iteration of batch then we need to build skeleton sql
461
$fieldNames = array_map(static fn ($columnName) => trim($columnName, '"'), $keys);
463
$constraints = $this->QBOptions['constraints'] ?? [];
465
if (empty($constraints)) {
466
$allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames) {
467
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
469
return ($index->type === 'UNIQUE' || $index->type === 'PRIMARY') && $hasAllFields;
472
foreach (array_map(static fn ($index) => $index->fields, $allIndexes) as $index) {
473
$constraints[] = current($index);
474
// only one index can be used?
478
$constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? [];
481
if (empty($constraints)) {
482
if ($this->db->DBDebug) {
483
throw new DatabaseException('No constraint found for upsert.');
486
return ''; // @codeCoverageIgnore
489
// in value set - replace null with DEFAULT where constraint is presumed not null
490
// autoincrement identity field must use DEFAULT and not NULL
491
// this could be removed in favour of leaving to developer but does make things easier and function like other DBMS
492
foreach ($constraints as $constraint) {
493
$key = array_search(trim((string) $constraint, '"'), $fieldNames, true);
495
if ($key !== false) {
496
foreach ($values as $arrayKey => $value) {
497
if (strtoupper((string) $value[$key]) === 'NULL') {
498
$values[$arrayKey][$key] = 'DEFAULT';
504
$alias = $this->QBOptions['alias'] ?? '"excluded"';
506
if (strtolower($alias) !== '"excluded"') {
507
throw new InvalidArgumentException('Postgres alias is always named "excluded". A custom alias cannot be used.');
510
$updateFields = $this->QBOptions['updateFields'] ?? $this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ?? [];
512
$sql = 'INSERT INTO ' . $table . ' (';
514
$sql .= implode(', ', $keys);
518
$sql .= '{:_table_:}';
520
$sql .= 'ON CONFLICT(' . implode(',', $constraints) . ")\n";
522
$sql .= "DO UPDATE SET\n";
527
static fn ($key, $value) => $key . ($value instanceof RawSql ?
529
" = {$alias}.{$value}"),
530
array_keys($updateFields),
535
$this->QBOptions['sql'] = $sql;
538
if (isset($this->QBOptions['setQueryAsData'])) {
539
$data = $this->QBOptions['setQueryAsData'];
541
$data = 'VALUES ' . implode(', ', $this->formatValues($values)) . "\n";
544
return str_replace('{:_table_:}', $data, $sql);
548
* Generates a platform-specific batch update string from the supplied data
550
protected function _deleteBatch(string $table, array $keys, array $values): string
552
$sql = $this->QBOptions['sql'] ?? '';
554
// if this is the first iteration of batch then we need to build skeleton sql
556
$constraints = $this->QBOptions['constraints'] ?? [];
558
if ($constraints === []) {
559
if ($this->db->DBDebug) {
560
throw new DatabaseException('You must specify a constraint to match on for batch deletes.'); // @codeCoverageIgnore
563
return ''; // @codeCoverageIgnore
566
$alias = $this->QBOptions['alias'] ?? '_u';
568
$sql = 'DELETE FROM ' . $table . "\n";
570
$sql .= "USING (\n{:_table_:}";
572
$sql .= ') ' . $alias . "\n";
575
$sql .= 'WHERE ' . implode(
578
static function ($key, $value) use ($table, $alias, $that) {
579
if ($value instanceof RawSql) {
583
if (is_string($key)) {
584
return $table . '.' . $key . ' = '
586
$alias . '.' . $value,
587
$that->getFieldType($table, $key)
591
return $table . '.' . $value . ' = ' . $alias . '.' . $value;
593
array_keys($constraints),
598
// convert binds in where
599
foreach ($this->QBWhere as $key => $where) {
600
foreach ($this->binds as $field => $bind) {
601
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
605
$sql .= ' ' . str_replace(
608
$this->compileWhereHaving('QBWhere')
611
$this->QBOptions['sql'] = $sql;
614
if (isset($this->QBOptions['setQueryAsData'])) {
615
$data = $this->QBOptions['setQueryAsData'];
620
static fn ($value) => 'SELECT ' . implode(', ', array_map(
621
static fn ($key, $index) => $index . ' ' . $key,
630
return str_replace('{:_table_:}', $data, $sql);