Total Complexity | 73 |
Total Lines | 484 |
Duplicated Lines | 0 % |
Changes | 4 | ||
Bugs | 0 | Features | 0 |
Complex classes like SqlMySql 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 SqlMySql, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
27 | class SqlMySql extends SqlHelper |
||
28 | { |
||
29 | /** |
||
30 | * Retorna las comillas que encierran al nombre de la tabla en una consulta SQL. |
||
31 | * |
||
32 | * @author Rafael San José Tovar <[email protected]> |
||
33 | * @version 2023.0108 |
||
34 | * |
||
35 | * @return string |
||
36 | */ |
||
37 | public static function getTableQuote(): string |
||
38 | { |
||
39 | return '`'; |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * Retorna las comillas que encierran al nombre de un campo en una consulta SQL |
||
44 | * |
||
45 | * @author Rafael San José Tovar <[email protected]> |
||
46 | * @version 2023.0108 |
||
47 | * |
||
48 | * @return string |
||
49 | */ |
||
50 | public static function getFieldQuote(): string |
||
51 | { |
||
52 | return '"'; |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * Retorna true si la tabla existe en la base de datos. |
||
57 | * |
||
58 | * @author Rafael San José Tovar <[email protected]> |
||
59 | * @version 2023.0106 |
||
60 | * |
||
61 | * @param string $tableName |
||
62 | * |
||
63 | * @return bool |
||
64 | */ |
||
65 | public static function tableExists(string $tableName): bool |
||
66 | { |
||
67 | $dbName = DB::$dbName; |
||
68 | $sql = "SELECT COUNT(*) AS Total FROM information_schema.tables WHERE table_schema = '{$dbName}' AND table_name='{$tableName}'"; |
||
69 | |||
70 | $data = DB::select($sql); |
||
71 | $result = reset($data); |
||
72 | |||
73 | return $result['Total'] === '1'; |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Retorna un array con la asociación de tipos del motor SQL para cada tipo definido |
||
78 | * en el Schema. |
||
79 | * |
||
80 | * @author Rafael San José Tovar <[email protected]> |
||
81 | * @version 2023.0108 |
||
82 | * |
||
83 | * @return array[] |
||
84 | */ |
||
85 | public static function getDataTypes(): array |
||
97 | ]; |
||
98 | } |
||
99 | |||
100 | /** |
||
101 | * Retorna un array con el nombre de todas las tablas de la base de datos. |
||
102 | * |
||
103 | * @return array |
||
104 | */ |
||
105 | public static function getTables(): array |
||
109 | } |
||
110 | |||
111 | /** |
||
112 | * Retorna el tipo de dato que se utiliza para los índices autoincrementados |
||
113 | * |
||
114 | * @author Rafael San José Tovar <[email protected]> |
||
115 | * @version 2023.0108 |
||
116 | * |
||
117 | * @return string |
||
118 | */ |
||
119 | public static function getIndexType(): string |
||
122 | } |
||
123 | |||
124 | public static function getIntegerMinMax(int $size, bool $unsigned): array |
||
125 | { |
||
126 | switch ($size) { |
||
127 | case 1: |
||
128 | $type = 'tinyint'; |
||
129 | break; |
||
130 | case 2: |
||
131 | $type = 'smallint'; |
||
132 | break; |
||
133 | case 3: |
||
134 | $type = 'mediumint'; |
||
135 | break; |
||
136 | case 4: |
||
137 | $type = 'int'; |
||
138 | break; |
||
139 | default: |
||
140 | $type = 'bigint'; |
||
141 | $size = 8; |
||
142 | break; |
||
143 | } |
||
144 | |||
145 | $bits = 8 * (int) $size; |
||
146 | $physicalMaxLength = 2 ** $bits; |
||
147 | |||
148 | /** |
||
149 | * $minDataLength y $maxDataLength contendrán el mínimo y máximo valor que puede contener el campo. |
||
150 | */ |
||
151 | $minDataLength = $unsigned ? 0 : -$physicalMaxLength / 2; |
||
152 | $maxDataLength = ($unsigned ? $physicalMaxLength : $physicalMaxLength / 2) - 1; |
||
153 | |||
154 | /** |
||
155 | * De momento, se asignan los límites máximos por el tipo de dato. |
||
156 | * En $min y $max, iremos arrastrando los límites conforme se vayan comprobando. |
||
157 | * $min nunca podrá ser menor que $minDataLength. |
||
158 | * $max nunca podrá ser mayor que $maxDataLength. |
||
159 | */ |
||
160 | $min = $minDataLength; |
||
161 | $max = $maxDataLength; |
||
162 | |||
163 | return [ |
||
164 | 'dbtype' => $type, |
||
165 | 'min' => $min, |
||
166 | 'max' => $max, |
||
167 | 'size' => $size, |
||
168 | 'unsigned' => $unsigned, |
||
169 | ]; |
||
170 | } |
||
171 | |||
172 | /** |
||
173 | * Retorna un array asociativo con la información de cada columna de la tabla. |
||
174 | * El resultado será dependiente del motor de base de datos. |
||
175 | * |
||
176 | * @author Rafael San José Tovar <[email protected]> |
||
177 | * @version 2023.0108 |
||
178 | * |
||
179 | * @param string $tableName |
||
180 | * |
||
181 | * @return array |
||
182 | */ |
||
183 | public static function getColumns(string $tableName): array |
||
192 | } |
||
193 | |||
194 | public static function yamlFieldIntegerToDb(array $data): string |
||
216 | } |
||
217 | |||
218 | public static function yamlFieldToDb(array $data): array |
||
219 | { |
||
220 | $nullable = strtolower($data['nullable']) !== 'no'; |
||
221 | |||
222 | $result = []; |
||
223 | $result['Field'] = $data['name']; |
||
224 | |||
225 | $type = $data['dbtype']; |
||
226 | switch ($data['generictype']) { |
||
227 | case Schema::TYPE_INTEGER: |
||
228 | $type = self::yamlFieldIntegerToDb($data); |
||
229 | break; |
||
230 | case Schema::TYPE_FLOAT: |
||
231 | case Schema::TYPE_DECIMAL: |
||
232 | break; |
||
233 | case Schema::TYPE_STRING: |
||
234 | $type = 'varchar(' . $data['length'] . ')'; |
||
235 | break; |
||
236 | case Schema::TYPE_TEXT: |
||
237 | case Schema::TYPE_DATE: |
||
238 | case Schema::TYPE_TIME: |
||
239 | case Schema::TYPE_DATETIME: |
||
240 | break; |
||
241 | case Schema::TYPE_BOOLEAN: |
||
242 | // $type = 'tinyint(1)'; |
||
243 | break; |
||
244 | } |
||
245 | $result['Type'] = $type; |
||
246 | $result['Null'] = $nullable ? 'YES' : 'NO'; |
||
247 | $result['Key'] = $data['type'] === 'autoincrement' ? 'PRI' : ''; |
||
248 | $result['Default'] = $data['default'] ?? null; |
||
249 | $result['Extra'] = $data['type'] === 'autoincrement' ? 'auto_increment' : ''; |
||
250 | return $result; |
||
251 | } |
||
252 | |||
253 | public static function getSqlField(array $column): string |
||
254 | { |
||
255 | $field = $column['Field']; |
||
256 | $type = $column['Type']; |
||
257 | $null = $column['Null']; |
||
258 | $key = $column['Key']; |
||
259 | $default = $column['Default']; |
||
260 | $extra = $column['Extra']; |
||
261 | |||
262 | $sql = self::quoteTableName($field) . ' ' . $type; |
||
263 | $nulo = ($null === 'YES'); |
||
264 | if ($extra === 'auto_increment') { |
||
265 | $nulo = false; |
||
266 | $sql .= ' PRIMARY KEY AUTO_INCREMENT'; |
||
267 | } |
||
268 | |||
269 | $sql .= ($nulo ? '' : ' NOT') . ' NULL'; |
||
270 | |||
271 | $defecto = ''; |
||
272 | if (isset($default)) { |
||
273 | if ($default === 'CURRENT_TIMESTAMP') { |
||
274 | $defecto = $default; |
||
275 | } elseif (is_bool($default)) { |
||
276 | $defecto = $default ? 1 : 0; |
||
277 | } else { |
||
278 | $defecto = "'$defecto'"; |
||
279 | } |
||
280 | } else { |
||
281 | if ($nulo) { |
||
282 | $defecto = 'NULL'; |
||
283 | } |
||
284 | } |
||
285 | |||
286 | if (!empty($defecto)) { |
||
287 | $sql .= ' DEFAULT ' . $defecto; |
||
288 | } |
||
289 | return $sql; |
||
290 | } |
||
291 | |||
292 | public static function _dbFieldToSchema(array $data): array |
||
293 | { |
||
294 | return $data; |
||
295 | } |
||
296 | |||
297 | public static function _dbFieldToYaml(array $data): array |
||
298 | { |
||
299 | return $data; |
||
300 | } |
||
301 | |||
302 | /** |
||
303 | * Recibiendo un array con los datos de un campo tal y como lo retorna la base de |
||
304 | * datos, devuelve la información normalizada para ser utilizada por Schema. |
||
305 | * |
||
306 | * @author Rafael San José Tovar <[email protected]> |
||
307 | * @version 2023.0108 |
||
308 | * |
||
309 | * @param array $row |
||
310 | * |
||
311 | * @return array |
||
312 | */ |
||
313 | public static function _normalizeDbField(array $row): array |
||
314 | { |
||
315 | $result = []; |
||
316 | $result['Field'] = $row['key']; |
||
317 | $result['Type'] = $row['type']; |
||
318 | $result['Null'] = $row['nullable'] ? 'YES' : 'NO'; |
||
319 | $result['Key'] = $row['type'] === 'autoincrement' ? 'PRI' : ''; |
||
320 | $result['Default'] = $row['default'] ?? null; |
||
321 | $result['Extra'] = $row['type'] === 'autoincrement' ? 'auto_increment' : ''; |
||
322 | return $result; |
||
323 | } |
||
324 | |||
325 | /** |
||
326 | * Divide the data type of a MySQL field into its various components: type, |
||
327 | * length, unsigned or zerofill, if applicable. |
||
328 | * |
||
329 | * @param string $originalType |
||
330 | * |
||
331 | * @return array |
||
332 | */ |
||
333 | private static function _splitType(string $originalType): array |
||
334 | { |
||
335 | $explode = explode(' ', strtolower($originalType)); |
||
336 | |||
337 | $pos = strpos($explode[0], '('); |
||
338 | |||
339 | $type = $pos ? substr($explode[0], 0, $pos) : $explode[0]; |
||
340 | $length = $pos ? intval(substr($explode[0], $pos + 1)) : null; |
||
341 | |||
342 | $pos = array_search('unsigned', $explode); |
||
343 | $unsigned = $pos ? 'unsigned' : null; |
||
344 | |||
345 | $pos = array_search('zerofill', $explode); |
||
346 | $zerofill = $pos ? 'zerofill' : null; |
||
347 | |||
348 | return ['type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'zerofill' => $zerofill]; |
||
349 | } |
||
350 | |||
351 | /** |
||
352 | * Returns an array with the index information, and if there are, also constraints. |
||
353 | * |
||
354 | * @param array $row |
||
355 | * |
||
356 | * @return array |
||
357 | */ |
||
358 | public function _normalizeIndexes(array $row): array |
||
378 | } |
||
379 | |||
380 | /** |
||
381 | * The data about the constraint that is found in the KEY_COLUMN_USAGE table |
||
382 | * is returned. |
||
383 | * Attempting to return the consolidated data generates an extremely slow query |
||
384 | * in some MySQL installations, so 2 additional simple queries are made. |
||
385 | * |
||
386 | * @param string $tableName |
||
387 | * @param string $constraintName |
||
388 | * |
||
389 | * @return array |
||
390 | */ |
||
391 | private function _getConstraintData(string $tableName, string $constraintName): array |
||
392 | { |
||
393 | $dbName = Config::getVar('dbName') ?? 'Unknown'; |
||
394 | |||
395 | return DB::select(' |
||
396 | SELECT |
||
397 | TABLE_NAME, |
||
398 | COLUMN_NAME, |
||
399 | CONSTRAINT_NAME, |
||
400 | REFERENCED_TABLE_NAME, |
||
401 | REFERENCED_COLUMN_NAME |
||
402 | FROM |
||
403 | INFORMATION_SCHEMA.KEY_COLUMN_USAGE |
||
404 | WHERE |
||
405 | TABLE_SCHEMA = ' . $this->quoteFieldName($dbName) . ' AND |
||
406 | TABLE_NAME = ' . $this->quoteFieldName($tableName) . ' AND |
||
407 | constraint_name = ' . $this->quoteFieldName($constraintName) . ' AND |
||
408 | REFERENCED_COLUMN_NAME IS NOT NULL; |
||
409 | '); |
||
410 | } |
||
411 | |||
412 | /** |
||
413 | * The rules for updating and deleting data with constraint (table |
||
414 | * REFERENTIAL_CONSTRAINTS) are returned. |
||
415 | * Attempting to return the consolidated data generates an extremely slow query |
||
416 | * in some MySQL installations, so 2 additional simple queries are made. |
||
417 | * |
||
418 | * @param string $tableName |
||
419 | * @param string $constraintName |
||
420 | * |
||
421 | * @return array |
||
422 | */ |
||
423 | private function _getConstraintRules(string $tableName, string $constraintName): array |
||
424 | { |
||
425 | $dbName = Config::getVar('dbName') ?? 'Unknown'; |
||
426 | |||
427 | return DB::selectselect(' |
||
428 | SELECT |
||
429 | MATCH_OPTION, |
||
430 | UPDATE_RULE, |
||
431 | DELETE_RULE |
||
432 | FROM information_schema.REFERENTIAL_CONSTRAINTS |
||
433 | WHERE |
||
434 | constraint_schema = ' . $this->quoteFieldName($dbName) . ' AND |
||
435 | table_name = ' . $this->quoteFieldName($tableName) . ' AND |
||
436 | constraint_name = ' . $this->quoteFieldName($constraintName) . '; |
||
437 | '); |
||
438 | } |
||
439 | |||
440 | /** |
||
441 | * Obtain an array with the basic information about the indexes of the table, |
||
442 | * which will be supplemented with the restrictions later. |
||
443 | * |
||
444 | * @param string $tableName |
||
445 | * |
||
446 | * @return string |
||
447 | */ |
||
448 | public function _getIndexesSql(string $tableName): string |
||
453 | } |
||
454 | |||
455 | /** |
||
456 | * Toma la estructura de un campo obtenida de la base de datos, y la retorna |
||
457 | * de la misma forma en la que se usó al ser creada. |
||
458 | * Esto es necesario, porque algunas bases de datos cambian tipos como boolean por |
||
459 | * tinyint(1), o int por int(10) |
||
460 | * |
||
461 | * @author Rafael San José Tovar <[email protected]> |
||
462 | * |
||
463 | * @param string $genericType |
||
464 | * @param array $structure |
||
465 | * |
||
466 | * @return array |
||
467 | */ |
||
468 | public static function sanitizeDbStructure(string $genericType, array $structure): array |
||
469 | { |
||
470 | $type = $structure['Type']; |
||
471 | switch ($genericType) { |
||
472 | // Tipos que no cambian |
||
473 | case Schema::TYPE_FLOAT: |
||
474 | case Schema::TYPE_DECIMAL: |
||
475 | case Schema::TYPE_STRING: |
||
476 | case Schema::TYPE_TEXT: |
||
477 | case Schema::TYPE_DATE: |
||
478 | case Schema::TYPE_TIME: |
||
479 | case Schema::TYPE_DATETIME: |
||
480 | break; |
||
481 | // Tipos a los que hay que quitar los paréntesis |
||
482 | case Schema::TYPE_INTEGER: |
||
483 | $type = preg_replace("/\((.*?)\)/i", "", $type); |
||
484 | break; |
||
485 | // Tipos que cambian durante la creación |
||
486 | case Schema::TYPE_BOOLEAN: |
||
487 | $type = 'boolean'; // Se crea como boolean y se retorna como tinyint(1) |
||
488 | $structure['Default'] = ($structure['Default'] === '1'); |
||
489 | break; |
||
490 | } |
||
491 | $structure['Type'] = $type; |
||
492 | return $structure; |
||
493 | } |
||
494 | |||
495 | public static function modify(string $tableName, array $oldField, array $newField): string |
||
511 | } |
||
512 | } |
||
513 |