Passed
Pull Request — master (#684)
by Def
02:13
created

AbstractCommand::logQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Command;
6
7
use Closure;
8
use Throwable;
9
use Yiisoft\Db\Exception\Exception;
10
use Yiisoft\Db\Expression\Expression;
11
use Yiisoft\Db\Query\Data\DataReaderInterface;
12
use Yiisoft\Db\Query\QueryInterface;
13
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
14
15
use function current;
16
use function explode;
17
use function get_resource_type;
18
use function is_array;
19
use function is_bool;
20
use function is_int;
21
use function is_object;
22
use function is_resource;
23
use function is_scalar;
24
use function is_string;
25
use function preg_replace_callback;
26
use function stream_get_contents;
27
use function strncmp;
28
29
/**
30
 * Represents an SQL statement to execute in a database.
31
 *
32
 * It's usually created by calling {@see \Yiisoft\Db\Connection\ConnectionInterface::createCommand()}.
33
 *
34
 * You can get the SQL statement it represents via the {@see getSql()} method.
35
 *
36
 * To execute a non-query SQL (such as `INSERT`, `DELETE`, `UPDATE`), call {@see execute()}.
37
 *
38
 * To execute a SQL statement that returns a result (such as `SELECT`), use {@see queryAll()}, {@see queryOne()},
39
 * {@see queryColumn()}, {@see queryScalar()}, or {@see query()}.
40
 *
41
 * For example,
42
 *
43
 * ```php
44
 * $users = $connectionInterface->createCommand('SELECT * FROM user')->queryAll();
45
 * ```
46
 *
47
 * Abstract command supports SQL prepared statements and parameter binding.
48
 *
49
 * Call {@see bindValue()} to bind a value to a SQL parameter.
50
 * Call {@see bindParam()} to bind a PHP variable to a SQL parameter.
51
 *
52
 * When binding a parameter, the SQL statement is automatically prepared. You may also call {@see prepare()} explicitly
53
 * to do it.
54
 *
55
 * Abstract command supports building some SQL statements using methods such as {@see insert()}, {@see update()}, {@see delete()},
56
 * etc.
57
 *
58
 * For example, the following code will create and execute an `INSERT` SQL statement:
59
 *
60
 * ```php
61
 * $connectionInterface->createCommand()->insert(
62
 *     'user',
63
 *     ['name' => 'Sam', 'age' => 30],
64
 * )->execute();
65
 * ```
66
 *
67
 * To build `SELECT` SQL statements, please use {@see QueryInterface} and its implementations instead.
68
 */
69
abstract class AbstractCommand implements CommandInterface
70
{
71
    /**
72
     * Command in this query mode returns count of affected rows.
73
     *
74
     * @see execute()
75
     */
76
    protected const QUERY_MODE_EXECUTE = 1;
77
    /**
78
     * Command in this query mode returns the first row of selected data.
79
     *
80
     * @see queryOne()
81
     */
82
    protected const QUERY_MODE_ROW = 2;
83
    /**
84
     * Command in this query mode returns all rows of selected data.
85
     *
86
     * @see queryAll()
87
     */
88
    protected const QUERY_MODE_ALL = 4;
89
    /**
90
     * Command in this query mode returns all rows with the first column of selected data.
91
     *
92
     * @see queryColumn()
93
     */
94
    protected const QUERY_MODE_COLUMN = 8;
95
    /**
96
     * Command in this query mode returns {@see DataReaderInterface}, an abstraction for database cursor for
97
     * selected data.
98
     *
99
     * @see query()
100
     */
101
    protected const QUERY_MODE_CURSOR = 16;
102
    /**
103
     * Command in this query mode returns the first column in the first row of the query result
104
     *
105
     * @see queryScalar()
106
     */
107
    protected const QUERY_MODE_SCALAR = 32;
108
109
    /**
110
     * @var string|null Transaction isolation level.
111
     */
112
    protected string|null $isolationLevel = null;
113
    /**
114
     * @var array Parameters to use.
115
     *
116
     * @psalm-var ParamInterface[]
117
     */
118
    protected array $params = [];
119
    /**
120
     * @var string|null Name of the table to refresh schema for. Null means not to refresh the schema.
121
     */
122
    protected string|null $refreshTableName = null;
123
    protected Closure|null $retryHandler = null;
124
    /**
125
     * @var string The SQL statement to execute.
126
     */
127
    private string $sql = '';
128
129
    public function addCheck(string $table, string $name, string $expression): static
130
    {
131
        $sql = $this->getQueryBuilder()->addCheck($table, $name, $expression);
132
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
133
    }
134
135
    public function addColumn(string $table, string $column, string $type): static
136
    {
137
        $sql = $this->getQueryBuilder()->addColumn($table, $column, $type);
138
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
139
    }
140
141
    public function addCommentOnColumn(string $table, string $column, string $comment): static
142
    {
143
        $sql = $this->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
144
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
145
    }
146
147
    public function addCommentOnTable(string $table, string $comment): static
148
    {
149
        $sql = $this->getQueryBuilder()->addCommentOnTable($table, $comment);
150
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
151
    }
152
153
    public function addDefaultValue(string $table, string $name, string $column, mixed $value): static
154
    {
155
        $sql = $this->getQueryBuilder()->addDefaultValue($table, $name, $column, $value);
156
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
157
    }
158
159
    public function addForeignKey(
160
        string $table,
161
        string $name,
162
        array|string $columns,
163
        string $referenceTable,
164
        array|string $referenceColumns,
165
        string $delete = null,
166
        string $update = null
167
    ): static {
168
        $sql = $this->getQueryBuilder()->addForeignKey(
169
            $table,
170
            $name,
171
            $columns,
172
            $referenceTable,
173
            $referenceColumns,
174
            $delete,
175
            $update
176
        );
177
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
178
    }
179
180
    public function addPrimaryKey(string $table, string $name, array|string $columns): static
181
    {
182
        $sql = $this->getQueryBuilder()->addPrimaryKey($table, $name, $columns);
183
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
184
    }
185
186
    public function addUnique(string $table, string $name, array|string $columns): static
187
    {
188
        $sql = $this->getQueryBuilder()->addUnique($table, $name, $columns);
189
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
190
    }
191
192
    public function alterColumn(string $table, string $column, string $type): static
193
    {
194
        $sql = $this->getQueryBuilder()->alterColumn($table, $column, $type);
195
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
196
    }
197
198
    public function batchInsert(string $table, array $columns, iterable $rows): static
199
    {
200
        $table = $this->getQueryBuilder()->quoter()->quoteSql($table);
201
202
        /** @psalm-var string[] $columns */
203
        foreach ($columns as &$column) {
204
            $column = $this->getQueryBuilder()->quoter()->quoteSql($column);
205
        }
206
207
        unset($column);
208
209
        $params = [];
210
        $sql = $this->getQueryBuilder()->batchInsert($table, $columns, $rows, $params);
211
212
        $this->setRawSql($sql);
213
        $this->bindValues($params);
214
215
        return $this;
216
    }
217
218
    abstract public function bindValue(int|string $name, mixed $value, int $dataType = null): static;
219
220
    abstract public function bindValues(array $values): static;
221
222
    public function checkIntegrity(string $schema, string $table, bool $check = true): static
223
    {
224
        $sql = $this->getQueryBuilder()->checkIntegrity($schema, $table, $check);
225
        return $this->setSql($sql);
226
    }
227
228
    public function createIndex(
229
        string $table,
230
        string $name,
231
        array|string $columns,
232
        string $indexType = null,
233
        string $indexMethod = null
234
    ): static {
235
        $sql = $this->getQueryBuilder()->createIndex($table, $name, $columns, $indexType, $indexMethod);
236
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
237
    }
238
239
    public function createTable(string $table, array $columns, string $options = null): static
240
    {
241
        $sql = $this->getQueryBuilder()->createTable($table, $columns, $options);
242
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
243
    }
244
245
    public function createView(string $viewName, QueryInterface|string $subQuery): static
246
    {
247
        $sql = $this->getQueryBuilder()->createView($viewName, $subQuery);
248
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
249
    }
250
251
    public function delete(string $table, array|string $condition = '', array $params = []): static
252
    {
253
        $sql = $this->getQueryBuilder()->delete($table, $condition, $params);
254
        return $this->setSql($sql)->bindValues($params);
255
    }
256
257
    public function dropCheck(string $table, string $name): static
258
    {
259
        $sql = $this->getQueryBuilder()->dropCheck($table, $name);
260
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
261
    }
262
263
    public function dropColumn(string $table, string $column): static
264
    {
265
        $sql = $this->getQueryBuilder()->dropColumn($table, $column);
266
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
267
    }
268
269
    public function dropCommentFromColumn(string $table, string $column): static
270
    {
271
        $sql = $this->getQueryBuilder()->dropCommentFromColumn($table, $column);
272
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
273
    }
274
275
    public function dropCommentFromTable(string $table): static
276
    {
277
        $sql = $this->getQueryBuilder()->dropCommentFromTable($table);
278
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
279
    }
280
281
    public function dropDefaultValue(string $table, string $name): static
282
    {
283
        $sql = $this->getQueryBuilder()->dropDefaultValue($table, $name);
284
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
285
    }
286
287
    public function dropForeignKey(string $table, string $name): static
288
    {
289
        $sql = $this->getQueryBuilder()->dropForeignKey($table, $name);
290
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
291
    }
292
293
    public function dropIndex(string $table, string $name): static
294
    {
295
        $sql = $this->getQueryBuilder()->dropIndex($table, $name);
296
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
297
    }
298
299
    public function dropPrimaryKey(string $table, string $name): static
300
    {
301
        $sql = $this->getQueryBuilder()->dropPrimaryKey($table, $name);
302
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
303
    }
304
305
    public function dropTable(string $table): static
306
    {
307
        $sql = $this->getQueryBuilder()->dropTable($table);
308
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
309
    }
310
311
    public function dropUnique(string $table, string $name): static
312
    {
313
        $sql = $this->getQueryBuilder()->dropUnique($table, $name);
314
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
315
    }
316
317
    public function dropView(string $viewName): static
318
    {
319
        $sql = $this->getQueryBuilder()->dropView($viewName);
320
        return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
321
    }
322
323
    public function getParams(bool $asValues = true): array
324
    {
325
        if (!$asValues) {
326
            return $this->params;
327
        }
328
329
        $buildParams = [];
330
331
        foreach ($this->params as $name => $value) {
332
            /** @psalm-var mixed */
333
            $buildParams[$name] = $value->getValue();
334
        }
335
336
        return $buildParams;
337
    }
338
339
    public function getRawSql(): string
340
    {
341
        if (empty($this->params)) {
342
            return $this->sql;
343
        }
344
345
        $params = [];
346
347
        /** @psalm-var mixed $value */
348
        foreach ($this->params as $name => $value) {
349
            if (is_string($name) && strncmp(':', $name, 1)) {
350
                $name = ':' . $name;
351
            }
352
353
            if ($value instanceof ParamInterface) {
354
                /** @psalm-var mixed $value */
355
                $value = $value->getValue();
356
            }
357
358
            if (is_string($value)) {
359
                /** @psalm-var mixed */
360
                $params[$name] = $this->getQueryBuilder()->quoter()->quoteValue($value);
361
            } elseif (is_bool($value)) {
362
                /** @psalm-var string */
363
                $params[$name] = $value ? 'TRUE' : 'FALSE';
364
            } elseif ($value === null) {
365
                $params[$name] = 'NULL';
366
            } elseif ((!is_object($value) && !is_resource($value)) || $value instanceof Expression) {
367
                /** @psalm-var mixed */
368
                $params[$name] = $value;
369
            }
370
        }
371
372
        if (!isset($params[0])) {
373
            return preg_replace_callback('#(:\w+)#', static function (array $matches) use ($params): string {
374
                $m = $matches[1];
375
                return (string)($params[$m] ?? $m);
376
            }, $this->sql);
377
        }
378
379
        // Support unnamed placeholders should be dropped
380
        $sql = '';
381
382
        foreach (explode('?', $this->sql) as $i => $part) {
383
            $sql .= $part . (string)($params[$i] ?? '');
384
        }
385
386
        return $sql;
387
    }
388
389
    public function getSql(): string
390
    {
391
        return $this->sql;
392
    }
393
394
    public function insert(string $table, QueryInterface|array $columns): static
395
    {
396
        $params = [];
397
        $sql = $this->getQueryBuilder()->insert($table, $columns, $params);
398
        return $this->setSql($sql)->bindValues($params);
399
    }
400
401
    public function insertWithReturningPks(string $table, array $columns): bool|array
402
    {
403
        $params = [];
404
405
        $sql = $this->getQueryBuilder()->insertWithReturningPks($table, $columns, $params);
406
407
        $this->setSql($sql)->bindValues($params);
408
409
        /** @psalm-var array|bool $result */
410
        $result = $this->queryInternal(self::QUERY_MODE_ROW | self::QUERY_MODE_EXECUTE);
411
412
        return is_array($result) ? $result : false;
413
    }
414
415
    public function execute(): int
416
    {
417
        $sql = $this->getSql();
418
419
        if ($sql === '') {
420
            return 0;
421
        }
422
423
        /** @psalm-var int|bool $execute */
424
        $execute = $this->queryInternal(self::QUERY_MODE_EXECUTE);
425
426
        return is_int($execute) ? $execute : 0;
427
    }
428
429
    public function query(): DataReaderInterface
430
    {
431
        /** @psalm-var DataReaderInterface */
432
        return $this->queryInternal(self::QUERY_MODE_CURSOR);
433
    }
434
435
    public function queryAll(): array
436
    {
437
        /** @psalm-var array<array-key, array>|null $results */
438
        $results = $this->queryInternal(self::QUERY_MODE_ALL);
439
        return $results ?? [];
440
    }
441
442
    public function queryColumn(): array
443
    {
444
        /** @psalm-var mixed $results */
445
        $results = $this->queryInternal(self::QUERY_MODE_COLUMN);
446
        return is_array($results) ? $results : [];
447
    }
448
449
    public function queryOne(): array|null
450
    {
451
        /** @psalm-var mixed $results */
452
        $results = $this->queryInternal(self::QUERY_MODE_ROW);
453
        return is_array($results) ? $results : null;
454
    }
455
456
    public function queryScalar(): bool|string|null|int|float
457
    {
458
        /** @psalm-var mixed $result */
459
        $result = $this->queryInternal(self::QUERY_MODE_SCALAR);
460
461
        if (is_resource($result) && get_resource_type($result) === 'stream') {
462
            return stream_get_contents($result);
463
        }
464
465
        return is_scalar($result) ? $result : null;
466
    }
467
468
    public function renameColumn(string $table, string $oldName, string $newName): static
469
    {
470
        $sql = $this->getQueryBuilder()->renameColumn($table, $oldName, $newName);
471
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
472
    }
473
474
    public function renameTable(string $table, string $newName): static
475
    {
476
        $sql = $this->getQueryBuilder()->renameTable($table, $newName);
477
        return $this->setSql($sql)->requireTableSchemaRefresh($table);
478
    }
479
480
    public function resetSequence(string $table, int|string $value = null): static
481
    {
482
        $sql = $this->getQueryBuilder()->resetSequence($table, $value);
483
        return $this->setSql($sql);
484
    }
485
486
    public function setRawSql(string $sql): static
487
    {
488
        if ($sql !== $this->sql) {
489
            $this->cancel();
490
            $this->reset();
491
            $this->sql = $sql;
492
        }
493
494
        return $this;
495
    }
496
497
    public function setSql(string $sql): static
498
    {
499
        $this->cancel();
500
        $this->reset();
501
        $this->sql = $this->getQueryBuilder()->quoter()->quoteSql($sql);
502
        return $this;
503
    }
504
505
    public function setRetryHandler(Closure|null $handler): static
506
    {
507
        $this->retryHandler = $handler;
508
        return $this;
509
    }
510
511
    public function truncateTable(string $table): static
512
    {
513
        $sql = $this->getQueryBuilder()->truncateTable($table);
514
        return $this->setSql($sql);
515
    }
516
517
    public function update(string $table, array $columns, array|string $condition = '', array $params = []): static
518
    {
519
        $sql = $this->getQueryBuilder()->update($table, $columns, $condition, $params);
520
        return $this->setSql($sql)->bindValues($params);
521
    }
522
523
    public function upsert(
524
        string $table,
525
        QueryInterface|array $insertColumns,
526
        bool|array $updateColumns = true,
527
        array $params = []
528
    ): static {
529
        $sql = $this->getQueryBuilder()->upsert($table, $insertColumns, $updateColumns, $params);
530
        return $this->setSql($sql)->bindValues($params);
531
    }
532
533
    /**
534
     * @return QueryBuilderInterface The query builder instance.
535
     */
536
    abstract protected function getQueryBuilder(): QueryBuilderInterface;
537
538
    /**
539
     * Returns the query result.
540
     *
541
     * @param int $queryMode Query mode, `QUERY_MODE_*`.
542
     *
543
     * @throws Exception
544
     * @throws Throwable
545
     */
546
    abstract protected function internalGetQueryResult(int $queryMode): mixed;
547
548
    /**
549
     * Executes a prepared statement.
550
     *
551
     * @param string|null $rawSql The rawSql if it has been created.
552
     *
553
     * @throws Exception
554
     * @throws Throwable
555
     */
556
    abstract protected function internalExecute(string|null $rawSql): void;
557
558
    /**
559
     * Check if the value has a given flag.
560
     *
561
     * @param int $value Flags value to check.
562
     * @param int $flag Flag to look for in the value.
563
     *
564
     * @return bool Whether the value has a given flag.
565
     */
566
    protected function is(int $value, int $flag): bool
567
    {
568
        return ($value & $flag) === $flag;
569
    }
570
571
    /**
572
     * The method is called after the query is executed.
573
     *
574
     * @param int $queryMode Query mode, `QUERY_MODE_*`.
575
     *
576
     * @throws Exception
577
     * @throws Throwable
578
     */
579
    protected function queryInternal(int $queryMode): mixed
580
    {
581
        $isReadMode = $this->isReadMode($queryMode);
582
        $this->prepare($isReadMode);
583
584
        try {
585
            $this->internalExecute($this->getRawSql());
586
587
            /** @psalm-var mixed $result */
588
            $result = $this->internalGetQueryResult($queryMode);
589
590
            if (!$isReadMode) {
591
                $this->refreshTableSchema();
592
            }
593
        } catch (Exception $e) {
594
            throw $e;
595
        }
596
597
        return $result;
598
    }
599
600
    /**
601
     * Refreshes table schema, which was marked by {@see requireTableSchemaRefresh()}.
602
     */
603
    abstract protected function refreshTableSchema(): void;
604
605
    /**
606
     * Marks a specified table schema to be refreshed after command execution.
607
     *
608
     * @param string $name Name of the table, which schema should be refreshed.
609
     */
610
    protected function requireTableSchemaRefresh(string $name): static
611
    {
612
        $this->refreshTableName = $name;
613
        return $this;
614
    }
615
616
    /**
617
     * Marks the command to execute in transaction.
618
     *
619
     * @param string|null $isolationLevel The isolation level to use for this transaction.
620
     *
621
     * {@see \Yiisoft\Db\Transaction\TransactionInterface::begin()} for details.
622
     */
623
    protected function requireTransaction(string $isolationLevel = null): static
624
    {
625
        $this->isolationLevel = $isolationLevel;
626
        return $this;
627
    }
628
629
    /**
630
     * Resets the command object, so it can be reused to build another SQL statement.
631
     */
632
    protected function reset(): void
633
    {
634
        $this->sql = '';
635
        $this->params = [];
636
        $this->refreshTableName = null;
637
        $this->isolationLevel = null;
638
        $this->retryHandler = null;
639
    }
640
641
    /**
642
     * Checks if the query mode is a read mode.
643
     */
644
    private function isReadMode(int $queryMode): bool
645
    {
646
        return !$this->is($queryMode, self::QUERY_MODE_EXECUTE);
647
    }
648
}
649