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