3879708688ec684255b8d777c28959de621b4be3
[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 = $GLOBALS['TYPO3_DB']->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 if (method_exists($GLOBALS['TYPO3_DB'], 'admin_get_charsets')) {
157 $this->character_sets = $GLOBALS['TYPO3_DB']->admin_get_charsets();
158 } else {
159 // Add empty element to avoid that the check will be repeated
160 $this->character_sets[$charset] = array();
161 }
162 }
163 $collation = '';
164 if (isset($this->character_sets[$charset]['Default collation'])) {
165 $collation = $this->character_sets[$charset]['Default collation'];
166 }
167 return $collation;
168 }
169
170 /**
171 * Reads the field definitions for the current database
172 *
173 * @return array Array with information about table.
174 */
175 public function getFieldDefinitions_database() {
176 $total = array();
177 $tempKeys = array();
178 $tempKeysPrefix = array();
179 $GLOBALS['TYPO3_DB']->connectDB();
180 echo $GLOBALS['TYPO3_DB']->sql_error();
181 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables();
182 foreach ($tables as $tableName => $tableStatus) {
183 // Fields
184 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
185 foreach ($fieldInformation as $fN => $fieldRow) {
186 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
187 }
188 // Keys
189 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
190 foreach ($keyInformation as $keyRow) {
191 $keyName = $keyRow['Key_name'];
192 $colName = $keyRow['Column_name'];
193 if ($keyRow['Sub_part'] && $keyRow['Index_type'] !== 'SPATIAL') {
194 $colName .= '(' . $keyRow['Sub_part'] . ')';
195 }
196 $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
197 if ($keyName == 'PRIMARY') {
198 $prefix = 'PRIMARY KEY';
199 } else {
200 if ($keyRow['Index_type'] === 'FULLTEXT') {
201 $prefix = 'FULLTEXT';
202 } elseif ($keyRow['Index_type'] === 'SPATIAL') {
203 $prefix = 'SPATIAL';
204 } elseif ($keyRow['Non_unique']) {
205 $prefix = 'KEY';
206 } else {
207 $prefix = 'UNIQUE';
208 }
209 $prefix .= ' ' . $keyName;
210 }
211 $tempKeysPrefix[$tableName][$keyName] = $prefix;
212 }
213 // Table status (storage engine, collaction, etc.)
214 if (is_array($tableStatus)) {
215 $tableExtraFields = array(
216 'Engine' => 'ENGINE',
217 'Collation' => 'COLLATE'
218 );
219 foreach ($tableExtraFields as $mysqlKey => $internalKey) {
220 if (isset($tableStatus[$mysqlKey])) {
221 $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
222 }
223 }
224 }
225 }
226 // Compile key information:
227 if (!empty($tempKeys)) {
228 foreach ($tempKeys as $table => $keyInf) {
229 foreach ($keyInf as $kName => $index) {
230 ksort($index);
231 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName] . ' (' . implode(',', $index) . ')';
232 }
233 }
234 }
235 return $total;
236 }
237
238 /**
239 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
240 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
241 *
242 * @param array $FDsrc Field definitions, source (from getFieldDefinitions_fileContent())
243 * @param array $FDcomp Field definitions, comparison. (from getFieldDefinitions_database())
244 * @param string $onlyTableList Table names (in list) which is the ONLY one observed.
245 * @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.
246 * @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
247 */
248 public function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList = '', $ignoreNotNullWhenComparing = FALSE) {
249 $extraArr = array();
250 $diffArr = array();
251 if (is_array($FDsrc)) {
252 foreach ($FDsrc as $table => $info) {
253 if ($onlyTableList === '' || \TYPO3\CMS\Core\Utility\GeneralUtility::inList($onlyTableList, $table)) {
254 if (!isset($FDcomp[$table])) {
255 // If the table was not in the FDcomp-array, the result array is loaded with that table.
256 $extraArr[$table] = $info;
257 $extraArr[$table]['whole_table'] = 1;
258 } else {
259 $keyTypes = explode(',', 'extra,fields,keys');
260 foreach ($keyTypes as $theKey) {
261 if (is_array($info[$theKey])) {
262 foreach ($info[$theKey] as $fieldN => $fieldC) {
263 $fieldN = str_replace('`', '', $fieldN);
264 if ($this->isDbalEnabled() && $fieldN === 'ENGINE') {
265 continue;
266 }
267 if ($fieldN == 'COLLATE') {
268 // @todo collation support is currently disabled (needs more testing)
269 continue;
270 }
271 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
272 $extraArr[$table][$theKey][$fieldN] = $fieldC;
273 } else {
274 $fieldC = trim($fieldC);
275
276 // Lowercase the field type to surround false-positive schema changes to be
277 // reported just because of different caseing of characters
278 // The regex does just trigger for the first word followed by parentheses
279 // that contain a length. It does not trigger for e.g. "PRIMARY KEY" because
280 // "PRIMARY KEY" is being returned from the DB in upper case.
281 $fieldC = preg_replace_callback(
282 '/^([a-zA-Z0-9]+)(\([^)]*\)\s.*)/',
283 function($matches) { return strtolower($matches[1]) . $matches[2]; },
284 $fieldC
285 );
286
287 // Ignore nonstandard MySQL numeric field attributes UNSIGNED and ZEROFILL
288 if ($this->isDbalEnabled() && preg_match('/^(TINYINT|SMALLINT|MEDIUMINT|INT|INTEGER|BIGINT|REAL|DOUBLE|FLOAT|DECIMAL|NUMERIC)\([^\)]+\)\s+(UNSIGNED|ZEROFILL)/i', $fieldC)) {
289 $fieldC = str_ireplace(array(' UNSIGNED', ' ZEROFILL'), '', $fieldC);
290 $FDcomp[$table][$theKey][$fieldN] = str_ireplace(array(' UNSIGNED', ' ZEROFILL'), '', $FDcomp[$table][$theKey][$fieldN]);
291 }
292 if ($ignoreNotNullWhenComparing) {
293 $fieldC = str_replace(' NOT NULL', '', $fieldC);
294 $FDcomp[$table][$theKey][$fieldN] = str_replace(' NOT NULL', '', $FDcomp[$table][$theKey][$fieldN]);
295 }
296 if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
297 $diffArr[$table][$theKey][$fieldN] = $fieldC;
298 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
299 }
300 }
301 }
302 }
303 }
304 }
305 }
306 }
307 }
308 $output = array(
309 'extra' => $extraArr,
310 'diff' => $diffArr,
311 'diff_currentValues' => $diffArr_cur
312 );
313 return $output;
314 }
315
316 /**
317 * Returns an array with SQL-statements that is needed to update according to the diff-array
318 *
319 * @param array $diffArr Array with differences of current and needed DB settings. (from getDatabaseExtra())
320 * @param string $keyList List of fields in diff array to take notice of.
321 * @return array Array of SQL statements (organized in keys depending on type)
322 */
323 public function getUpdateSuggestions($diffArr, $keyList = 'extra,diff') {
324 $statements = array();
325 $deletedPrefixKey = $this->deletedPrefixKey;
326 $deletedPrefixLength = strlen($deletedPrefixKey);
327 $remove = 0;
328 if ($keyList == 'remove') {
329 $remove = 1;
330 $keyList = 'extra';
331 }
332 $keyList = explode(',', $keyList);
333 foreach ($keyList as $theKey) {
334 if (is_array($diffArr[$theKey])) {
335 foreach ($diffArr[$theKey] as $table => $info) {
336 $whole_table = array();
337 if (isset($info['keys']) && is_array($info['keys'])) {
338 foreach ($info['keys'] as $fN => $fV) {
339 if (!$info['whole_table'] && $theKey === 'extra' && $remove) {
340 $statement = 'ALTER TABLE ' . $table . ($fN === 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
341 $statements['drop'][md5($statement)] = $statement;
342 }
343 }
344 }
345 if (is_array($info['fields'])) {
346 foreach ($info['fields'] as $fN => $fV) {
347 if ($info['whole_table']) {
348 $whole_table[] = $fN . ' ' . $fV;
349 } else {
350 // Special case to work around MySQL problems when adding auto_increment fields:
351 if (stristr($fV, 'auto_increment')) {
352 // The field can only be set "auto_increment" if there exists a PRIMARY key of that field already.
353 // The check does not look up which field is primary but just assumes it must be the field with the auto_increment value...
354 if (isset($diffArr['extra'][$table]['keys']['PRIMARY'])) {
355 // Remove "auto_increment" from the statement - it will be suggested in a 2nd step after the primary key was created
356 $fV = str_replace(' auto_increment', '', $fV);
357 } else {
358 // In the next step, attempt to clear the table once again (2 = force)
359 $info['extra']['CLEAR'] = 2;
360 }
361 }
362 if ($theKey == 'extra') {
363 if ($remove) {
364 if (substr($fN, 0, $deletedPrefixLength) !== $deletedPrefixKey) {
365 // we've to make sure we don't exceed the maximal length
366 $prefixedFieldName = $deletedPrefixKey . substr($fN, ($deletedPrefixLength - self::MYSQL_MAXIMUM_FIELD_WIDTH));
367 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $prefixedFieldName . ' ' . $fV . ';';
368 $statements['change'][md5($statement)] = $statement;
369 } else {
370 $statement = 'ALTER TABLE ' . $table . ' DROP ' . $fN . ';';
371 $statements['drop'][md5($statement)] = $statement;
372 }
373 } else {
374 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fN . ' ' . $fV . ';';
375 $statements['add'][md5($statement)] = $statement;
376 }
377 } elseif ($theKey == 'diff') {
378 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $fN . ' ' . $fV . ';';
379 $statements['change'][md5($statement)] = $statement;
380 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
381 }
382 }
383 }
384 }
385 if (is_array($info['keys'])) {
386 foreach ($info['keys'] as $fN => $fV) {
387 if ($info['whole_table']) {
388 $whole_table[] = $fV;
389 } else {
390 if ($theKey == 'extra') {
391 if (!$remove) {
392 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
393 $statements['add'][md5($statement)] = $statement;
394 }
395 } elseif ($theKey == 'diff') {
396 $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
397 $statements['change'][md5($statement)] = $statement;
398 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
399 $statements['change'][md5($statement)] = $statement;
400 }
401 }
402 }
403 }
404 if (is_array($info['extra'])) {
405 $extras = array();
406 $extras_currentValue = array();
407 $clear_table = FALSE;
408 foreach ($info['extra'] as $fN => $fV) {
409 // Only consider statements which are missing in the database but don't remove existing properties
410 if (!$remove) {
411 if (!$info['whole_table']) {
412 // If the whole table is created at once, we take care of this later by imploding all elements of $info['extra']
413 if ($fN == 'CLEAR') {
414 // Truncate table must happen later, not now
415 // Valid values for CLEAR: 1=only clear if keys are missing, 2=clear anyway (force)
416 if (!empty($info['keys']) || $fV == 2) {
417 $clear_table = TRUE;
418 }
419 continue;
420 } else {
421 $extras[] = $fN . '=' . $fV;
422 $extras_currentValue[] = $fN . '=' . $diffArr['diff_currentValues'][$table]['extra'][$fN];
423 }
424 }
425 }
426 }
427 if ($clear_table) {
428 $statement = 'TRUNCATE TABLE ' . $table . ';';
429 $statements['clear_table'][md5($statement)] = $statement;
430 }
431 if (!empty($extras)) {
432 $statement = 'ALTER TABLE ' . $table . ' ' . implode(' ', $extras) . ';';
433 $statements['change'][md5($statement)] = $statement;
434 $statements['change_currentValue'][md5($statement)] = implode(' ', $extras_currentValue);
435 }
436 }
437 if ($info['whole_table']) {
438 if ($remove) {
439 if (substr($table, 0, $deletedPrefixLength) !== $deletedPrefixKey) {
440 // we've to make sure we don't exceed the maximal length
441 $prefixedTableName = $deletedPrefixKey . substr($table, ($deletedPrefixLength - self::MYSQL_MAXIMUM_FIELD_WIDTH));
442 $statement = 'ALTER TABLE ' . $table . ' RENAME ' . $prefixedTableName . ';';
443 $statements['change_table'][md5($statement)] = $statement;
444 } else {
445 $statement = 'DROP TABLE ' . $table . ';';
446 $statements['drop_table'][md5($statement)] = $statement;
447 }
448 // Count
449 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', $table);
450 $statements['tables_count'][md5($statement)] = $count ? 'Records in table: ' . $count : '';
451 } else {
452 $statement = 'CREATE TABLE ' . $table . ' (
453 ' . implode(',
454 ', $whole_table) . '
455 )';
456 if ($info['extra']) {
457 foreach ($info['extra'] as $k => $v) {
458 if ($k == 'COLLATE' || $k == 'CLEAR') {
459 // Skip these special statements.
460 // @todo collation support is currently disabled (needs more testing)
461 continue;
462 }
463 // Add extra attributes like ENGINE, CHARSET, etc.
464 $statement .= ' ' . $k . '=' . $v;
465 }
466 }
467 $statement .= ';';
468 $statements['create_table'][md5($statement)] = $statement;
469 }
470 }
471 }
472 }
473 }
474 return $statements;
475 }
476
477 /**
478 * Converts a result row with field information into the SQL field definition string
479 *
480 * @param array $row MySQL result row
481 * @return string Field definition
482 */
483 public function assembleFieldDefinition($row) {
484 $field = array($row['Type']);
485 if ($row['Null'] == 'NO') {
486 $field[] = 'NOT NULL';
487 }
488 if (!strstr($row['Type'], 'blob') && !strstr($row['Type'], 'text')) {
489 // Add a default value if the field is not auto-incremented (these fields never have a default definition)
490 if (!stristr($row['Extra'], 'auto_increment')) {
491 if ($row['Default'] === NULL) {
492 $field[] = 'default NULL';
493 } else {
494 $field[] = 'default \'' . addslashes($row['Default']) . '\'';
495 }
496 }
497 }
498 if ($row['Extra']) {
499 $field[] = $row['Extra'];
500 }
501 if (trim($row['Comment']) !== '') {
502 $field[] = "COMMENT '" . $row['Comment'] . "'";
503 }
504 return implode(' ', $field);
505 }
506
507 /**
508 * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
509 *
510 * @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.
511 * @param bool $removeNonSQL If set, non-SQL content (like comments and blank lines) is not included in the final output
512 * @param string $query_regex Regex to filter SQL lines to include
513 * @return array Array of SQL statements
514 */
515 public function getStatementArray($sqlcode, $removeNonSQL = FALSE, $query_regex = '') {
516 $sqlcodeArr = explode(LF, $sqlcode);
517 // Based on the assumption that the sql-dump has
518 $statementArray = array();
519 $statementArrayPointer = 0;
520 foreach ($sqlcodeArr as $line => $lineContent) {
521 $lineContent = trim($lineContent);
522 $is_set = 0;
523 // Auto_increment fields cannot have a default value!
524 if (stristr($lineContent, 'auto_increment')) {
525 $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
526 }
527 if (!$removeNonSQL || $lineContent !== '' && $lineContent[0] !== '#' && substr($lineContent, 0, 2) !== '--') {
528 // '--' is seen as mysqldump comments from server version 3.23.49
529 $statementArray[$statementArrayPointer] .= $lineContent;
530 $is_set = 1;
531 }
532 if (substr($lineContent, -1) === ';') {
533 if (isset($statementArray[$statementArrayPointer])) {
534 if (!trim($statementArray[$statementArrayPointer]) || $query_regex && !preg_match(('/' . $query_regex . '/i'), trim($statementArray[$statementArrayPointer]))) {
535 unset($statementArray[$statementArrayPointer]);
536 }
537 }
538 $statementArrayPointer++;
539 } elseif ($is_set) {
540 $statementArray[$statementArrayPointer] .= LF;
541 }
542 }
543 return $statementArray;
544 }
545
546 /**
547 * Returns tables to create and how many records in each
548 *
549 * @param array $statements Array of SQL statements to analyse.
550 * @param bool $insertCountFlag If set, will count number of INSERT INTO statements following that table definition
551 * @return array Array with table definitions in index 0 and count in index 1
552 */
553 public function getCreateTables($statements, $insertCountFlag = FALSE) {
554 $crTables = array();
555 $insertCount = array();
556 foreach ($statements as $line => $lineContent) {
557 $reg = array();
558 if (preg_match('/^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
559 $table = trim($reg[1]);
560 if ($table) {
561 // Table names are always lowercase on Windows!
562 if (TYPO3_OS == 'WIN') {
563 $table = strtolower($table);
564 }
565 $sqlLines = explode(LF, $lineContent);
566 foreach ($sqlLines as $k => $v) {
567 if (stristr($v, 'auto_increment')) {
568 $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
569 }
570 }
571 $lineContent = implode(LF, $sqlLines);
572 $crTables[$table] = $lineContent;
573 }
574 } elseif ($insertCountFlag && preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
575 $nTable = trim($reg[1]);
576 $insertCount[$nTable]++;
577 }
578 }
579 return array($crTables, $insertCount);
580 }
581
582 /**
583 * Extracts all insert statements from $statement array where content is inserted into $table
584 *
585 * @param array $statements Array of SQL statements
586 * @param string $table Table name
587 * @return array Array of INSERT INTO statements where table match $table
588 */
589 public function getTableInsertStatements($statements, $table) {
590 $outStatements = array();
591 foreach ($statements as $line => $lineContent) {
592 $reg = array();
593 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
594 $nTable = trim($reg[1]);
595 if ($nTable && $table === $nTable) {
596 $outStatements[] = $lineContent;
597 }
598 }
599 }
600 return $outStatements;
601 }
602
603 /**
604 * Performs the queries passed from the input array.
605 *
606 * @param array $arr Array of SQL queries to execute.
607 * @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)
608 * @return mixed Array with error message from database if any occurred. Otherwise TRUE if everything was executed successfully.
609 */
610 public function performUpdateQueries($arr, $keyArr) {
611 $result = array();
612 if (is_array($arr)) {
613 foreach ($arr as $key => $string) {
614 if (isset($keyArr[$key]) && $keyArr[$key]) {
615 $res = $GLOBALS['TYPO3_DB']->admin_query($string);
616 if ($res === FALSE) {
617 $result[$key] = $GLOBALS['TYPO3_DB']->sql_error();
618 } elseif (is_resource($res) || is_a($res, '\\mysqli_result')) {
619 $GLOBALS['TYPO3_DB']->sql_free_result($res);
620 }
621 }
622 }
623 }
624 if (!empty($result)) {
625 return $result;
626 } else {
627 return TRUE;
628 }
629 }
630
631 /**
632 * Returns list of tables in the database
633 *
634 * @return array List of tables.
635 * @see \TYPO3\CMS\Core\Database\DatabaseConnection::admin_get_tables()
636 */
637 public function getListOfTables() {
638 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
639 foreach ($whichTables as $key => &$value) {
640 $value = $key;
641 }
642 unset($value);
643 return $whichTables;
644 }
645
646 /**
647 * Checks if DBAL is enabled for the database connection
648 *
649 * @return bool
650 */
651 protected function isDbalEnabled() {
652 return \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('dbal');
653 }
654
655 }