Total Complexity | 70 |
Total Lines | 916 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like Schema 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 Schema, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
38 | final class Schema extends AbstractSchema implements ConstraintFinderInterface |
||
39 | { |
||
40 | use ViewFinderTrait; |
||
41 | use ConstraintFinderTrait; |
||
42 | |||
43 | public const TYPE_JSONB = 'jsonb'; |
||
44 | |||
45 | /** |
||
46 | * @var array mapping from physical column types (keys) to abstract column types (values). |
||
47 | * |
||
48 | * {@see http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-TABLE} |
||
49 | */ |
||
50 | private array $typeMap = [ |
||
51 | 'bit' => self::TYPE_INTEGER, |
||
52 | 'bit varying' => self::TYPE_INTEGER, |
||
53 | 'varbit' => self::TYPE_INTEGER, |
||
54 | 'bool' => self::TYPE_BOOLEAN, |
||
55 | 'boolean' => self::TYPE_BOOLEAN, |
||
56 | 'box' => self::TYPE_STRING, |
||
57 | 'circle' => self::TYPE_STRING, |
||
58 | 'point' => self::TYPE_STRING, |
||
59 | 'line' => self::TYPE_STRING, |
||
60 | 'lseg' => self::TYPE_STRING, |
||
61 | 'polygon' => self::TYPE_STRING, |
||
62 | 'path' => self::TYPE_STRING, |
||
63 | 'character' => self::TYPE_CHAR, |
||
64 | 'char' => self::TYPE_CHAR, |
||
65 | 'bpchar' => self::TYPE_CHAR, |
||
66 | 'character varying' => self::TYPE_STRING, |
||
67 | 'varchar' => self::TYPE_STRING, |
||
68 | 'text' => self::TYPE_TEXT, |
||
69 | 'bytea' => self::TYPE_BINARY, |
||
70 | 'cidr' => self::TYPE_STRING, |
||
71 | 'inet' => self::TYPE_STRING, |
||
72 | 'macaddr' => self::TYPE_STRING, |
||
73 | 'real' => self::TYPE_FLOAT, |
||
74 | 'float4' => self::TYPE_FLOAT, |
||
75 | 'double precision' => self::TYPE_DOUBLE, |
||
76 | 'float8' => self::TYPE_DOUBLE, |
||
77 | 'decimal' => self::TYPE_DECIMAL, |
||
78 | 'numeric' => self::TYPE_DECIMAL, |
||
79 | 'money' => self::TYPE_MONEY, |
||
80 | 'smallint' => self::TYPE_SMALLINT, |
||
81 | 'int2' => self::TYPE_SMALLINT, |
||
82 | 'int4' => self::TYPE_INTEGER, |
||
83 | 'int' => self::TYPE_INTEGER, |
||
84 | 'integer' => self::TYPE_INTEGER, |
||
85 | 'bigint' => self::TYPE_BIGINT, |
||
86 | 'int8' => self::TYPE_BIGINT, |
||
87 | 'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal! |
||
88 | 'smallserial' => self::TYPE_SMALLINT, |
||
89 | 'serial2' => self::TYPE_SMALLINT, |
||
90 | 'serial4' => self::TYPE_INTEGER, |
||
91 | 'serial' => self::TYPE_INTEGER, |
||
92 | 'bigserial' => self::TYPE_BIGINT, |
||
93 | 'serial8' => self::TYPE_BIGINT, |
||
94 | 'pg_lsn' => self::TYPE_BIGINT, |
||
95 | 'date' => self::TYPE_DATE, |
||
96 | 'interval' => self::TYPE_STRING, |
||
97 | 'time without time zone' => self::TYPE_TIME, |
||
98 | 'time' => self::TYPE_TIME, |
||
99 | 'time with time zone' => self::TYPE_TIME, |
||
100 | 'timetz' => self::TYPE_TIME, |
||
101 | 'timestamp without time zone' => self::TYPE_TIMESTAMP, |
||
102 | 'timestamp' => self::TYPE_TIMESTAMP, |
||
103 | 'timestamp with time zone' => self::TYPE_TIMESTAMP, |
||
104 | 'timestamptz' => self::TYPE_TIMESTAMP, |
||
105 | 'abstime' => self::TYPE_TIMESTAMP, |
||
106 | 'tsquery' => self::TYPE_STRING, |
||
107 | 'tsvector' => self::TYPE_STRING, |
||
108 | 'txid_snapshot' => self::TYPE_STRING, |
||
109 | 'unknown' => self::TYPE_STRING, |
||
110 | 'uuid' => self::TYPE_STRING, |
||
111 | 'json' => self::TYPE_JSON, |
||
112 | 'jsonb' => self::TYPE_JSON, |
||
113 | 'xml' => self::TYPE_STRING, |
||
114 | ]; |
||
115 | |||
116 | /** |
||
117 | * @var string the default schema used for the current session. |
||
118 | */ |
||
119 | protected ?string $defaultSchema = 'public'; |
||
120 | |||
121 | /** |
||
122 | * @var string|string[] character used to quote schema, table, etc. names. An array of 2 characters can be used in |
||
123 | * case starting and ending characters are different. |
||
124 | */ |
||
125 | protected $tableQuoteCharacter = '"'; |
||
126 | |||
127 | /** |
||
128 | * Resolves the table name and schema name (if any). |
||
129 | * |
||
130 | * @param string $name the table name. |
||
131 | * |
||
132 | * @return TableSchema with resolved table, schema, etc. names. |
||
133 | * |
||
134 | * {@see TableSchema} |
||
135 | */ |
||
136 | protected function resolveTableName(string $name): TableSchema |
||
137 | { |
||
138 | $resolvedName = new TableSchema(); |
||
139 | |||
140 | $parts = explode('.', str_replace('"', '', $name)); |
||
141 | |||
142 | if (isset($parts[1])) { |
||
143 | $resolvedName->schemaName($parts[0]); |
||
144 | $resolvedName->name($parts[1]); |
||
145 | } else { |
||
146 | $resolvedName->schemaName($this->defaultSchema); |
||
147 | $resolvedName->name($name); |
||
148 | } |
||
149 | |||
150 | $resolvedName->fullName( |
||
151 | ( |
||
152 | $resolvedName->getSchemaName() !== $this->defaultSchema ? $resolvedName->getSchemaName() . '.' : '' |
||
153 | ) . $resolvedName->getName() |
||
154 | ); |
||
155 | |||
156 | return $resolvedName; |
||
157 | } |
||
158 | |||
159 | /** |
||
160 | * Returns all schema names in the database, including the default one but not system schemas. |
||
161 | * |
||
162 | * This method should be overridden by child classes in order to support this feature because the default |
||
163 | * implementation simply throws an exception. |
||
164 | * |
||
165 | * @throws Exception |
||
166 | * @throws InvalidArgumentException |
||
167 | * @throws InvalidConfigException |
||
168 | * |
||
169 | * @return array all schema names in the database, except system schemas. |
||
170 | */ |
||
171 | protected function findSchemaNames(): array |
||
172 | { |
||
173 | static $sql = <<<'SQL' |
||
174 | SELECT "ns"."nspname" |
||
175 | FROM "pg_namespace" AS "ns" |
||
176 | WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%' |
||
177 | ORDER BY "ns"."nspname" ASC |
||
178 | SQL; |
||
179 | |||
180 | return $this->getDb()->createCommand($sql)->queryColumn(); |
||
181 | } |
||
182 | |||
183 | /** |
||
184 | * Returns all table names in the database. |
||
185 | * |
||
186 | * This method should be overridden by child classes in order to support this feature because the default |
||
187 | * implementation simply throws an exception. |
||
188 | * |
||
189 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. |
||
190 | * |
||
191 | * @throws Exception |
||
192 | * @throws InvalidArgumentException |
||
193 | * @throws InvalidConfigException |
||
194 | * |
||
195 | * @return array all table names in the database. The names have NO schema name prefix. |
||
196 | */ |
||
197 | protected function findTableNames(string $schema = ''): array |
||
198 | { |
||
199 | if ($schema === '') { |
||
200 | $schema = $this->defaultSchema; |
||
201 | } |
||
202 | |||
203 | $sql = <<<'SQL' |
||
204 | SELECT c.relname AS table_name |
||
205 | FROM pg_class c |
||
206 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
207 | WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p') |
||
208 | ORDER BY c.relname |
||
209 | SQL; |
||
210 | |||
211 | return $this->getDb()->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
212 | } |
||
213 | |||
214 | /** |
||
215 | * Loads the metadata for the specified table. |
||
216 | * |
||
217 | * @param string $name table name. |
||
218 | * |
||
219 | * @throws Exception |
||
220 | * @throws InvalidArgumentException |
||
221 | * @throws InvalidConfigException |
||
222 | * @throws NotSupportedException |
||
223 | * |
||
224 | * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist. |
||
225 | */ |
||
226 | protected function loadTableSchema(string $name): ?TableSchema |
||
227 | { |
||
228 | $table = new TableSchema(); |
||
229 | |||
230 | $this->resolveTableNames($table, $name); |
||
231 | |||
232 | if ($this->findColumns($table)) { |
||
233 | $this->findConstraints($table); |
||
234 | return $table; |
||
235 | } |
||
236 | |||
237 | return null; |
||
238 | } |
||
239 | |||
240 | /** |
||
241 | * Loads a primary key for the given table. |
||
242 | * |
||
243 | * @param string $tableName table name. |
||
244 | * |
||
245 | * @throws Exception |
||
246 | * @throws InvalidArgumentException |
||
247 | * @throws InvalidConfigException |
||
248 | * |
||
249 | * @return Constraint|null primary key for the given table, `null` if the table has no primary key. |
||
250 | */ |
||
251 | protected function loadTablePrimaryKey(string $tableName): ?Constraint |
||
252 | { |
||
253 | return $this->loadTableConstraints($tableName, 'primaryKey'); |
||
254 | } |
||
255 | |||
256 | /** |
||
257 | * Loads all foreign keys for the given table. |
||
258 | * |
||
259 | * @param string $tableName table name. |
||
260 | * |
||
261 | * @throws Exception |
||
262 | * @throws InvalidArgumentException |
||
263 | * @throws InvalidConfigException |
||
264 | * |
||
265 | * @return ForeignKeyConstraint[] foreign keys for the given table. |
||
266 | */ |
||
267 | protected function loadTableForeignKeys($tableName): array |
||
268 | { |
||
269 | return $this->loadTableConstraints($tableName, 'foreignKeys'); |
||
270 | } |
||
271 | |||
272 | /** |
||
273 | * Loads all indexes for the given table. |
||
274 | * |
||
275 | * @param string $tableName table name. |
||
276 | * |
||
277 | * @throws Exception |
||
278 | * @throws InvalidArgumentException |
||
279 | * @throws InvalidConfigException |
||
280 | * |
||
281 | * @return IndexConstraint[] indexes for the given table. |
||
282 | */ |
||
283 | protected function loadTableIndexes(string $tableName): array |
||
284 | { |
||
285 | static $sql = <<<'SQL' |
||
286 | SELECT |
||
287 | "ic"."relname" AS "name", |
||
288 | "ia"."attname" AS "column_name", |
||
289 | "i"."indisunique" AS "index_is_unique", |
||
290 | "i"."indisprimary" AS "index_is_primary" |
||
291 | FROM "pg_class" AS "tc" |
||
292 | INNER JOIN "pg_namespace" AS "tcns" |
||
293 | ON "tcns"."oid" = "tc"."relnamespace" |
||
294 | INNER JOIN "pg_index" AS "i" |
||
295 | ON "i"."indrelid" = "tc"."oid" |
||
296 | INNER JOIN "pg_class" AS "ic" |
||
297 | ON "ic"."oid" = "i"."indexrelid" |
||
298 | INNER JOIN "pg_attribute" AS "ia" |
||
299 | ON "ia"."attrelid" = "i"."indrelid" AND "ia"."attnum" = ANY ("i"."indkey") |
||
300 | WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName |
||
301 | ORDER BY "ia"."attnum" ASC |
||
302 | SQL; |
||
303 | |||
304 | $resolvedName = $this->resolveTableName($tableName); |
||
305 | |||
306 | $indexes = $this->getDb()->createCommand($sql, [ |
||
307 | ':schemaName' => $resolvedName->getSchemaName(), |
||
308 | ':tableName' => $resolvedName->getName(), |
||
309 | ])->queryAll(); |
||
310 | |||
311 | $indexes = $this->normalizePdoRowKeyCase($indexes, true); |
||
312 | $indexes = ArrayHelper::index($indexes, null, 'name'); |
||
313 | $result = []; |
||
314 | |||
315 | foreach ($indexes as $name => $index) { |
||
316 | $ic = (new IndexConstraint()) |
||
317 | ->name($name) |
||
318 | ->columnNames(ArrayHelper::getColumn($index, 'column_name')) |
||
319 | ->primary((bool) $index[0]['index_is_primary']) |
||
320 | ->unique((bool) $index[0]['index_is_unique']); |
||
321 | |||
322 | $result[] = $ic; |
||
323 | } |
||
324 | |||
325 | return $result; |
||
326 | } |
||
327 | |||
328 | /** |
||
329 | * Loads all unique constraints for the given table. |
||
330 | * |
||
331 | * @param string $tableName table name. |
||
332 | * |
||
333 | * @throws Exception |
||
334 | * @throws InvalidArgumentException |
||
335 | * @throws InvalidConfigException |
||
336 | * |
||
337 | * @return Constraint[] unique constraints for the given table. |
||
338 | */ |
||
339 | protected function loadTableUniques(string $tableName): array |
||
340 | { |
||
341 | return $this->loadTableConstraints($tableName, 'uniques'); |
||
342 | } |
||
343 | |||
344 | /** |
||
345 | * Loads all check constraints for the given table. |
||
346 | * |
||
347 | * @param string $tableName table name. |
||
348 | * |
||
349 | * @throws Exception |
||
350 | * @throws InvalidArgumentException |
||
351 | * @throws InvalidConfigException |
||
352 | * |
||
353 | * @return CheckConstraint[] check constraints for the given table. |
||
354 | */ |
||
355 | protected function loadTableChecks(string $tableName): array |
||
356 | { |
||
357 | return $this->loadTableConstraints($tableName, 'checks'); |
||
358 | } |
||
359 | |||
360 | /** |
||
361 | * Loads all default value constraints for the given table. |
||
362 | * |
||
363 | * @param string $tableName table name. |
||
364 | * |
||
365 | * @throws NotSupportedException |
||
366 | * |
||
367 | * @return DefaultValueConstraint[] default value constraints for the given table. |
||
368 | */ |
||
369 | protected function loadTableDefaultValues($tableName): array |
||
|
|||
370 | { |
||
371 | throw new NotSupportedException('PostgreSQL does not support default value constraints.'); |
||
372 | } |
||
373 | |||
374 | /** |
||
375 | * Creates a query builder for the PostgreSQL database. |
||
376 | * |
||
377 | * @return QueryBuilder query builder instance |
||
378 | */ |
||
379 | public function createQueryBuilder(): QueryBuilder |
||
380 | { |
||
381 | return new QueryBuilder($this->getDb()); |
||
382 | } |
||
383 | |||
384 | /** |
||
385 | * Resolves the table name and schema name (if any). |
||
386 | * |
||
387 | * @param TableSchema $table the table metadata object. |
||
388 | * @param string $name the table name |
||
389 | */ |
||
390 | protected function resolveTableNames(TableSchema $table, string $name): void |
||
391 | { |
||
392 | $parts = explode('.', str_replace('"', '', $name)); |
||
393 | |||
394 | if (isset($parts[1])) { |
||
395 | $table->schemaName($parts[0]); |
||
396 | $table->name($parts[1]); |
||
397 | } else { |
||
398 | $table->schemaName($this->defaultSchema); |
||
399 | $table->name($parts[0]); |
||
400 | } |
||
401 | |||
402 | $table->fullName($table->getSchemaName() !== $this->defaultSchema ? $table->getSchemaName() . '.' |
||
403 | . $table->getName() : $table->getName()); |
||
404 | } |
||
405 | |||
406 | protected function findViewNames(string $schema = ''): array |
||
407 | { |
||
408 | if ($schema === '') { |
||
409 | $schema = $this->defaultSchema; |
||
410 | } |
||
411 | |||
412 | $sql = <<<'SQL' |
||
413 | SELECT c.relname AS table_name |
||
414 | FROM pg_class c |
||
415 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
416 | WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm') |
||
417 | ORDER BY c.relname |
||
418 | SQL; |
||
419 | |||
420 | return $this->getDb()->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
421 | } |
||
422 | |||
423 | /** |
||
424 | * Collects the foreign key column details for the given table. |
||
425 | * |
||
426 | * @param TableSchema $table the table metadata |
||
427 | * |
||
428 | * @throws Exception |
||
429 | * @throws InvalidArgumentException |
||
430 | * @throws InvalidConfigException |
||
431 | */ |
||
432 | protected function findConstraints(TableSchema $table) |
||
494 | } |
||
495 | } |
||
496 | |||
497 | /** |
||
498 | * Gets information about given table unique indexes. |
||
499 | * |
||
500 | * @param TableSchema $table the table metadata. |
||
501 | * |
||
502 | * @throws Exception |
||
503 | * @throws InvalidArgumentException |
||
504 | * @throws InvalidConfigException |
||
505 | * |
||
506 | * @return array with index and column names. |
||
507 | */ |
||
508 | protected function getUniqueIndexInformation(TableSchema $table): array |
||
509 | { |
||
510 | $sql = <<<'SQL' |
||
511 | SELECT |
||
512 | i.relname as indexname, |
||
513 | pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname |
||
514 | FROM ( |
||
515 | SELECT *, generate_subscripts(indkey, 1) AS k |
||
516 | FROM pg_index |
||
517 | ) idx |
||
518 | INNER JOIN pg_class i ON i.oid = idx.indexrelid |
||
519 | INNER JOIN pg_class c ON c.oid = idx.indrelid |
||
520 | INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid |
||
521 | WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE |
||
522 | AND c.relname = :tableName AND ns.nspname = :schemaName |
||
523 | ORDER BY i.relname, k |
||
524 | SQL; |
||
525 | |||
526 | return $this->getDb()->createCommand($sql, [ |
||
527 | ':schemaName' => $table->getSchemaName(), |
||
528 | ':tableName' => $table->getName(), |
||
529 | ])->queryAll(); |
||
530 | } |
||
531 | |||
532 | /** |
||
533 | * Returns all unique indexes for the given table. |
||
534 | * |
||
535 | * Each array element is of the following structure: |
||
536 | * |
||
537 | * ```php |
||
538 | * [ |
||
539 | * 'IndexName1' => ['col1' [, ...]], |
||
540 | * 'IndexName2' => ['col2' [, ...]], |
||
541 | * ] |
||
542 | * ``` |
||
543 | * |
||
544 | * @param TableSchema $table the table metadata |
||
545 | * |
||
546 | * @throws Exception |
||
547 | * @throws InvalidArgumentException |
||
548 | * @throws InvalidConfigException |
||
549 | * |
||
550 | * @return array all unique indexes for the given table. |
||
551 | */ |
||
552 | public function findUniqueIndexes($table): array |
||
553 | { |
||
554 | $uniqueIndexes = []; |
||
555 | |||
556 | foreach ($this->getUniqueIndexInformation($table) as $row) { |
||
557 | if ($this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) { |
||
558 | $row = array_change_key_case($row, CASE_LOWER); |
||
559 | } |
||
560 | |||
561 | $column = $row['columnname']; |
||
562 | |||
563 | if (!empty($column) && $column[0] === '"') { |
||
564 | /** |
||
565 | * postgres will quote names that are not lowercase-only. |
||
566 | * |
||
567 | * {@see https://github.com/yiisoft/yii2/issues/10613} |
||
568 | */ |
||
569 | $column = substr($column, 1, -1); |
||
570 | } |
||
571 | |||
572 | $uniqueIndexes[$row['indexname']][] = $column; |
||
573 | } |
||
574 | |||
575 | return $uniqueIndexes; |
||
576 | } |
||
577 | |||
578 | /** |
||
579 | * Collects the metadata of table columns. |
||
580 | * |
||
581 | * @param TableSchema $table the table metadata. |
||
582 | * |
||
583 | * @throws Exception |
||
584 | * @throws InvalidArgumentException |
||
585 | * @throws InvalidConfigException |
||
586 | * @throws NotSupportedException |
||
587 | * |
||
588 | * @return bool whether the table exists in the database. |
||
589 | */ |
||
590 | protected function findColumns(TableSchema $table): bool |
||
717 | } |
||
718 | |||
719 | /** |
||
720 | * Loads the column information into a {@see ColumnSchema} object. |
||
721 | * |
||
722 | * @param array $info column information. |
||
723 | * |
||
724 | * @return ColumnSchema the column schema object. |
||
725 | */ |
||
726 | protected function loadColumnSchema(array $info): ColumnSchema |
||
727 | { |
||
728 | /** @var ColumnSchema $column */ |
||
729 | $column = $this->createColumnSchema(); |
||
730 | $column->allowNull($info['is_nullable']); |
||
731 | $column->autoIncrement($info['is_autoinc']); |
||
732 | $column->comment($info['column_comment']); |
||
733 | $column->dbType($info['data_type']); |
||
734 | $column->defaultValue($info['column_default']); |
||
735 | $column->enumValues(($info['enum_values'] !== null) |
||
736 | ? explode(',', str_replace(["''"], ["'"], $info['enum_values'])) : null); |
||
737 | $column->unsigned(false); // has no meaning in PG |
||
738 | $column->primaryKey((bool) $info['is_pkey']); |
||
739 | $column->name($info['column_name']); |
||
740 | $column->precision($info['numeric_precision']); |
||
741 | $column->scale($info['numeric_scale']); |
||
742 | $column->size($info['size'] === null ? null : (int) $info['size']); |
||
743 | $column->dimension((int) $info['dimension']); |
||
744 | |||
745 | /** |
||
746 | * pg_get_serial_sequence() doesn't track DEFAULT value change. GENERATED BY IDENTITY columns always have null |
||
747 | * default value. |
||
748 | */ |
||
749 | |||
750 | $defaultValue = $column->getDefaultValue(); |
||
751 | if ( |
||
752 | isset($defaultValue) && |
||
753 | preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $defaultValue) === 1 |
||
754 | ) { |
||
755 | $column->sequenceName(preg_replace( |
||
756 | ['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], |
||
757 | '', |
||
758 | $defaultValue |
||
759 | )); |
||
760 | } elseif (isset($info['sequence_name'])) { |
||
761 | $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName()); |
||
762 | } |
||
763 | |||
764 | if (isset($this->typeMap[$column->getDbType()])) { |
||
765 | $column->type($this->typeMap[$column->getDbType()]); |
||
766 | } else { |
||
767 | $column->type(self::TYPE_STRING); |
||
768 | } |
||
769 | |||
770 | $column->phpType($this->getColumnPhpType($column)); |
||
771 | |||
772 | return $column; |
||
773 | } |
||
774 | |||
775 | /** |
||
776 | * Executes the INSERT command, returning primary key values. |
||
777 | * |
||
778 | * @param string $table the table that new rows will be inserted into. |
||
779 | * @param array $columns the column data (name => value) to be inserted into the table. |
||
780 | * |
||
781 | * @throws Exception |
||
782 | * @throws InvalidArgumentException |
||
783 | * @throws InvalidConfigException |
||
784 | * @throws NotSupportedException |
||
785 | * |
||
786 | * @return array|false primary key values or false if the command fails. |
||
787 | */ |
||
788 | public function insert(string $table, array $columns) |
||
789 | { |
||
790 | $params = []; |
||
791 | $sql = $this->getDb()->getQueryBuilder()->insert($table, $columns, $params); |
||
792 | $returnColumns = $this->getTableSchema($table)->getPrimaryKey(); |
||
793 | |||
794 | if (!empty($returnColumns)) { |
||
795 | $returning = []; |
||
796 | foreach ((array) $returnColumns as $name) { |
||
797 | $returning[] = $this->quoteColumnName($name); |
||
798 | } |
||
799 | $sql .= ' RETURNING ' . implode(', ', $returning); |
||
800 | } |
||
801 | |||
802 | $command = $this->getDb()->createCommand($sql, $params); |
||
803 | $command->prepare(false); |
||
804 | $result = $command->queryOne(); |
||
805 | |||
806 | return !$command->getPdoStatement()->rowCount() ? false : $result; |
||
807 | } |
||
808 | |||
809 | /** |
||
810 | * Loads multiple types of constraints and returns the specified ones. |
||
811 | * |
||
812 | * @param string $tableName table name. |
||
813 | * @param string $returnType return type: |
||
814 | * - primaryKey |
||
815 | * - foreignKeys |
||
816 | * - uniques |
||
817 | * - checks |
||
818 | * |
||
819 | * @throws Exception |
||
820 | * @throws InvalidArgumentException |
||
821 | * @throws InvalidConfigException |
||
822 | * |
||
823 | * @return mixed constraints. |
||
824 | */ |
||
825 | private function loadTableConstraints(string $tableName, string $returnType) |
||
826 | { |
||
827 | static $sql = <<<'SQL' |
||
828 | SELECT |
||
829 | "c"."conname" AS "name", |
||
830 | "a"."attname" AS "column_name", |
||
831 | "c"."contype" AS "type", |
||
832 | "ftcns"."nspname" AS "foreign_table_schema", |
||
833 | "ftc"."relname" AS "foreign_table_name", |
||
834 | "fa"."attname" AS "foreign_column_name", |
||
835 | "c"."confupdtype" AS "on_update", |
||
836 | "c"."confdeltype" AS "on_delete", |
||
837 | pg_get_constraintdef("c"."oid") AS "check_expr" |
||
838 | FROM "pg_class" AS "tc" |
||
839 | INNER JOIN "pg_namespace" AS "tcns" |
||
840 | ON "tcns"."oid" = "tc"."relnamespace" |
||
841 | INNER JOIN "pg_constraint" AS "c" |
||
842 | ON "c"."conrelid" = "tc"."oid" |
||
843 | INNER JOIN "pg_attribute" AS "a" |
||
844 | ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey") |
||
845 | LEFT JOIN "pg_class" AS "ftc" |
||
846 | ON "ftc"."oid" = "c"."confrelid" |
||
847 | LEFT JOIN "pg_namespace" AS "ftcns" |
||
848 | ON "ftcns"."oid" = "ftc"."relnamespace" |
||
849 | LEFT JOIN "pg_attribute" "fa" |
||
850 | ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey") |
||
851 | WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName |
||
852 | ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC |
||
853 | SQL; |
||
854 | |||
855 | static $actionTypes = [ |
||
856 | 'a' => 'NO ACTION', |
||
857 | 'r' => 'RESTRICT', |
||
858 | 'c' => 'CASCADE', |
||
859 | 'n' => 'SET NULL', |
||
860 | 'd' => 'SET DEFAULT', |
||
861 | ]; |
||
862 | |||
863 | $resolvedName = $this->resolveTableName($tableName); |
||
864 | $constraints = $this->getDb()->createCommand($sql, [ |
||
865 | ':schemaName' => $resolvedName->getSchemaName(), |
||
866 | ':tableName' => $resolvedName->getName(), |
||
867 | ])->queryAll(); |
||
868 | $constraints = $this->normalizePdoRowKeyCase($constraints, true); |
||
869 | $constraints = ArrayHelper::index($constraints, null, ['type', 'name']); |
||
870 | $result = [ |
||
871 | 'primaryKey' => null, |
||
872 | 'foreignKeys' => [], |
||
873 | 'uniques' => [], |
||
874 | 'checks' => [], |
||
875 | ]; |
||
876 | |||
877 | foreach ($constraints as $type => $names) { |
||
878 | foreach ($names as $name => $constraint) { |
||
879 | switch ($type) { |
||
880 | case 'p': |
||
881 | $ct = (new Constraint()) |
||
882 | ->name($name) |
||
883 | ->columnNames(ArrayHelper::getColumn($constraint, 'column_name')); |
||
884 | |||
885 | $result['primaryKey'] = $ct; |
||
886 | break; |
||
887 | case 'f': |
||
888 | $fk = (new ForeignKeyConstraint()) |
||
889 | ->name($name) |
||
890 | ->columnNames(array_values( |
||
891 | array_unique(ArrayHelper::getColumn($constraint, 'column_name')) |
||
892 | )) |
||
893 | ->foreignSchemaName($constraint[0]['foreign_table_schema']) |
||
894 | ->foreignTableName($constraint[0]['foreign_table_name']) |
||
895 | ->foreignColumnNames(array_values( |
||
896 | array_unique(ArrayHelper::getColumn($constraint, 'foreign_column_name')) |
||
897 | )) |
||
898 | ->onDelete($actionTypes[$constraint[0]['on_delete']] ?? null) |
||
899 | ->onUpdate($actionTypes[$constraint[0]['on_update']] ?? null); |
||
900 | |||
901 | $result['foreignKeys'][] = $fk; |
||
902 | break; |
||
903 | case 'u': |
||
904 | $ct = (new Constraint()) |
||
905 | ->name($name) |
||
906 | ->columnNames(ArrayHelper::getColumn($constraint, 'column_name')); |
||
907 | |||
908 | $result['uniques'][] = $ct; |
||
909 | break; |
||
910 | case 'c': |
||
911 | $ck = (new CheckConstraint()) |
||
912 | ->name($name) |
||
913 | ->columnNames(ArrayHelper::getColumn($constraint, 'column_name')) |
||
914 | ->expression($constraint[0]['check_expr']); |
||
915 | |||
916 | $result['checks'][] = $ck; |
||
917 | break; |
||
918 | } |
||
919 | } |
||
920 | } |
||
921 | |||
922 | foreach ($result as $type => $data) { |
||
923 | $this->setTableMetadata($tableName, $type, $data); |
||
924 | } |
||
925 | |||
926 | return $result[$returnType]; |
||
927 | } |
||
928 | |||
929 | /** |
||
930 | * Creates a column schema for the database. |
||
931 | * |
||
932 | * This method may be overridden by child classes to create a DBMS-specific column schema. |
||
933 | * |
||
934 | * @return ColumnSchema column schema instance. |
||
935 | */ |
||
936 | private function createColumnSchema(): ColumnSchema |
||
939 | } |
||
940 | |||
941 | /** |
||
942 | * Create a column schema builder instance giving the type and value precision. |
||
943 | * |
||
944 | * This method may be overridden by child classes to create a DBMS-specific column schema builder. |
||
945 | * |
||
946 | * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}. |
||
947 | * @param int|string|array $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}. |
||
948 | * |
||
949 | * @return ColumnSchemaBuilder column schema builder instance |
||
950 | */ |
||
951 | public function createColumnSchemaBuilder(string $type, $length = null): ColumnSchemaBuilder |
||
954 | } |
||
955 | } |
||
956 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.