| Total Complexity | 107 |
| Total Lines | 1167 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Complex classes like SchemaPDOPgsql 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 SchemaPDOPgsql, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 89 | final class SchemaPDOPgsql extends Schema implements ViewInterface |
||
| 90 | { |
||
| 91 | public const TYPE_JSONB = 'jsonb'; |
||
| 92 | |||
| 93 | /** |
||
| 94 | * @var array<array-key, string> mapping from physical column types (keys) to abstract column types (values). |
||
| 95 | * |
||
| 96 | * {@see http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-TABLE} |
||
| 97 | */ |
||
| 98 | private array $typeMap = [ |
||
| 99 | 'bit' => self::TYPE_INTEGER, |
||
| 100 | 'bit varying' => self::TYPE_INTEGER, |
||
| 101 | 'varbit' => self::TYPE_INTEGER, |
||
| 102 | 'bool' => self::TYPE_BOOLEAN, |
||
| 103 | 'boolean' => self::TYPE_BOOLEAN, |
||
| 104 | 'box' => self::TYPE_STRING, |
||
| 105 | 'circle' => self::TYPE_STRING, |
||
| 106 | 'point' => self::TYPE_STRING, |
||
| 107 | 'line' => self::TYPE_STRING, |
||
| 108 | 'lseg' => self::TYPE_STRING, |
||
| 109 | 'polygon' => self::TYPE_STRING, |
||
| 110 | 'path' => self::TYPE_STRING, |
||
| 111 | 'character' => self::TYPE_CHAR, |
||
| 112 | 'char' => self::TYPE_CHAR, |
||
| 113 | 'bpchar' => self::TYPE_CHAR, |
||
| 114 | 'character varying' => self::TYPE_STRING, |
||
| 115 | 'varchar' => self::TYPE_STRING, |
||
| 116 | 'text' => self::TYPE_TEXT, |
||
| 117 | 'bytea' => self::TYPE_BINARY, |
||
| 118 | 'cidr' => self::TYPE_STRING, |
||
| 119 | 'inet' => self::TYPE_STRING, |
||
| 120 | 'macaddr' => self::TYPE_STRING, |
||
| 121 | 'real' => self::TYPE_FLOAT, |
||
| 122 | 'float4' => self::TYPE_FLOAT, |
||
| 123 | 'double precision' => self::TYPE_DOUBLE, |
||
| 124 | 'float8' => self::TYPE_DOUBLE, |
||
| 125 | 'decimal' => self::TYPE_DECIMAL, |
||
| 126 | 'numeric' => self::TYPE_DECIMAL, |
||
| 127 | 'money' => self::TYPE_MONEY, |
||
| 128 | 'smallint' => self::TYPE_SMALLINT, |
||
| 129 | 'int2' => self::TYPE_SMALLINT, |
||
| 130 | 'int4' => self::TYPE_INTEGER, |
||
| 131 | 'int' => self::TYPE_INTEGER, |
||
| 132 | 'integer' => self::TYPE_INTEGER, |
||
| 133 | 'bigint' => self::TYPE_BIGINT, |
||
| 134 | 'int8' => self::TYPE_BIGINT, |
||
| 135 | 'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal! |
||
| 136 | 'smallserial' => self::TYPE_SMALLINT, |
||
| 137 | 'serial2' => self::TYPE_SMALLINT, |
||
| 138 | 'serial4' => self::TYPE_INTEGER, |
||
| 139 | 'serial' => self::TYPE_INTEGER, |
||
| 140 | 'bigserial' => self::TYPE_BIGINT, |
||
| 141 | 'serial8' => self::TYPE_BIGINT, |
||
| 142 | 'pg_lsn' => self::TYPE_BIGINT, |
||
| 143 | 'date' => self::TYPE_DATE, |
||
| 144 | 'interval' => self::TYPE_STRING, |
||
| 145 | 'time without time zone' => self::TYPE_TIME, |
||
| 146 | 'time' => self::TYPE_TIME, |
||
| 147 | 'time with time zone' => self::TYPE_TIME, |
||
| 148 | 'timetz' => self::TYPE_TIME, |
||
| 149 | 'timestamp without time zone' => self::TYPE_TIMESTAMP, |
||
| 150 | 'timestamp' => self::TYPE_TIMESTAMP, |
||
| 151 | 'timestamp with time zone' => self::TYPE_TIMESTAMP, |
||
| 152 | 'timestamptz' => self::TYPE_TIMESTAMP, |
||
| 153 | 'abstime' => self::TYPE_TIMESTAMP, |
||
| 154 | 'tsquery' => self::TYPE_STRING, |
||
| 155 | 'tsvector' => self::TYPE_STRING, |
||
| 156 | 'txid_snapshot' => self::TYPE_STRING, |
||
| 157 | 'unknown' => self::TYPE_STRING, |
||
| 158 | 'uuid' => self::TYPE_STRING, |
||
| 159 | 'json' => self::TYPE_JSON, |
||
| 160 | 'jsonb' => self::TYPE_JSON, |
||
| 161 | 'xml' => self::TYPE_STRING, |
||
| 162 | ]; |
||
| 163 | |||
| 164 | private ?string $serverVersion = null; |
||
| 165 | private array $viewNames = []; |
||
| 166 | |||
| 167 | public function __construct(private ConnectionPDOInterface $db, SchemaCache $schemaCache) |
||
| 168 | { |
||
| 169 | parent::__construct($schemaCache); |
||
| 170 | } |
||
| 171 | |||
| 172 | /** |
||
| 173 | * @var string|null the default schema used for the current session. |
||
| 174 | */ |
||
| 175 | protected ?string $defaultSchema = 'public'; |
||
| 176 | |||
| 177 | /** |
||
| 178 | * @var string|string[] character used to quote schema, table, etc. names. An array of 2 characters can be used in |
||
| 179 | * case starting and ending characters are different. |
||
| 180 | */ |
||
| 181 | protected string|array $tableQuoteCharacter = '"'; |
||
| 182 | |||
| 183 | /** |
||
| 184 | * Resolves the table name and schema name (if any). |
||
| 185 | * |
||
| 186 | * @param string $name the table name. |
||
| 187 | * |
||
| 188 | * @return TableSchema with resolved table, schema, etc. names. |
||
| 189 | * |
||
| 190 | * {@see TableSchema} |
||
| 191 | */ |
||
| 192 | protected function resolveTableName(string $name): TableSchema |
||
| 193 | { |
||
| 194 | $resolvedName = new TableSchema(); |
||
| 195 | |||
| 196 | $parts = explode('.', str_replace('"', '', $name)); |
||
| 197 | |||
| 198 | if (isset($parts[1])) { |
||
| 199 | $resolvedName->schemaName($parts[0]); |
||
| 200 | $resolvedName->name($parts[1]); |
||
| 201 | } else { |
||
| 202 | $resolvedName->schemaName($this->defaultSchema); |
||
| 203 | $resolvedName->name($name); |
||
| 204 | } |
||
| 205 | |||
| 206 | $resolvedName->fullName( |
||
| 207 | ( |
||
| 208 | $resolvedName->getSchemaName() !== $this->defaultSchema ? |
||
| 209 | (string) $resolvedName->getSchemaName() . '.' : |
||
| 210 | '' |
||
| 211 | ) . $resolvedName->getName() |
||
| 212 | ); |
||
| 213 | |||
| 214 | return $resolvedName; |
||
| 215 | } |
||
| 216 | |||
| 217 | /** |
||
| 218 | * Returns all schema names in the database, including the default one but not system schemas. |
||
| 219 | * |
||
| 220 | * This method should be overridden by child classes in order to support this feature because the default |
||
| 221 | * implementation simply throws an exception. |
||
| 222 | * |
||
| 223 | * @throws Exception|InvalidConfigException|Throwable |
||
| 224 | * |
||
| 225 | * @return array all schema names in the database, except system schemas. |
||
| 226 | */ |
||
| 227 | protected function findSchemaNames(): array |
||
| 228 | { |
||
| 229 | $sql = <<<SQL |
||
| 230 | SELECT "ns"."nspname" |
||
| 231 | FROM "pg_namespace" AS "ns" |
||
| 232 | WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%' |
||
| 233 | ORDER BY "ns"."nspname" ASC |
||
| 234 | SQL; |
||
| 235 | |||
| 236 | return $this->db->createCommand($sql)->queryColumn(); |
||
| 237 | } |
||
| 238 | |||
| 239 | /** |
||
| 240 | * Returns all table names in the database. |
||
| 241 | * |
||
| 242 | * This method should be overridden by child classes in order to support this feature because the default |
||
| 243 | * implementation simply throws an exception. |
||
| 244 | * |
||
| 245 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. |
||
| 246 | * |
||
| 247 | * @throws Exception|InvalidConfigException|Throwable |
||
| 248 | * |
||
| 249 | * @return array all table names in the database. The names have NO schema name prefix. |
||
| 250 | */ |
||
| 251 | protected function findTableNames(string $schema = ''): array |
||
| 252 | { |
||
| 253 | if ($schema === '') { |
||
| 254 | $schema = $this->defaultSchema; |
||
| 255 | } |
||
| 256 | |||
| 257 | $sql = <<<SQL |
||
| 258 | SELECT c.relname AS table_name |
||
| 259 | FROM pg_class c |
||
| 260 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
| 261 | WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p') |
||
| 262 | ORDER BY c.relname |
||
| 263 | SQL; |
||
| 264 | |||
| 265 | return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
| 266 | } |
||
| 267 | |||
| 268 | /** |
||
| 269 | * Loads the metadata for the specified table. |
||
| 270 | * |
||
| 271 | * @param string $name table name. |
||
| 272 | * |
||
| 273 | * @throws Exception|InvalidConfigException|Throwable |
||
| 274 | * |
||
| 275 | * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist. |
||
| 276 | */ |
||
| 277 | protected function loadTableSchema(string $name): ?TableSchema |
||
| 278 | { |
||
| 279 | $table = new TableSchema(); |
||
| 280 | |||
| 281 | $this->resolveTableNames($table, $name); |
||
| 282 | |||
| 283 | if ($this->findColumns($table)) { |
||
| 284 | $this->findConstraints($table); |
||
| 285 | return $table; |
||
| 286 | } |
||
| 287 | |||
| 288 | return null; |
||
| 289 | } |
||
| 290 | |||
| 291 | /** |
||
| 292 | * Loads a primary key for the given table. |
||
| 293 | * |
||
| 294 | * @param string $tableName table name. |
||
| 295 | * |
||
| 296 | * @throws Exception|InvalidConfigException|Throwable |
||
| 297 | * |
||
| 298 | * @return Constraint|null primary key for the given table, `null` if the table has no primary key. |
||
| 299 | */ |
||
| 300 | protected function loadTablePrimaryKey(string $tableName): ?Constraint |
||
| 301 | { |
||
| 302 | $tablePrimaryKey = $this->loadTableConstraints($tableName, 'primaryKey'); |
||
| 303 | |||
| 304 | return $tablePrimaryKey instanceof Constraint ? $tablePrimaryKey : null; |
||
| 305 | } |
||
| 306 | |||
| 307 | /** |
||
| 308 | * Loads all foreign keys for the given table. |
||
| 309 | * |
||
| 310 | * @param string $tableName table name. |
||
| 311 | * |
||
| 312 | * @throws Exception|InvalidConfigException|Throwable |
||
| 313 | * |
||
| 314 | * @return array|ForeignKeyConstraint[] foreign keys for the given table. |
||
| 315 | */ |
||
| 316 | protected function loadTableForeignKeys(string $tableName): array |
||
| 317 | { |
||
| 318 | $tableForeignKeys = $this->loadTableConstraints($tableName, 'foreignKeys'); |
||
| 319 | |||
| 320 | return is_array($tableForeignKeys) ? $tableForeignKeys : []; |
||
| 321 | } |
||
| 322 | |||
| 323 | /** |
||
| 324 | * Loads all indexes for the given table. |
||
| 325 | * |
||
| 326 | * @param string $tableName table name. |
||
| 327 | * |
||
| 328 | * @throws Exception|InvalidConfigException|Throwable |
||
| 329 | * |
||
| 330 | * @return IndexConstraint[] indexes for the given table. |
||
| 331 | */ |
||
| 332 | protected function loadTableIndexes(string $tableName): array |
||
| 333 | { |
||
| 334 | $sql = <<<SQL |
||
| 335 | SELECT |
||
| 336 | "ic"."relname" AS "name", |
||
| 337 | "ia"."attname" AS "column_name", |
||
| 338 | "i"."indisunique" AS "index_is_unique", |
||
| 339 | "i"."indisprimary" AS "index_is_primary" |
||
| 340 | FROM "pg_class" AS "tc" |
||
| 341 | INNER JOIN "pg_namespace" AS "tcns" |
||
| 342 | ON "tcns"."oid" = "tc"."relnamespace" |
||
| 343 | INNER JOIN "pg_index" AS "i" |
||
| 344 | ON "i"."indrelid" = "tc"."oid" |
||
| 345 | INNER JOIN "pg_class" AS "ic" |
||
| 346 | ON "ic"."oid" = "i"."indexrelid" |
||
| 347 | INNER JOIN "pg_attribute" AS "ia" |
||
| 348 | ON "ia"."attrelid" = "i"."indexrelid" |
||
| 349 | WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName |
||
| 350 | ORDER BY "ia"."attnum" ASC |
||
| 351 | SQL; |
||
| 352 | |||
| 353 | $resolvedName = $this->resolveTableName($tableName); |
||
| 354 | |||
| 355 | $indexes = $this->db->createCommand($sql, [ |
||
| 356 | ':schemaName' => $resolvedName->getSchemaName(), |
||
| 357 | ':tableName' => $resolvedName->getName(), |
||
| 358 | ])->queryAll(); |
||
| 359 | |||
| 360 | /** @var array[] @indexes */ |
||
| 361 | $indexes = $this->normalizePdoRowKeyCase($indexes, true); |
||
| 362 | $indexes = ArrayHelper::index($indexes, null, 'name'); |
||
| 363 | $result = []; |
||
| 364 | |||
| 365 | /** |
||
| 366 | * @var object|string|null $name |
||
| 367 | * @var array< |
||
| 368 | * array-key, |
||
| 369 | * array{ |
||
| 370 | * name: string, |
||
| 371 | * column_name: string, |
||
| 372 | * index_is_unique: bool, |
||
| 373 | * index_is_primary: bool |
||
| 374 | * } |
||
| 375 | * > $index |
||
| 376 | */ |
||
| 377 | foreach ($indexes as $name => $index) { |
||
| 378 | $ic = (new IndexConstraint()) |
||
| 379 | ->name($name) |
||
| 380 | ->columnNames(ArrayHelper::getColumn($index, 'column_name')) |
||
| 381 | ->primary($index[0]['index_is_primary']) |
||
| 382 | ->unique($index[0]['index_is_unique']); |
||
| 383 | |||
| 384 | $result[] = $ic; |
||
| 385 | } |
||
| 386 | |||
| 387 | return $result; |
||
| 388 | } |
||
| 389 | |||
| 390 | /** |
||
| 391 | * Loads all unique constraints for the given table. |
||
| 392 | * |
||
| 393 | * @param string $tableName table name. |
||
| 394 | * |
||
| 395 | * @throws Exception|InvalidConfigException|Throwable |
||
| 396 | * |
||
| 397 | * @return array|Constraint[] unique constraints for the given table. |
||
| 398 | */ |
||
| 399 | protected function loadTableUniques(string $tableName): array |
||
| 400 | { |
||
| 401 | $tableUniques = $this->loadTableConstraints($tableName, 'uniques'); |
||
| 402 | |||
| 403 | return is_array($tableUniques) ? $tableUniques : []; |
||
| 404 | } |
||
| 405 | |||
| 406 | /** |
||
| 407 | * Loads all check constraints for the given table. |
||
| 408 | * |
||
| 409 | * @param string $tableName table name. |
||
| 410 | * |
||
| 411 | * @throws Exception|InvalidConfigException|Throwable |
||
| 412 | * |
||
| 413 | * @return array|CheckConstraint[] check constraints for the given table. |
||
| 414 | */ |
||
| 415 | protected function loadTableChecks(string $tableName): array |
||
| 416 | { |
||
| 417 | $tableChecks = $this->loadTableConstraints($tableName, 'checks'); |
||
| 418 | |||
| 419 | return is_array($tableChecks) ? $tableChecks : []; |
||
| 420 | } |
||
| 421 | |||
| 422 | /** |
||
| 423 | * Loads all default value constraints for the given table. |
||
| 424 | * |
||
| 425 | * @param string $tableName table name. |
||
| 426 | * |
||
| 427 | * @throws NotSupportedException |
||
| 428 | * |
||
| 429 | * @return DefaultValueConstraint[] default value constraints for the given table. |
||
| 430 | */ |
||
| 431 | protected function loadTableDefaultValues(string $tableName): array |
||
| 432 | { |
||
| 433 | throw new NotSupportedException('PostgreSQL does not support default value constraints.'); |
||
| 434 | } |
||
| 435 | |||
| 436 | /** |
||
| 437 | * Resolves the table name and schema name (if any). |
||
| 438 | * |
||
| 439 | * @param TableSchema $table the table metadata object. |
||
| 440 | * @param string $name the table name |
||
| 441 | */ |
||
| 442 | protected function resolveTableNames(TableSchema $table, string $name): void |
||
| 443 | { |
||
| 444 | $parts = explode('.', str_replace('"', '', $name)); |
||
| 445 | |||
| 446 | if (isset($parts[1])) { |
||
| 447 | $table->schemaName($parts[0]); |
||
| 448 | $table->name($parts[1]); |
||
| 449 | } else { |
||
| 450 | $table->schemaName($this->defaultSchema); |
||
| 451 | $table->name($parts[0]); |
||
| 452 | } |
||
| 453 | |||
| 454 | if ($table->getSchemaName() !== $this->defaultSchema) { |
||
| 455 | $name = (string) $table->getSchemaName() . '.' . $table->getName(); |
||
| 456 | } else { |
||
| 457 | $name = $table->getName(); |
||
| 458 | } |
||
| 459 | |||
| 460 | $table->fullName($name); |
||
| 461 | } |
||
| 462 | |||
| 463 | /** |
||
| 464 | * @throws Exception|InvalidConfigException|Throwable |
||
| 465 | */ |
||
| 466 | public function findViewNames(string $schema = ''): array |
||
| 467 | { |
||
| 468 | if ($schema === '') { |
||
| 469 | $schema = $this->defaultSchema; |
||
| 470 | } |
||
| 471 | |||
| 472 | $sql = <<<SQL |
||
| 473 | SELECT c.relname AS table_name |
||
| 474 | FROM pg_class c |
||
| 475 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
| 476 | WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm') |
||
| 477 | ORDER BY c.relname |
||
| 478 | SQL; |
||
| 479 | |||
| 480 | return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
| 481 | } |
||
| 482 | |||
| 483 | /** |
||
| 484 | * Collects the foreign key column details for the given table. |
||
| 485 | * |
||
| 486 | * @param TableSchema $table the table metadata |
||
| 487 | * |
||
| 488 | * @throws Exception|InvalidConfigException|Throwable |
||
| 489 | */ |
||
| 490 | protected function findConstraints(TableSchema $table): void |
||
| 491 | { |
||
| 492 | $tableName = $table->getName(); |
||
| 493 | $tableSchema = $table->getSchemaName(); |
||
| 494 | |||
| 495 | $tableName = $this->db->getQuoter()->quoteValue($tableName); |
||
| 496 | |||
| 497 | if ($tableSchema !== null) { |
||
| 498 | $tableSchema = $this->db->getQuoter()->quoteValue($tableSchema); |
||
| 499 | } |
||
| 500 | |||
| 501 | /** |
||
| 502 | * We need to extract the constraints de hard way since: |
||
| 503 | * {@see http://www.postgresql.org/message-id/[email protected]} |
||
| 504 | */ |
||
| 505 | |||
| 506 | $sql = <<<SQL |
||
| 507 | SELECT |
||
| 508 | ct.conname as constraint_name, |
||
| 509 | a.attname as column_name, |
||
| 510 | fc.relname as foreign_table_name, |
||
| 511 | fns.nspname as foreign_table_schema, |
||
| 512 | fa.attname as foreign_column_name |
||
| 513 | FROM |
||
| 514 | (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, |
||
| 515 | generate_subscripts(ct.conkey, 1) AS s |
||
| 516 | FROM pg_constraint ct |
||
| 517 | ) AS ct |
||
| 518 | inner join pg_class c on c.oid=ct.conrelid |
||
| 519 | inner join pg_namespace ns on c.relnamespace=ns.oid |
||
| 520 | inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s] |
||
| 521 | left join pg_class fc on fc.oid=ct.confrelid |
||
| 522 | left join pg_namespace fns on fc.relnamespace=fns.oid |
||
| 523 | left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s] |
||
| 524 | WHERE |
||
| 525 | ct.contype='f' |
||
| 526 | and c.relname=$tableName |
||
| 527 | and ns.nspname=$tableSchema |
||
| 528 | ORDER BY |
||
| 529 | fns.nspname, fc.relname, a.attnum |
||
| 530 | SQL; |
||
| 531 | |||
| 532 | /** @var array{array{tableName: string, columns: array}} $constraints */ |
||
| 533 | $constraints = []; |
||
| 534 | |||
| 535 | $slavePdo = $this->db->getSlavePdo(); |
||
| 536 | |||
| 537 | foreach ($this->db->createCommand($sql)->queryAll() as $constraint) { |
||
| 538 | if ($slavePdo !== null && $slavePdo->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) { |
||
| 539 | $constraint = array_change_key_case($constraint, CASE_LOWER); |
||
| 540 | } |
||
| 541 | |||
| 542 | if ($constraint['foreign_table_schema'] !== $this->defaultSchema) { |
||
| 543 | $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name']; |
||
| 544 | } else { |
||
| 545 | $foreignTable = $constraint['foreign_table_name']; |
||
| 546 | } |
||
| 547 | |||
| 548 | $name = $constraint['constraint_name']; |
||
| 549 | |||
| 550 | if (!isset($constraints[$name])) { |
||
| 551 | $constraints[$name] = [ |
||
| 552 | 'tableName' => $foreignTable, |
||
| 553 | 'columns' => [], |
||
| 554 | ]; |
||
| 555 | } |
||
| 556 | |||
| 557 | $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name']; |
||
| 558 | } |
||
| 559 | |||
| 560 | /** |
||
| 561 | * @var int|string $foreingKeyName. |
||
| 562 | * @var array{tableName: string, columns: array} $constraint |
||
| 563 | */ |
||
| 564 | foreach ($constraints as $foreingKeyName => $constraint) { |
||
| 565 | $table->foreignKey( |
||
| 566 | (string) $foreingKeyName, |
||
| 567 | array_merge([$constraint['tableName']], $constraint['columns']) |
||
| 568 | ); |
||
| 569 | } |
||
| 570 | } |
||
| 571 | |||
| 572 | /** |
||
| 573 | * Gets information about given table unique indexes. |
||
| 574 | * |
||
| 575 | * @param TableSchema $table the table metadata. |
||
| 576 | * |
||
| 577 | * @throws Exception|InvalidConfigException|Throwable |
||
| 578 | * |
||
| 579 | * @return array with index and column names. |
||
| 580 | */ |
||
| 581 | protected function getUniqueIndexInformation(TableSchema $table): array |
||
| 582 | { |
||
| 583 | $sql = <<<'SQL' |
||
| 584 | SELECT |
||
| 585 | i.relname as indexname, |
||
| 586 | pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname |
||
| 587 | FROM ( |
||
| 588 | SELECT *, generate_subscripts(indkey, 1) AS k |
||
| 589 | FROM pg_index |
||
| 590 | ) idx |
||
| 591 | INNER JOIN pg_class i ON i.oid = idx.indexrelid |
||
| 592 | INNER JOIN pg_class c ON c.oid = idx.indrelid |
||
| 593 | INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid |
||
| 594 | WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE |
||
| 595 | AND c.relname = :tableName AND ns.nspname = :schemaName |
||
| 596 | ORDER BY i.relname, k |
||
| 597 | SQL; |
||
| 598 | |||
| 599 | return $this->db->createCommand($sql, [ |
||
| 600 | ':schemaName' => $table->getSchemaName(), |
||
| 601 | ':tableName' => $table->getName(), |
||
| 602 | ])->queryAll(); |
||
| 603 | } |
||
| 604 | |||
| 605 | /** |
||
| 606 | * Returns all unique indexes for the given table. |
||
| 607 | * |
||
| 608 | * Each array element is of the following structure: |
||
| 609 | * |
||
| 610 | * ```php |
||
| 611 | * [ |
||
| 612 | * 'IndexName1' => ['col1' [, ...]], |
||
| 613 | * 'IndexName2' => ['col2' [, ...]], |
||
| 614 | * ] |
||
| 615 | * ``` |
||
| 616 | * |
||
| 617 | * @param TableSchema $table the table metadata |
||
| 618 | * |
||
| 619 | * @throws Exception|InvalidConfigException|Throwable |
||
| 620 | * |
||
| 621 | * @return array all unique indexes for the given table. |
||
| 622 | */ |
||
| 623 | public function findUniqueIndexes(TableSchema $table): array |
||
| 624 | { |
||
| 625 | $uniqueIndexes = []; |
||
| 626 | $slavePdo = $this->db->getSlavePdo(); |
||
| 627 | |||
| 628 | /** @var array{indexname: string, columnname: string} $row */ |
||
| 629 | foreach ($this->getUniqueIndexInformation($table) as $row) { |
||
| 630 | if ($slavePdo !== null && $slavePdo->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) { |
||
| 631 | $row = array_change_key_case($row, CASE_LOWER); |
||
| 632 | } |
||
| 633 | |||
| 634 | $column = $row['columnname']; |
||
| 635 | |||
| 636 | if (!empty($column) && $column[0] === '"') { |
||
| 637 | /** |
||
| 638 | * postgres will quote names that are not lowercase-only. |
||
| 639 | * |
||
| 640 | * {@see https://github.com/yiisoft/yii2/issues/10613} |
||
| 641 | */ |
||
| 642 | $column = substr($column, 1, -1); |
||
| 643 | } |
||
| 644 | |||
| 645 | $uniqueIndexes[$row['indexname']][] = $column; |
||
| 646 | } |
||
| 647 | |||
| 648 | return $uniqueIndexes; |
||
| 649 | } |
||
| 650 | |||
| 651 | /** |
||
| 652 | * Collects the metadata of table columns. |
||
| 653 | * |
||
| 654 | * @param TableSchema $table the table metadata. |
||
| 655 | * |
||
| 656 | * @throws Exception|InvalidConfigException|JsonException|Throwable |
||
| 657 | * |
||
| 658 | * @return bool whether the table exists in the database. |
||
| 659 | */ |
||
| 660 | protected function findColumns(TableSchema $table): bool |
||
| 661 | { |
||
| 662 | $tableName = $table->getName(); |
||
| 663 | $schemaName = $table->getSchemaName(); |
||
| 664 | $orIdentity = ''; |
||
| 665 | |||
| 666 | $tableName = $this->db->getQuoter()->quoteValue($tableName); |
||
| 667 | |||
| 668 | if ($schemaName !== null) { |
||
| 669 | $schemaName = $this->db->getQuoter()->quoteValue($schemaName); |
||
| 670 | } |
||
| 671 | |||
| 672 | if (version_compare($this->db->getServerVersion(), '12.0', '>=')) { |
||
| 673 | $orIdentity = 'OR a.attidentity != \'\''; |
||
| 674 | } |
||
| 675 | |||
| 676 | $sql = <<<SQL |
||
| 677 | SELECT |
||
| 678 | d.nspname AS table_schema, |
||
| 679 | c.relname AS table_name, |
||
| 680 | a.attname AS column_name, |
||
| 681 | COALESCE(td.typname, tb.typname, t.typname) AS data_type, |
||
| 682 | COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type, |
||
| 683 | a.attlen AS character_maximum_length, |
||
| 684 | pg_catalog.col_description(c.oid, a.attnum) AS column_comment, |
||
| 685 | a.atttypmod AS modifier, |
||
| 686 | a.attnotnull = false AS is_nullable, |
||
| 687 | CAST(pg_get_expr(ad.adbin, ad.adrelid) AS varchar) AS column_default, |
||
| 688 | coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval',false) $orIdentity AS is_autoinc, |
||
| 689 | pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname) |
||
| 690 | AS sequence_name, |
||
| 691 | CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char |
||
| 692 | THEN array_to_string( |
||
| 693 | ( |
||
| 694 | SELECT array_agg(enumlabel) |
||
| 695 | FROM pg_enum |
||
| 696 | WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid) |
||
| 697 | )::varchar[], |
||
| 698 | ',') |
||
| 699 | ELSE NULL |
||
| 700 | END AS enum_values, |
||
| 701 | CASE atttypid |
||
| 702 | WHEN 21 /*int2*/ THEN 16 |
||
| 703 | WHEN 23 /*int4*/ THEN 32 |
||
| 704 | WHEN 20 /*int8*/ THEN 64 |
||
| 705 | WHEN 1700 /*numeric*/ THEN |
||
| 706 | CASE WHEN atttypmod = -1 |
||
| 707 | THEN null |
||
| 708 | ELSE ((atttypmod - 4) >> 16) & 65535 |
||
| 709 | END |
||
| 710 | WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/ |
||
| 711 | WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/ |
||
| 712 | ELSE null |
||
| 713 | END AS numeric_precision, |
||
| 714 | CASE |
||
| 715 | WHEN atttypid IN (21, 23, 20) THEN 0 |
||
| 716 | WHEN atttypid IN (1700) THEN |
||
| 717 | CASE |
||
| 718 | WHEN atttypmod = -1 THEN null |
||
| 719 | ELSE (atttypmod - 4) & 65535 |
||
| 720 | END |
||
| 721 | ELSE null |
||
| 722 | END AS numeric_scale, |
||
| 723 | CAST( |
||
| 724 | information_schema._pg_char_max_length( |
||
| 725 | information_schema._pg_truetypid(a, t), |
||
| 726 | information_schema._pg_truetypmod(a, t) |
||
| 727 | ) AS numeric |
||
| 728 | ) AS size, |
||
| 729 | a.attnum = any (ct.conkey) as is_pkey, |
||
| 730 | COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension |
||
| 731 | FROM |
||
| 732 | pg_class c |
||
| 733 | LEFT JOIN pg_attribute a ON a.attrelid = c.oid |
||
| 734 | LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum |
||
| 735 | LEFT JOIN pg_type t ON a.atttypid = t.oid |
||
| 736 | LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid |
||
| 737 | OR t.typbasetype > 0 AND t.typbasetype = tb.oid |
||
| 738 | LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid |
||
| 739 | LEFT JOIN pg_namespace d ON d.oid = c.relnamespace |
||
| 740 | LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p' |
||
| 741 | WHERE |
||
| 742 | a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped |
||
| 743 | AND c.relname = $tableName |
||
| 744 | AND d.nspname = $schemaName |
||
| 745 | ORDER BY |
||
| 746 | a.attnum; |
||
| 747 | SQL; |
||
| 748 | |||
| 749 | /** @var array columns */ |
||
| 750 | $columns = $this->db->createCommand($sql)->queryAll(); |
||
| 751 | $slavePdo = $this->db->getSlavePdo(); |
||
| 752 | |||
| 753 | if (empty($columns)) { |
||
| 754 | return false; |
||
| 755 | } |
||
| 756 | |||
| 757 | /** @var array $column */ |
||
| 758 | foreach ($columns as $column) { |
||
| 759 | if ($slavePdo !== null && $slavePdo->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) { |
||
| 760 | $column = array_change_key_case($column, CASE_LOWER); |
||
| 761 | } |
||
| 762 | |||
| 763 | /** @psalm-var ColumnArray $column */ |
||
| 764 | $loadColumnSchema = $this->loadColumnSchema($column); |
||
| 765 | $table->columns($loadColumnSchema->getName(), $loadColumnSchema); |
||
| 766 | $defaultValue = $loadColumnSchema->getDefaultValue(); |
||
| 767 | |||
| 768 | if ($loadColumnSchema->isPrimaryKey()) { |
||
| 769 | $table->primaryKey($loadColumnSchema->getName()); |
||
| 770 | |||
| 771 | if ($table->getSequenceName() === null) { |
||
| 772 | $table->sequenceName($loadColumnSchema->getSequenceName()); |
||
| 773 | } |
||
| 774 | |||
| 775 | $loadColumnSchema->defaultValue(null); |
||
| 776 | } elseif ($defaultValue) { |
||
| 777 | if ( |
||
| 778 | is_string($defaultValue) && |
||
| 779 | in_array( |
||
| 780 | $loadColumnSchema->getType(), |
||
| 781 | [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], |
||
| 782 | true |
||
| 783 | ) && |
||
| 784 | in_array( |
||
| 785 | strtoupper($defaultValue), |
||
| 786 | ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], |
||
| 787 | true |
||
| 788 | ) |
||
| 789 | ) { |
||
| 790 | $loadColumnSchema->defaultValue(new Expression($defaultValue)); |
||
| 791 | } elseif ($loadColumnSchema->getType() === 'boolean') { |
||
| 792 | $loadColumnSchema->defaultValue(($defaultValue === 'true')); |
||
| 793 | } elseif (is_string($defaultValue) && preg_match("/^B'(.*?)'::/", $defaultValue, $matches)) { |
||
| 794 | $loadColumnSchema->defaultValue(bindec($matches[1])); |
||
| 795 | } elseif (is_string($defaultValue) && preg_match("/^'(\d+)'::\"bit\"$/", $defaultValue, $matches)) { |
||
| 796 | $loadColumnSchema->defaultValue(bindec($matches[1])); |
||
| 797 | } elseif (is_string($defaultValue) && preg_match("/^'(.*?)'::/", $defaultValue, $matches)) { |
||
| 798 | $loadColumnSchema->defaultValue($loadColumnSchema->phpTypecast($matches[1])); |
||
| 799 | } elseif ( |
||
| 800 | is_string($defaultValue) && |
||
| 801 | preg_match('/^(\()?(.*?)(?(1)\))(?:::.+)?$/', $defaultValue, $matches) |
||
| 802 | ) { |
||
| 803 | if ($matches[2] === 'NULL') { |
||
| 804 | $loadColumnSchema->defaultValue(null); |
||
| 805 | } else { |
||
| 806 | $loadColumnSchema->defaultValue($loadColumnSchema->phpTypecast($matches[2])); |
||
| 807 | } |
||
| 808 | } else { |
||
| 809 | $loadColumnSchema->defaultValue($loadColumnSchema->phpTypecast($defaultValue)); |
||
| 810 | } |
||
| 811 | } |
||
| 812 | } |
||
| 813 | |||
| 814 | return true; |
||
| 815 | } |
||
| 816 | |||
| 817 | /** |
||
| 818 | * Loads the column information into a {@see ColumnSchema} object. |
||
| 819 | * |
||
| 820 | * @param array{ |
||
| 821 | * table_schema: string, |
||
| 822 | * table_name: string, |
||
| 823 | * column_name: string, |
||
| 824 | * data_type: string, |
||
| 825 | * type_type: string|null, |
||
| 826 | * character_maximum_length: int, |
||
| 827 | * column_comment: string|null, |
||
| 828 | * modifier: int, |
||
| 829 | * is_nullable: bool, |
||
| 830 | * column_default: mixed, |
||
| 831 | * is_autoinc: bool, |
||
| 832 | * sequence_name: string|null, |
||
| 833 | * enum_values: array<array-key, float|int|string>|string|null, |
||
| 834 | * numeric_precision: int|null, |
||
| 835 | * numeric_scale: int|null, |
||
| 836 | * size: string|null, |
||
| 837 | * is_pkey: bool|null, |
||
| 838 | * dimension: int |
||
| 839 | * } $info column information. |
||
| 840 | * |
||
| 841 | * @return ColumnSchema the column schema object. |
||
| 842 | */ |
||
| 843 | protected function loadColumnSchema(array $info): ColumnSchema |
||
| 844 | { |
||
| 845 | $column = $this->createColumnSchema(); |
||
| 846 | $column->allowNull($info['is_nullable']); |
||
| 847 | $column->autoIncrement($info['is_autoinc']); |
||
| 848 | $column->comment($info['column_comment']); |
||
| 849 | $column->dbType($info['data_type']); |
||
| 850 | $column->defaultValue($info['column_default']); |
||
| 851 | $column->enumValues(($info['enum_values'] !== null) |
||
| 852 | ? explode(',', str_replace(["''"], ["'"], $info['enum_values'])) : null); |
||
| 853 | $column->unsigned(false); // has no meaning in PG |
||
| 854 | $column->primaryKey((bool) $info['is_pkey']); |
||
| 855 | $column->name($info['column_name']); |
||
| 856 | $column->precision($info['numeric_precision']); |
||
| 857 | $column->scale($info['numeric_scale']); |
||
| 858 | $column->size($info['size'] === null ? null : (int) $info['size']); |
||
| 859 | $column->dimension($info['dimension']); |
||
| 860 | |||
| 861 | /** |
||
| 862 | * pg_get_serial_sequence() doesn't track DEFAULT value change. GENERATED BY IDENTITY columns always have null |
||
| 863 | * default value. |
||
| 864 | */ |
||
| 865 | $defaultValue = $column->getDefaultValue(); |
||
| 866 | $sequenceName = $info['sequence_name'] ?? null; |
||
| 867 | |||
| 868 | if ( |
||
| 869 | isset($defaultValue) && |
||
| 870 | is_string($defaultValue) && |
||
| 871 | preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $defaultValue) === 1 |
||
| 872 | ) { |
||
| 873 | $column->sequenceName(preg_replace( |
||
| 874 | ['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], |
||
| 875 | '', |
||
| 876 | $defaultValue |
||
| 877 | )); |
||
| 878 | } elseif ($sequenceName !== null) { |
||
| 879 | $column->sequenceName($this->resolveTableName($sequenceName)->getFullName()); |
||
| 880 | } |
||
| 881 | |||
| 882 | if (isset($this->typeMap[$column->getDbType()])) { |
||
| 883 | $column->type($this->typeMap[$column->getDbType()]); |
||
| 884 | } else { |
||
| 885 | $column->type(self::TYPE_STRING); |
||
| 886 | } |
||
| 887 | |||
| 888 | $column->phpType($this->getColumnPhpType($column)); |
||
| 889 | |||
| 890 | return $column; |
||
| 891 | } |
||
| 892 | |||
| 893 | /** |
||
| 894 | * Executes the INSERT command, returning primary key values. |
||
| 895 | * |
||
| 896 | * @param string $table the table that new rows will be inserted into. |
||
| 897 | * @param array $columns the column data (name => value) to be inserted into the table. |
||
| 898 | * |
||
| 899 | * @throws Exception|InvalidConfigException|Throwable |
||
| 900 | * |
||
| 901 | * @return array|false primary key values or false if the command fails. |
||
| 902 | */ |
||
| 903 | public function insert(string $table, array $columns): bool|array |
||
| 904 | { |
||
| 905 | $params = []; |
||
| 906 | $returnColumns = []; |
||
| 907 | $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params); |
||
| 908 | |||
| 909 | $tableSchema = $this->getTableSchema($table); |
||
| 910 | |||
| 911 | if ($tableSchema !== null) { |
||
| 912 | $returnColumns = $tableSchema->getPrimaryKey(); |
||
| 913 | } |
||
| 914 | |||
| 915 | if (!empty($returnColumns)) { |
||
| 916 | $returning = []; |
||
| 917 | /** @var string $name */ |
||
| 918 | foreach ($returnColumns as $name) { |
||
| 919 | $returning[] = $this->db->getQuoter()->quoteColumnName($name); |
||
| 920 | } |
||
| 921 | $sql .= ' RETURNING ' . implode(', ', $returning); |
||
| 922 | } |
||
| 923 | |||
| 924 | $command = $this->db->createCommand($sql, $params); |
||
| 925 | $command->prepare(false); |
||
| 926 | $result = $command->queryOne(); |
||
| 927 | |||
| 928 | $pdoStatement = $command->getPdoStatement(); |
||
| 929 | |||
| 930 | return $pdoStatement !== null && !$pdoStatement->rowCount() ? false : $result; |
||
| 931 | } |
||
| 932 | |||
| 933 | /** |
||
| 934 | * Loads multiple types of constraints and returns the specified ones. |
||
| 935 | * |
||
| 936 | * @param string $tableName table name. |
||
| 937 | * @param string $returnType return type: |
||
| 938 | * - primaryKey |
||
| 939 | * - foreignKeys |
||
| 940 | * - uniques |
||
| 941 | * - checks |
||
| 942 | * |
||
| 943 | * @return array|Constraint|null (CheckConstraint|Constraint|ForeignKeyConstraint)[]|Constraint|null constraints. |
||
| 944 | * |
||
| 945 | * @throws Exception|InvalidConfigException|Throwable |
||
| 946 | */ |
||
| 947 | private function loadTableConstraints(string $tableName, string $returnType): array|Constraint|null |
||
| 948 | { |
||
| 949 | $sql = <<<SQL |
||
| 950 | SELECT |
||
| 951 | "c"."conname" AS "name", |
||
| 952 | "a"."attname" AS "column_name", |
||
| 953 | "c"."contype" AS "type", |
||
| 954 | "ftcns"."nspname" AS "foreign_table_schema", |
||
| 955 | "ftc"."relname" AS "foreign_table_name", |
||
| 956 | "fa"."attname" AS "foreign_column_name", |
||
| 957 | "c"."confupdtype" AS "on_update", |
||
| 958 | "c"."confdeltype" AS "on_delete", |
||
| 959 | pg_get_constraintdef("c"."oid") AS "check_expr" |
||
| 960 | FROM "pg_class" AS "tc" |
||
| 961 | INNER JOIN "pg_namespace" AS "tcns" |
||
| 962 | ON "tcns"."oid" = "tc"."relnamespace" |
||
| 963 | INNER JOIN "pg_constraint" AS "c" |
||
| 964 | ON "c"."conrelid" = "tc"."oid" |
||
| 965 | INNER JOIN "pg_attribute" AS "a" |
||
| 966 | ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey") |
||
| 967 | LEFT JOIN "pg_class" AS "ftc" |
||
| 968 | ON "ftc"."oid" = "c"."confrelid" |
||
| 969 | LEFT JOIN "pg_namespace" AS "ftcns" |
||
| 970 | ON "ftcns"."oid" = "ftc"."relnamespace" |
||
| 971 | LEFT JOIN "pg_attribute" "fa" |
||
| 972 | ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey") |
||
| 973 | WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName |
||
| 974 | ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC |
||
| 975 | SQL; |
||
| 976 | |||
| 977 | /** @var array<array-key, string> $actionTypes */ |
||
| 978 | $actionTypes = [ |
||
| 979 | 'a' => 'NO ACTION', |
||
| 980 | 'r' => 'RESTRICT', |
||
| 981 | 'c' => 'CASCADE', |
||
| 982 | 'n' => 'SET NULL', |
||
| 983 | 'd' => 'SET DEFAULT', |
||
| 984 | ]; |
||
| 985 | |||
| 986 | $resolvedName = $this->resolveTableName($tableName); |
||
| 987 | |||
| 988 | $constraints = $this->db->createCommand($sql, [ |
||
| 989 | ':schemaName' => $resolvedName->getSchemaName(), |
||
| 990 | ':tableName' => $resolvedName->getName(), |
||
| 991 | ])->queryAll(); |
||
| 992 | |||
| 993 | /** @var array<array-key, array> $constraints */ |
||
| 994 | $constraints = $this->normalizePdoRowKeyCase($constraints, true); |
||
| 995 | $constraints = ArrayHelper::index($constraints, null, ['type', 'name']); |
||
| 996 | |||
| 997 | $result = [ |
||
| 998 | 'primaryKey' => null, |
||
| 999 | 'foreignKeys' => [], |
||
| 1000 | 'uniques' => [], |
||
| 1001 | 'checks' => [], |
||
| 1002 | ]; |
||
| 1003 | |||
| 1004 | /** |
||
| 1005 | * @var string $type |
||
| 1006 | * @var array $names |
||
| 1007 | */ |
||
| 1008 | foreach ($constraints as $type => $names) { |
||
| 1009 | /** |
||
| 1010 | * @psalm-var object|string|null $name |
||
| 1011 | * @psalm-var ConstraintArray $constraint |
||
| 1012 | */ |
||
| 1013 | foreach ($names as $name => $constraint) { |
||
| 1014 | switch ($type) { |
||
| 1015 | case 'p': |
||
| 1016 | $ct = (new Constraint()) |
||
| 1017 | ->name($name) |
||
| 1018 | ->columnNames(ArrayHelper::getColumn($constraint, 'column_name')); |
||
| 1019 | |||
| 1020 | $result['primaryKey'] = $ct; |
||
| 1021 | break; |
||
| 1022 | case 'f': |
||
| 1023 | $onDelete = $actionTypes[$constraint[0]['on_delete']] ?? null; |
||
| 1024 | $onUpdate = $actionTypes[$constraint[0]['on_update']] ?? null; |
||
| 1025 | |||
| 1026 | $fk = (new ForeignKeyConstraint()) |
||
| 1027 | ->name($name) |
||
| 1028 | ->columnNames(array_values( |
||
| 1029 | array_unique(ArrayHelper::getColumn($constraint, 'column_name')) |
||
| 1030 | )) |
||
| 1031 | ->foreignSchemaName($constraint[0]['foreign_table_schema']) |
||
| 1032 | ->foreignTableName($constraint[0]['foreign_table_name']) |
||
| 1033 | ->foreignColumnNames(array_values( |
||
| 1034 | array_unique(ArrayHelper::getColumn($constraint, 'foreign_column_name')) |
||
| 1035 | )) |
||
| 1036 | ->onDelete($onDelete) |
||
| 1037 | ->onUpdate($onUpdate); |
||
| 1038 | |||
| 1039 | $result['foreignKeys'][] = $fk; |
||
| 1040 | break; |
||
| 1041 | case 'u': |
||
| 1042 | $ct = (new Constraint()) |
||
| 1043 | ->name($name) |
||
| 1044 | ->columnNames(ArrayHelper::getColumn($constraint, 'column_name')); |
||
| 1045 | |||
| 1046 | $result['uniques'][] = $ct; |
||
| 1047 | break; |
||
| 1048 | case 'c': |
||
| 1049 | $ck = (new CheckConstraint()) |
||
| 1050 | ->name($name) |
||
| 1051 | ->columnNames(ArrayHelper::getColumn($constraint, 'column_name')) |
||
| 1052 | ->expression($constraint[0]['check_expr']); |
||
| 1053 | |||
| 1054 | $result['checks'][] = $ck; |
||
| 1055 | break; |
||
| 1056 | } |
||
| 1057 | } |
||
| 1058 | } |
||
| 1059 | |||
| 1060 | foreach ($result as $type => $data) { |
||
| 1061 | $this->setTableMetadata($tableName, $type, $data); |
||
| 1062 | } |
||
| 1063 | |||
| 1064 | return $result[$returnType]; |
||
| 1065 | } |
||
| 1066 | |||
| 1067 | /** |
||
| 1068 | * Creates a column schema for the database. |
||
| 1069 | * |
||
| 1070 | * This method may be overridden by child classes to create a DBMS-specific column schema. |
||
| 1071 | * |
||
| 1072 | * @return ColumnSchema column schema instance. |
||
| 1073 | */ |
||
| 1074 | private function createColumnSchema(): ColumnSchema |
||
| 1075 | { |
||
| 1076 | return new ColumnSchema(); |
||
| 1077 | } |
||
| 1078 | |||
| 1079 | /** |
||
| 1080 | * Create a column schema builder instance giving the type and value precision. |
||
| 1081 | * |
||
| 1082 | * This method may be overridden by child classes to create a DBMS-specific column schema builder. |
||
| 1083 | * |
||
| 1084 | * @param string $type type of the column. See {@see ColumnSchemaBuilder::$type}. |
||
| 1085 | * @param array|int|string|null $length length or precision of the column. See {@see ColumnSchemaBuilder::$length}. |
||
| 1086 | * |
||
| 1087 | * @return ColumnSchemaBuilder column schema builder instance |
||
| 1088 | */ |
||
| 1089 | public function createColumnSchemaBuilder(string $type, array|int|string $length = null): ColumnSchemaBuilder |
||
| 1090 | { |
||
| 1091 | return new ColumnSchemaBuilder($type, $length); |
||
| 1092 | } |
||
| 1093 | |||
| 1094 | public function rollBackSavepoint(string $name): void |
||
| 1095 | { |
||
| 1096 | $this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute(); |
||
| 1097 | } |
||
| 1098 | |||
| 1099 | public function setTransactionIsolationLevel(string $level): void |
||
| 1100 | { |
||
| 1101 | $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute(); |
||
| 1102 | } |
||
| 1103 | |||
| 1104 | /** |
||
| 1105 | * Returns the actual name of a given table name. |
||
| 1106 | * |
||
| 1107 | * This method will strip off curly brackets from the given table name and replace the percentage character '%' with |
||
| 1108 | * {@see ConnectionInterface::tablePrefix}. |
||
| 1109 | * |
||
| 1110 | * @param string $name the table name to be converted. |
||
| 1111 | * |
||
| 1112 | * @return string the real name of the given table name. |
||
| 1113 | */ |
||
| 1114 | public function getRawTableName(string $name): string |
||
| 1115 | { |
||
| 1116 | if (str_contains($name, '{{')) { |
||
| 1117 | $name = preg_replace('/{{(.*?)}}/', '\1', $name); |
||
| 1118 | |||
| 1119 | return str_replace('%', $this->db->getTablePrefix(), $name); |
||
| 1120 | } |
||
| 1121 | |||
| 1122 | return $name; |
||
| 1123 | } |
||
| 1124 | |||
| 1125 | /** |
||
| 1126 | * Returns the cache key for the specified table name. |
||
| 1127 | * |
||
| 1128 | * @param string $name the table name. |
||
| 1129 | * |
||
| 1130 | * @return array the cache key. |
||
| 1131 | */ |
||
| 1132 | protected function getCacheKey(string $name): array |
||
| 1133 | { |
||
| 1134 | return [ |
||
| 1135 | __CLASS__, |
||
| 1136 | $this->db->getDriver()->getDsn(), |
||
| 1137 | $this->db->getDriver()->getUsername(), |
||
| 1138 | $this->getRawTableName($name), |
||
| 1139 | ]; |
||
| 1140 | } |
||
| 1141 | |||
| 1142 | /** |
||
| 1143 | * Returns the cache tag name. |
||
| 1144 | * |
||
| 1145 | * This allows {@see refresh()} to invalidate all cached table schemas. |
||
| 1146 | * |
||
| 1147 | * @return string the cache tag name. |
||
| 1148 | */ |
||
| 1149 | protected function getCacheTag(): string |
||
| 1150 | { |
||
| 1151 | return md5(serialize([ |
||
| 1152 | __CLASS__, |
||
| 1153 | $this->db->getDriver()->getDsn(), |
||
| 1154 | $this->db->getDriver()->getUsername(), |
||
| 1155 | ])); |
||
| 1156 | } |
||
| 1157 | |||
| 1158 | /** |
||
| 1159 | * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint). |
||
| 1160 | */ |
||
| 1161 | public function supportsSavepoint(): bool |
||
| 1162 | { |
||
| 1163 | return $this->db->isSavepointEnabled(); |
||
| 1164 | } |
||
| 1165 | |||
| 1166 | /** |
||
| 1167 | * Returns a server version as a string comparable by {@see version_compare()}. |
||
| 1168 | * |
||
| 1169 | * @throws Exception |
||
| 1170 | * |
||
| 1171 | * @return string server version as a string. |
||
| 1172 | */ |
||
| 1173 | public function getServerVersion(): string |
||
| 1174 | { |
||
| 1175 | if ($this->serverVersion === null) { |
||
| 1176 | $this->serverVersion = $this->db->getSlavePdo()->getAttribute(PDO::ATTR_SERVER_VERSION); |
||
| 1177 | } |
||
| 1178 | |||
| 1179 | return $this->serverVersion; |
||
| 1180 | } |
||
| 1181 | |||
| 1182 | /** |
||
| 1183 | * Changes row's array key case to lower if PDO one is set to uppercase. |
||
| 1184 | * |
||
| 1185 | * @param array $row row's array or an array of row's arrays. |
||
| 1186 | * @param bool $multiple whether multiple rows or a single row passed. |
||
| 1187 | * |
||
| 1188 | * @throws Exception |
||
| 1189 | * |
||
| 1190 | * @return array normalized row or rows. |
||
| 1191 | */ |
||
| 1192 | protected function normalizePdoRowKeyCase(array $row, bool $multiple): array |
||
| 1193 | { |
||
| 1194 | if ($this->db->getSlavePdo()->getAttribute(PDO::ATTR_CASE) !== PDO::CASE_UPPER) { |
||
| 1195 | return $row; |
||
| 1196 | } |
||
| 1197 | |||
| 1198 | if ($multiple) { |
||
| 1199 | return array_map(static function (array $row) { |
||
| 1200 | return array_change_key_case($row, CASE_LOWER); |
||
| 1201 | }, $row); |
||
| 1202 | } |
||
| 1203 | |||
| 1204 | return array_change_key_case($row, CASE_LOWER); |
||
| 1205 | } |
||
| 1206 | |||
| 1207 | /** |
||
| 1208 | * Returns the ID of the last inserted row or sequence value. |
||
| 1209 | * |
||
| 1210 | * @param string $sequenceName name of the sequence object (required by some DBMS) |
||
| 1211 | * |
||
| 1212 | * @throws InvalidCallException if the DB connection is not active |
||
| 1213 | * |
||
| 1214 | * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object |
||
| 1215 | * |
||
| 1216 | * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php |
||
| 1217 | */ |
||
| 1218 | public function getLastInsertID(string $sequenceName = ''): string |
||
| 1219 | { |
||
| 1220 | if ($this->db->isActive()) { |
||
| 1221 | return $this->db->getPDO()->lastInsertId( |
||
| 1222 | $sequenceName === '' ? null : $this->db->getQuoter()->quoteTableName($sequenceName) |
||
| 1223 | ); |
||
| 1224 | } |
||
| 1225 | |||
| 1226 | throw new InvalidCallException('DB Connection is not active.'); |
||
| 1227 | } |
||
| 1228 | |||
| 1229 | /** |
||
| 1230 | * Creates a new savepoint. |
||
| 1231 | * |
||
| 1232 | * @param string $name the savepoint name |
||
| 1233 | * |
||
| 1234 | * @throws Exception|InvalidConfigException|Throwable |
||
| 1235 | */ |
||
| 1236 | public function createSavepoint(string $name): void |
||
| 1239 | } |
||
| 1240 | |||
| 1241 | /** |
||
| 1242 | * @throws Exception|InvalidConfigException|Throwable |
||
| 1243 | */ |
||
| 1244 | public function releaseSavepoint(string $name): void |
||
| 1245 | { |
||
| 1246 | $this->db->createCommand("RELEASE SAVEPOINT $name")->execute(); |
||
| 1247 | } |
||
| 1248 | |||
| 1249 | public function getViewNames(string $schema = '', bool $refresh = false): array |
||
| 1256 | } |
||
| 1257 | } |
||
| 1258 |
The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g.
excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths