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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 |
||
41 | abstract class Schema extends Object |
||
42 | { |
||
43 | // The following are the supported abstract column data types. |
||
44 | const TYPE_PK = 'pk'; |
||
45 | const TYPE_UPK = 'upk'; |
||
46 | const TYPE_BIGPK = 'bigpk'; |
||
47 | const TYPE_UBIGPK = 'ubigpk'; |
||
48 | const TYPE_CHAR = 'char'; |
||
49 | const TYPE_STRING = 'string'; |
||
50 | const TYPE_TEXT = 'text'; |
||
51 | const TYPE_SMALLINT = 'smallint'; |
||
52 | const TYPE_INTEGER = 'integer'; |
||
53 | const TYPE_BIGINT = 'bigint'; |
||
54 | const TYPE_FLOAT = 'float'; |
||
55 | const TYPE_DOUBLE = 'double'; |
||
56 | const TYPE_DECIMAL = 'decimal'; |
||
57 | const TYPE_DATETIME = 'datetime'; |
||
58 | const TYPE_TIMESTAMP = 'timestamp'; |
||
59 | const TYPE_TIME = 'time'; |
||
60 | const TYPE_DATE = 'date'; |
||
61 | const TYPE_BINARY = 'binary'; |
||
62 | const TYPE_BOOLEAN = 'boolean'; |
||
63 | const TYPE_MONEY = 'money'; |
||
64 | |||
65 | /** |
||
66 | * Schema cache version, to detect incompatibilities in cached values when the |
||
67 | * data format of the cache changes. |
||
68 | */ |
||
69 | const SCHEMA_CACHE_VERSION = 1; |
||
70 | |||
71 | /** |
||
72 | * @var Connection the database connection |
||
73 | */ |
||
74 | public $db; |
||
75 | /** |
||
76 | * @var string the default schema name used for the current session. |
||
77 | */ |
||
78 | public $defaultSchema; |
||
79 | /** |
||
80 | * @var array map of DB errors and corresponding exceptions |
||
81 | * If left part is found in DB error message exception class from the right part is used. |
||
82 | */ |
||
83 | public $exceptionMap = [ |
||
84 | 'SQLSTATE[23' => 'yii\db\IntegrityException', |
||
85 | ]; |
||
86 | /** |
||
87 | * @var string column schema class |
||
88 | * @since 2.0.11 |
||
89 | */ |
||
90 | public $columnSchemaClass = 'yii\db\ColumnSchema'; |
||
91 | |||
92 | /** |
||
93 | * @var array list of ALL schema names in the database, except system schemas |
||
94 | */ |
||
95 | private $_schemaNames; |
||
96 | /** |
||
97 | * @var array list of ALL table names in the database |
||
98 | */ |
||
99 | private $_tableNames = []; |
||
100 | /** |
||
101 | * @var array list of loaded table metadata (table name => metadata type => metadata). |
||
102 | */ |
||
103 | private $_tableMetadata = []; |
||
104 | /** |
||
105 | * @var QueryBuilder the query builder for this database |
||
106 | */ |
||
107 | private $_builder; |
||
108 | |||
109 | |||
110 | /** |
||
111 | * Resolves the table name and schema name (if any). |
||
112 | * @param string $name the table name |
||
113 | * @return TableSchema [[TableSchema]] with resolved table, schema, etc. names. |
||
114 | * @throws NotSupportedException if this method is not supported by the DBMS. |
||
115 | * @since 2.0.13 |
||
116 | */ |
||
117 | protected function resolveTableName($name) |
||
121 | |||
122 | /** |
||
123 | * Returns all schema names in the database, including the default one but not system schemas. |
||
124 | * This method should be overridden by child classes in order to support this feature |
||
125 | * because the default implementation simply throws an exception. |
||
126 | * @return array all schema names in the database, except system schemas. |
||
127 | * @throws NotSupportedException if this method is not supported by the DBMS. |
||
128 | * @since 2.0.4 |
||
129 | */ |
||
130 | protected function findSchemaNames() |
||
134 | |||
135 | /** |
||
136 | * Returns all table names in the database. |
||
137 | * This method should be overridden by child classes in order to support this feature |
||
138 | * because the default implementation simply throws an exception. |
||
139 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. |
||
140 | * @return array all table names in the database. The names have NO schema name prefix. |
||
141 | * @throws NotSupportedException if this method is not supported by the DBMS. |
||
142 | */ |
||
143 | protected function findTableNames($schema = '') |
||
147 | |||
148 | /** |
||
149 | * Loads the metadata for the specified table. |
||
150 | * @param string $name table name |
||
151 | * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist. |
||
152 | */ |
||
153 | abstract protected function loadTableSchema($name); |
||
154 | |||
155 | /** |
||
156 | * Creates a column schema for the database. |
||
157 | * This method may be overridden by child classes to create a DBMS-specific column schema. |
||
158 | * @return ColumnSchema column schema instance. |
||
159 | * @throws InvalidConfigException if a column schema class cannot be created. |
||
160 | */ |
||
161 | 405 | protected function createColumnSchema() |
|
165 | |||
166 | /** |
||
167 | * Obtains the metadata for the named table. |
||
168 | * @param string $name table name. The table name may contain schema name if any. Do not quote the table name. |
||
169 | * @param bool $refresh whether to reload the table schema even if it is found in the cache. |
||
170 | * @return TableSchema|null table metadata. `null` if the named table does not exist. |
||
171 | */ |
||
172 | 450 | public function getTableSchema($name, $refresh = false) |
|
176 | |||
177 | /** |
||
178 | * Returns the metadata for all tables in the database. |
||
179 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name. |
||
180 | * @param bool $refresh whether to fetch the latest available table schemas. If this is `false`, |
||
181 | * cached data may be returned if available. |
||
182 | * @return TableSchema[] the metadata for all tables in the database. |
||
183 | * Each array element is an instance of [[TableSchema]] or its child class. |
||
184 | */ |
||
185 | 6 | public function getTableSchemas($schema = '', $refresh = false) |
|
189 | |||
190 | /** |
||
191 | * Returns all schema names in the database, except system schemas. |
||
192 | * @param bool $refresh whether to fetch the latest available schema names. If this is false, |
||
193 | * schema names fetched previously (if available) will be returned. |
||
194 | * @return string[] all schema names in the database, except system schemas. |
||
195 | * @since 2.0.4 |
||
196 | */ |
||
197 | 1 | public function getSchemaNames($refresh = false) |
|
205 | |||
206 | /** |
||
207 | * Returns all table names in the database. |
||
208 | * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name. |
||
209 | * If not empty, the returned table names will be prefixed with the schema name. |
||
210 | * @param bool $refresh whether to fetch the latest available table names. If this is false, |
||
211 | * table names fetched previously (if available) will be returned. |
||
212 | * @return string[] all table names in the database. |
||
213 | */ |
||
214 | 10 | public function getTableNames($schema = '', $refresh = false) |
|
222 | |||
223 | /** |
||
224 | * @return QueryBuilder the query builder for this connection. |
||
225 | */ |
||
226 | 462 | public function getQueryBuilder() |
|
234 | |||
235 | /** |
||
236 | * Determines the PDO type for the given PHP data value. |
||
237 | * @param mixed $data the data whose PDO type is to be determined |
||
238 | * @return int the PDO type |
||
239 | * @see http://www.php.net/manual/en/pdo.constants.php |
||
240 | */ |
||
241 | 453 | public function getPdoType($data) |
|
255 | |||
256 | /** |
||
257 | * Refreshes the schema. |
||
258 | * This method cleans up all cached table schemas so that they can be re-created later |
||
259 | * to reflect the database schema change. |
||
260 | */ |
||
261 | 18 | public function refresh() |
|
262 | { |
||
263 | /* @var $cache CacheInterface */ |
||
264 | 18 | $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache; |
|
265 | 18 | if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) { |
|
266 | TagDependency::invalidate($cache, $this->getCacheTag()); |
||
267 | } |
||
268 | 18 | $this->_tableNames = []; |
|
269 | 18 | $this->_tableMetadata = []; |
|
270 | 18 | } |
|
271 | |||
272 | /** |
||
273 | * Refreshes the particular table schema. |
||
274 | * This method cleans up cached table schema so that it can be re-created later |
||
275 | * to reflect the database schema change. |
||
276 | * @param string $name table name. |
||
277 | * @since 2.0.6 |
||
278 | */ |
||
279 | 91 | public function refreshTableSchema($name) |
|
289 | |||
290 | /** |
||
291 | * Creates a query builder for the database. |
||
292 | * This method may be overridden by child classes to create a DBMS-specific query builder. |
||
293 | * @return QueryBuilder query builder instance |
||
294 | */ |
||
295 | public function createQueryBuilder() |
||
299 | |||
300 | /** |
||
301 | * Create a column schema builder instance giving the type and value precision. |
||
302 | * |
||
303 | * This method may be overridden by child classes to create a DBMS-specific column schema builder. |
||
304 | * |
||
305 | * @param string $type type of the column. See [[ColumnSchemaBuilder::$type]]. |
||
306 | * @param int|string|array $length length or precision of the column. See [[ColumnSchemaBuilder::$length]]. |
||
307 | * @return ColumnSchemaBuilder column schema builder instance |
||
308 | * @since 2.0.6 |
||
309 | */ |
||
310 | 7 | public function createColumnSchemaBuilder($type, $length = null) |
|
314 | |||
315 | /** |
||
316 | * Returns all unique indexes for the given table. |
||
317 | * Each array element is of the following structure: |
||
318 | * |
||
319 | * ```php |
||
320 | * [ |
||
321 | * 'IndexName1' => ['col1' [, ...]], |
||
322 | * 'IndexName2' => ['col2' [, ...]], |
||
323 | * ] |
||
324 | * ``` |
||
325 | * |
||
326 | * This method should be overridden by child classes in order to support this feature |
||
327 | * because the default implementation simply throws an exception |
||
328 | * @param TableSchema $table the table metadata |
||
329 | * @return array all unique indexes for the given table. |
||
330 | * @throws NotSupportedException if this method is called |
||
331 | */ |
||
332 | public function findUniqueIndexes($table) |
||
336 | |||
337 | /** |
||
338 | * Returns the ID of the last inserted row or sequence value. |
||
339 | * @param string $sequenceName name of the sequence object (required by some DBMS) |
||
340 | * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object |
||
341 | * @throws InvalidCallException if the DB connection is not active |
||
342 | * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php |
||
343 | */ |
||
344 | 36 | public function getLastInsertID($sequenceName = '') |
|
345 | { |
||
346 | 36 | if ($this->db->isActive) { |
|
347 | 36 | return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName)); |
|
348 | } |
||
349 | |||
350 | throw new InvalidCallException('DB Connection is not active.'); |
||
351 | } |
||
352 | |||
353 | /** |
||
354 | * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint). |
||
355 | */ |
||
356 | 2 | public function supportsSavepoint() |
|
360 | |||
361 | /** |
||
362 | * Creates a new savepoint. |
||
363 | * @param string $name the savepoint name |
||
364 | */ |
||
365 | 2 | public function createSavepoint($name) |
|
369 | |||
370 | /** |
||
371 | * Releases an existing savepoint. |
||
372 | * @param string $name the savepoint name |
||
373 | */ |
||
374 | public function releaseSavepoint($name) |
||
378 | |||
379 | /** |
||
380 | * Rolls back to a previously created savepoint. |
||
381 | * @param string $name the savepoint name |
||
382 | */ |
||
383 | 2 | public function rollBackSavepoint($name) |
|
387 | |||
388 | /** |
||
389 | * Sets the isolation level of the current transaction. |
||
390 | * @param string $level The transaction isolation level to use for this transaction. |
||
391 | * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]], [[Transaction::REPEATABLE_READ]] |
||
392 | * and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific syntax to be used |
||
393 | * after `SET TRANSACTION ISOLATION LEVEL`. |
||
394 | * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels |
||
395 | */ |
||
396 | 2 | public function setTransactionIsolationLevel($level) |
|
400 | |||
401 | /** |
||
402 | * Executes the INSERT command, returning primary key values. |
||
403 | * @param string $table the table that new rows will be inserted into. |
||
404 | * @param array $columns the column data (name => value) to be inserted into the table. |
||
405 | * @return array|false primary key values or false if the command fails |
||
406 | * @since 2.0.4 |
||
407 | */ |
||
408 | 38 | public function insert($table, $columns) |
|
409 | { |
||
410 | 38 | $command = $this->db->createCommand()->insert($table, $columns); |
|
411 | 38 | if (!$command->execute()) { |
|
412 | return false; |
||
413 | } |
||
414 | 38 | $tableSchema = $this->getTableSchema($table); |
|
415 | 38 | $result = []; |
|
416 | 38 | foreach ($tableSchema->primaryKey as $name) { |
|
417 | 36 | if ($tableSchema->columns[$name]->autoIncrement) { |
|
418 | 34 | $result[$name] = $this->getLastInsertID($tableSchema->sequenceName); |
|
419 | 34 | break; |
|
420 | } |
||
421 | |||
422 | 3 | $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue; |
|
423 | } |
||
424 | 38 | return $result; |
|
425 | } |
||
426 | |||
427 | /** |
||
428 | * Quotes a string value for use in a query. |
||
429 | * Note that if the parameter is not a string, it will be returned without change. |
||
430 | * @param string $str string to be quoted |
||
431 | * @return string the properly quoted string |
||
432 | * @see http://www.php.net/manual/en/function.PDO-quote.php |
||
433 | */ |
||
434 | 440 | public function quoteValue($str) |
|
435 | { |
||
436 | 440 | if (!is_string($str)) { |
|
437 | 2 | return $str; |
|
438 | } |
||
439 | |||
440 | 440 | if (($value = $this->db->getSlavePdo()->quote($str)) !== false) { |
|
441 | 438 | return $value; |
|
442 | } |
||
443 | |||
444 | // the driver doesn't support quote (e.g. oci) |
||
445 | return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'"; |
||
446 | } |
||
447 | |||
448 | /** |
||
449 | * Quotes a table name for use in a query. |
||
450 | * If the table name contains schema prefix, the prefix will also be properly quoted. |
||
451 | * If the table name is already quoted or contains '(' or '{{', |
||
452 | * then this method will do nothing. |
||
453 | * @param string $name table name |
||
454 | * @return string the properly quoted table name |
||
455 | * @see quoteSimpleTableName() |
||
456 | */ |
||
457 | 594 | public function quoteTableName($name) |
|
472 | |||
473 | /** |
||
474 | * Quotes a column name for use in a query. |
||
475 | * If the column name contains prefix, the prefix will also be properly quoted. |
||
476 | * If the column name is already quoted or contains '(', '[[' or '{{', |
||
477 | * then this method will do nothing. |
||
478 | * @param string $name column name |
||
479 | * @return string the properly quoted column name |
||
480 | * @see quoteSimpleColumnName() |
||
481 | */ |
||
482 | 674 | public function quoteColumnName($name) |
|
498 | |||
499 | /** |
||
500 | * Quotes a simple table name for use in a query. |
||
501 | * A simple table name should contain the table name only without any schema prefix. |
||
502 | * If the table name is already quoted, this method will do nothing. |
||
503 | * @param string $name table name |
||
504 | * @return string the properly quoted table name |
||
505 | */ |
||
506 | public function quoteSimpleTableName($name) |
||
510 | |||
511 | /** |
||
512 | * Quotes a simple column name for use in a query. |
||
513 | * A simple column name should contain the column name only without any prefix. |
||
514 | * If the column name is already quoted or is the asterisk character '*', this method will do nothing. |
||
515 | * @param string $name column name |
||
516 | * @return string the properly quoted column name |
||
517 | */ |
||
518 | 308 | public function quoteSimpleColumnName($name) |
|
522 | |||
523 | /** |
||
524 | * Returns the actual name of a given table name. |
||
525 | * This method will strip off curly brackets from the given table name |
||
526 | * and replace the percentage character '%' with [[Connection::tablePrefix]]. |
||
527 | * @param string $name the table name to be converted |
||
528 | * @return string the real name of the given table name |
||
529 | */ |
||
530 | 550 | public function getRawTableName($name) |
|
531 | { |
||
532 | 550 | if (strpos($name, '{{') !== false) { |
|
533 | 112 | $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name); |
|
534 | |||
535 | 112 | return str_replace('%', $this->db->tablePrefix, $name); |
|
536 | } |
||
537 | |||
538 | 440 | return $name; |
|
539 | } |
||
540 | |||
541 | /** |
||
542 | * Extracts the PHP type from abstract DB type. |
||
543 | * @param ColumnSchema $column the column schema information |
||
544 | * @return string PHP type name |
||
545 | */ |
||
546 | 405 | protected function getColumnPhpType($column) |
|
547 | { |
||
548 | 405 | static $typeMap = [ |
|
549 | // abstract type => php type |
||
550 | 'smallint' => 'integer', |
||
551 | 'integer' => 'integer', |
||
552 | 'bigint' => 'integer', |
||
553 | 'boolean' => 'boolean', |
||
554 | 'float' => 'double', |
||
555 | 'double' => 'double', |
||
556 | 'binary' => 'resource', |
||
557 | ]; |
||
558 | 405 | if (isset($typeMap[$column->type])) { |
|
559 | 400 | if ($column->type === 'bigint') { |
|
560 | 23 | return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string'; |
|
561 | 400 | } elseif ($column->type === 'integer') { |
|
562 | 400 | return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer'; |
|
563 | } |
||
564 | |||
565 | 155 | return $typeMap[$column->type]; |
|
566 | } |
||
567 | |||
568 | 385 | return 'string'; |
|
569 | } |
||
570 | |||
571 | /** |
||
572 | * Converts a DB exception to a more concrete one if possible. |
||
573 | * |
||
574 | * @param \Exception $e |
||
575 | * @param string $rawSql SQL that produced exception |
||
576 | * @return Exception |
||
577 | */ |
||
578 | 7 | public function convertException(\Exception $e, $rawSql) |
|
594 | |||
595 | /** |
||
596 | * Returns a value indicating whether a SQL statement is for read purpose. |
||
597 | * @param string $sql the SQL statement |
||
598 | * @return bool whether a SQL statement is for read purpose. |
||
599 | */ |
||
600 | 6 | public function isReadQuery($sql) |
|
605 | |||
606 | /** |
||
607 | * Returns the cache key for the specified table name. |
||
608 | * @param string $name the table name |
||
609 | * @return mixed the cache key |
||
610 | */ |
||
611 | 4 | protected function getCacheKey($name) |
|
620 | |||
621 | /** |
||
622 | * Returns the cache tag name. |
||
623 | * This allows [[refresh()]] to invalidate all cached table schemas. |
||
624 | * @return string the cache tag name |
||
625 | */ |
||
626 | 4 | protected function getCacheTag() |
|
634 | |||
635 | /** |
||
636 | * Returns the metadata of the given type for the given table. |
||
637 | * If there's no metadata in the cache, this method will call |
||
638 | * a `'loadTable' . ucfirst($type)` named method with the table name to obtain the metadata. |
||
639 | * @param string $name table name. The table name may contain schema name if any. Do not quote the table name. |
||
640 | * @param string $type metadata type. |
||
641 | * @param bool $refresh whether to reload the table metadata even if it is found in the cache. |
||
642 | * @return mixed metadata. |
||
643 | * @since 2.0.13 |
||
644 | */ |
||
645 | 570 | protected function getTableMetadata($name, $type, $refresh) |
|
663 | |||
664 | /** |
||
665 | * Returns the metadata of the given type for all tables in the given schema. |
||
666 | * This method will call a `'getTable' . ucfirst($type)` named method with the table name |
||
667 | * and the refresh flag to obtain the metadata. |
||
668 | * @param string $schema the schema of the metadata. Defaults to empty string, meaning the current or default schema name. |
||
669 | * @param string $type metadata type. |
||
670 | * @param bool $refresh whether to fetch the latest available table metadata. If this is `false`, |
||
671 | * cached data may be returned if available. |
||
672 | * @return array array of metadata. |
||
673 | * @since 2.0.13 |
||
674 | */ |
||
675 | 6 | protected function getSchemaMetadata($schema, $type, $refresh) |
|
690 | |||
691 | /** |
||
692 | * Sets the metadata of the given type for the given table. |
||
693 | * @param string $name table name. |
||
694 | * @param string $type metadata type. |
||
695 | * @param mixed $data metadata. |
||
696 | * @since 2.0.13 |
||
697 | */ |
||
698 | 77 | protected function setTableMetadata($name, $type, $data) |
|
702 | |||
703 | /** |
||
704 | * Changes row's array key case to lower if PDO's one is set to uppercase. |
||
705 | * @param array $row row's array or an array of row's arrays. |
||
706 | * @param bool $multiple whether multiple rows or a single row passed. |
||
707 | * @return array normalized row or rows. |
||
708 | * @since 2.0.13 |
||
709 | */ |
||
710 | 90 | protected function normalizePdoRowKeyCase(array $row, $multiple) |
|
724 | |||
725 | /** |
||
726 | * Tries to load and populate table metadata from cache. |
||
727 | * @param Cache|null $cache |
||
728 | * @param string $name |
||
729 | */ |
||
730 | 550 | private function loadTableMetadataFromCache($cache, $name) |
|
746 | |||
747 | /** |
||
748 | * Saves table metadata to cache. |
||
749 | * @param Cache|null $cache |
||
750 | * @param string $name |
||
751 | */ |
||
752 | 538 | private function saveTableMetadataToCache($cache, $name) |
|
767 | } |
||
768 |