Passed
Pull Request — master (#785)
by Sergei
02:10
created

AbstractCommand   F

Complexity

Total Complexity 74

Size/Duplication

Total Lines 573
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 175
c 3
b 0
f 0
dl 0
loc 573
rs 2.48
wmc 74

52 Methods

Rating   Name   Duplication   Size   Complexity  
A addDefaultValue() 0 4 1
A addCommentOnTable() 0 4 1
A addUnique() 0 4 1
A createTable() 0 4 1
A alterColumn() 0 4 1
A delete() 0 4 1
A checkIntegrity() 0 4 1
A dropCommentFromColumn() 0 4 1
A dropUnique() 0 4 1
A dropIndex() 0 4 1
A dropCommentFromTable() 0 4 1
A batchInsert() 0 18 2
A dropColumn() 0 4 1
A dropPrimaryKey() 0 4 1
A dropDefaultValue() 0 4 1
A dropForeignKey() 0 4 1
A dropView() 0 4 1
A getParams() 0 14 3
A dropCheck() 0 4 1
A addForeignKey() 0 19 1
A addCheck() 0 4 1
A addColumn() 0 4 1
A createView() 0 4 1
A createIndex() 0 9 1
A dropTable() 0 4 1
A addCommentOnColumn() 0 4 1
A addPrimaryKey() 0 4 1
B getRawSql() 0 47 10
A queryInternal() 0 15 2
A execute() 0 12 3
A resetSequence() 0 4 1
A requireTableSchemaRefresh() 0 4 1
A setRawSql() 0 9 2
A queryColumn() 0 5 2
A queryAll() 0 5 1
A renameColumn() 0 4 1
A queryOne() 0 5 2
A getSql() 0 3 1
A insertWithReturningPks() 0 12 2
A truncateTable() 0 4 1
A setRetryHandler() 0 4 1
A reset() 0 7 1
A renameTable() 0 4 1
A update() 0 4 1
A query() 0 4 1
A is() 0 3 1
A requireTransaction() 0 4 1
A queryScalar() 0 10 4
A setSql() 0 6 1
A isReadMode() 0 3 1
A insert() 0 5 1
A upsert() 0 8 1

How to fix   Complexity   

Complex Class

Complex classes like AbstractCommand often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractCommand, and based on these observations, apply Extract Interface, too.

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