| Total Complexity | 69 |
| Total Lines | 895 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like PgsqlSchema 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 PgsqlSchema, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 38 | final class PgsqlSchema extends Schema 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 PgsqlTableSchema with resolved table, schema, etc. names. |
||
| 133 | * |
||
| 134 | * {@see \Yiisoft\Db\Schema\TableSchema} |
||
| 135 | */ |
||
| 136 | protected function resolveTableName(string $name): PgsqlTableSchema |
||
| 137 | { |
||
| 138 | $resolvedName = new PgsqlTableSchema(); |
||
| 139 | $parts = explode('.', str_replace('"', '', $name)); |
||
| 140 | |||
| 141 | if (isset($parts[1])) { |
||
| 142 | $resolvedName->schemaName($parts[0]); |
||
| 143 | $resolvedName->name($parts[1]); |
||
| 144 | } else { |
||
| 145 | $resolvedName->schemaName($this->defaultSchema); |
||
| 146 | $resolvedName->name($name); |
||
| 147 | } |
||
| 148 | |||
| 149 | $resolvedName->fullName( |
||
| 150 | ( |
||
| 151 | $resolvedName->getSchemaName() !== $this->defaultSchema ? $resolvedName->getSchemaName() . '.' : '' |
||
| 152 | ) . $resolvedName->getName() |
||
| 153 | ); |
||
| 154 | |||
| 155 | return $resolvedName; |
||
| 156 | } |
||
| 157 | |||
| 158 | /** |
||
| 159 | * Returns all schema names in the database, including the default one but not system schemas. |
||
| 160 | * |
||
| 161 | * This method should be overridden by child classes in order to support this feature because the default |
||
| 162 | * implementation simply throws an exception. |
||
| 163 | * |
||
| 164 | * @throws Exception |
||
| 165 | * @throws InvalidArgumentException |
||
| 166 | * @throws InvalidConfigException |
||
| 167 | * |
||
| 168 | * @return array all schema names in the database, except system schemas. |
||
| 169 | */ |
||
| 170 | protected function findSchemaNames(): array |
||
| 171 | { |
||
| 172 | static $sql = <<<'SQL' |
||
| 173 | SELECT "ns"."nspname" |
||
| 174 | FROM "pg_namespace" AS "ns" |
||
| 175 | WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%' |
||
| 176 | ORDER BY "ns"."nspname" ASC |
||
| 177 | SQL; |
||
| 178 | |||
| 179 | return $this->getDb()->createCommand($sql)->queryColumn(); |
||
| 180 | } |
||
| 181 | |||
| 182 | /** |
||
| 183 | * Returns all table names in the database. |
||
| 184 | * |
||
| 185 | * This method should be overridden by child classes in order to support this feature because the default |
||
| 186 | * implementation simply throws an exception. |
||
| 187 | * |
||
| 188 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. |
||
| 189 | * |
||
| 190 | * @throws Exception |
||
| 191 | * @throws InvalidArgumentException |
||
| 192 | * @throws InvalidConfigException |
||
| 193 | * |
||
| 194 | * @return array all table names in the database. The names have NO schema name prefix. |
||
| 195 | */ |
||
| 196 | protected function findTableNames(string $schema = ''): array |
||
| 197 | { |
||
| 198 | if ($schema === '') { |
||
| 199 | $schema = $this->defaultSchema; |
||
| 200 | } |
||
| 201 | |||
| 202 | $sql = <<<'SQL' |
||
| 203 | SELECT c.relname AS table_name |
||
| 204 | FROM pg_class c |
||
| 205 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
| 206 | WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p') |
||
| 207 | ORDER BY c.relname |
||
| 208 | SQL; |
||
| 209 | return $this->getDb()->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
| 210 | } |
||
| 211 | |||
| 212 | /** |
||
| 213 | * Loads the metadata for the specified table. |
||
| 214 | * |
||
| 215 | * @param string $name table name. |
||
| 216 | * |
||
| 217 | * @throws Exception |
||
| 218 | * @throws InvalidArgumentException |
||
| 219 | * @throws InvalidConfigException |
||
| 220 | * @throws NotSupportedException |
||
| 221 | * |
||
| 222 | * @return PgsqlTableSchema|null DBMS-dependent table metadata, `null` if the table does not exist. |
||
| 223 | */ |
||
| 224 | protected function loadTableSchema(string $name): ?PgsqlTableSchema |
||
| 225 | { |
||
| 226 | $table = new PgsqlTableSchema(); |
||
| 227 | |||
| 228 | $this->resolveTableNames($table, $name); |
||
| 229 | |||
| 230 | if ($this->findColumns($table)) { |
||
| 231 | $this->findConstraints($table); |
||
| 232 | return $table; |
||
| 233 | } |
||
| 234 | |||
| 235 | return null; |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * Loads a primary key for the given table. |
||
| 240 | * |
||
| 241 | * @param string $tableName table name. |
||
| 242 | * |
||
| 243 | * @throws Exception |
||
| 244 | * @throws InvalidArgumentException |
||
| 245 | * @throws InvalidConfigException |
||
| 246 | * |
||
| 247 | * @return Constraint|null primary key for the given table, `null` if the table has no primary key. |
||
| 248 | */ |
||
| 249 | protected function loadTablePrimaryKey(string $tableName): ?Constraint |
||
| 250 | { |
||
| 251 | return $this->loadTableConstraints($tableName, 'primaryKey'); |
||
| 252 | } |
||
| 253 | |||
| 254 | /** |
||
| 255 | * Loads all foreign keys for the given table. |
||
| 256 | * |
||
| 257 | * @param string $tableName table name. |
||
| 258 | * |
||
| 259 | * @throws Exception |
||
| 260 | * @throws InvalidArgumentException |
||
| 261 | * @throws InvalidConfigException |
||
| 262 | * |
||
| 263 | * @return ForeignKeyConstraint[] foreign keys for the given table. |
||
| 264 | */ |
||
| 265 | protected function loadTableForeignKeys($tableName): array |
||
| 266 | { |
||
| 267 | return $this->loadTableConstraints($tableName, 'foreignKeys'); |
||
| 268 | } |
||
| 269 | |||
| 270 | /** |
||
| 271 | * Loads all indexes for the given table. |
||
| 272 | * |
||
| 273 | * @param string $tableName table name. |
||
| 274 | * |
||
| 275 | * @throws Exception |
||
| 276 | * @throws InvalidArgumentException |
||
| 277 | * @throws InvalidConfigException |
||
| 278 | * |
||
| 279 | * @return IndexConstraint[] indexes for the given table. |
||
| 280 | */ |
||
| 281 | protected function loadTableIndexes(string $tableName): array |
||
| 282 | { |
||
| 283 | static $sql = <<<'SQL' |
||
| 284 | SELECT |
||
| 285 | "ic"."relname" AS "name", |
||
| 286 | "ia"."attname" AS "column_name", |
||
| 287 | "i"."indisunique" AS "index_is_unique", |
||
| 288 | "i"."indisprimary" AS "index_is_primary" |
||
| 289 | FROM "pg_class" AS "tc" |
||
| 290 | INNER JOIN "pg_namespace" AS "tcns" |
||
| 291 | ON "tcns"."oid" = "tc"."relnamespace" |
||
| 292 | INNER JOIN "pg_index" AS "i" |
||
| 293 | ON "i"."indrelid" = "tc"."oid" |
||
| 294 | INNER JOIN "pg_class" AS "ic" |
||
| 295 | ON "ic"."oid" = "i"."indexrelid" |
||
| 296 | INNER JOIN "pg_attribute" AS "ia" |
||
| 297 | ON "ia"."attrelid" = "i"."indrelid" AND "ia"."attnum" = ANY ("i"."indkey") |
||
| 298 | WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName |
||
| 299 | ORDER BY "ia"."attnum" ASC |
||
| 300 | SQL; |
||
| 301 | |||
| 302 | $resolvedName = $this->resolveTableName($tableName); |
||
| 303 | |||
| 304 | $indexes = $this->getDb()->createCommand($sql, [ |
||
| 305 | ':schemaName' => $resolvedName->getSchemaName(), |
||
| 306 | ':tableName' => $resolvedName->getName(), |
||
| 307 | ])->queryAll(); |
||
| 308 | |||
| 309 | $indexes = $this->normalizePdoRowKeyCase($indexes, true); |
||
| 310 | $indexes = ArrayHelper::index($indexes, null, 'name'); |
||
| 311 | $result = []; |
||
| 312 | |||
| 313 | foreach ($indexes as $name => $index) { |
||
| 314 | $ic = (new IndexConstraint()) |
||
| 315 | ->name($name) |
||
| 316 | ->columnNames(ArrayHelper::getColumn($index, 'column_name')) |
||
| 317 | ->primary((bool) $index[0]['index_is_primary']) |
||
| 318 | ->unique((bool) $index[0]['index_is_unique']); |
||
| 319 | |||
| 320 | $result[] = $ic; |
||
| 321 | } |
||
| 322 | |||
| 323 | return $result; |
||
| 324 | } |
||
| 325 | |||
| 326 | /** |
||
| 327 | * Loads all unique constraints for the given table. |
||
| 328 | * |
||
| 329 | * @param string $tableName table name. |
||
| 330 | * |
||
| 331 | * @throws Exception |
||
| 332 | * @throws InvalidArgumentException |
||
| 333 | * @throws InvalidConfigException |
||
| 334 | * |
||
| 335 | * @return Constraint[] unique constraints for the given table. |
||
| 336 | */ |
||
| 337 | protected function loadTableUniques(string $tableName): array |
||
| 338 | { |
||
| 339 | return $this->loadTableConstraints($tableName, 'uniques'); |
||
| 340 | } |
||
| 341 | |||
| 342 | /** |
||
| 343 | * Loads all check constraints for the given table. |
||
| 344 | * |
||
| 345 | * @param string $tableName table name. |
||
| 346 | * |
||
| 347 | * @throws Exception |
||
| 348 | * @throws InvalidArgumentException |
||
| 349 | * @throws InvalidConfigException |
||
| 350 | * |
||
| 351 | * @return CheckConstraint[] check constraints for the given table. |
||
| 352 | */ |
||
| 353 | protected function loadTableChecks(string $tableName): array |
||
| 354 | { |
||
| 355 | return $this->loadTableConstraints($tableName, 'checks'); |
||
| 356 | } |
||
| 357 | |||
| 358 | /** |
||
| 359 | * Loads all default value constraints for the given table. |
||
| 360 | * |
||
| 361 | * @param string $tableName table name. |
||
| 362 | * |
||
| 363 | * @throws NotSupportedException |
||
| 364 | * |
||
| 365 | * @return DefaultValueConstraint[] default value constraints for the given table. |
||
| 366 | */ |
||
| 367 | protected function loadTableDefaultValues($tableName): array |
||
|
|
|||
| 368 | { |
||
| 369 | throw new NotSupportedException('PostgreSQL does not support default value constraints.'); |
||
| 370 | } |
||
| 371 | |||
| 372 | /** |
||
| 373 | * Creates a query builder for the PostgreSQL database. |
||
| 374 | * |
||
| 375 | * @return PgsqlQueryBuilder query builder instance |
||
| 376 | */ |
||
| 377 | public function createQueryBuilder(): PgsqlQueryBuilder |
||
| 378 | { |
||
| 379 | return new PgsqlQueryBuilder($this->getDb()); |
||
| 380 | } |
||
| 381 | |||
| 382 | /** |
||
| 383 | * Resolves the table name and schema name (if any). |
||
| 384 | * |
||
| 385 | * @param PgsqlTableSchema $table the table metadata object. |
||
| 386 | * @param string $name the table name |
||
| 387 | */ |
||
| 388 | protected function resolveTableNames(PgsqlTableSchema $table, string $name): void |
||
| 389 | { |
||
| 390 | $parts = explode('.', str_replace('"', '', $name)); |
||
| 391 | |||
| 392 | if (isset($parts[1])) { |
||
| 393 | $table->schemaName($parts[0]); |
||
| 394 | $table->name($parts[1]); |
||
| 395 | } else { |
||
| 396 | $table->schemaName($this->defaultSchema); |
||
| 397 | $table->name($parts[0]); |
||
| 398 | } |
||
| 399 | |||
| 400 | $table->fullName($table->getSchemaName() !== $this->defaultSchema ? $table->getSchemaName() . '.' |
||
| 401 | . $table->getName() : $table->getName()); |
||
| 402 | } |
||
| 403 | |||
| 404 | protected function findViewNames(string $schema = ''): array |
||
| 405 | { |
||
| 406 | if ($schema === '') { |
||
| 407 | $schema = $this->defaultSchema; |
||
| 408 | } |
||
| 409 | $sql = <<<'SQL' |
||
| 410 | SELECT c.relname AS table_name |
||
| 411 | FROM pg_class c |
||
| 412 | INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace |
||
| 413 | WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm') |
||
| 414 | ORDER BY c.relname |
||
| 415 | SQL; |
||
| 416 | return $this->getDb()->createCommand($sql, [':schemaName' => $schema])->queryColumn(); |
||
| 417 | } |
||
| 418 | |||
| 419 | /** |
||
| 420 | * Collects the foreign key column details for the given table. |
||
| 421 | * |
||
| 422 | * @param PgsqlTableSchema $table the table metadata |
||
| 423 | * |
||
| 424 | * @throws Exception |
||
| 425 | * @throws InvalidArgumentException |
||
| 426 | * @throws InvalidConfigException |
||
| 427 | */ |
||
| 428 | protected function findConstraints(PgsqlTableSchema $table) |
||
| 429 | { |
||
| 430 | $tableName = $this->quoteValue($table->getName()); |
||
| 431 | $tableSchema = $this->quoteValue($table->getSchemaName()); |
||
| 432 | |||
| 433 | /** |
||
| 434 | * We need to extract the constraints de hard way since: |
||
| 435 | * {@see http://www.postgresql.org/message-id/[email protected]} |
||
| 436 | */ |
||
| 437 | |||
| 438 | $sql = <<<SQL |
||
| 439 | select |
||
| 440 | ct.conname as constraint_name, |
||
| 441 | a.attname as column_name, |
||
| 442 | fc.relname as foreign_table_name, |
||
| 443 | fns.nspname as foreign_table_schema, |
||
| 444 | fa.attname as foreign_column_name |
||
| 445 | from |
||
| 446 | (SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, generate_subscripts(ct.conkey, 1) AS s |
||
| 447 | FROM pg_constraint ct |
||
| 448 | ) AS ct |
||
| 449 | inner join pg_class c on c.oid=ct.conrelid |
||
| 450 | inner join pg_namespace ns on c.relnamespace=ns.oid |
||
| 451 | inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s] |
||
| 452 | left join pg_class fc on fc.oid=ct.confrelid |
||
| 453 | left join pg_namespace fns on fc.relnamespace=fns.oid |
||
| 454 | left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s] |
||
| 455 | where |
||
| 456 | ct.contype='f' |
||
| 457 | and c.relname={$tableName} |
||
| 458 | and ns.nspname={$tableSchema} |
||
| 459 | order by |
||
| 460 | fns.nspname, fc.relname, a.attnum |
||
| 461 | SQL; |
||
| 462 | |||
| 463 | $constraints = []; |
||
| 464 | |||
| 465 | foreach ($this->getDb()->createCommand($sql)->queryAll() as $constraint) { |
||
| 466 | if ($this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) { |
||
| 467 | $constraint = array_change_key_case($constraint, CASE_LOWER); |
||
| 468 | } |
||
| 469 | |||
| 470 | if ($constraint['foreign_table_schema'] !== $this->defaultSchema) { |
||
| 471 | $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name']; |
||
| 472 | } else { |
||
| 473 | $foreignTable = $constraint['foreign_table_name']; |
||
| 474 | } |
||
| 475 | |||
| 476 | $name = $constraint['constraint_name']; |
||
| 477 | |||
| 478 | if (!isset($constraints[$name])) { |
||
| 479 | $constraints[$name] = [ |
||
| 480 | 'tableName' => $foreignTable, |
||
| 481 | 'columns' => [], |
||
| 482 | ]; |
||
| 483 | } |
||
| 484 | |||
| 485 | $constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name']; |
||
| 486 | } |
||
| 487 | |||
| 488 | foreach ($constraints as $name => $constraint) { |
||
| 489 | $table->foreignKey($name, array_merge([$constraint['tableName']], $constraint['columns'])); |
||
| 490 | } |
||
| 491 | } |
||
| 492 | |||
| 493 | /** |
||
| 494 | * Gets information about given table unique indexes. |
||
| 495 | * |
||
| 496 | * @param PgsqlTableSchema $table the table metadata. |
||
| 497 | * |
||
| 498 | * @throws Exception |
||
| 499 | * @throws InvalidArgumentException |
||
| 500 | * @throws InvalidConfigException |
||
| 501 | * |
||
| 502 | * @return array with index and column names. |
||
| 503 | */ |
||
| 504 | protected function getUniqueIndexInformation(PgsqlTableSchema $table): array |
||
| 505 | { |
||
| 506 | $sql = <<<'SQL' |
||
| 507 | SELECT |
||
| 508 | i.relname as indexname, |
||
| 509 | pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname |
||
| 510 | FROM ( |
||
| 511 | SELECT *, generate_subscripts(indkey, 1) AS k |
||
| 512 | FROM pg_index |
||
| 513 | ) idx |
||
| 514 | INNER JOIN pg_class i ON i.oid = idx.indexrelid |
||
| 515 | INNER JOIN pg_class c ON c.oid = idx.indrelid |
||
| 516 | INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid |
||
| 517 | WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE |
||
| 518 | AND c.relname = :tableName AND ns.nspname = :schemaName |
||
| 519 | ORDER BY i.relname, k |
||
| 520 | SQL; |
||
| 521 | |||
| 522 | return $this->getDb()->createCommand($sql, [ |
||
| 523 | ':schemaName' => $table->getSchemaName(), |
||
| 524 | ':tableName' => $table->getName(), |
||
| 525 | ])->queryAll(); |
||
| 526 | } |
||
| 527 | |||
| 528 | /** |
||
| 529 | * Returns all unique indexes for the given table. |
||
| 530 | * |
||
| 531 | * Each array element is of the following structure: |
||
| 532 | * |
||
| 533 | * ```php |
||
| 534 | * [ |
||
| 535 | * 'IndexName1' => ['col1' [, ...]], |
||
| 536 | * 'IndexName2' => ['col2' [, ...]], |
||
| 537 | * ] |
||
| 538 | * ``` |
||
| 539 | * |
||
| 540 | * @param PgsqlTableSchema $table the table metadata |
||
| 541 | * |
||
| 542 | * @throws Exception |
||
| 543 | * @throws InvalidArgumentException |
||
| 544 | * @throws InvalidConfigException |
||
| 545 | * |
||
| 546 | * @return array all unique indexes for the given table. |
||
| 547 | */ |
||
| 548 | public function findUniqueIndexes($table): array |
||
| 549 | { |
||
| 550 | $uniqueIndexes = []; |
||
| 551 | |||
| 552 | foreach ($this->getUniqueIndexInformation($table) as $row) { |
||
| 553 | if ($this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) { |
||
| 554 | $row = array_change_key_case($row, CASE_LOWER); |
||
| 555 | } |
||
| 556 | |||
| 557 | $column = $row['columnname']; |
||
| 558 | |||
| 559 | if (!empty($column) && $column[0] === '"') { |
||
| 560 | /** |
||
| 561 | * postgres will quote names that are not lowercase-only. |
||
| 562 | * |
||
| 563 | * {@see https://github.com/yiisoft/yii2/issues/10613} |
||
| 564 | */ |
||
| 565 | $column = substr($column, 1, -1); |
||
| 566 | } |
||
| 567 | |||
| 568 | $uniqueIndexes[$row['indexname']][] = $column; |
||
| 569 | } |
||
| 570 | |||
| 571 | return $uniqueIndexes; |
||
| 572 | } |
||
| 573 | |||
| 574 | /** |
||
| 575 | * Collects the metadata of table columns. |
||
| 576 | * |
||
| 577 | * @param PgsqlTableSchema $table the table metadata. |
||
| 578 | * |
||
| 579 | * @throws Exception |
||
| 580 | * @throws InvalidArgumentException |
||
| 581 | * @throws InvalidConfigException |
||
| 582 | * @throws NotSupportedException |
||
| 583 | * |
||
| 584 | * @return bool whether the table exists in the database. |
||
| 585 | */ |
||
| 586 | protected function findColumns(PgsqlTableSchema $table): bool |
||
| 587 | { |
||
| 588 | $tableName = $this->getDb()->quoteValue($table->getName()); |
||
| 589 | $schemaName = $this->getDb()->quoteValue($table->getSchemaName()); |
||
| 590 | |||
| 591 | $orIdentity = ''; |
||
| 592 | |||
| 593 | if (version_compare($this->getDb()->getServerVersion(), '12.0', '>=')) { |
||
| 594 | $orIdentity = 'OR a.attidentity != \'\''; |
||
| 595 | } |
||
| 596 | |||
| 597 | $sql = <<<SQL |
||
| 598 | SELECT |
||
| 599 | d.nspname AS table_schema, |
||
| 600 | c.relname AS table_name, |
||
| 601 | a.attname AS column_name, |
||
| 602 | COALESCE(td.typname, tb.typname, t.typname) AS data_type, |
||
| 603 | COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type, |
||
| 604 | a.attlen AS character_maximum_length, |
||
| 605 | pg_catalog.col_description(c.oid, a.attnum) AS column_comment, |
||
| 606 | a.atttypmod AS modifier, |
||
| 607 | a.attnotnull = false AS is_nullable, |
||
| 608 | CAST(pg_get_expr(ad.adbin, ad.adrelid) AS varchar) AS column_default, |
||
| 609 | coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval',false) {$orIdentity} AS is_autoinc, |
||
| 610 | pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname) AS sequence_name, |
||
| 611 | CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char |
||
| 612 | THEN array_to_string((SELECT array_agg(enumlabel) FROM pg_enum WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid))::varchar[], ',') |
||
| 613 | ELSE NULL |
||
| 614 | END AS enum_values, |
||
| 615 | CASE atttypid |
||
| 616 | WHEN 21 /*int2*/ THEN 16 |
||
| 617 | WHEN 23 /*int4*/ THEN 32 |
||
| 618 | WHEN 20 /*int8*/ THEN 64 |
||
| 619 | WHEN 1700 /*numeric*/ THEN |
||
| 620 | CASE WHEN atttypmod = -1 |
||
| 621 | THEN null |
||
| 622 | ELSE ((atttypmod - 4) >> 16) & 65535 |
||
| 623 | END |
||
| 624 | WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/ |
||
| 625 | WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/ |
||
| 626 | ELSE null |
||
| 627 | END AS numeric_precision, |
||
| 628 | CASE |
||
| 629 | WHEN atttypid IN (21, 23, 20) THEN 0 |
||
| 630 | WHEN atttypid IN (1700) THEN |
||
| 631 | CASE |
||
| 632 | WHEN atttypmod = -1 THEN null |
||
| 633 | ELSE (atttypmod - 4) & 65535 |
||
| 634 | END |
||
| 635 | ELSE null |
||
| 636 | END AS numeric_scale, |
||
| 637 | CAST( |
||
| 638 | information_schema._pg_char_max_length(information_schema._pg_truetypid(a, t), information_schema._pg_truetypmod(a, t)) |
||
| 639 | AS numeric |
||
| 640 | ) AS size, |
||
| 641 | a.attnum = any (ct.conkey) as is_pkey, |
||
| 642 | COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension |
||
| 643 | FROM |
||
| 644 | pg_class c |
||
| 645 | LEFT JOIN pg_attribute a ON a.attrelid = c.oid |
||
| 646 | LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum |
||
| 647 | LEFT JOIN pg_type t ON a.atttypid = t.oid |
||
| 648 | LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid OR t.typbasetype > 0 AND t.typbasetype = tb.oid |
||
| 649 | LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid |
||
| 650 | LEFT JOIN pg_namespace d ON d.oid = c.relnamespace |
||
| 651 | LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p' |
||
| 652 | WHERE |
||
| 653 | a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped |
||
| 654 | AND c.relname = {$tableName} |
||
| 655 | AND d.nspname = {$schemaName} |
||
| 656 | ORDER BY |
||
| 657 | a.attnum; |
||
| 658 | SQL; |
||
| 659 | |||
| 660 | $columns = $this->getDb()->createCommand($sql)->queryAll(); |
||
| 661 | |||
| 662 | if (empty($columns)) { |
||
| 663 | return false; |
||
| 664 | } |
||
| 665 | |||
| 666 | foreach ($columns as $column) { |
||
| 667 | if ($this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_CASE) === PDO::CASE_UPPER) { |
||
| 668 | $column = array_change_key_case($column, CASE_LOWER); |
||
| 669 | } |
||
| 670 | |||
| 671 | $column = $this->loadColumnSchema($column); |
||
| 672 | $table->columns($column->getName(), $column); |
||
| 673 | |||
| 674 | if ($column->isPrimaryKey()) { |
||
| 675 | $table->primaryKey($column->getName()); |
||
| 676 | |||
| 677 | if ($table->getSequenceName() === null) { |
||
| 678 | $table->sequenceName($column->getSequenceName()); |
||
| 679 | } |
||
| 680 | |||
| 681 | $column->defaultValue(null); |
||
| 682 | } elseif ($column->getDefaultValue()) { |
||
| 683 | if ( |
||
| 684 | in_array($column->getType(), [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true) && |
||
| 685 | in_array( |
||
| 686 | strtoupper($column->getDefaultValue()), |
||
| 687 | ['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], |
||
| 688 | true |
||
| 689 | ) |
||
| 690 | ) { |
||
| 691 | $column->defaultValue(new Expression($column->getDefaultValue())); |
||
| 692 | } elseif ($column->getType() === 'boolean') { |
||
| 693 | $column->defaultValue(($column->getDefaultValue() === 'true')); |
||
| 694 | } elseif (preg_match("/^B'(.*?)'::/", $column->getDefaultValue(), $matches)) { |
||
| 695 | $column->defaultValue(bindec($matches[1])); |
||
| 696 | } elseif (preg_match("/^'(\d+)'::\"bit\"$/", $column->getDefaultValue(), $matches)) { |
||
| 697 | $column->defaultValue(bindec($matches[1])); |
||
| 698 | } elseif (preg_match("/^'(.*?)'::/", $column->getDefaultValue(), $matches)) { |
||
| 699 | $column->defaultValue($column->phpTypecast($matches[1])); |
||
| 700 | } elseif (preg_match('/^(\()?(.*?)(?(1)\))(?:::.+)?$/', $column->getDefaultValue(), $matches)) { |
||
| 701 | if ($matches[2] === 'NULL') { |
||
| 702 | $column->defaultValue(null); |
||
| 703 | } else { |
||
| 704 | $column->defaultValue($column->phpTypecast($matches[2])); |
||
| 705 | } |
||
| 706 | } else { |
||
| 707 | $column->defaultValue($column->phpTypecast($column->getDefaultValue())); |
||
| 708 | } |
||
| 709 | } |
||
| 710 | } |
||
| 711 | |||
| 712 | return true; |
||
| 713 | } |
||
| 714 | |||
| 715 | /** |
||
| 716 | * Loads the column information into a {@see PgsqlColumnSchema} object. |
||
| 717 | * |
||
| 718 | * @param array $info column information. |
||
| 719 | * |
||
| 720 | * @return PgsqlColumnSchema the column schema object. |
||
| 721 | */ |
||
| 722 | protected function loadColumnSchema(array $info): PgsqlColumnSchema |
||
| 723 | { |
||
| 724 | /** @var PgsqlColumnSchema $column */ |
||
| 725 | $column = $this->createColumnSchema(); |
||
| 726 | $column->allowNull($info['is_nullable']); |
||
| 727 | $column->autoIncrement($info['is_autoinc']); |
||
| 728 | $column->comment($info['column_comment']); |
||
| 729 | $column->dbType($info['data_type']); |
||
| 730 | $column->defaultValue($info['column_default']); |
||
| 731 | $column->enumValues(($info['enum_values'] !== null) |
||
| 732 | ? explode(',', str_replace(["''"], ["'"], $info['enum_values'])) : null); |
||
| 733 | $column->unsigned(false); // has no meaning in PG |
||
| 734 | $column->primaryKey((bool) $info['is_pkey']); |
||
| 735 | $column->name($info['column_name']); |
||
| 736 | $column->precision($info['numeric_precision']); |
||
| 737 | $column->scale($info['numeric_scale']); |
||
| 738 | $column->size($info['size'] === null ? null : (int) $info['size']); |
||
| 739 | $column->dimension((int) $info['dimension']); |
||
| 740 | |||
| 741 | /** |
||
| 742 | * pg_get_serial_sequence() doesn't track DEFAULT value change. GENERATED BY IDENTITY columns always have null |
||
| 743 | * default value. |
||
| 744 | */ |
||
| 745 | |||
| 746 | $defaultValue = $column->getDefaultValue(); |
||
| 747 | if ( |
||
| 748 | isset($defaultValue) && |
||
| 749 | preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $defaultValue) === 1 |
||
| 750 | ) { |
||
| 751 | $column->sequenceName(preg_replace( |
||
| 752 | ['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], |
||
| 753 | '', |
||
| 754 | $defaultValue |
||
| 755 | )); |
||
| 756 | } elseif (isset($info['sequence_name'])) { |
||
| 757 | $column->sequenceName($this->resolveTableName($info['sequence_name'])->getFullName()); |
||
| 758 | } |
||
| 759 | |||
| 760 | if (isset($this->typeMap[$column->getDbType()])) { |
||
| 761 | $column->type($this->typeMap[$column->getDbType()]); |
||
| 762 | } else { |
||
| 763 | $column->type(self::TYPE_STRING); |
||
| 764 | } |
||
| 765 | |||
| 766 | $column->phpType($this->getColumnPhpType($column)); |
||
| 767 | |||
| 768 | return $column; |
||
| 769 | } |
||
| 770 | |||
| 771 | /** |
||
| 772 | * Executes the INSERT command, returning primary key values. |
||
| 773 | * |
||
| 774 | * @param string $table the table that new rows will be inserted into. |
||
| 775 | * @param array $columns the column data (name => value) to be inserted into the table. |
||
| 776 | * |
||
| 777 | * @throws Exception |
||
| 778 | * @throws InvalidArgumentException |
||
| 779 | * @throws InvalidConfigException |
||
| 780 | * @throws NotSupportedException |
||
| 781 | * |
||
| 782 | * @return array|false primary key values or false if the command fails. |
||
| 783 | */ |
||
| 784 | public function insert(string $table, array $columns) |
||
| 785 | { |
||
| 786 | $params = []; |
||
| 787 | $sql = $this->getDb()->getQueryBuilder()->insert($table, $columns, $params); |
||
| 788 | $returnColumns = $this->getTableSchema($table)->getPrimaryKey(); |
||
| 789 | |||
| 790 | if (!empty($returnColumns)) { |
||
| 791 | $returning = []; |
||
| 792 | foreach ((array) $returnColumns as $name) { |
||
| 793 | $returning[] = $this->quoteColumnName($name); |
||
| 794 | } |
||
| 795 | $sql .= ' RETURNING ' . implode(', ', $returning); |
||
| 796 | } |
||
| 797 | |||
| 798 | $command = $this->getDb()->createCommand($sql, $params); |
||
| 799 | $command->prepare(false); |
||
| 800 | $result = $command->queryOne(); |
||
| 801 | |||
| 802 | return !$command->getPdoStatement()->rowCount() ? false : $result; |
||
| 803 | } |
||
| 804 | |||
| 805 | /** |
||
| 806 | * Loads multiple types of constraints and returns the specified ones. |
||
| 807 | * |
||
| 808 | * @param string $tableName table name. |
||
| 809 | * @param string $returnType return type: |
||
| 810 | * - primaryKey |
||
| 811 | * - foreignKeys |
||
| 812 | * - uniques |
||
| 813 | * - checks |
||
| 814 | * |
||
| 815 | * @throws Exception |
||
| 816 | * @throws InvalidArgumentException |
||
| 817 | * @throws InvalidConfigException |
||
| 818 | * |
||
| 819 | * @return mixed constraints. |
||
| 820 | */ |
||
| 821 | private function loadTableConstraints(string $tableName, string $returnType) |
||
| 921 | } |
||
| 922 | |||
| 923 | /** |
||
| 924 | * Creates a column schema for the database. |
||
| 925 | * |
||
| 926 | * This method may be overridden by child classes to create a DBMS-specific column schema. |
||
| 927 | * |
||
| 928 | * @return PgsqlColumnSchema column schema instance. |
||
| 929 | */ |
||
| 930 | protected function createColumnSchema(): PgsqlColumnSchema |
||
| 931 | { |
||
| 932 | return new PgsqlColumnSchema(); |
||
| 933 | } |
||
| 934 | } |
||
| 935 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.