Total Complexity | 74 |
Total Lines | 997 |
Duplicated Lines | 0 % |
Changes | 14 | ||
Bugs | 2 | Features | 1 |
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 |
||
82 | final class Schema extends AbstractPdoSchema |
||
83 | { |
||
84 | /** |
||
85 | * Define the abstract column type as `bit`. |
||
86 | */ |
||
87 | public const TYPE_BIT = 'bit'; |
||
88 | /** |
||
89 | * Define the abstract column type as `composite`. |
||
90 | */ |
||
91 | public const TYPE_COMPOSITE = 'composite'; |
||
92 | |||
93 | /** |
||
94 | * The mapping from physical column types (keys) to abstract column types (values). |
||
95 | * |
||
96 | * @link https://www.postgresql.org/docs/current/datatype.html#DATATYPE-TABLE |
||
97 | * |
||
98 | * @var string[] |
||
99 | */ |
||
100 | private const TYPE_MAP = [ |
||
101 | 'bit' => self::TYPE_BIT, |
||
102 | 'bit varying' => self::TYPE_BIT, |
||
103 | 'varbit' => self::TYPE_BIT, |
||
104 | 'bool' => self::TYPE_BOOLEAN, |
||
105 | 'boolean' => self::TYPE_BOOLEAN, |
||
106 | 'box' => self::TYPE_STRING, |
||
107 | 'circle' => self::TYPE_STRING, |
||
108 | 'point' => self::TYPE_STRING, |
||
109 | 'line' => self::TYPE_STRING, |
||
110 | 'lseg' => self::TYPE_STRING, |
||
111 | 'polygon' => self::TYPE_STRING, |
||
112 | 'path' => self::TYPE_STRING, |
||
113 | 'character' => self::TYPE_CHAR, |
||
114 | 'char' => self::TYPE_CHAR, |
||
115 | 'bpchar' => self::TYPE_CHAR, |
||
116 | 'character varying' => self::TYPE_STRING, |
||
117 | 'varchar' => self::TYPE_STRING, |
||
118 | 'text' => self::TYPE_TEXT, |
||
119 | 'bytea' => self::TYPE_BINARY, |
||
120 | 'cidr' => self::TYPE_STRING, |
||
121 | 'inet' => self::TYPE_STRING, |
||
122 | 'macaddr' => self::TYPE_STRING, |
||
123 | 'real' => self::TYPE_FLOAT, |
||
124 | 'float4' => self::TYPE_FLOAT, |
||
125 | 'double precision' => self::TYPE_DOUBLE, |
||
126 | 'float8' => self::TYPE_DOUBLE, |
||
127 | 'decimal' => self::TYPE_DECIMAL, |
||
128 | 'numeric' => self::TYPE_DECIMAL, |
||
129 | 'money' => self::TYPE_MONEY, |
||
130 | 'smallint' => self::TYPE_SMALLINT, |
||
131 | 'int2' => self::TYPE_SMALLINT, |
||
132 | 'int4' => self::TYPE_INTEGER, |
||
133 | 'int' => self::TYPE_INTEGER, |
||
134 | 'integer' => self::TYPE_INTEGER, |
||
135 | 'bigint' => self::TYPE_BIGINT, |
||
136 | 'int8' => self::TYPE_BIGINT, |
||
137 | 'oid' => self::TYPE_BIGINT, // shouldn't be used. it's pg internal! |
||
138 | 'smallserial' => self::TYPE_SMALLINT, |
||
139 | 'serial2' => self::TYPE_SMALLINT, |
||
140 | 'serial4' => self::TYPE_INTEGER, |
||
141 | 'serial' => self::TYPE_INTEGER, |
||
142 | 'bigserial' => self::TYPE_BIGINT, |
||
143 | 'serial8' => self::TYPE_BIGINT, |
||
144 | 'pg_lsn' => self::TYPE_BIGINT, |
||
145 | 'date' => self::TYPE_DATE, |
||
146 | 'interval' => self::TYPE_STRING, |
||
147 | 'time without time zone' => self::TYPE_TIME, |
||
148 | 'time' => self::TYPE_TIME, |
||
149 | 'time with time zone' => self::TYPE_TIME, |
||
150 | 'timetz' => self::TYPE_TIME, |
||
151 | 'timestamp without time zone' => self::TYPE_TIMESTAMP, |
||
152 | 'timestamp' => self::TYPE_TIMESTAMP, |
||
153 | 'timestamp with time zone' => self::TYPE_TIMESTAMP, |
||
154 | 'timestamptz' => self::TYPE_TIMESTAMP, |
||
155 | 'abstime' => self::TYPE_TIMESTAMP, |
||
156 | 'tsquery' => self::TYPE_STRING, |
||
157 | 'tsvector' => self::TYPE_STRING, |
||
158 | 'txid_snapshot' => self::TYPE_STRING, |
||
159 | 'unknown' => self::TYPE_STRING, |
||
160 | 'uuid' => self::TYPE_STRING, |
||
161 | 'json' => self::TYPE_JSON, |
||
162 | 'jsonb' => self::TYPE_JSON, |
||
163 | 'xml' => self::TYPE_STRING, |
||
164 | ]; |
||
165 | |||
166 | /** |
||
167 | * @var string|null The default schema used for the current session. |
||
168 | */ |
||
169 | protected string|null $defaultSchema = 'public'; |
||
170 | |||
171 | /** |
||
172 | * @var string|string[] Character used to quote schema, table, etc. names. |
||
173 | * |
||
174 | * An array of 2 characters can be used in case starting and ending characters are different. |
||
175 | */ |
||
176 | protected string|array $tableQuoteCharacter = '"'; |
||
177 | |||
178 | public function createColumn(string $type, array|int|string $length = null): ColumnInterface |
||
179 | { |
||
180 | return new Column($type, $length); |
||
181 | } |
||
182 | |||
183 | /** |
||
184 | * Resolves the table name and schema name (if any). |
||
185 | * |
||
186 | * @param string $name The table name. |
||
187 | * |
||
188 | * @return TableSchemaInterface With resolved table, schema, etc. names. |
||
189 | * |
||
190 | * @see TableSchemaInterface |
||
191 | */ |
||
192 | protected function resolveTableName(string $name): TableSchemaInterface |
||
193 | { |
||
194 | $resolvedName = new TableSchema(); |
||
195 | |||
196 | $parts = array_reverse($this->db->getQuoter()->getTableNameParts($name)); |
||
197 | $resolvedName->name($parts[0] ?? ''); |
||
198 | $resolvedName->schemaName($parts[1] ?? $this->defaultSchema); |
||
199 | |||
200 | $resolvedName->fullName( |
||
201 | $resolvedName->getSchemaName() !== $this->defaultSchema ? |
||
202 | implode('.', array_reverse($parts)) : $resolvedName->getName() |
||
203 | ); |
||
204 | |||
205 | return $resolvedName; |
||
206 | } |
||
207 | |||
208 | /** |
||
209 | * Returns all schema names in the database, including the default one but not system schemas. |
||
210 | * |
||
211 | * This method should be overridden by child classes to support this feature because the default implementation |
||
212 | * simply throws an exception. |
||
213 | * |
||
214 | * @throws Exception |
||
215 | * @throws InvalidConfigException |
||
216 | * @throws Throwable |
||
217 | * |
||
218 | * @return array All schemas name in the database, except system schemas. |
||
219 | */ |
||
220 | protected function findSchemaNames(): array |
||
221 | { |
||
222 | $sql = <<<SQL |
||
223 | SELECT "ns"."nspname" |
||
224 | FROM "pg_namespace" AS "ns" |
||
225 | WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%' |
||
226 | ORDER BY "ns"."nspname" ASC |
||
227 | SQL; |
||
228 | |||
229 | return $this->db->createCommand($sql)->queryColumn(); |
||
230 | } |
||
231 | |||
232 | /** |
||
233 | * @throws Exception |
||
234 | * @throws InvalidConfigException |
||
235 | * @throws Throwable |
||
236 | */ |
||
237 | protected function findTableComment(TableSchemaInterface $tableSchema): void |
||
238 | { |
||
239 | $sql = <<<SQL |
||
240 | SELECT obj_description(pc.oid, 'pg_class') |
||
241 | FROM pg_catalog.pg_class pc |
||
242 | INNER JOIN pg_namespace pn ON pc.relnamespace = pn.oid |
||
243 | WHERE |
||
244 | pc.relname=:tableName AND |
||
245 | pn.nspname=:schemaName |
||
246 | SQL; |
||
247 | |||
248 | $comment = $this->db->createCommand($sql, [ |
||
249 | ':schemaName' => $tableSchema->getSchemaName(), |
||
250 | ':tableName' => $tableSchema->getName(), |
||
251 | ])->queryScalar(); |
||
252 | |||
253 | $tableSchema->comment(is_string($comment) ? $comment : null); |
||
254 | } |
||
255 | |||
256 | /** |
||
257 | * Returns all table names in the database. |
||
258 | * |
||
259 | * This method should be overridden by child classes to support this feature because the default implementation |
||
260 | * simply throws an exception. |
||
261 | * |
||
262 | * @param string $schema The schema of the tables. |
||
263 | * Defaults to empty string, meaning the current or default schema. |
||
264 | * |
||
265 | * @throws Exception |
||
266 | * @throws InvalidConfigException |
||
267 | * @throws Throwable |
||
268 | * |
||
269 | * @return array All tables name in the database. The names have NO schema name prefix. |
||
270 | */ |
||
271 | protected function findTableNames(string $schema = ''): array |
||
272 | { |
||
273 | if ($schema === '') { |
||
274 | $schema = $this->defaultSchema; |
||
275 | } |
||
276 | |||
277 | $sql = <<<SQL |
||
278 | SELECT c.relname AS table_name |
||
279 | FROM pg_class c |
||
280 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
281 | WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p') |
||
282 | ORDER BY c.relname |
||
283 | SQL; |
||
284 | |||
285 | return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
286 | } |
||
287 | |||
288 | /** |
||
289 | * Loads the metadata for the specified table. |
||
290 | * |
||
291 | * @param string $name The table name. |
||
292 | * |
||
293 | * @throws Exception |
||
294 | * @throws InvalidConfigException |
||
295 | * @throws Throwable |
||
296 | * |
||
297 | * @return TableSchemaInterface|null DBMS-dependent table metadata, `null` if the table doesn't exist. |
||
298 | */ |
||
299 | protected function loadTableSchema(string $name): TableSchemaInterface|null |
||
300 | { |
||
301 | $table = $this->resolveTableName($name); |
||
302 | $this->findTableComment($table); |
||
303 | |||
304 | if ($this->findColumns($table)) { |
||
305 | $this->findConstraints($table); |
||
306 | return $table; |
||
307 | } |
||
308 | |||
309 | return null; |
||
310 | } |
||
311 | |||
312 | /** |
||
313 | * Loads a primary key for the given table. |
||
314 | * |
||
315 | * @param string $tableName The table name. |
||
316 | * |
||
317 | * @throws Exception |
||
318 | * @throws InvalidConfigException |
||
319 | * @throws Throwable |
||
320 | * |
||
321 | * @return Constraint|null Primary key for the given table, `null` if the table has no primary key. |
||
322 | */ |
||
323 | protected function loadTablePrimaryKey(string $tableName): Constraint|null |
||
324 | { |
||
325 | $tablePrimaryKey = $this->loadTableConstraints($tableName, self::PRIMARY_KEY); |
||
326 | |||
327 | return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null; |
||
328 | } |
||
329 | |||
330 | /** |
||
331 | * Loads all foreign keys for the given table. |
||
332 | * |
||
333 | * @param string $tableName The table name. |
||
334 | * |
||
335 | * @throws Exception |
||
336 | * @throws InvalidConfigException |
||
337 | * @throws Throwable |
||
338 | * |
||
339 | * @return array Foreign keys for the given table. |
||
340 | * |
||
341 | * @psaml-return array|ForeignKeyConstraint[] |
||
342 | */ |
||
343 | protected function loadTableForeignKeys(string $tableName): array |
||
344 | { |
||
345 | $tableForeignKeys = $this->loadTableConstraints($tableName, self::FOREIGN_KEYS); |
||
346 | |||
347 | return is_array($tableForeignKeys) ? $tableForeignKeys : []; |
||
348 | } |
||
349 | |||
350 | /** |
||
351 | * Loads all indexes for the given table. |
||
352 | * |
||
353 | * @param string $tableName The table name. |
||
354 | * |
||
355 | * @throws Exception |
||
356 | * @throws InvalidConfigException |
||
357 | * @throws Throwable |
||
358 | * |
||
359 | * @return IndexConstraint[] Indexes for the given table. |
||
360 | */ |
||
361 | protected function loadTableIndexes(string $tableName): array |
||
362 | { |
||
363 | $sql = <<<SQL |
||
364 | SELECT |
||
365 | "ic"."relname" AS "name", |
||
366 | "ia"."attname" AS "column_name", |
||
367 | "i"."indisunique" AS "index_is_unique", |
||
368 | "i"."indisprimary" AS "index_is_primary" |
||
369 | FROM "pg_class" AS "tc" |
||
370 | INNER JOIN "pg_namespace" AS "tcns" |
||
371 | ON "tcns"."oid" = "tc"."relnamespace" |
||
372 | LEFT JOIN pg_rewrite AS rw |
||
373 | ON tc.relkind = 'v' AND rw.ev_class = tc.oid AND rw.rulename = '_RETURN' |
||
374 | INNER JOIN "pg_index" AS "i" |
||
375 | ON "i"."indrelid" = "tc"."oid" |
||
376 | OR rw.ev_action IS NOT NULL |
||
377 | AND (SELECT regexp_matches( |
||
378 | rw.ev_action, |
||
379 | '{TARGETENTRY .*? :resorigtbl ' || "i"."indrelid" || ' :resorigcol ' || "i"."indkey"[0] || ' ' |
||
380 | )) IS NOT NULL |
||
381 | INNER JOIN "pg_class" AS "ic" |
||
382 | ON "ic"."oid" = "i"."indexrelid" |
||
383 | INNER JOIN "pg_attribute" AS "ia" |
||
384 | ON "ia"."attrelid" = "i"."indexrelid" AND "ia"."attnum" <= cardinality("i"."indoption") |
||
385 | WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName |
||
386 | ORDER BY "ia"."attnum" ASC |
||
387 | SQL; |
||
388 | |||
389 | $resolvedName = $this->resolveTableName($tableName); |
||
390 | $indexes = $this->db->createCommand($sql, [ |
||
391 | ':schemaName' => $resolvedName->getSchemaName(), |
||
392 | ':tableName' => $resolvedName->getName(), |
||
393 | ])->queryAll(); |
||
394 | |||
395 | /** @psalm-var array[] $indexes */ |
||
396 | $indexes = $this->normalizeRowKeyCase($indexes, true); |
||
397 | $indexes = DbArrayHelper::index($indexes, null, ['name']); |
||
398 | $result = []; |
||
399 | |||
400 | /** |
||
401 | * @psalm-var object|string|null $name |
||
402 | * @psalm-var array< |
||
403 | * array-key, |
||
404 | * array{ |
||
405 | * name: string, |
||
406 | * column_name: string, |
||
407 | * index_is_unique: bool, |
||
408 | * index_is_primary: bool |
||
409 | * } |
||
410 | * > $index |
||
411 | */ |
||
412 | foreach ($indexes as $name => $index) { |
||
413 | $ic = (new IndexConstraint()) |
||
414 | ->name($name) |
||
415 | ->columnNames(DbArrayHelper::getColumn($index, 'column_name')) |
||
416 | ->primary($index[0]['index_is_primary']) |
||
417 | ->unique($index[0]['index_is_unique']); |
||
418 | |||
419 | $result[] = $ic; |
||
420 | } |
||
421 | |||
422 | return $result; |
||
423 | } |
||
424 | |||
425 | /** |
||
426 | * Loads all unique constraints for the given table. |
||
427 | * |
||
428 | * @param string $tableName The table name. |
||
429 | * |
||
430 | * @throws Exception |
||
431 | * @throws InvalidConfigException |
||
432 | * @throws Throwable |
||
433 | * |
||
434 | * @return array Unique constraints for the given table. |
||
435 | * |
||
436 | * @psalm-return array|Constraint[] |
||
437 | */ |
||
438 | protected function loadTableUniques(string $tableName): array |
||
439 | { |
||
440 | $tableUniques = $this->loadTableConstraints($tableName, self::UNIQUES); |
||
441 | |||
442 | return is_array($tableUniques) ? $tableUniques : []; |
||
443 | } |
||
444 | |||
445 | /** |
||
446 | * Loads all check constraints for the given table. |
||
447 | * |
||
448 | * @param string $tableName The table name. |
||
449 | * |
||
450 | * @throws Exception |
||
451 | * @throws InvalidConfigException |
||
452 | * @throws Throwable |
||
453 | * |
||
454 | * @return array Check constraints for the given table. |
||
455 | * |
||
456 | * @psaml-return array|CheckConstraint[] |
||
457 | */ |
||
458 | protected function loadTableChecks(string $tableName): array |
||
459 | { |
||
460 | $tableChecks = $this->loadTableConstraints($tableName, self::CHECKS); |
||
461 | |||
462 | return is_array($tableChecks) ? $tableChecks : []; |
||
463 | } |
||
464 | |||
465 | /** |
||
466 | * Loads all default value constraints for the given table. |
||
467 | * |
||
468 | * @param string $tableName The table name. |
||
469 | * |
||
470 | * @throws NotSupportedException |
||
471 | * |
||
472 | * @return DefaultValueConstraint[] Default value constraints for the given table. |
||
473 | */ |
||
474 | protected function loadTableDefaultValues(string $tableName): array |
||
475 | { |
||
476 | throw new NotSupportedException(__METHOD__ . ' is not supported by PostgreSQL.'); |
||
477 | } |
||
478 | |||
479 | /** |
||
480 | * @throws Exception |
||
481 | * @throws InvalidConfigException |
||
482 | * @throws Throwable |
||
483 | */ |
||
484 | protected function findViewNames(string $schema = ''): array |
||
485 | { |
||
486 | if ($schema === '') { |
||
487 | $schema = $this->defaultSchema; |
||
488 | } |
||
489 | |||
490 | $sql = <<<SQL |
||
491 | SELECT c.relname AS table_name |
||
492 | FROM pg_class c |
||
493 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
494 | WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm') |
||
495 | ORDER BY c.relname |
||
496 | SQL; |
||
497 | |||
498 | return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
499 | } |
||
500 | |||
501 | /** |
||
502 | * Collects the foreign key column details for the given table. |
||
503 | * |
||
504 | * @param TableSchemaInterface $table The table metadata |
||
505 | * |
||
506 | * @throws Exception |
||
507 | * @throws InvalidConfigException |
||
508 | * @throws Throwable |
||
509 | */ |
||
510 | protected function findConstraints(TableSchemaInterface $table): void |
||
511 | { |
||
512 | /** |
||
513 | * We need to extract the constraints de hard way since: |
||
514 | * {@see https://www.postgresql.org/message-id/[email protected]} |
||
515 | */ |
||
516 | |||
517 | $sql = <<<SQL |
||
518 | SELECT |
||
519 | ct.conname as constraint_name, |
||
520 | a.attname as column_name, |
||
521 | fc.relname as foreign_table_name, |
||
522 | fns.nspname as foreign_table_schema, |
||
523 | fa.attname as foreign_column_name |
||
524 | FROM |
||
525 | (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, |
||
526 | generate_subscripts(ct.conkey, 1) AS s |
||
527 | FROM pg_constraint ct |
||
528 | ) AS ct |
||
529 | inner join pg_class c on c.oid=ct.conrelid |
||
530 | inner join pg_namespace ns on c.relnamespace=ns.oid |
||
531 | inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s] |
||
532 | left join pg_class fc on fc.oid=ct.confrelid |
||
533 | left join pg_namespace fns on fc.relnamespace=fns.oid |
||
534 | left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s] |
||
535 | WHERE |
||
536 | ct.contype='f' |
||
537 | and c.relname=:tableName |
||
538 | and ns.nspname=:schemaName |
||
539 | ORDER BY |
||
540 | fns.nspname, fc.relname, a.attnum |
||
541 | SQL; |
||
542 | |||
543 | /** @psalm-var array{array{tableName: string, columns: array}} $constraints */ |
||
544 | $constraints = []; |
||
545 | |||
546 | /** @psalm-var array<FindConstraintArray> $rows */ |
||
547 | $rows = $this->db->createCommand($sql, [ |
||
548 | ':schemaName' => $table->getSchemaName(), |
||
549 | ':tableName' => $table->getName(), |
||
550 | ])->queryAll(); |
||
551 | |||
552 | foreach ($rows as $constraint) { |
||
553 | /** @psalm-var FindConstraintArray $constraint */ |
||
554 | $constraint = $this->normalizeRowKeyCase($constraint, false); |
||
555 | |||
556 | if ($constraint['foreign_table_schema'] !== $this->defaultSchema) { |
||
557 | $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name']; |
||
558 | } else { |
||
559 | $foreignTable = $constraint['foreign_table_name']; |
||
560 | } |
||
561 | |||
562 | $name = $constraint['constraint_name']; |
||
563 | |||
564 | if (!isset($constraints[$name])) { |
||
565 | $constraints[$name] = [ |
||
566 | 'tableName' => $foreignTable, |
||
567 | 'columns' => [], |
||
568 | ]; |
||
569 | } |
||
570 | |||
571 | $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name']; |
||
572 | } |
||
573 | |||
574 | /** |
||
575 | * @psalm-var int|string $foreingKeyName. |
||
576 | * @psalm-var array{tableName: string, columns: array} $constraint |
||
577 | */ |
||
578 | foreach ($constraints as $foreingKeyName => $constraint) { |
||
579 | $table->foreignKey( |
||
580 | (string) $foreingKeyName, |
||
581 | array_merge([$constraint['tableName']], $constraint['columns']) |
||
582 | ); |
||
583 | } |
||
584 | } |
||
585 | |||
586 | /** |
||
587 | * Gets information about given table unique indexes. |
||
588 | * |
||
589 | * @param TableSchemaInterface $table The table metadata. |
||
590 | * |
||
591 | * @throws Exception |
||
592 | * @throws InvalidConfigException |
||
593 | * @throws Throwable |
||
594 | * |
||
595 | * @return array With index and column names. |
||
596 | */ |
||
597 | protected function getUniqueIndexInformation(TableSchemaInterface $table): array |
||
598 | { |
||
599 | $sql = <<<'SQL' |
||
600 | SELECT |
||
601 | i.relname as indexname, |
||
602 | pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname |
||
603 | FROM ( |
||
604 | SELECT *, generate_subscripts(indkey, 1) AS k |
||
605 | FROM pg_index |
||
606 | ) idx |
||
607 | INNER JOIN pg_class i ON i.oid = idx.indexrelid |
||
608 | INNER JOIN pg_class c ON c.oid = idx.indrelid |
||
609 | INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid |
||
610 | WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE |
||
611 | AND c.relname = :tableName AND ns.nspname = :schemaName |
||
612 | ORDER BY i.relname, k |
||
613 | SQL; |
||
614 | |||
615 | return $this->db->createCommand($sql, [ |
||
616 | ':schemaName' => $table->getSchemaName(), |
||
617 | ':tableName' => $table->getName(), |
||
618 | ])->queryAll(); |
||
619 | } |
||
620 | |||
621 | /** |
||
622 | * Returns all unique indexes for the given table. |
||
623 | * |
||
624 | * Each array element is of the following structure: |
||
625 | * |
||
626 | * ```php |
||
627 | * [ |
||
628 | * 'IndexName1' => ['col1' [, ...]], |
||
629 | * 'IndexName2' => ['col2' [, ...]], |
||
630 | * ] |
||
631 | * ``` |
||
632 | * |
||
633 | * @param TableSchemaInterface $table The table metadata |
||
634 | * |
||
635 | * @throws Exception |
||
636 | * @throws InvalidConfigException |
||
637 | * @throws Throwable |
||
638 | * |
||
639 | * @return array All unique indexes for the given table. |
||
640 | */ |
||
641 | public function findUniqueIndexes(TableSchemaInterface $table): array |
||
642 | { |
||
643 | $uniqueIndexes = []; |
||
644 | |||
645 | /** @psalm-var array{indexname: string, columnname: string} $row */ |
||
646 | foreach ($this->getUniqueIndexInformation($table) as $row) { |
||
647 | /** @psalm-var array{indexname: string, columnname: string} $row */ |
||
648 | $row = $this->normalizeRowKeyCase($row, false); |
||
649 | |||
650 | $column = $row['columnname']; |
||
651 | |||
652 | if (str_starts_with($column, '"') && str_ends_with($column, '"')) { |
||
653 | /** |
||
654 | * postgres will quote names that aren't lowercase-only. |
||
655 | * |
||
656 | * {@see https://github.com/yiisoft/yii2/issues/10613} |
||
657 | */ |
||
658 | $column = substr($column, 1, -1); |
||
659 | } |
||
660 | |||
661 | $uniqueIndexes[$row['indexname']][] = $column; |
||
662 | } |
||
663 | |||
664 | return $uniqueIndexes; |
||
665 | } |
||
666 | |||
667 | /** |
||
668 | * Collects the metadata of table columns. |
||
669 | * |
||
670 | * @param TableSchemaInterface $table The table metadata. |
||
671 | * |
||
672 | * @throws Exception |
||
673 | * @throws InvalidConfigException |
||
674 | * @throws JsonException |
||
675 | * @throws Throwable |
||
676 | * |
||
677 | * @return bool Whether the table exists in the database. |
||
678 | */ |
||
679 | protected function findColumns(TableSchemaInterface $table): bool |
||
680 | { |
||
681 | $orIdentity = ''; |
||
682 | |||
683 | if (version_compare($this->db->getServerVersion(), '12.0', '>=')) { |
||
684 | $orIdentity = 'OR a.attidentity != \'\''; |
||
685 | } |
||
686 | |||
687 | $sql = <<<SQL |
||
688 | SELECT |
||
689 | d.nspname AS table_schema, |
||
690 | c.relname AS table_name, |
||
691 | a.attname AS column_name, |
||
692 | COALESCE(td.typname, tb.typname, t.typname) AS data_type, |
||
693 | COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type, |
||
694 | (SELECT nspname FROM pg_namespace WHERE oid = COALESCE(td.typnamespace, tb.typnamespace, t.typnamespace)) AS type_scheme, |
||
695 | a.attlen AS character_maximum_length, |
||
696 | pg_catalog.col_description(c.oid, a.attnum) AS column_comment, |
||
697 | information_schema._pg_truetypmod(a, t) AS modifier, |
||
698 | NOT (a.attnotnull OR t.typnotnull) AS is_nullable, |
||
699 | COALESCE(t.typdefault, pg_get_expr(ad.adbin, ad.adrelid)) AS column_default, |
||
700 | COALESCE(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval', false) $orIdentity AS is_autoinc, |
||
701 | pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname) |
||
702 | AS sequence_name, |
||
703 | CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char |
||
704 | THEN array_to_string( |
||
705 | ( |
||
706 | SELECT array_agg(enumlabel) |
||
707 | FROM pg_enum |
||
708 | WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid) |
||
709 | )::varchar[], |
||
710 | ',') |
||
711 | ELSE NULL |
||
712 | END AS enum_values, |
||
713 | information_schema._pg_numeric_precision( |
||
714 | COALESCE(td.oid, tb.oid, a.atttypid), |
||
715 | information_schema._pg_truetypmod(a, t) |
||
716 | ) AS numeric_precision, |
||
717 | information_schema._pg_numeric_scale( |
||
718 | COALESCE(td.oid, tb.oid, a.atttypid), |
||
719 | information_schema._pg_truetypmod(a, t) |
||
720 | ) AS numeric_scale, |
||
721 | information_schema._pg_char_max_length( |
||
722 | COALESCE(td.oid, tb.oid, a.atttypid), |
||
723 | information_schema._pg_truetypmod(a, t) |
||
724 | ) AS size, |
||
725 | ct.oid IS NOT NULL AS is_pkey, |
||
726 | COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension |
||
727 | FROM |
||
728 | pg_class c |
||
729 | LEFT JOIN pg_attribute a ON a.attrelid = c.oid |
||
730 | LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum |
||
731 | LEFT JOIN pg_type t ON a.atttypid = t.oid |
||
732 | LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid |
||
733 | OR t.typbasetype > 0 AND t.typbasetype = tb.oid |
||
734 | LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid |
||
735 | LEFT JOIN pg_namespace d ON d.oid = c.relnamespace |
||
736 | LEFT JOIN pg_rewrite rw ON c.relkind = 'v' AND rw.ev_class = c.oid AND rw.rulename = '_RETURN' |
||
737 | LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p' AND a.attnum = ANY (ct.conkey) |
||
738 | OR rw.ev_action IS NOT NULL AND ct.contype = 'p' |
||
739 | AND (ARRAY( |
||
740 | SELECT regexp_matches(rw.ev_action, '{TARGETENTRY .*? :resorigtbl (\d+) :resorigcol (\d+) ', 'g') |
||
741 | ))[a.attnum:a.attnum] <@ (ct.conrelid::text || ct.conkey::text[]) |
||
742 | WHERE |
||
743 | a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped |
||
744 | AND c.relname = :tableName |
||
745 | AND d.nspname = :schemaName |
||
746 | ORDER BY |
||
747 | a.attnum; |
||
748 | SQL; |
||
749 | |||
750 | $columns = $this->db->createCommand($sql, [ |
||
751 | ':schemaName' => $table->getSchemaName(), |
||
752 | ':tableName' => $table->getName(), |
||
753 | ])->queryAll(); |
||
754 | |||
755 | if (empty($columns)) { |
||
756 | return false; |
||
757 | } |
||
758 | |||
759 | /** @psalm-var ColumnArray $info */ |
||
760 | foreach ($columns as $info) { |
||
761 | /** @psalm-var ColumnArray $info */ |
||
762 | $info = $this->normalizeRowKeyCase($info, false); |
||
763 | |||
764 | /** @psalm-var ColumnSchema $column */ |
||
765 | $column = $this->loadColumnSchema($info); |
||
766 | |||
767 | $table->column($column->getName(), $column); |
||
768 | |||
769 | if ($column->isPrimaryKey()) { |
||
770 | $table->primaryKey($column->getName()); |
||
771 | |||
772 | if ($table->getSequenceName() === null) { |
||
773 | $table->sequenceName($column->getSequenceName()); |
||
774 | } |
||
775 | } |
||
776 | } |
||
777 | |||
778 | return true; |
||
779 | } |
||
780 | |||
781 | /** |
||
782 | * Loads the column information into a {@see ColumnSchemaInterface} object. |
||
783 | * |
||
784 | * @psalm-param ColumnArray $info Column information. |
||
785 | * |
||
786 | * @return ColumnSchemaInterface The column schema object. |
||
787 | */ |
||
788 | protected function loadColumnSchema(array $info): ColumnSchemaInterface |
||
789 | { |
||
790 | $column = $this->createColumnSchema($info['column_name']); |
||
791 | $column->allowNull($info['is_nullable']); |
||
792 | $column->autoIncrement($info['is_autoinc']); |
||
793 | $column->comment($info['column_comment']); |
||
794 | |||
795 | if (!in_array($info['type_scheme'], [$this->defaultSchema, 'pg_catalog'], true)) { |
||
796 | $column->dbType($info['type_scheme'] . '.' . $info['data_type']); |
||
797 | } else { |
||
798 | $column->dbType($info['data_type']); |
||
799 | } |
||
800 | |||
801 | $column->enumValues($info['enum_values'] !== null |
||
802 | ? explode(',', str_replace(["''"], ["'"], $info['enum_values'])) |
||
803 | : null); |
||
804 | $column->unsigned(false); // has no meaning in PG |
||
805 | $column->primaryKey((bool) $info['is_pkey']); |
||
806 | $column->precision($info['numeric_precision']); |
||
807 | $column->scale($info['numeric_scale']); |
||
808 | $column->size($info['size'] === null ? null : (int) $info['size']); |
||
809 | $column->dimension($info['dimension']); |
||
810 | |||
811 | /** |
||
812 | * pg_get_serial_sequence() doesn't track DEFAULT value change. |
||
813 | * GENERATED BY IDENTITY columns always have a null default value. |
||
814 | */ |
||
815 | $defaultValue = $info['column_default']; |
||
816 | |||
817 | if ( |
||
818 | $defaultValue !== null |
||
819 | && preg_match("/^nextval\('([^']+)/", $defaultValue, $matches) === 1 |
||
820 | ) { |
||
821 | $column->sequenceName($matches[1]); |
||
822 | } elseif ($info['sequence_name'] !== null) { |
||
823 | $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName()); |
||
824 | } |
||
825 | |||
826 | if ($info['type_type'] === 'c') { |
||
827 | $column->type(self::TYPE_COMPOSITE); |
||
828 | $composite = $this->resolveTableName((string) $column->getDbType()); |
||
829 | |||
830 | if ($this->findColumns($composite)) { |
||
831 | $column->columns($composite->getColumns()); |
||
832 | } |
||
833 | } else { |
||
834 | $column->type(self::TYPE_MAP[(string) $column->getDbType()] ?? self::TYPE_STRING); |
||
835 | } |
||
836 | |||
837 | $column->phpType($this->getColumnPhpType($column)); |
||
838 | $column->defaultValue($this->normalizeDefaultValue($defaultValue, $column)); |
||
839 | |||
840 | if ($column->getType() === self::TYPE_COMPOSITE && $column->getDimension() === 0) { |
||
841 | /** @psalm-var array|null $defaultValue */ |
||
842 | $defaultValue = $column->getDefaultValue(); |
||
843 | if (is_array($defaultValue)) { |
||
844 | foreach ($column->getColumns() as $compositeColumnName => $compositeColumn) { |
||
845 | $compositeColumn->defaultValue($defaultValue[$compositeColumnName] ?? null); |
||
846 | } |
||
847 | } |
||
848 | } |
||
849 | |||
850 | return $column; |
||
851 | } |
||
852 | |||
853 | /** |
||
854 | * Extracts the PHP type from an abstract DB type. |
||
855 | * |
||
856 | * @param ColumnSchemaInterface $column The column schema information. |
||
857 | * |
||
858 | * @return string The PHP type name. |
||
859 | */ |
||
860 | protected function getColumnPhpType(ColumnSchemaInterface $column): string |
||
861 | { |
||
862 | return match ($column->getType()) { |
||
863 | self::TYPE_BIT => self::PHP_TYPE_INTEGER, |
||
864 | self::TYPE_COMPOSITE => self::PHP_TYPE_ARRAY, |
||
865 | default => parent::getColumnPhpType($column), |
||
866 | }; |
||
867 | } |
||
868 | |||
869 | /** |
||
870 | * Converts column's default value according to {@see ColumnSchema::phpType} after retrieval from the database. |
||
871 | * |
||
872 | * @param string|null $defaultValue The default value retrieved from the database. |
||
873 | * @param ColumnSchemaInterface $column The column schema object. |
||
874 | * |
||
875 | * @return mixed The normalized default value. |
||
876 | */ |
||
877 | private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed |
||
878 | { |
||
879 | if ( |
||
880 | $defaultValue === null |
||
881 | || $column->isPrimaryKey() |
||
882 | || str_starts_with($defaultValue, 'NULL::') |
||
883 | ) { |
||
884 | return null; |
||
885 | } |
||
886 | |||
887 | if ($column->getType() === self::TYPE_BOOLEAN && in_array($defaultValue, ['true', 'false'], true)) { |
||
888 | return $defaultValue === 'true'; |
||
889 | } |
||
890 | |||
891 | if ( |
||
892 | in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true) |
||
893 | && in_array(strtoupper($defaultValue), ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], true) |
||
894 | ) { |
||
895 | return new Expression($defaultValue); |
||
896 | } |
||
897 | |||
898 | $value = preg_replace("/^B?['(](.*?)[)'](?:::[^:]+)?$/s", '$1', $defaultValue); |
||
899 | $value = str_replace("''", "'", $value); |
||
900 | |||
901 | if ($column->getType() === self::TYPE_BINARY && str_starts_with($value, '\\x')) { |
||
902 | return hex2bin(substr($value, 2)); |
||
903 | } |
||
904 | |||
905 | return $column->phpTypecast($value); |
||
906 | } |
||
907 | |||
908 | /** |
||
909 | * Loads multiple types of constraints and returns the specified ones. |
||
910 | * |
||
911 | * @param string $tableName The table name. |
||
912 | * @param string $returnType The return type: |
||
913 | * - primaryKey |
||
914 | * - foreignKeys |
||
915 | * - uniques |
||
916 | * - checks |
||
917 | * |
||
918 | * @throws Exception |
||
919 | * @throws InvalidConfigException |
||
920 | * @throws Throwable |
||
921 | * |
||
922 | * @return array|Constraint|null Constraints. |
||
923 | * |
||
924 | * @psalm-return CheckConstraint[]|Constraint[]|ForeignKeyConstraint[]|Constraint|null |
||
925 | */ |
||
926 | private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null |
||
927 | { |
||
928 | $sql = <<<SQL |
||
929 | SELECT |
||
930 | "c"."conname" AS "name", |
||
931 | "a"."attname" AS "column_name", |
||
932 | "c"."contype" AS "type", |
||
933 | "ftcns"."nspname" AS "foreign_table_schema", |
||
934 | "ftc"."relname" AS "foreign_table_name", |
||
935 | "fa"."attname" AS "foreign_column_name", |
||
936 | "c"."confupdtype" AS "on_update", |
||
937 | "c"."confdeltype" AS "on_delete", |
||
938 | pg_get_constraintdef("c"."oid") AS "check_expr" |
||
939 | FROM "pg_class" AS "tc" |
||
940 | INNER JOIN "pg_namespace" AS "tcns" |
||
941 | ON "tcns"."oid" = "tc"."relnamespace" |
||
942 | INNER JOIN "pg_attribute" AS "a" |
||
943 | ON "a"."attrelid" = "tc"."oid" |
||
944 | LEFT JOIN pg_rewrite AS rw |
||
945 | ON "tc"."relkind" = 'v' AND "rw"."ev_class" = "tc"."oid" AND "rw"."rulename" = '_RETURN' |
||
946 | INNER JOIN "pg_constraint" AS "c" |
||
947 | ON "c"."conrelid" = "tc"."oid" AND "a"."attnum" = ANY ("c"."conkey") |
||
948 | OR "rw"."ev_action" IS NOT NULL AND "c"."conrelid" != 0 |
||
949 | AND (ARRAY( |
||
950 | SELECT regexp_matches("rw"."ev_action", '{TARGETENTRY .*? :resorigtbl (\d+) :resorigcol (\d+) ', 'g') |
||
951 | ))["a"."attnum":"a"."attnum"] <@ ("c"."conrelid"::text || "c"."conkey"::text[]) |
||
952 | LEFT JOIN "pg_class" AS "ftc" |
||
953 | ON "ftc"."oid" = "c"."confrelid" |
||
954 | LEFT JOIN "pg_namespace" AS "ftcns" |
||
955 | ON "ftcns"."oid" = "ftc"."relnamespace" |
||
956 | LEFT JOIN "pg_attribute" "fa" |
||
957 | ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey") |
||
958 | WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName |
||
959 | ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC |
||
960 | SQL; |
||
961 | |||
962 | /** @psalm-var string[] $actionTypes */ |
||
963 | $actionTypes = [ |
||
964 | 'a' => 'NO ACTION', |
||
965 | 'r' => 'RESTRICT', |
||
966 | 'c' => 'CASCADE', |
||
967 | 'n' => 'SET NULL', |
||
968 | 'd' => 'SET DEFAULT', |
||
969 | ]; |
||
970 | |||
971 | $resolvedName = $this->resolveTableName($tableName); |
||
972 | $constraints = $this->db->createCommand($sql, [ |
||
973 | ':schemaName' => $resolvedName->getSchemaName(), |
||
974 | ':tableName' => $resolvedName->getName(), |
||
975 | ])->queryAll(); |
||
976 | |||
977 | /** @psalm-var array[][] $constraints */ |
||
978 | $constraints = $this->normalizeRowKeyCase($constraints, true); |
||
979 | $constraints = DbArrayHelper::index($constraints, null, ['type', 'name']); |
||
980 | |||
981 | $result = [ |
||
982 | self::PRIMARY_KEY => null, |
||
983 | self::FOREIGN_KEYS => [], |
||
984 | self::UNIQUES => [], |
||
985 | self::CHECKS => [], |
||
986 | ]; |
||
987 | |||
988 | /** |
||
989 | * @psalm-var string $type |
||
990 | * @psalm-var array $names |
||
991 | */ |
||
992 | foreach ($constraints as $type => $names) { |
||
993 | /** |
||
994 | * @psalm-var object|string|null $name |
||
995 | * @psalm-var ConstraintArray $constraint |
||
996 | */ |
||
997 | foreach ($names as $name => $constraint) { |
||
998 | switch ($type) { |
||
999 | case 'p': |
||
1000 | $result[self::PRIMARY_KEY] = (new Constraint()) |
||
1001 | ->name($name) |
||
1002 | ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name')); |
||
1003 | break; |
||
1004 | case 'f': |
||
1005 | $onDelete = $actionTypes[$constraint[0]['on_delete']] ?? null; |
||
1006 | $onUpdate = $actionTypes[$constraint[0]['on_update']] ?? null; |
||
1007 | |||
1008 | $result[self::FOREIGN_KEYS][] = (new ForeignKeyConstraint()) |
||
1009 | ->name($name) |
||
1010 | ->columnNames(array_values( |
||
1011 | array_unique(DbArrayHelper::getColumn($constraint, 'column_name')) |
||
1012 | )) |
||
1013 | ->foreignSchemaName($constraint[0]['foreign_table_schema']) |
||
1014 | ->foreignTableName($constraint[0]['foreign_table_name']) |
||
1015 | ->foreignColumnNames(array_values( |
||
1016 | array_unique(DbArrayHelper::getColumn($constraint, 'foreign_column_name')) |
||
1017 | )) |
||
1018 | ->onDelete($onDelete) |
||
1019 | ->onUpdate($onUpdate); |
||
1020 | break; |
||
1021 | case 'u': |
||
1022 | $result[self::UNIQUES][] = (new Constraint()) |
||
1023 | ->name($name) |
||
1024 | ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name')); |
||
1025 | break; |
||
1026 | case 'c': |
||
1027 | $result[self::CHECKS][] = (new CheckConstraint()) |
||
1028 | ->name($name) |
||
1029 | ->columnNames(DbArrayHelper::getColumn($constraint, 'column_name')) |
||
1030 | ->expression($constraint[0]['check_expr']); |
||
1031 | break; |
||
1032 | } |
||
1033 | } |
||
1034 | } |
||
1035 | |||
1036 | foreach ($result as $type => $data) { |
||
1037 | $this->setTableMetadata($tableName, $type, $data); |
||
1038 | } |
||
1039 | |||
1040 | return $result[$returnType]; |
||
1041 | } |
||
1042 | |||
1043 | /** |
||
1044 | * Creates a column schema for the database. |
||
1045 | * |
||
1046 | * This method may be overridden by child classes to create a DBMS-specific column schema. |
||
1047 | * |
||
1048 | * @param string $name Name of the column. |
||
1049 | * |
||
1050 | * @return ColumnSchema |
||
1051 | */ |
||
1052 | private function createColumnSchema(string $name): ColumnSchema |
||
1053 | { |
||
1054 | return new ColumnSchema($name); |
||
1055 | } |
||
1056 | |||
1057 | /** |
||
1058 | * Returns the cache key for the specified table name. |
||
1059 | * |
||
1060 | * @param string $name The table name. |
||
1061 | * |
||
1062 | * @return array The cache key. |
||
1063 | */ |
||
1064 | protected function getCacheKey(string $name): array |
||
1065 | { |
||
1066 | return array_merge([self::class], $this->generateCacheKey(), [$this->getRawTableName($name)]); |
||
1067 | } |
||
1068 | |||
1069 | /** |
||
1070 | * Returns the cache tag name. |
||
1071 | * |
||
1072 | * This allows {@see refresh()} to invalidate all cached table schemas. |
||
1073 | * |
||
1074 | * @return string The cache tag name. |
||
1075 | */ |
||
1076 | protected function getCacheTag(): string |
||
1079 | } |
||
1080 | } |
||
1081 |