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