6da1582d24d1bb9b8857008281bd6705e292d577
[Packages/TYPO3.CMS.git] / typo3 / sysext / install / Classes / Service / SqlSchemaMigrationService.php
1 <?php
2 namespace TYPO3\CMS\Install\Service;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Doctrine\DBAL\DBALException;
18 use TYPO3\CMS\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Verify TYPO3 DB table structure. Mainly used in install tool
23 * compare wizard and extension manager.
24 */
25 class SqlSchemaMigrationService
26 {
27 /**
28 * @constant Maximum field width of MySQL
29 */
30 const MYSQL_MAXIMUM_FIELD_WIDTH = 64;
31
32 /**
33 * @var string Prefix of deleted tables
34 */
35 protected $deletedPrefixKey = 'zzz_deleted_';
36
37 /**
38 * @var array Caching output "SHOW CHARACTER SET"
39 */
40 protected $character_sets = [];
41
42 /**
43 * Set prefix of deleted tables
44 *
45 * @param string $prefix Prefix string
46 */
47 public function setDeletedPrefixKey($prefix)
48 {
49 $this->deletedPrefixKey = $prefix;
50 }
51
52 /**
53 * Get prefix of deleted tables
54 *
55 * @return string
56 */
57 public function getDeletedPrefixKey()
58 {
59 return $this->deletedPrefixKey;
60 }
61
62 /**
63 * Reads the field definitions for the input SQL-file string
64 *
65 * @param string $fileContent Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
66 * @return array Array with information about table.
67 */
68 public function getFieldDefinitions_fileContent($fileContent)
69 {
70 $lines = GeneralUtility::trimExplode(LF, $fileContent, true);
71 $table = '';
72 $total = [];
73 foreach ($lines as $value) {
74 if ($value[0] === '#') {
75 // Ignore comments
76 continue;
77 }
78 if ($table === '') {
79 $parts = GeneralUtility::trimExplode(' ', $value, true);
80 if (strtoupper($parts[0]) === 'CREATE' && strtoupper($parts[1]) === 'TABLE') {
81 $table = str_replace('`', '', $parts[2]);
82 // tablenames are always lowercase on windows!
83 if (TYPO3_OS == 'WIN') {
84 $table = strtolower($table);
85 }
86 }
87 } else {
88 if ($value[0] === ')' && substr($value, -1) === ';') {
89 $ttype = [];
90 if (preg_match('/(ENGINE|TYPE)[ ]*=[ ]*([a-zA-Z]*)/', $value, $ttype)) {
91 $total[$table]['extra']['ENGINE'] = $ttype[2];
92 }
93 // Otherwise, just do nothing: If table engine is not defined, just accept the system default.
94 // Set the collation, if specified
95 if (preg_match('/(COLLATE)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcollation)) {
96 $total[$table]['extra']['COLLATE'] = $tcollation[2];
97 } else {
98 // Otherwise, get the CHARACTER SET and try to find the default collation for it as returned by "SHOW CHARACTER SET" query (for details, see http://dev.mysql.com/doc/refman/5.1/en/charset-table.html)
99 if (preg_match('/(CHARSET|CHARACTER SET)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcharset)) {
100 // Note: Keywords "DEFAULT CHARSET" and "CHARSET" are the same, so "DEFAULT" can just be ignored
101 $charset = $tcharset[2];
102 } else {
103 $charset = 'utf8';
104 }
105 $total[$table]['extra']['COLLATE'] = $this->getCollationForCharset($charset);
106 }
107 // Remove table marker and start looking for the next "CREATE TABLE" statement
108 $table = '';
109 } else {
110 // Strip trailing commas
111 $lineV = preg_replace('/,$/', '', $value);
112 $lineV = str_replace('`', '', $lineV);
113 // Reduce multiple blanks and tabs except newline
114 $lineV = preg_replace('/\h+/', ' ', $lineV);
115 $parts = explode(' ', $lineV, 2);
116 // Field definition
117 if (!preg_match('/(PRIMARY|UNIQUE|FULLTEXT|SPATIAL|INDEX|KEY)/', $parts[0])) {
118 // Make sure there is no default value when auto_increment is set
119 if (stristr($parts[1], 'auto_increment')) {
120 $parts[1] = preg_replace('/ default \'0\'/i', '', $parts[1]);
121 }
122 // "default" is always lower-case
123 if (stristr($parts[1], ' DEFAULT ')) {
124 $parts[1] = str_ireplace(' DEFAULT ', ' default ', $parts[1]);
125 }
126 // Change order of "default" and "NULL" statements
127 $parts[1] = preg_replace('/(.*) (default .*) (NOT NULL)/', '$1 $3 $2', $parts[1]);
128 $parts[1] = preg_replace('/(.*) (default .*) (NULL)/', '$1 $3 $2', $parts[1]);
129 $key = $parts[0];
130 $total[$table]['fields'][$key] = $parts[1];
131 } else {
132 // Key definition
133 $search = ['/UNIQUE (INDEX|KEY)/', '/FULLTEXT (INDEX|KEY)/', '/SPATIAL (INDEX|KEY)/', '/INDEX/'];
134 $replace = ['UNIQUE', 'FULLTEXT', 'SPATIAL', 'KEY'];
135 $lineV = preg_replace($search, $replace, $lineV);
136 if (preg_match('/PRIMARY|UNIQUE|FULLTEXT|SPATIAL/', $parts[0])) {
137 $parts[1] = preg_replace('/^(KEY|INDEX) /', '', $parts[1]);
138 }
139 $newParts = explode(' ', $parts[1], 2);
140 $key = $parts[0] == 'PRIMARY' ? $parts[0] : $newParts[0];
141 $total[$table]['keys'][$key] = $lineV;
142 // This is a protection against doing something stupid: Only allow clearing of cache_* and index_* tables.
143 if (preg_match('/^(cache|index)_/', $table)) {
144 // Suggest to truncate (clear) this table
145 $total[$table]['extra']['CLEAR'] = 1;
146 }
147 }
148 }
149 }
150 }
151 return $total;
152 }
153
154 /**
155 * Look up the default collation for specified character set based on "SHOW CHARACTER SET" output
156 *
157 * @param string $charset Character set
158 * @return string Corresponding default collation
159 */
160 public function getCollationForCharset($charset)
161 {
162 // Load character sets, if not cached already
163 if (empty($this->character_sets)) {
164 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionByName('Default');
165 $statement = $connection->query('SHOW CHARACTER SET');
166 $this->character_sets = [];
167 while ($row = $statement->fetch()) {
168 $this->character_sets[$row['Charset']] = $row;
169 }
170 }
171 $collation = '';
172 if (isset($this->character_sets[$charset]['Default collation'])) {
173 $collation = $this->character_sets[$charset]['Default collation'];
174 }
175 return $collation;
176 }
177
178 /**
179 * Reads the field definitions for the current database
180 *
181 * @return array Array with information about table.
182 */
183 public function getFieldDefinitions_database()
184 {
185 $total = [];
186 $tempKeys = [];
187 $tempKeysPrefix = [];
188 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionByName('Default');
189 $statement = $connection->query('SHOW TABLE STATUS FROM `' . $connection->getDatabase() . '`');
190 $tables = [];
191 while ($theTable = $statement->fetch()) {
192 $tables[$theTable['Name']] = $theTable;
193 }
194 foreach ($tables as $tableName => $tableStatus) {
195 // Fields
196 $statement = $connection->query('SHOW FULL COLUMNS FROM `' . $tableName . '`');
197 $fieldInformation = [];
198 while ($fieldRow = $statement->fetch()) {
199 $fieldInformation[$fieldRow['Field']] = $fieldRow;
200 }
201 foreach ($fieldInformation as $fN => $fieldRow) {
202 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
203 }
204 // Keys
205 $statement = $connection->query('SHOW KEYS FROM `' . $tableName . '`');
206 $keyInformation = [];
207 while ($keyRow = $statement->fetch()) {
208 $keyInformation[] = $keyRow;
209 }
210 foreach ($keyInformation as $keyRow) {
211 $keyName = $keyRow['Key_name'];
212 $colName = $keyRow['Column_name'];
213 if ($keyRow['Sub_part'] && $keyRow['Index_type'] !== 'SPATIAL') {
214 $colName .= '(' . $keyRow['Sub_part'] . ')';
215 }
216 $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
217 if ($keyName == 'PRIMARY') {
218 $prefix = 'PRIMARY KEY';
219 } else {
220 if ($keyRow['Index_type'] === 'FULLTEXT') {
221 $prefix = 'FULLTEXT';
222 } elseif ($keyRow['Index_type'] === 'SPATIAL') {
223 $prefix = 'SPATIAL';
224 } elseif ($keyRow['Non_unique']) {
225 $prefix = 'KEY';
226 } else {
227 $prefix = 'UNIQUE';
228 }
229 $prefix .= ' ' . $keyName;
230 }
231 $tempKeysPrefix[$tableName][$keyName] = $prefix;
232 }
233 // Table status (storage engine, collaction, etc.)
234 if (is_array($tableStatus)) {
235 $tableExtraFields = [
236 'Engine' => 'ENGINE',
237 'Collation' => 'COLLATE'
238 ];
239 foreach ($tableExtraFields as $mysqlKey => $internalKey) {
240 if (isset($tableStatus[$mysqlKey])) {
241 $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
242 }
243 }
244 }
245 }
246 // Compile key information:
247 if (!empty($tempKeys)) {
248 foreach ($tempKeys as $table => $keyInf) {
249 foreach ($keyInf as $kName => $index) {
250 ksort($index);
251 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName] . ' (' . implode(',', $index) . ')';
252 }
253 }
254 }
255 return $total;
256 }
257
258 /**
259 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
260 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
261 *
262 * @param array $FDsrc Field definitions, source (from getFieldDefinitions_fileContent())
263 * @param array $FDcomp Field definitions, comparison. (from getFieldDefinitions_database())
264 * @param string $onlyTableList Table names (in list) which is the ONLY one observed.
265 * @param bool $ignoreNotNullWhenComparing If set, this function ignores NOT NULL statements of the SQL file field definition when comparing current field definition from database with field definition from SQL file. This way, NOT NULL statements will be executed when the field is initially created, but the SQL parser will never complain about missing NOT NULL statements afterwards.
266 * @return array Returns an array with 1) all elements from $FDsrc that is not in $FDcomp (in key 'extra') and 2) all elements from $FDsrc that is different from the ones in $FDcomp
267 */
268 public function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList = '', $ignoreNotNullWhenComparing = false)
269 {
270 $extraArr = [];
271 $diffArr = [];
272 if (is_array($FDsrc)) {
273 foreach ($FDsrc as $table => $info) {
274 if ($onlyTableList === '' || GeneralUtility::inList($onlyTableList, $table)) {
275 if (!isset($FDcomp[$table])) {
276 // If the table was not in the FDcomp-array, the result array is loaded with that table.
277 $extraArr[$table] = $info;
278 $extraArr[$table]['whole_table'] = 1;
279 } else {
280 $keyTypes = explode(',', 'extra,fields,keys');
281 foreach ($keyTypes as $theKey) {
282 if (is_array($info[$theKey])) {
283 foreach ($info[$theKey] as $fieldN => $fieldC) {
284 $fieldN = str_replace('`', '', $fieldN);
285 if ($fieldN == 'COLLATE') {
286 // @todo collation support is currently disabled (needs more testing)
287 continue;
288 }
289 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
290 $extraArr[$table][$theKey][$fieldN] = $fieldC;
291 } else {
292 $fieldC = trim($fieldC);
293
294 // Lowercase the field type to surround false-positive schema changes to be
295 // reported just because of different caseing of characters
296 // The regex does just trigger for the first word followed by parentheses
297 // that contain a length. It does not trigger for e.g. "PRIMARY KEY" because
298 // "PRIMARY KEY" is being returned from the DB in upper case.
299 $fieldC = preg_replace_callback(
300 '/^([a-zA-Z0-9]+)(\([^)]*\)\s.*)/',
301 function ($matches) {
302 return strtolower($matches[1]) . $matches[2];
303 },
304 $fieldC
305 );
306
307 if ($ignoreNotNullWhenComparing) {
308 $fieldC = str_replace(' NOT NULL', '', $fieldC);
309 $FDcomp[$table][$theKey][$fieldN] = str_replace(' NOT NULL', '', $FDcomp[$table][$theKey][$fieldN]);
310 }
311 if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
312 $diffArr[$table][$theKey][$fieldN] = $fieldC;
313 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
314 }
315 }
316 }
317 }
318 }
319 }
320 }
321 }
322 }
323 $output = [
324 'extra' => $extraArr,
325 'diff' => $diffArr,
326 'diff_currentValues' => $diffArr_cur
327 ];
328 return $output;
329 }
330
331 /**
332 * Returns an array with SQL-statements that is needed to update according to the diff-array
333 *
334 * @param array $diffArr Array with differences of current and needed DB settings. (from getDatabaseExtra())
335 * @param string $keyList List of fields in diff array to take notice of.
336 * @return array Array of SQL statements (organized in keys depending on type)
337 */
338 public function getUpdateSuggestions($diffArr, $keyList = 'extra,diff')
339 {
340 $statements = [];
341 $deletedPrefixKey = $this->deletedPrefixKey;
342 $deletedPrefixLength = strlen($deletedPrefixKey);
343 $remove = 0;
344 if ($keyList == 'remove') {
345 $remove = 1;
346 $keyList = 'extra';
347 }
348 $keyList = explode(',', $keyList);
349 foreach ($keyList as $theKey) {
350 if (is_array($diffArr[$theKey])) {
351 foreach ($diffArr[$theKey] as $table => $info) {
352 $whole_table = [];
353 if (isset($info['keys']) && is_array($info['keys'])) {
354 foreach ($info['keys'] as $fN => $fV) {
355 if (!$info['whole_table'] && $theKey === 'extra' && $remove) {
356 $statement = 'ALTER TABLE ' . $table . ($fN === 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
357 $statements['drop'][md5($statement)] = $statement;
358 }
359 }
360 }
361 if (is_array($info['fields'])) {
362 foreach ($info['fields'] as $fN => $fV) {
363 if ($info['whole_table']) {
364 $whole_table[] = $fN . ' ' . $fV;
365 } else {
366 // Special case to work around MySQL problems when adding auto_increment fields:
367 if (stristr($fV, 'auto_increment')) {
368 // The field can only be set "auto_increment" if there exists a PRIMARY key of that field already.
369 // The check does not look up which field is primary but just assumes it must be the field with the auto_increment value...
370 if (isset($info['keys']['PRIMARY'])) {
371 // Combine adding the field and the primary key into a single statement
372 $fV .= ', ADD PRIMARY KEY (' . $fN . ')';
373 unset($info['keys']['PRIMARY']);
374 } else {
375 // In the next step, attempt to clear the table once again (2 = force)
376 $info['extra']['CLEAR'] = 2;
377 }
378 }
379 if ($theKey == 'extra') {
380 if ($remove) {
381 if (substr($fN, 0, $deletedPrefixLength) !== $deletedPrefixKey) {
382 // we've to make sure we don't exceed the maximal length
383 $prefixedFieldName = $deletedPrefixKey . substr($fN, ($deletedPrefixLength - self::MYSQL_MAXIMUM_FIELD_WIDTH));
384 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $prefixedFieldName . ' ' . $fV . ';';
385 $statements['change'][md5($statement)] = $statement;
386 } else {
387 $statement = 'ALTER TABLE ' . $table . ' DROP ' . $fN . ';';
388 $statements['drop'][md5($statement)] = $statement;
389 }
390 } else {
391 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fN . ' ' . $fV . ';';
392 $statements['add'][md5($statement)] = $statement;
393 }
394 } elseif ($theKey == 'diff') {
395 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $fN . ' ' . $fV . ';';
396 $statements['change'][md5($statement)] = $statement;
397 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
398 }
399 }
400 }
401 }
402 if (is_array($info['keys'])) {
403 foreach ($info['keys'] as $fN => $fV) {
404 if ($info['whole_table']) {
405 $whole_table[] = $fV;
406 } else {
407 if ($theKey == 'extra') {
408 if (!$remove) {
409 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
410 $statements['add'][md5($statement)] = $statement;
411 }
412 } elseif ($theKey == 'diff') {
413 $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
414 $statements['change'][md5($statement)] = $statement;
415 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
416 $statements['change'][md5($statement)] = $statement;
417 }
418 }
419 }
420 }
421 if (is_array($info['extra'])) {
422 $extras = [];
423 $extras_currentValue = [];
424 $clear_table = false;
425 foreach ($info['extra'] as $fN => $fV) {
426 // Only consider statements which are missing in the database but don't remove existing properties
427 if (!$remove) {
428 if (!$info['whole_table']) {
429 // If the whole table is created at once, we take care of this later by imploding all elements of $info['extra']
430 if ($fN == 'CLEAR') {
431 // Truncate table must happen later, not now
432 // Valid values for CLEAR: 1=only clear if keys are missing, 2=clear anyway (force)
433 if (!empty($info['keys']) || $fV == 2) {
434 $clear_table = true;
435 }
436 continue;
437 } else {
438 $extras[] = $fN . '=' . $fV;
439 $extras_currentValue[] = $fN . '=' . $diffArr['diff_currentValues'][$table]['extra'][$fN];
440 }
441 }
442 }
443 }
444 if ($clear_table) {
445 $statement = 'TRUNCATE TABLE ' . $table . ';';
446 $statements['clear_table'][md5($statement)] = $statement;
447 }
448 if (!empty($extras)) {
449 $statement = 'ALTER TABLE ' . $table . ' ' . implode(' ', $extras) . ';';
450 $statements['change'][md5($statement)] = $statement;
451 $statements['change_currentValue'][md5($statement)] = implode(' ', $extras_currentValue);
452 }
453 }
454 if ($info['whole_table']) {
455 if ($remove) {
456 if (substr($table, 0, $deletedPrefixLength) !== $deletedPrefixKey) {
457 // we've to make sure we don't exceed the maximal length
458 $prefixedTableName = $deletedPrefixKey . substr($table, ($deletedPrefixLength - self::MYSQL_MAXIMUM_FIELD_WIDTH));
459 $statement = 'ALTER TABLE ' . $table . ' RENAME ' . $prefixedTableName . ';';
460 $statements['change_table'][md5($statement)] = $statement;
461 } else {
462 $statement = 'DROP TABLE ' . $table . ';';
463 $statements['drop_table'][md5($statement)] = $statement;
464 }
465 // Count
466 $count = GeneralUtility::makeInstance(ConnectionPool::class)
467 ->getConnectionByName('Default')
468 ->count('*', $table, []);
469 $statements['tables_count'][md5($statement)] = $count ? 'Records in table: ' . $count : '';
470 } else {
471 $statement = 'CREATE TABLE ' . $table . ' (
472 ' . implode(',
473 ', $whole_table) . '
474 )';
475 if ($info['extra']) {
476 foreach ($info['extra'] as $k => $v) {
477 if ($k == 'COLLATE' || $k == 'CLEAR') {
478 // Skip these special statements.
479 // @todo collation support is currently disabled (needs more testing)
480 continue;
481 }
482 // Add extra attributes like ENGINE, CHARSET, etc.
483 $statement .= ' ' . $k . '=' . $v;
484 }
485 }
486 $statement .= ';';
487 $statements['create_table'][md5($statement)] = $statement;
488 }
489 }
490 }
491 }
492 }
493
494 return $statements;
495 }
496
497 /**
498 * Converts a result row with field information into the SQL field definition string
499 *
500 * @param array $row MySQL result row
501 * @return string Field definition
502 */
503 public function assembleFieldDefinition($row)
504 {
505 $field = [$row['Type']];
506 if ($row['Null'] == 'NO') {
507 $field[] = 'NOT NULL';
508 }
509 if (!strstr($row['Type'], 'blob') && !strstr($row['Type'], 'text')) {
510 // Add a default value if the field is not auto-incremented (these fields never have a default definition)
511 if (!stristr($row['Extra'], 'auto_increment')) {
512 if ($row['Default'] === null) {
513 $field[] = 'default NULL';
514 } else {
515 $field[] = 'default \'' . addslashes($row['Default']) . '\'';
516 }
517 }
518 }
519 if ($row['Extra']) {
520 $field[] = $row['Extra'];
521 }
522 if (trim($row['Comment']) !== '') {
523 $field[] = "COMMENT '" . $row['Comment'] . "'";
524 }
525 return implode(' ', $field);
526 }
527
528 /**
529 * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
530 *
531 * @param string $sqlcode The SQL-file content. Provided that 1) every query in the input is ended with ';' and that a line in the file contains only one query or a part of a query.
532 * @param bool $removeNonSQL If set, non-SQL content (like comments and blank lines) is not included in the final output
533 * @param string $query_regex Regex to filter SQL lines to include
534 * @return array Array of SQL statements
535 */
536 public function getStatementArray($sqlcode, $removeNonSQL = false, $query_regex = '')
537 {
538 $sqlcodeArr = explode(LF, $sqlcode);
539 // Based on the assumption that the sql-dump has
540 $statementArray = [];
541 $statementArrayPointer = 0;
542 foreach ($sqlcodeArr as $line => $lineContent) {
543 $lineContent = trim($lineContent);
544 $is_set = 0;
545 // Auto_increment fields cannot have a default value!
546 if (stristr($lineContent, 'auto_increment')) {
547 $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
548 }
549 if (!$removeNonSQL || $lineContent !== '' && $lineContent[0] !== '#' && substr($lineContent, 0, 2) !== '--') {
550 // '--' is seen as mysqldump comments from server version 3.23.49
551 $statementArray[$statementArrayPointer] .= $lineContent;
552 $is_set = 1;
553 }
554 if (substr($lineContent, -1) === ';') {
555 if (isset($statementArray[$statementArrayPointer])) {
556 if (!trim($statementArray[$statementArrayPointer]) || $query_regex && !preg_match(('/' . $query_regex . '/i'), trim($statementArray[$statementArrayPointer]))) {
557 unset($statementArray[$statementArrayPointer]);
558 }
559 }
560 $statementArrayPointer++;
561 } elseif ($is_set) {
562 $statementArray[$statementArrayPointer] .= LF;
563 }
564 }
565 return $statementArray;
566 }
567
568 /**
569 * Returns tables to create and how many records in each
570 *
571 * @param array $statements Array of SQL statements to analyse.
572 * @param bool $insertCountFlag If set, will count number of INSERT INTO statements following that table definition
573 * @return array Array with table definitions in index 0 and count in index 1
574 */
575 public function getCreateTables($statements, $insertCountFlag = false)
576 {
577 $crTables = [];
578 $insertCount = [];
579 foreach ($statements as $line => $lineContent) {
580 $reg = [];
581 if (preg_match('/^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
582 $table = trim($reg[1]);
583 if ($table) {
584 // Table names are always lowercase on Windows!
585 if (TYPO3_OS == 'WIN') {
586 $table = strtolower($table);
587 }
588 $sqlLines = explode(LF, $lineContent);
589 foreach ($sqlLines as $k => $v) {
590 if (stristr($v, 'auto_increment')) {
591 $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
592 }
593 }
594 $lineContent = implode(LF, $sqlLines);
595 $crTables[$table] = $lineContent;
596 }
597 } elseif ($insertCountFlag && preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
598 $nTable = trim($reg[1]);
599 $insertCount[$nTable]++;
600 }
601 }
602 return [$crTables, $insertCount];
603 }
604
605 /**
606 * Extracts all insert statements from $statement array where content is inserted into $table
607 *
608 * @param array $statements Array of SQL statements
609 * @param string $table Table name
610 * @return array Array of INSERT INTO statements where table match $table
611 */
612 public function getTableInsertStatements($statements, $table)
613 {
614 $outStatements = [];
615 foreach ($statements as $line => $lineContent) {
616 $reg = [];
617 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
618 $nTable = trim($reg[1]);
619 if ($nTable && $table === $nTable) {
620 $outStatements[] = $lineContent;
621 }
622 }
623 }
624 return $outStatements;
625 }
626
627 /**
628 * Performs the queries passed from the input array.
629 *
630 * @param array $arr Array of SQL queries to execute.
631 * @param array $keyArr Array with keys that must match keys in $arr. Only where a key in this array is set and TRUE will the query be executed (meant to be passed from a form checkbox)
632 * @return mixed Array with error message from database if any occurred. Otherwise TRUE if everything was executed successfully.
633 */
634 public function performUpdateQueries($arr, $keyArr)
635 {
636 $result = [];
637 if (is_array($arr)) {
638 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionByName('Default');
639 foreach ($arr as $key => $string) {
640 if (isset($keyArr[$key]) && $keyArr[$key]) {
641 try {
642 $connection->query($string);
643 } catch (DBALException $e) {
644 $result[$key] = $e->getMessage();
645 }
646 }
647 }
648 }
649 if (!empty($result)) {
650 return $result;
651 } else {
652 return true;
653 }
654 }
655
656 /**
657 * Returns list of tables in the database
658 *
659 * @return array List of tables.
660 * @see \TYPO3\CMS\Core\Database\DatabaseConnection::admin_get_tables()
661 */
662 public function getListOfTables()
663 {
664 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionByName('Default');
665 $statement = $connection->query('SHOW TABLE STATUS FROM `' . $connection->getDatabase() . '`');
666 $tables = [];
667 while ($theTable = $statement->fetch()) {
668 $tables[$theTable['Name']] = $theTable;
669 }
670 foreach ($tables as $key => &$value) {
671 $value = $key;
672 }
673 unset($value);
674 return $tables;
675 }
676 }