Complex classes like QueryBuilder 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 QueryBuilder, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
20 | class QueryBuilder extends \yii\db\QueryBuilder |
||
21 | { |
||
22 | /** |
||
23 | * @var array mapping from abstract column types (keys) to physical column types (values). |
||
24 | */ |
||
25 | public $typeMap = [ |
||
26 | Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY', |
||
27 | Schema::TYPE_UPK => 'int IDENTITY PRIMARY KEY', |
||
28 | Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY', |
||
29 | Schema::TYPE_UBIGPK => 'bigint IDENTITY PRIMARY KEY', |
||
30 | Schema::TYPE_CHAR => 'nchar(1)', |
||
31 | Schema::TYPE_STRING => 'nvarchar(255)', |
||
32 | Schema::TYPE_TEXT => 'nvarchar(max)', |
||
33 | Schema::TYPE_TINYINT => 'tinyint', |
||
34 | Schema::TYPE_SMALLINT => 'smallint', |
||
35 | Schema::TYPE_INTEGER => 'int', |
||
36 | Schema::TYPE_BIGINT => 'bigint', |
||
37 | Schema::TYPE_FLOAT => 'float', |
||
38 | Schema::TYPE_DOUBLE => 'float', |
||
39 | Schema::TYPE_DECIMAL => 'decimal(18,0)', |
||
40 | Schema::TYPE_DATETIME => 'datetime', |
||
41 | Schema::TYPE_TIMESTAMP => 'datetime', |
||
42 | Schema::TYPE_TIME => 'time', |
||
43 | Schema::TYPE_DATE => 'date', |
||
44 | Schema::TYPE_BINARY => 'varbinary(max)', |
||
45 | Schema::TYPE_BOOLEAN => 'bit', |
||
46 | Schema::TYPE_MONEY => 'decimal(19,4)', |
||
47 | ]; |
||
48 | |||
49 | /** |
||
50 | * {@inheritdoc} |
||
51 | */ |
||
52 | protected function defaultExpressionBuilders() |
||
53 | { |
||
54 | return array_merge(parent::defaultExpressionBuilders(), [ |
||
55 | 'yii\db\conditions\InCondition' => 'yii\db\mssql\conditions\InConditionBuilder', |
||
56 | 'yii\db\conditions\LikeCondition' => 'yii\db\mssql\conditions\LikeConditionBuilder', |
||
57 | ]); |
||
58 | } |
||
59 | |||
60 | /** |
||
61 | * {@inheritdoc} |
||
62 | */ |
||
63 | public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
||
64 | { |
||
65 | if (!$this->hasOffset($offset) && !$this->hasLimit($limit)) { |
||
66 | $orderBy = $this->buildOrderBy($orderBy); |
||
|
|||
67 | return $orderBy === '' ? $sql : $sql . $this->separator . $orderBy; |
||
68 | } |
||
69 | |||
70 | if (version_compare($this->db->getSchema()->getServerVersion(), '11', '<')) { |
||
71 | return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset); |
||
72 | } |
||
73 | |||
74 | return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset); |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer. |
||
79 | * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) |
||
80 | * @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter. |
||
81 | * @param int $limit the limit number. See [[\yii\db\Query::limit]] for more details. |
||
82 | * @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details. |
||
83 | * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) |
||
84 | */ |
||
85 | protected function newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
||
103 | |||
104 | /** |
||
105 | * Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008. |
||
106 | * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET) |
||
107 | * @param array $orderBy the order by columns. See [[\yii\db\Query::orderBy]] for more details on how to specify this parameter. |
||
108 | * @param int $limit the limit number. See [[\yii\db\Query::limit]] for more details. |
||
109 | * @param int $offset the offset number. See [[\yii\db\Query::offset]] for more details. |
||
110 | * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any) |
||
111 | */ |
||
112 | protected function oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset) |
||
133 | |||
134 | /** |
||
135 | * Builds a SQL statement for renaming a DB table. |
||
136 | * @param string $oldName the table to be renamed. The name will be properly quoted by the method. |
||
137 | * @param string $newName the new table name. The name will be properly quoted by the method. |
||
138 | * @return string the SQL statement for renaming a DB table. |
||
139 | */ |
||
140 | public function renameTable($oldName, $newName) |
||
144 | |||
145 | /** |
||
146 | * Builds a SQL statement for renaming a column. |
||
147 | * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method. |
||
148 | * @param string $oldName the old name of the column. The name will be properly quoted by the method. |
||
149 | * @param string $newName the new name of the column. The name will be properly quoted by the method. |
||
150 | * @return string the SQL statement for renaming a DB column. |
||
151 | */ |
||
152 | public function renameColumn($table, $oldName, $newName) |
||
159 | |||
160 | /** |
||
161 | * Builds a SQL statement for changing the definition of a column. |
||
162 | * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method. |
||
163 | * @param string $column the name of the column to be changed. The name will be properly quoted by the method. |
||
164 | * @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any) |
||
165 | * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL. |
||
166 | * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'. |
||
167 | * @return string the SQL statement for changing the definition of a column. |
||
168 | */ |
||
169 | public function alterColumn($table, $column, $type) |
||
178 | |||
179 | /** |
||
180 | * @inheritDoc |
||
181 | */ |
||
182 | public function addDefaultValue($name, $table, $column, $value) |
||
188 | |||
189 | /** |
||
190 | * @inheritDoc |
||
191 | */ |
||
192 | public function dropDefaultValue($name, $table) |
||
197 | |||
198 | /** |
||
199 | * Creates a SQL statement for resetting the sequence value of a table's primary key. |
||
200 | * The sequence will be reset such that the primary key of the next new row inserted |
||
201 | * will have the specified value or 1. |
||
202 | * @param string $tableName the name of the table whose primary key sequence will be reset |
||
203 | * @param mixed $value the value for the primary key of the next new row inserted. If this is not set, |
||
204 | * the next new row's primary key will have a value 1. |
||
205 | * @return string the SQL statement for resetting sequence |
||
206 | * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table. |
||
207 | */ |
||
208 | public function resetSequence($tableName, $value = null) |
||
209 | { |
||
210 | $table = $this->db->getTableSchema($tableName); |
||
211 | if ($table !== null && $table->sequenceName !== null) { |
||
212 | $tableName = $this->db->quoteTableName($tableName); |
||
213 | if ($value === null) { |
||
214 | $key = $this->db->quoteColumnName(reset($table->primaryKey)); |
||
215 | $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1"; |
||
216 | } else { |
||
217 | $value = (int) $value; |
||
218 | } |
||
219 | |||
220 | return "DBCC CHECKIDENT ('{$tableName}', RESEED, {$value})"; |
||
221 | } elseif ($table === null) { |
||
222 | throw new InvalidArgumentException("Table not found: $tableName"); |
||
223 | } |
||
224 | |||
225 | throw new InvalidArgumentException("There is not sequence associated with table '$tableName'."); |
||
226 | } |
||
227 | |||
228 | /** |
||
229 | * Builds a SQL statement for enabling or disabling integrity check. |
||
230 | * @param bool $check whether to turn on or off the integrity check. |
||
231 | * @param string $schema the schema of the tables. |
||
232 | * @param string $table the table name. |
||
233 | * @return string the SQL statement for checking integrity |
||
234 | */ |
||
235 | public function checkIntegrity($check = true, $schema = '', $table = '') |
||
251 | |||
252 | /** |
||
253 | * {@inheritdoc} |
||
254 | * @since 2.0.8 |
||
255 | */ |
||
256 | public function addCommentOnColumn($table, $column, $comment) |
||
260 | |||
261 | /** |
||
262 | * {@inheritdoc} |
||
263 | * @since 2.0.8 |
||
264 | */ |
||
265 | public function addCommentOnTable($table, $comment) |
||
269 | |||
270 | /** |
||
271 | * {@inheritdoc} |
||
272 | * @since 2.0.8 |
||
273 | */ |
||
274 | public function dropCommentFromColumn($table, $column) |
||
278 | |||
279 | /** |
||
280 | * {@inheritdoc} |
||
281 | * @since 2.0.8 |
||
282 | */ |
||
283 | public function dropCommentFromTable($table) |
||
287 | |||
288 | /** |
||
289 | * Returns an array of column names given model name. |
||
290 | * |
||
291 | * @param string $modelClass name of the model class |
||
292 | * @return array|null array of column names |
||
293 | */ |
||
294 | protected function getAllColumnNames($modelClass = null) |
||
303 | |||
304 | /** |
||
305 | * @return bool whether the version of the MSSQL being used is older than 2012. |
||
306 | * @throws \yii\base\InvalidConfigException |
||
307 | * @throws \yii\db\Exception |
||
308 | * @deprecated 2.0.14 Use [[Schema::getServerVersion]] with [[\version_compare()]]. |
||
309 | */ |
||
310 | protected function isOldMssql() |
||
311 | { |
||
312 | return version_compare($this->db->getSchema()->getServerVersion(), '11', '<'); |
||
313 | } |
||
314 | |||
315 | /** |
||
316 | * {@inheritdoc} |
||
317 | * @since 2.0.8 |
||
318 | */ |
||
319 | public function selectExists($rawSql) |
||
320 | { |
||
321 | return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END'; |
||
322 | } |
||
323 | |||
324 | /** |
||
325 | * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary. |
||
326 | * @param string $table the table that data will be saved into. |
||
327 | * @param array $columns the column data (name => value) to be saved into the table. |
||
328 | * @return array normalized columns |
||
329 | */ |
||
330 | private function normalizeTableRowData($table, $columns, &$params) |
||
331 | { |
||
332 | if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) { |
||
333 | $columnSchemas = $tableSchema->columns; |
||
334 | foreach ($columns as $name => $value) { |
||
335 | // @see https://github.com/yiisoft/yii2/issues/12599 |
||
336 | if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && $columnSchemas[$name]->dbType === 'varbinary' && is_string($value)) { |
||
337 | $exParams = []; |
||
338 | $phName = $this->bindParam($value, $exParams); |
||
339 | $columns[$name] = new Expression("CONVERT(VARBINARY, $phName)", $exParams); |
||
340 | } |
||
341 | } |
||
342 | } |
||
343 | |||
344 | return $columns; |
||
345 | } |
||
346 | |||
347 | /** |
||
348 | * {@inheritdoc} |
||
349 | */ |
||
350 | public function insert($table, $columns, &$params) |
||
351 | { |
||
352 | return parent::insert($table, $this->normalizeTableRowData($table, $columns, $params), $params); |
||
353 | } |
||
354 | |||
355 | /** |
||
356 | * @inheritdoc |
||
357 | * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql |
||
358 | * @see http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx |
||
359 | */ |
||
360 | public function upsert($table, $insertColumns, $updateColumns, &$params) |
||
361 | { |
||
362 | /** @var Constraint[] $constraints */ |
||
363 | list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints); |
||
364 | if (empty($uniqueNames)) { |
||
365 | return $this->insert($table, $insertColumns, $params); |
||
366 | } |
||
367 | |||
368 | $onCondition = ['or']; |
||
369 | $quotedTableName = $this->db->quoteTableName($table); |
||
370 | foreach ($constraints as $constraint) { |
||
371 | $constraintCondition = ['and']; |
||
372 | foreach ($constraint->columnNames as $name) { |
||
373 | $quotedName = $this->db->quoteColumnName($name); |
||
374 | $constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName"; |
||
375 | } |
||
376 | $onCondition[] = $constraintCondition; |
||
377 | } |
||
378 | $on = $this->buildCondition($onCondition, $params); |
||
379 | list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params); |
||
380 | $mergeSql = 'MERGE ' . $this->db->quoteTableName($table) . ' WITH (HOLDLOCK) ' |
||
381 | . 'USING (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNames) . ') ' |
||
382 | . 'ON ' . $on; |
||
383 | $insertValues = []; |
||
384 | foreach ($insertNames as $name) { |
||
385 | $quotedName = $this->db->quoteColumnName($name); |
||
386 | if (strrpos($quotedName, '.') === false) { |
||
387 | $quotedName = '[EXCLUDED].' . $quotedName; |
||
388 | } |
||
389 | $insertValues[] = $quotedName; |
||
390 | } |
||
391 | $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' |
||
392 | . ' VALUES (' . implode(', ', $insertValues) . ')'; |
||
393 | if ($updateColumns === false) { |
||
394 | return "$mergeSql WHEN NOT MATCHED THEN $insertSql;"; |
||
395 | } |
||
396 | |||
397 | if ($updateColumns === true) { |
||
398 | $updateColumns = []; |
||
399 | foreach ($updateNames as $name) { |
||
400 | $quotedName = $this->db->quoteColumnName($name); |
||
401 | if (strrpos($quotedName, '.') === false) { |
||
402 | $quotedName = '[EXCLUDED].' . $quotedName; |
||
403 | } |
||
404 | $updateColumns[$name] = new Expression($quotedName); |
||
405 | } |
||
406 | } |
||
407 | list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params); |
||
408 | $updateSql = 'UPDATE SET ' . implode(', ', $updates); |
||
409 | return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;"; |
||
410 | } |
||
411 | |||
412 | /** |
||
413 | * {@inheritdoc} |
||
414 | */ |
||
415 | public function update($table, $columns, $condition, &$params) |
||
419 | } |
||
420 |
This check looks for function calls that miss required arguments.