6e8f8d27621ed2b62e9033d4be41e216ef440419
[Packages/TYPO3.CMS.git] / typo3 / sysext / dbal / Classes / Database / DatabaseConnection.php
1 <?php
2 namespace TYPO3\CMS\Dbal\Database;
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 TYPO3\CMS\Core\Utility\GeneralUtility;
18
19 /**
20 * TYPO3 database abstraction layer
21 *
22 * @author Kasper Skårhøj <kasper@typo3.com>
23 * @author Karsten Dambekalns <k.dambekalns@fishfarm.de>
24 * @author Xavier Perseguers <xavier@typo3.org>
25 */
26 class DatabaseConnection extends \TYPO3\CMS\Core\Database\DatabaseConnection {
27
28 /**
29 * @var bool
30 */
31 protected $printErrors = FALSE;
32
33 /**
34 * Enable output of SQL errors after query executions.
35 * @var bool
36 */
37 public $debug = FALSE;
38
39 /**
40 * Enable debug mode
41 * @var bool
42 */
43 public $conf = array();
44
45 /**
46 * Configuration array, copied from TYPO3_CONF_VARS in constructor.
47 * @var array
48 */
49 public $mapping = array();
50
51 /**
52 * See manual
53 * @var array
54 */
55 protected $table2handlerKeys = array();
56
57 /**
58 * See manual
59 * @var array
60 */
61 public $handlerCfg = array(
62 '_DEFAULT' => array(
63 'type' => 'native',
64 'config' => array(
65 'username' => '',
66 // Set by default (overridden)
67 'password' => '',
68 // Set by default (overridden)
69 'host' => '',
70 // Set by default (overridden)
71 'database' => '',
72 // Set by default (overridden)
73 'driver' => '',
74 // ONLY "adodb" type; eg. "mysql"
75 'sequenceStart' => 1,
76 // ONLY "adodb", first number in sequences/serials/...
77 'useNameQuote' => 0,
78 // ONLY "adodb", whether to use NameQuote() method from ADOdb to quote names
79 'quoteClob' => FALSE
80 )
81 )
82 );
83
84 /**
85 * Contains instance of the handler objects as they are created.
86 *
87 * Exception is the native mySQL calls, which are registered as an array with keys
88 * "handlerType" = "native" and
89 * "link" pointing to the link object of the connection.
90 *
91 * @var array
92 */
93 public $handlerInstance = array();
94
95 /**
96 * Storage of the handler key of last ( SELECT) query - used for subsequent fetch-row calls etc.
97 * @var string
98 */
99 public $lastHandlerKey = '';
100
101 /**
102 * Storage of last SELECT query
103 * @var string
104 */
105 protected $lastQuery = '';
106
107 /**
108 * The last parsed query array
109 * @var array
110 */
111 protected $lastParsedAndMappedQueryArray = array();
112
113 /**
114 * @var array
115 */
116 protected $resourceIdToTableNameMap = array();
117
118 /**
119 * @var array
120 */
121 protected $cache_handlerKeyFromTableList = array();
122
123 /**
124 * @var array
125 */
126 protected $cache_mappingFromTableList = array();
127
128 /**
129 * parsed SQL from standard DB dump file
130 * @var array
131 */
132 public $cache_autoIncFields = array();
133
134 /**
135 * @var array
136 */
137 public $cache_fieldType = array();
138
139 /**
140 * @var array
141 */
142 public $cache_primaryKeys = array();
143
144 /**
145 * @var string
146 */
147 protected $cacheIdentifier = 'DatabaseConnection_fieldInfo';
148
149 /**
150 * SQL parser
151 *
152 * @var \TYPO3\CMS\Core\Database\SqlParser
153 */
154 public $SQLparser;
155
156 /**
157 * @var \TYPO3\CMS\Install\Service\SqlSchemaMigrationService
158 */
159 protected $installerSql = NULL;
160
161 /**
162 * Cache for queries
163 *
164 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
165 */
166 protected $queryCache;
167
168 /**
169 * mysql_field_type compatibility map
170 * taken from: http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php#89117
171 * Constant numbers see http://php.net/manual/en/mysqli.constants.php
172 *
173 * @var array
174 */
175 protected $mysqlDataTypeMapping = array(
176 MYSQLI_TYPE_TINY => 'tinyint',
177 MYSQLI_TYPE_CHAR => 'tinyint',
178 MYSQLI_TYPE_SHORT => 'smallint',
179 MYSQLI_TYPE_LONG => 'int',
180 MYSQLI_TYPE_FLOAT => 'float',
181 MYSQLI_TYPE_DOUBLE => 'double',
182 MYSQLI_TYPE_TIMESTAMP => 'timestamp',
183 MYSQLI_TYPE_LONGLONG => 'bigint',
184 MYSQLI_TYPE_INT24 => 'mediumint',
185 MYSQLI_TYPE_DATE => 'date',
186 MYSQLI_TYPE_NEWDATE => 'date',
187 MYSQLI_TYPE_TIME => 'time',
188 MYSQLI_TYPE_DATETIME => 'datetime',
189 MYSQLI_TYPE_YEAR => 'year',
190 MYSQLI_TYPE_BIT => 'bit',
191 MYSQLI_TYPE_INTERVAL => 'interval',
192 MYSQLI_TYPE_ENUM => 'enum',
193 MYSQLI_TYPE_SET => 'set',
194 MYSQLI_TYPE_TINY_BLOB => 'blob',
195 MYSQLI_TYPE_MEDIUM_BLOB => 'blob',
196 MYSQLI_TYPE_LONG_BLOB => 'blob',
197 MYSQLI_TYPE_BLOB => 'blob',
198 MYSQLI_TYPE_VAR_STRING => 'varchar',
199 MYSQLI_TYPE_STRING => 'char',
200 MYSQLI_TYPE_DECIMAL => 'decimal',
201 MYSQLI_TYPE_NEWDECIMAL => 'decimal',
202 MYSQLI_TYPE_GEOMETRY => 'geometry'
203 );
204
205 /**
206 * @var Specifics\AbstractSpecifics
207 */
208 protected $dbmsSpecifics;
209
210 /**
211 * Constructor.
212 * Creates SQL parser object and imports configuration from $TYPO3_CONF_VARS['EXTCONF']['dbal']
213 */
214 public function __construct() {
215 // Set SQL parser object for internal use:
216 $this->SQLparser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\SqlParser::class, $this);
217 $this->installerSql = GeneralUtility::makeInstance(\TYPO3\CMS\Install\Service\SqlSchemaMigrationService::class);
218 $this->queryCache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('dbal');
219 // Set internal variables with configuration:
220 $this->conf = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal'];
221 }
222
223 /**
224 * Initialize the database connection
225 *
226 * @return void
227 */
228 public function initialize() {
229 // Set outside configuration:
230 if (isset($this->conf['mapping'])) {
231 $this->mapping = $this->conf['mapping'];
232 }
233 if (isset($this->conf['table2handlerKeys'])) {
234 $this->table2handlerKeys = $this->conf['table2handlerKeys'];
235 }
236 if (isset($this->conf['handlerCfg'])) {
237 $this->handlerCfg = $this->conf['handlerCfg'];
238
239 if (isset($this->handlerCfg['_DEFAULT']['config']['driver'])) {
240 // load DBMS specifics
241 $driver = $this->handlerCfg['_DEFAULT']['config']['driver'];
242 $className = 'TYPO3\\CMS\\Dbal\\Database\\Specifics\\' . ucfirst(strtolower($driver));
243 if (class_exists($className)) {
244 if (!is_subclass_of($className, Specifics\AbstractSpecifics::class)) {
245 throw new \InvalidArgumentException($className . ' must inherit from ' . Specifics\AbstractSpecifics::class, 1416919866);
246 }
247 $this->dbmsSpecifics = GeneralUtility::makeInstance($className);
248 }
249 }
250 }
251 $this->cacheFieldInfo();
252 // Debugging settings:
253 $this->printErrors = !empty($this->conf['debugOptions']['printErrors']);
254 $this->debug = !empty($this->conf['debugOptions']['enabled']);
255 }
256
257 /**
258 * Gets the DBMS specifics object
259 *
260 * @return Specifics\AbstractSpecifics
261 */
262 public function getSpecifics() {
263 return $this->dbmsSpecifics;
264 }
265
266 /**
267 * @return \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend
268 */
269 protected function getFieldInfoCache() {
270 return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_phpcode');
271 }
272
273 /**
274 * Clears the cached field information file.
275 *
276 * @return void
277 */
278 public function clearCachedFieldInfo() {
279 $this->getFieldInfoCache()->flushByTag('DatabaseConnection');
280 }
281
282 /**
283 * Caches the field information.
284 *
285 * @return void
286 */
287 public function cacheFieldInfo() {
288 $phpCodeCache = $this->getFieldInfoCache();
289 // try to fetch cache
290 // cache is flushed when admin_query() is called
291 if ($phpCodeCache->has($this->cacheIdentifier)) {
292 $fieldInformation = $phpCodeCache->requireOnce($this->cacheIdentifier);
293 $this->cache_autoIncFields = $fieldInformation['incFields'];
294 $this->cache_fieldType = $fieldInformation['fieldTypes'];
295 $this->cache_primaryKeys = $fieldInformation['primaryKeys'];
296 } else {
297 $this->analyzeCachingTables();
298 $this->analyzeExtensionTables();
299 $completeFieldInformation = $this->getCompleteFieldInformation();
300 $phpCodeCache->set($this->cacheIdentifier, $this->getCacheableString($completeFieldInformation), array('DatabaseConnection'));
301 }
302 }
303
304 /**
305 * Loop through caching configurations
306 * to find the usage of database backends and
307 * parse and analyze table definitions
308 *
309 * @return void
310 */
311 protected function analyzeCachingTables() {
312 $this->parseAndAnalyzeSql(\TYPO3\CMS\Core\Cache\Cache::getDatabaseTableDefinitions());
313 }
314
315 /**
316 * Loop over all installed extensions
317 * parse and analyze table definitions (if any)
318 *
319 * @return void
320 */
321 protected function analyzeExtensionTables() {
322 if (isset($GLOBALS['TYPO3_LOADED_EXT']) && (is_array($GLOBALS['TYPO3_LOADED_EXT']) || $GLOBALS['TYPO3_LOADED_EXT'] instanceof \ArrayAccess)) {
323 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extensionConfiguration) {
324 $isArray = (is_array($extensionConfiguration) || $extensionConfiguration instanceof \ArrayAccess);
325 if (!$isArray || ($isArray && !isset($extensionConfiguration['ext_tables.sql']))) {
326 continue;
327 }
328 $extensionsSql = file_get_contents($extensionConfiguration['ext_tables.sql']);
329 $this->parseAndAnalyzeSql($extensionsSql);
330 }
331 }
332 }
333
334 /**
335 * Parse and analyze given SQL string
336 *
337 * @param $sql
338 * @return void
339 */
340 protected function parseAndAnalyzeSql($sql) {
341 $parsedSql = $this->installerSql->getFieldDefinitions_fileContent($sql);
342 $this->analyzeFields($parsedSql);
343 }
344
345 /**
346 * Returns all field information gathered during
347 * analyzing all tables and fields.
348 *
349 * @return array
350 */
351 protected function getCompleteFieldInformation() {
352 return array('incFields' => $this->cache_autoIncFields, 'fieldTypes' => $this->cache_fieldType, 'primaryKeys' => $this->cache_primaryKeys);
353 }
354
355 /**
356 * Creates a PHP code representation of the array that can be cached
357 * in the PHP code cache.
358 *
359 * @param array $fieldInformation
360 * @return string
361 */
362 protected function getCacheableString(array $fieldInformation) {
363 $cacheString = 'return ';
364 $cacheString .= var_export($fieldInformation, TRUE);
365 $cacheString .= ';';
366 return $cacheString;
367 }
368
369 /**
370 * Analyzes fields and adds the extracted information to the field type, auto increment and primary key info caches.
371 *
372 * @param array $parsedExtSQL The output produced by \TYPO3\CMS\Install\Service\SqlSchemaMigrationService->getFieldDefinitions_fileContent()
373 * @return void
374 */
375 protected function analyzeFields($parsedExtSQL) {
376 foreach ($parsedExtSQL as $table => $tdef) {
377 // check if table is mapped
378 if (isset($this->mapping[$table])) {
379 $table = $this->mapping[$table]['mapTableName'];
380 }
381 if (is_array($tdef['fields'])) {
382 foreach ($tdef['fields'] as $field => $fdefString) {
383 $fdef = $this->SQLparser->parseFieldDef($fdefString);
384 $fieldType = isset($fdef['fieldType']) ? $fdef['fieldType'] : '';
385 $this->cache_fieldType[$table][$field]['type'] = $fieldType;
386 $this->cache_fieldType[$table][$field]['metaType'] = $this->MySQLMetaType($fieldType);
387 $this->cache_fieldType[$table][$field]['notnull'] = isset($fdef['featureIndex']['NOTNULL']) && !$this->SQLparser->checkEmptyDefaultValue($fdef['featureIndex']) ? 1 : 0;
388 if (isset($fdef['featureIndex']['DEFAULT'])) {
389 $default = $fdef['featureIndex']['DEFAULT']['value'][0];
390 if (isset($fdef['featureIndex']['DEFAULT']['value'][1])) {
391 $default = $fdef['featureIndex']['DEFAULT']['value'][1] . $default . $fdef['featureIndex']['DEFAULT']['value'][1];
392 }
393 $this->cache_fieldType[$table][$field]['default'] = $default;
394 }
395 if (isset($fdef['featureIndex']['AUTO_INCREMENT'])) {
396 $this->cache_autoIncFields[$table] = $field;
397 }
398 if (isset($tdef['keys']['PRIMARY'])) {
399 $this->cache_primaryKeys[$table] = substr($tdef['keys']['PRIMARY'], 13, -1);
400 }
401 }
402 }
403 }
404 }
405
406 /**
407 * This function builds all definitions for mapped tables and fields
408 *
409 * @param array $fieldInfo
410 * @return array
411 *
412 * @see cacheFieldInfo()
413 */
414 protected function mapCachedFieldInfo(array $fieldInfo) {
415 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['mapping'])) {
416 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['mapping'] as $mappedTable => $mappedConf) {
417 if (array_key_exists($mappedTable, $fieldInfo['incFields'])) {
418 $mappedTableAlias = $mappedConf['mapTableName'];
419 if (isset($mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]])) {
420 $fieldInfo['incFields'][$mappedTableAlias] = $mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]];
421 } else {
422 $fieldInfo['incFields'][$mappedTableAlias] = $fieldInfo['incFields'][$mappedTable];
423 }
424 }
425 if (array_key_exists($mappedTable, $fieldInfo['fieldTypes'])) {
426 $tempMappedFieldConf = array();
427 foreach ($fieldInfo['fieldTypes'][$mappedTable] as $field => $fieldConf) {
428 $tempMappedFieldConf[$mappedConf['mapFieldNames'][$field]] = $fieldConf;
429 }
430 $fieldInfo['fieldTypes'][$mappedConf['mapTableName']] = $tempMappedFieldConf;
431 }
432 if (array_key_exists($mappedTable, $fieldInfo['primaryKeys'])) {
433 $mappedTableAlias = $mappedConf['mapTableName'];
434 if (isset($mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]])) {
435 $fieldInfo['primaryKeys'][$mappedTableAlias] = $mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]];
436 } else {
437 $fieldInfo['primaryKeys'][$mappedTableAlias] = $fieldInfo['primaryKeys'][$mappedTable];
438 }
439 }
440 }
441 }
442 return $fieldInfo;
443 }
444
445 /************************************
446 *
447 * Query Building (Overriding parent methods)
448 * These functions are extending counterparts in the parent class.
449 *
450 **************************************/
451 /*
452 * From the ADOdb documentation, this is what we do (_Execute for SELECT, _query for the other actions)Execute()
453 * is the default way to run queries. You can use the low-level functions _Execute() and _query() to reduce query overhead.
454 * Both these functions share the same parameters as Execute().If you do not have any bind parameters or your database
455 * supports binding (without emulation), then you can call _Execute() directly.
456 * Calling this function bypasses bind emulation. Debugging is still supported in _Execute().If you do not require
457 * debugging facilities nor emulated binding, and do not require a recordset to be returned, then you can call _query.
458 * This is great for inserts, updates and deletes. Calling this function bypasses emulated binding, debugging,
459 * and recordset handling. Either the resultid, TRUE or FALSE are returned by _query().
460 */
461
462 /**
463 * Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
464 * Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
465 *
466 * @param string $table Table name
467 * @param array $fields_values Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$insertFields" with 'fieldname'=>'value' and pass it to this function as argument.
468 * @param bool|array|string $no_quote_fields See fullQuoteArray()
469 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
470 * @throws \RuntimeException
471 */
472 public function exec_INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
473 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
474 // Do field mapping if needed:
475 $ORIG_tableName = $table;
476 if ($tableArray = $this->map_needMapping($table)) {
477 // Field mapping of array:
478 $fields_values = $this->map_assocArray($fields_values, $tableArray);
479 // Table name:
480 if ($this->mapping[$table]['mapTableName']) {
481 $table = $this->mapping[$table]['mapTableName'];
482 }
483 }
484 // Select API:
485 $this->lastHandlerKey = $this->handler_getFromTableList($table);
486 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
487 $sqlResult = NULL;
488 switch ($hType) {
489 case 'native':
490 $this->lastQuery = $this->INSERTquery($table, $fields_values, $no_quote_fields);
491 if (is_string($this->lastQuery)) {
492 $sqlResult = $this->query($this->lastQuery);
493 } else {
494 $sqlResult = $this->query($this->lastQuery[0]);
495 $new_id = $this->sql_insert_id();
496 $where = $this->cache_autoIncFields[$table] . '=' . $new_id;
497 foreach ($this->lastQuery[1] as $field => $content) {
498 $stmt = 'UPDATE ' . $this->quoteFromTables($table) . ' SET ' . $this->quoteFromTables($field) . '=' . $this->fullQuoteStr($content, $table, TRUE) . ' WHERE ' . $this->quoteWhereClause($where);
499 $this->query($stmt);
500 }
501 }
502 break;
503 case 'adodb':
504 // auto generate ID for auto_increment fields if not present (static import needs this!)
505 // should we check the table name here (static_*)?
506 if (isset($this->cache_autoIncFields[$table])) {
507 if (isset($fields_values[$this->cache_autoIncFields[$table]])) {
508 $new_id = $fields_values[$this->cache_autoIncFields[$table]];
509 if ($table != 'tx_dbal_debuglog') {
510 $this->handlerInstance[$this->lastHandlerKey]->last_insert_id = $new_id;
511 }
512 } elseif (!$this->handlerInstance[$this->lastHandlerKey]->hasInsertID) {
513 // The table does not support auto-incremented fields, fall back to
514 // using a sequence table to simulate the auto-increment
515 $new_id = $this->handlerInstance[$this->lastHandlerKey]->GenID($table . '_' . $this->cache_autoIncFields[$table], $this->handlerInstance[$this->lastHandlerKey]->sequenceStart);
516 $fields_values[$this->cache_autoIncFields[$table]] = $new_id;
517 if ($table != 'tx_dbal_debuglog') {
518 $this->handlerInstance[$this->lastHandlerKey]->last_insert_id = $new_id;
519 }
520 }
521 }
522 $this->lastQuery = $this->INSERTquery($table, $fields_values, $no_quote_fields);
523 if (is_string($this->lastQuery)) {
524 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
525 } else {
526 $this->handlerInstance[$this->lastHandlerKey]->StartTrans();
527 if ((string)$this->lastQuery[0] !== '') {
528 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery[0], FALSE);
529 if ($this->handlerInstance[$this->lastHandlerKey]->hasInsertID) {
530 // The table is able to retrieve the ID of the last insert, use it to update the blob below
531 $new_id = $this->handlerInstance[$this->lastHandlerKey]->Insert_ID($table, $this->cache_autoIncFields[$table]);
532 if ($table !== 'tx_dbal_debuglog') {
533 $this->handlerInstance[$this->lastHandlerKey]->last_insert_id = $new_id;
534 }
535 }
536 }
537 if (is_array($this->lastQuery[1])) {
538 foreach ($this->lastQuery[1] as $field => $content) {
539 if (empty($content)) {
540 continue;
541 }
542 if (isset($this->cache_autoIncFields[$table]) && isset($new_id)) {
543 $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($this->cache_autoIncFields[$table] . '=' . $new_id));
544 } elseif (isset($this->cache_primaryKeys[$table])) {
545 $where = '';
546 $pks = explode(',', $this->cache_primaryKeys[$table]);
547 foreach ($pks as $pk) {
548 if (isset($fields_values[$pk])) {
549 $where .= $pk . '=' . $this->fullQuoteStr($fields_values[$pk], $table) . ' AND ';
550 }
551 }
552 $where = $this->quoteWhereClause($where . '1=1');
553 $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table), $field, $content, $where);
554 } else {
555 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans(FALSE);
556 // Should never ever happen
557 throw new \RuntimeException('Could not update BLOB >>>> no WHERE clause found!', 1321860519);
558 }
559 }
560 }
561 if (is_array($this->lastQuery[2])) {
562 foreach ($this->lastQuery[2] as $field => $content) {
563 if (empty($content)) {
564 continue;
565 }
566 if (isset($this->cache_autoIncFields[$table]) && isset($new_id)) {
567 $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($this->cache_autoIncFields[$table] . '=' . $new_id));
568 } elseif (isset($this->cache_primaryKeys[$table])) {
569 $where = '';
570 $pks = explode(',', $this->cache_primaryKeys[$table]);
571 foreach ($pks as $pk) {
572 if (isset($fields_values[$pk])) {
573 $where .= $pk . '=' . $this->fullQuoteStr($fields_values[$pk], $table) . ' AND ';
574 }
575 }
576 $where = $this->quoteWhereClause($where . '1=1');
577 $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table), $field, $content, $where);
578 } else {
579 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans(FALSE);
580 // Should never ever happen
581 throw new \RuntimeException('Could not update CLOB >>>> no WHERE clause found!', 1310027337);
582 }
583 }
584 }
585 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans();
586 }
587 break;
588 case 'userdefined':
589 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_INSERTquery($table, $fields_values, $no_quote_fields);
590 break;
591 }
592 if ($this->printErrors && $this->sql_error()) {
593 debug(array($this->lastQuery, $this->sql_error()));
594 }
595 if ($this->debug) {
596 $this->debugHandler('exec_INSERTquery', GeneralUtility::milliseconds() - $pt, array(
597 'handlerType' => $hType,
598 'args' => array($table, $fields_values),
599 'ORIG_tablename' => $ORIG_tableName
600 ));
601 }
602 foreach ($this->postProcessHookObjects as $hookObject) {
603 $hookObject->exec_INSERTquery_postProcessAction($table, $fields_values, $no_quote_fields, $this);
604 }
605 // Return output:
606 return $sqlResult;
607 }
608
609 /**
610 * Creates and executes an INSERT SQL-statement for $table with multiple rows.
611 *
612 * @param string $table Table name
613 * @param array $fields Field names
614 * @param array $rows Table rows. Each row should be an array with field values mapping to $fields
615 * @param bool|array|string $no_quote_fields See fullQuoteArray()
616 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
617 */
618 public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
619 $res = NULL;
620 if ((string)$this->handlerCfg[$this->lastHandlerKey]['type'] === 'native') {
621 $this->lastHandlerKey = $this->handler_getFromTableList($table);
622 $res = $this->query(parent::INSERTmultipleRows($table, $fields, $rows, $no_quote_fields));
623 } else {
624 foreach ($rows as $row) {
625 $fields_values = array();
626 foreach ($fields as $key => $value) {
627 $fields_values[$value] = $row[$key];
628 }
629 $res = $this->exec_INSERTquery($table, $fields_values, $no_quote_fields);
630 }
631 }
632 foreach ($this->postProcessHookObjects as $hookObject) {
633 $hookObject->exec_INSERTmultipleRows_postProcessAction($table, $fields, $rows, $no_quote_fields, $this);
634 }
635 return $res;
636 }
637
638 /**
639 * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
640 * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
641 *
642 * @param string $table Database tablename
643 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
644 * @param array $fields_values Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$updateFields" with 'fieldname'=>'value' and pass it to this function as argument.
645 * @param bool|array|string $no_quote_fields See fullQuoteArray()
646 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
647 */
648 public function exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
649 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
650 // Do table/field mapping:
651 $ORIG_tableName = $table;
652 if ($tableArray = $this->map_needMapping($table)) {
653 // Field mapping of array:
654 $fields_values = $this->map_assocArray($fields_values, $tableArray);
655 // Where clause table and field mapping:
656 $whereParts = $this->SQLparser->parseWhereClause($where);
657 $this->map_sqlParts($whereParts, $tableArray[0]['table']);
658 $where = $this->SQLparser->compileWhereClause($whereParts, FALSE);
659 // Table name:
660 if ($this->mapping[$table]['mapTableName']) {
661 $table = $this->mapping[$table]['mapTableName'];
662 }
663 }
664 // Select API
665 $this->lastHandlerKey = $this->handler_getFromTableList($table);
666 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
667 $sqlResult = NULL;
668 switch ($hType) {
669 case 'native':
670 $this->lastQuery = $this->UPDATEquery($table, $where, $fields_values, $no_quote_fields);
671 if (is_string($this->lastQuery)) {
672 $sqlResult = $this->query($this->lastQuery);
673 } else {
674 $sqlResult = $this->query($this->lastQuery[0]);
675 foreach ($this->lastQuery[1] as $field => $content) {
676 $stmt = 'UPDATE ' . $this->quoteFromTables($table) . ' SET ' . $this->quoteFromTables($field) . '=' . $this->fullQuoteStr($content, $table, TRUE) . ' WHERE ' . $this->quoteWhereClause($where);
677 $this->query($stmt);
678 }
679 }
680 break;
681 case 'adodb':
682 $this->lastQuery = $this->UPDATEquery($table, $where, $fields_values, $no_quote_fields);
683 if (is_string($this->lastQuery)) {
684 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
685 } else {
686 $this->handlerInstance[$this->lastHandlerKey]->StartTrans();
687 if ((string)$this->lastQuery[0] !== '') {
688 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery[0], FALSE);
689 }
690 if (is_array($this->lastQuery[1])) {
691 foreach ($this->lastQuery[1] as $field => $content) {
692 $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($where));
693 }
694 }
695 if (is_array($this->lastQuery[2])) {
696 foreach ($this->lastQuery[2] as $field => $content) {
697 $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($where));
698 }
699 }
700 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans();
701 }
702 break;
703 case 'userdefined':
704 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields);
705 break;
706 }
707 if ($this->printErrors && $this->sql_error()) {
708 debug(array($this->lastQuery, $this->sql_error()));
709 }
710 if ($this->debug) {
711 $this->debugHandler('exec_UPDATEquery', GeneralUtility::milliseconds() - $pt, array(
712 'handlerType' => $hType,
713 'args' => array($table, $where, $fields_values),
714 'ORIG_from_table' => $ORIG_tableName
715 ));
716 }
717 foreach ($this->postProcessHookObjects as $hookObject) {
718 $hookObject->exec_UPDATEquery_postProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
719 }
720 // Return result:
721 return $sqlResult;
722 }
723
724 /**
725 * Creates and executes a DELETE SQL-statement for $table where $where-clause
726 *
727 * @param string $table Database tablename
728 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
729 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
730 */
731 public function exec_DELETEquery($table, $where) {
732 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
733 // Do table/field mapping:
734 $ORIG_tableName = $table;
735 if ($tableArray = $this->map_needMapping($table)) {
736 // Where clause:
737 $whereParts = $this->SQLparser->parseWhereClause($where);
738 $this->map_sqlParts($whereParts, $tableArray[0]['table']);
739 $where = $this->SQLparser->compileWhereClause($whereParts, FALSE);
740 // Table name:
741 if ($this->mapping[$table]['mapTableName']) {
742 $table = $this->mapping[$table]['mapTableName'];
743 }
744 }
745 // Select API
746 $this->lastHandlerKey = $this->handler_getFromTableList($table);
747 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
748 $sqlResult = NULL;
749 switch ($hType) {
750 case 'native':
751 $this->lastQuery = $this->DELETEquery($table, $where);
752 $sqlResult = $this->query($this->lastQuery);
753 break;
754 case 'adodb':
755 $this->lastQuery = $this->DELETEquery($table, $where);
756 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
757 break;
758 case 'userdefined':
759 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_DELETEquery($table, $where);
760 break;
761 }
762 if ($this->printErrors && $this->sql_error()) {
763 debug(array($this->lastQuery, $this->sql_error()));
764 }
765 if ($this->debug) {
766 $this->debugHandler('exec_DELETEquery', GeneralUtility::milliseconds() - $pt, array(
767 'handlerType' => $hType,
768 'args' => array($table, $where),
769 'ORIG_from_table' => $ORIG_tableName
770 ));
771 }
772 foreach ($this->postProcessHookObjects as $hookObject) {
773 $hookObject->exec_DELETEquery_postProcessAction($table, $where, $this);
774 }
775 // Return result:
776 return $sqlResult;
777 }
778
779 /**
780 * Creates and executes a SELECT SQL-statement
781 * Using this function specifically allow us to handle the LIMIT feature independently of DB.
782 *
783 * @param string $select_fields List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
784 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
785 * @param string $where_clause Additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
786 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
787 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
788 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
789 * @throws \RuntimeException
790 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
791 */
792 public function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
793 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
794 // Map table / field names if needed:
795 $ORIG_tableName = $from_table;
796 // Saving table names in $ORIG_from_table since $from_table is transformed beneath:
797 $parsedFromTable = array();
798 $remappedParameters = array();
799 if ($tableArray = $this->map_needMapping($ORIG_tableName, FALSE, $parsedFromTable)) {
800 $from = $parsedFromTable ? $parsedFromTable : $from_table;
801 $remappedParameters = $this->map_remapSELECTQueryParts($select_fields, $from, $where_clause, $groupBy, $orderBy);
802 }
803 // Get handler key and select API:
804 if (count($remappedParameters) > 0) {
805 $mappedQueryParts = $this->compileSelectParameters($remappedParameters);
806 $fromTable = $mappedQueryParts[1];
807 } else {
808 $fromTable = $from_table;
809 }
810 $this->lastHandlerKey = $this->handler_getFromTableList($fromTable);
811 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
812 $sqlResult = NULL;
813 switch ($hType) {
814 case 'native':
815 if (count($remappedParameters) > 0) {
816 list($select_fields, $from_table, $where_clause, $groupBy, $orderBy) = $this->compileSelectParameters($remappedParameters);
817 }
818 $this->lastQuery = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
819 $sqlResult = $this->query($this->lastQuery);
820 $this->resourceIdToTableNameMap[serialize($sqlResult)] = $ORIG_tableName;
821 break;
822 case 'adodb':
823 if ($limit != '') {
824 $splitLimit = GeneralUtility::intExplode(',', $limit);
825 // Splitting the limit values:
826 if ($splitLimit[1]) {
827 // If there are two parameters, do mapping differently than otherwise:
828 $numrows = $splitLimit[1];
829 $offset = $splitLimit[0];
830 } else {
831 $numrows = $splitLimit[0];
832 $offset = 0;
833 }
834 if (count($remappedParameters) > 0) {
835 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->SelectLimit($this->SELECTqueryFromArray($remappedParameters), $numrows, $offset);
836 } else {
837 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->SelectLimit($this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy), $numrows, $offset);
838 }
839 $this->lastQuery = $sqlResult->sql;
840 } else {
841 if (count($remappedParameters) > 0) {
842 $this->lastQuery = $this->SELECTqueryFromArray($remappedParameters);
843 } else {
844 $this->lastQuery = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy);
845 }
846 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_Execute($this->lastQuery);
847 }
848 if (!is_object($sqlResult)) {
849 throw new \RuntimeException('ADOdb could not run this query: ' . $this->lastQuery, 1421053336);
850 }
851 $sqlResult->TYPO3_DBAL_handlerType = 'adodb';
852 // Setting handler type in result object (for later recognition!)
853 $sqlResult->TYPO3_DBAL_tableList = $ORIG_tableName;
854 break;
855 case 'userdefined':
856 if (count($remappedParameters) > 0) {
857 list($select_fields, $from_table, $where_clause, $groupBy, $orderBy) = $this->compileSelectParameters($remappedParameters);
858 }
859 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
860 if (is_object($sqlResult)) {
861 $sqlResult->TYPO3_DBAL_handlerType = 'userdefined';
862 // Setting handler type in result object (for later recognition!)
863 $sqlResult->TYPO3_DBAL_tableList = $ORIG_tableName;
864 }
865 break;
866 }
867 if ($this->printErrors && $this->sql_error()) {
868 debug(array($this->lastQuery, $this->sql_error()));
869 }
870 if ($this->debug) {
871 $data = array(
872 'handlerType' => $hType,
873 'args' => array($from_table, $select_fields, $where_clause, $groupBy, $orderBy, $limit),
874 'ORIG_from_table' => $ORIG_tableName
875 );
876 if ($this->conf['debugOptions']['numberRows']) {
877 $data['numberRows'] = $this->sql_num_rows($sqlResult);
878 }
879 $this->debugHandler('exec_SELECTquery', GeneralUtility::milliseconds() - $pt, $data);
880 }
881 // Return handler.
882 return $sqlResult;
883 }
884
885 /**
886 * Truncates a table.
887 *
888 * @param string $table Database tablename
889 * @return mixed Result from handler
890 */
891 public function exec_TRUNCATEquery($table) {
892 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
893 // Do table/field mapping:
894 $ORIG_tableName = $table;
895 if ($tableArray = $this->map_needMapping($table)) {
896 // Table name:
897 if ($this->mapping[$table]['mapTableName']) {
898 $table = $this->mapping[$table]['mapTableName'];
899 }
900 }
901 // Select API
902 $this->lastHandlerKey = $this->handler_getFromTableList($table);
903 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
904 $sqlResult = NULL;
905 switch ($hType) {
906 case 'native':
907 $this->lastQuery = $this->TRUNCATEquery($table);
908 $sqlResult = $this->query($this->lastQuery);
909 break;
910 case 'adodb':
911 $this->lastQuery = $this->TRUNCATEquery($table);
912 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
913 break;
914 case 'userdefined':
915 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_TRUNCATEquery($table);
916 break;
917 }
918 if ($this->printErrors && $this->sql_error()) {
919 debug(array($this->lastQuery, $this->sql_error()));
920 }
921 if ($this->debug) {
922 $this->debugHandler('exec_TRUNCATEquery', GeneralUtility::milliseconds() - $pt, array(
923 'handlerType' => $hType,
924 'args' => array($table),
925 'ORIG_from_table' => $ORIG_tableName
926 ));
927 }
928 foreach ($this->postProcessHookObjects as $hookObject) {
929 $hookObject->exec_TRUNCATEquery_postProcessAction($table, $this);
930 }
931 // Return result:
932 return $sqlResult;
933 }
934
935 /**
936 * Executes a query.
937 * EXPERIMENTAL since TYPO3 4.4.
938 *
939 * @param array $queryParts SQL parsed by method parseSQL() of \TYPO3\CMS\Core\Database\SqlParser
940 * @return \mysqli_result|object MySQLi result object / DBAL object
941 * @see self::sql_query()
942 */
943 protected function exec_query(array $queryParts) {
944 switch ($queryParts['type']) {
945 case 'SELECT':
946 $selectFields = $this->SQLparser->compileFieldList($queryParts['SELECT']);
947 $fromTables = $this->SQLparser->compileFromTables($queryParts['FROM']);
948 $whereClause = isset($queryParts['WHERE']) ? $this->SQLparser->compileWhereClause($queryParts['WHERE']) : '1=1';
949 $groupBy = isset($queryParts['GROUPBY']) ? $this->SQLparser->compileFieldList($queryParts['GROUPBY']) : '';
950 $orderBy = isset($queryParts['ORDERBY']) ? $this->SQLparser->compileFieldList($queryParts['ORDERBY']) : '';
951 $limit = isset($queryParts['LIMIT']) ? $queryParts['LIMIT'] : '';
952 return $this->exec_SELECTquery($selectFields, $fromTables, $whereClause, $groupBy, $orderBy, $limit);
953 case 'UPDATE':
954 $table = $queryParts['TABLE'];
955 $fields = array();
956 foreach ($queryParts['FIELDS'] as $fN => $fV) {
957 $fields[$fN] = $fV[0];
958 }
959 $whereClause = isset($queryParts['WHERE']) ? $this->SQLparser->compileWhereClause($queryParts['WHERE']) : '1=1';
960 return $this->exec_UPDATEquery($table, $whereClause, $fields);
961 case 'INSERT':
962 $table = $queryParts['TABLE'];
963 $values = array();
964 if (isset($queryParts['VALUES_ONLY']) && is_array($queryParts['VALUES_ONLY'])) {
965 $fields = $GLOBALS['TYPO3_DB']->cache_fieldType[$table];
966 $fc = 0;
967 foreach ($fields as $fn => $fd) {
968 $values[$fn] = $queryParts['VALUES_ONLY'][$fc++][0];
969 }
970 } else {
971 foreach ($queryParts['FIELDS'] as $fN => $fV) {
972 $values[$fN] = $fV[0];
973 }
974 }
975 return $this->exec_INSERTquery($table, $values);
976 case 'DELETE':
977 $table = $queryParts['TABLE'];
978 $whereClause = isset($queryParts['WHERE']) ? $this->SQLparser->compileWhereClause($queryParts['WHERE']) : '1=1';
979 return $this->exec_DELETEquery($table, $whereClause);
980 case 'TRUNCATETABLE':
981 $table = $queryParts['TABLE'];
982 return $this->exec_TRUNCATEquery($table);
983 default:
984 return NULL;
985 }
986 }
987
988 /**
989 * Central query method. Also checks if there is a database connection.
990 * Use this to execute database queries instead of directly calling $this->link->query()
991 *
992 * @param string $query The query to send to the database
993 * @return bool|\mysqli_result
994 */
995 protected function query($query) {
996 if (!$this->isConnected()) {
997 $this->connectDB();
998 }
999 return $this->handlerInstance[$this->lastHandlerKey]['link']->query($query);
1000 }
1001
1002 /**************************************
1003 *
1004 * Query building
1005 *
1006 **************************************/
1007 /**
1008 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
1009 *
1010 * @param string $table See exec_INSERTquery()
1011 * @param array $fields_values See exec_INSERTquery()
1012 * @param bool|array|string $no_quote_fields See fullQuoteArray()
1013 * @return string|NULL Full SQL query for INSERT, NULL if $rows is empty
1014 */
1015 public function INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
1016 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
1017 if (!is_array($fields_values) || count($fields_values) === 0) {
1018 return '';
1019 }
1020 foreach ($this->preProcessHookObjects as $hookObject) {
1021 $hookObject->INSERTquery_preProcessAction($table, $fields_values, $no_quote_fields, $this);
1022 }
1023 if (is_string($no_quote_fields)) {
1024 $no_quote_fields = explode(',', $no_quote_fields);
1025 } elseif (!is_array($no_quote_fields)) {
1026 $no_quote_fields = array();
1027 }
1028 $blobFields = $clobFields = array();
1029 $nArr = array();
1030 $handlerKey = $this->handler_getFromTableList($table);
1031 $quoteClob = isset($this->handlerCfg[$handlerKey]['config']['quoteClob']) ? $this->handlerCfg[$handlerKey]['config']['quoteClob'] : FALSE;
1032 foreach ($fields_values as $k => $v) {
1033 if (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'B') {
1034 // we skip the field in the regular INSERT statement, it is only in blobfields
1035 $blobFields[$this->quoteFieldNames($k)] = $v;
1036 } elseif (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'XL') {
1037 // we skip the field in the regular INSERT statement, it is only in clobfields
1038 $clobFields[$this->quoteFieldNames($k)] = $quoteClob ? $this->quoteStr($v, $table) : $v;
1039 } else {
1040 // Add slashes old-school:
1041 // cast numerical values
1042 $mt = $this->sql_field_metatype($table, $k);
1043 if ($mt[0] == 'I') {
1044 $v = (int)$v;
1045 } elseif ($mt[0] == 'F') {
1046 $v = (double) $v;
1047 }
1048 $nArr[$this->quoteFieldNames($k)] = !in_array($k, $no_quote_fields) ? $this->fullQuoteStr($v, $table, TRUE) : $v;
1049 }
1050 }
1051 if (count($blobFields) || count($clobFields)) {
1052 $query = array();
1053 if (count($nArr)) {
1054 $query[0] = 'INSERT INTO ' . $this->quoteFromTables($table) . '
1055 (
1056 ' . implode(',
1057 ', array_keys($nArr)) . '
1058 ) VALUES (
1059 ' . implode(',
1060 ', $nArr) . '
1061 )';
1062 }
1063 if (count($blobFields)) {
1064 $query[1] = $blobFields;
1065 }
1066 if (count($clobFields)) {
1067 $query[2] = $clobFields;
1068 }
1069 if (isset($query[0]) && ($this->debugOutput || $this->store_lastBuiltQuery)) {
1070 $this->debug_lastBuiltQuery = $query[0];
1071 }
1072 } else {
1073 $query = 'INSERT INTO ' . $this->quoteFromTables($table) . '
1074 (
1075 ' . implode(',
1076 ', array_keys($nArr)) . '
1077 ) VALUES (
1078 ' . implode(',
1079 ', $nArr) . '
1080 )';
1081 if ($this->debugOutput || $this->store_lastBuiltQuery) {
1082 $this->debug_lastBuiltQuery = $query;
1083 }
1084 }
1085 return $query;
1086 }
1087
1088 /**
1089 * Creates an INSERT SQL-statement for $table with multiple rows.
1090 *
1091 * @param string $table Table name
1092 * @param array $fields Field names
1093 * @param array $rows Table rows. Each row should be an array with field values mapping to $fields
1094 * @param bool|array|string $no_quote_fields See fullQuoteArray()
1095 * @return string|array Full SQL query for INSERT (unless $rows does not contain any elements in which case it will be FALSE)
1096 */
1097 public function INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
1098 if ((string)$this->handlerCfg[$this->lastHandlerKey]['type'] === 'native') {
1099 return parent::INSERTmultipleRows($table, $fields, $rows, $no_quote_fields);
1100 }
1101 $result = array();
1102 foreach ($rows as $row) {
1103 $fields_values = array();
1104 foreach ($fields as $key => $value) {
1105 $fields_values[$value] = $row[$key];
1106 }
1107 $rowQuery = $this->INSERTquery($table, $fields_values, $no_quote_fields);
1108 if (is_array($rowQuery)) {
1109 $result[] = $rowQuery;
1110 } else {
1111 $result[][0] = $rowQuery;
1112 }
1113 }
1114 return $result;
1115 }
1116
1117 /**
1118 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
1119 *
1120 *
1121 * @param string $table See exec_UPDATEquery()
1122 * @param string $where See exec_UPDATEquery()
1123 * @param array $fields_values See exec_UPDATEquery()
1124 * @param bool|array|string $no_quote_fields See fullQuoteArray()
1125 * @throws \InvalidArgumentException
1126 * @return string Full SQL query for UPDATE
1127 */
1128 public function UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
1129 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
1130 if (is_string($where)) {
1131 foreach ($this->preProcessHookObjects as $hookObject) {
1132 $hookObject->UPDATEquery_preProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
1133 }
1134 $blobFields = $clobFields = array();
1135 $nArr = array();
1136 if (is_array($fields_values) && count($fields_values)) {
1137 if (is_string($no_quote_fields)) {
1138 $no_quote_fields = explode(',', $no_quote_fields);
1139 } elseif (!is_array($no_quote_fields)) {
1140 $no_quote_fields = array();
1141 }
1142 $handlerKey = $this->handler_getFromTableList($table);
1143 $quoteClob = isset($this->handlerCfg[$handlerKey]['config']['quoteClob']) ? $this->handlerCfg[$handlerKey]['config']['quoteClob'] : FALSE;
1144 foreach ($fields_values as $k => $v) {
1145 if (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'B') {
1146 // we skip the field in the regular UPDATE statement, it is only in blobfields
1147 $blobFields[$this->quoteFieldNames($k)] = $v;
1148 } elseif (!$this->runningNative() && $this->sql_field_metatype($table, $k) == 'XL') {
1149 // we skip the field in the regular UPDATE statement, it is only in clobfields
1150 $clobFields[$this->quoteFieldNames($k)] = $quoteClob ? $this->quoteStr($v, $table) : $v;
1151 } else {
1152 // Add slashes old-school:
1153 // cast numeric values
1154 $mt = $this->sql_field_metatype($table, $k);
1155 if ($mt[0] == 'I') {
1156 $v = (int)$v;
1157 } elseif ($mt[0] == 'F') {
1158 $v = (double) $v;
1159 }
1160 $nArr[] = $this->quoteFieldNames($k) . '=' . (!in_array($k, $no_quote_fields) ? $this->fullQuoteStr($v, $table, TRUE) : $v);
1161 }
1162 }
1163 }
1164 if (count($blobFields) || count($clobFields)) {
1165 $query = array();
1166 if (count($nArr)) {
1167 $query[0] = 'UPDATE ' . $this->quoteFromTables($table) . '
1168 SET
1169 ' . implode(',
1170 ', $nArr) . ($where !== '' ? '
1171 WHERE
1172 ' . $this->quoteWhereClause($where) : '');
1173 }
1174 if (count($blobFields)) {
1175 $query[1] = $blobFields;
1176 }
1177 if (count($clobFields)) {
1178 $query[2] = $clobFields;
1179 }
1180 if (isset($query[0]) && ($this->debugOutput || $this->store_lastBuiltQuery)) {
1181 $this->debug_lastBuiltQuery = $query[0];
1182 }
1183 } else {
1184 $query = 'UPDATE ' . $this->quoteFromTables($table) . '
1185 SET
1186 ' . implode(',
1187 ', $nArr) . ($where !== '' ? '
1188 WHERE
1189 ' . $this->quoteWhereClause($where) : '');
1190 if ($this->debugOutput || $this->store_lastBuiltQuery) {
1191 $this->debug_lastBuiltQuery = $query;
1192 }
1193 }
1194 return $query;
1195 } else {
1196 throw new \InvalidArgumentException('TYPO3 Fatal Error: "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !', 1270853887);
1197 }
1198 }
1199
1200 /**
1201 * Creates a DELETE SQL-statement for $table where $where-clause
1202 *
1203 * @param string $table See exec_DELETEquery()
1204 * @param string $where See exec_DELETEquery()
1205 * @return string Full SQL query for DELETE
1206 * @throws \InvalidArgumentException
1207 */
1208 public function DELETEquery($table, $where) {
1209 if (is_string($where)) {
1210 foreach ($this->preProcessHookObjects as $hookObject) {
1211 $hookObject->DELETEquery_preProcessAction($table, $where, $this);
1212 }
1213 $table = $this->quoteFromTables($table);
1214 $where = $this->quoteWhereClause($where);
1215 $query = 'DELETE FROM ' . $table . ($where !== '' ? ' WHERE ' . $where : '');
1216 if ($this->debugOutput || $this->store_lastBuiltQuery) {
1217 $this->debug_lastBuiltQuery = $query;
1218 }
1219 return $query;
1220 } else {
1221 throw new \InvalidArgumentException('TYPO3 Fatal Error: "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !', 1310027383);
1222 }
1223 }
1224
1225 /**
1226 * Creates a SELECT SQL-statement
1227 *
1228 * @param string $select_fields See exec_SELECTquery()
1229 * @param string $from_table See exec_SELECTquery()
1230 * @param string $where_clause See exec_SELECTquery()
1231 * @param string $groupBy See exec_SELECTquery()
1232 * @param string $orderBy See exec_SELECTquery()
1233 * @param string $limit See exec_SELECTquery()
1234 * @return string Full SQL query for SELECT
1235 */
1236 public function SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
1237 $this->lastHandlerKey = $this->handler_getFromTableList($from_table);
1238 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
1239 if ($hType === 'adodb' && $this->runningADOdbDriver('postgres')) {
1240 // Possibly rewrite the LIMIT to be PostgreSQL-compatible
1241 $splitLimit = GeneralUtility::intExplode(',', $limit);
1242 // Splitting the limit values:
1243 if ($splitLimit[1]) {
1244 // If there are two parameters, do mapping differently than otherwise:
1245 $numrows = $splitLimit[1];
1246 $offset = $splitLimit[0];
1247 $limit = $numrows . ' OFFSET ' . $offset;
1248 }
1249 }
1250 $select_fields = $this->quoteFieldNames($select_fields);
1251 $from_table = $this->quoteFromTables($from_table);
1252 $where_clause = $this->quoteWhereClause($where_clause);
1253 $groupBy = $this->quoteGroupBy($groupBy);
1254 $orderBy = $this->quoteOrderBy($orderBy);
1255 // Call parent method to build actual query
1256 $query = parent::SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
1257 if ($this->debugOutput || $this->store_lastBuiltQuery) {
1258 $this->debug_lastBuiltQuery = $query;
1259 }
1260 return $query;
1261 }
1262
1263 /**
1264 * Creates a SELECT SQL-statement to be used with an ADOdb backend.
1265 *
1266 * @param array $params parsed parameters: array($select_fields, $from_table, $where_clause, $groupBy, $orderBy)
1267 * @return string Full SQL query for SELECT
1268 */
1269 protected function SELECTqueryFromArray(array $params) {
1270 // $select_fields
1271 $params[0] = $this->_quoteFieldNames($params[0]);
1272 // $from_table
1273 $params[1] = $this->_quoteFromTables($params[1]);
1274 // $where_clause
1275 if (count($params[2]) > 0) {
1276 $params[2] = $this->_quoteWhereClause($params[2]);
1277 }
1278 // $group_by
1279 if (count($params[3]) > 0) {
1280 $params[3] = $this->_quoteGroupBy($params[3]);
1281 }
1282 // $order_by
1283 if (count($params[4]) > 0) {
1284 $params[4] = $this->_quoteOrderBy($params[4]);
1285 }
1286 // Compile the SELECT parameters
1287 list($select_fields, $from_table, $where_clause, $groupBy, $orderBy) = $this->compileSelectParameters($params);
1288 // Call parent method to build actual query
1289 $query = parent::SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy);
1290 if ($this->debugOutput || $this->store_lastBuiltQuery) {
1291 $this->debug_lastBuiltQuery = $query;
1292 }
1293 return $query;
1294 }
1295
1296 /**
1297 * Compiles and returns an array of SELECTquery parameters (without $limit) to
1298 * be used with SELECTquery() or exec_SELECTquery().
1299 *
1300 * @param array $params
1301 * @return array array($select_fields, $from_table, $where_clause, $groupBy, $orderBy)
1302 */
1303 protected function compileSelectParameters(array $params) {
1304 $select_fields = $this->SQLparser->compileFieldList($params[0]);
1305 $from_table = $this->SQLparser->compileFromTables($params[1]);
1306 $where_clause = count($params[2]) > 0 ? $this->SQLparser->compileWhereClause($params[2]) : '';
1307 $groupBy = count($params[3]) > 0 ? $this->SQLparser->compileFieldList($params[3]) : '';
1308 $orderBy = count($params[4]) > 0 ? $this->SQLparser->compileFieldList($params[4]) : '';
1309 return array($select_fields, $from_table, $where_clause, $groupBy, $orderBy);
1310 }
1311
1312 /**
1313 * Creates a TRUNCATE TABLE SQL-statement
1314 *
1315 * @param string $table See exec_TRUNCATEquery()
1316 * @return string Full SQL query for TRUNCATE TABLE
1317 */
1318 public function TRUNCATEquery($table) {
1319 foreach ($this->preProcessHookObjects as $hookObject) {
1320 $hookObject->TRUNCATEquery_preProcessAction($table, $this);
1321 }
1322 $table = $this->quoteFromTables($table);
1323 // Build actual query
1324 $query = 'TRUNCATE TABLE ' . $table;
1325 if ($this->debugOutput || $this->store_lastBuiltQuery) {
1326 $this->debug_lastBuiltQuery = $query;
1327 }
1328 return $query;
1329 }
1330
1331 /**************************************
1332 *
1333 * Prepared Query Support
1334 *
1335 **************************************/
1336 /**
1337 * Creates a SELECT prepared SQL statement.
1338 *
1339 * @param string $select_fields See exec_SELECTquery()
1340 * @param string $from_table See exec_SELECTquery()
1341 * @param string $where_clause See exec_SELECTquery()
1342 * @param string $groupBy See exec_SELECTquery()
1343 * @param string $orderBy See exec_SELECTquery()
1344 * @param string $limit See exec_SELECTquery()
1345 * @param array $input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as \TYPO3\CMS\Core\Database\PreparedStatement::PARAM_AUTOTYPE.
1346 * @return \TYPO3\CMS\Core\Database\PreparedStatement Prepared statement
1347 */
1348 public function prepare_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', array $input_parameters = array()) {
1349 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
1350 $precompiledParts = array();
1351 if ($this->queryCache) {
1352 $cacheKey = 'prepare_SELECTquery-' . \TYPO3\CMS\Dbal\QueryCache::getCacheKey(array(
1353 'selectFields' => $select_fields,
1354 'fromTable' => $from_table,
1355 'whereClause' => $where_clause,
1356 'groupBy' => $groupBy,
1357 'orderBy' => $orderBy,
1358 'limit' => $limit
1359 ));
1360 if ($this->queryCache->has($cacheKey)) {
1361 $precompiledParts = $this->queryCache->get($cacheKey);
1362 if ($this->debug) {
1363 $data = array(
1364 'args' => array($from_table, $select_fields, $where_clause, $groupBy, $orderBy, $limit, $input_parameters),
1365 'precompiledParts' => $precompiledParts
1366 );
1367 $this->debugHandler('prepare_SELECTquery (cache hit)', GeneralUtility::milliseconds() - $pt, $data);
1368 }
1369 }
1370 }
1371 $ORIG_tableName = '';
1372 if (count($precompiledParts) == 0) {
1373 // Map table / field names if needed:
1374 $ORIG_tableName = $from_table;
1375 // Saving table names in $ORIG_from_table since $from_table is transformed beneath:
1376 $parsedFromTable = array();
1377 $queryComponents = array();
1378 if ($tableArray = $this->map_needMapping($ORIG_tableName, FALSE, $parsedFromTable)) {
1379 $from = $parsedFromTable ? $parsedFromTable : $from_table;
1380 $components = $this->map_remapSELECTQueryParts($select_fields, $from, $where_clause, $groupBy, $orderBy);
1381 $queryComponents['SELECT'] = $components[0];
1382 $queryComponents['FROM'] = $components[1];
1383 $queryComponents['WHERE'] = $components[2];
1384 $queryComponents['GROUPBY'] = $components[3];
1385 $queryComponents['ORDERBY'] = $components[4];
1386 $queryComponents['parameters'] = $components[5];
1387 } else {
1388 $queryComponents = $this->getQueryComponents($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
1389 }
1390 $queryComponents['ORIG_tableName'] = $ORIG_tableName;
1391 if (!$this->runningNative()) {
1392 // Quotes all fields
1393 $queryComponents['SELECT'] = $this->_quoteFieldNames($queryComponents['SELECT']);
1394 $queryComponents['FROM'] = $this->_quoteFromTables($queryComponents['FROM']);
1395 $queryComponents['WHERE'] = $this->_quoteWhereClause($queryComponents['WHERE']);
1396 $queryComponents['GROUPBY'] = $this->_quoteGroupBy($queryComponents['GROUPBY']);
1397 $queryComponents['ORDERBY'] = $this->_quoteOrderBy($queryComponents['ORDERBY']);
1398 }
1399 $precompiledParts = $this->precompileSELECTquery($queryComponents);
1400 if ($this->queryCache) {
1401 try {
1402 $this->queryCache->set($cacheKey, $precompiledParts);
1403 } catch (\TYPO3\CMS\Core\Cache\Exception $e) {
1404 if ($this->debug) {
1405 GeneralUtility::devLog($e->getMessage(), 'dbal', 1);
1406 }
1407 }
1408 }
1409 }
1410 $preparedStatement = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\PreparedStatement::class, '', $from_table, $precompiledParts);
1411 /* @var $preparedStatement \TYPO3\CMS\Core\Database\PreparedStatement */
1412 // Bind values to parameters
1413 foreach ($input_parameters as $key => $value) {
1414 $preparedStatement->bindValue($key, $value, \TYPO3\CMS\Core\Database\PreparedStatement::PARAM_AUTOTYPE);
1415 }
1416 if ($this->debug) {
1417 $data = array(
1418 'args' => array($from_table, $select_fields, $where_clause, $groupBy, $orderBy, $limit, $input_parameters),
1419 'ORIG_from_table' => $ORIG_tableName
1420 );
1421 $this->debugHandler('prepare_SELECTquery', GeneralUtility::milliseconds() - $pt, $data);
1422 }
1423 // Return prepared statement
1424 return $preparedStatement;
1425 }
1426
1427 /**
1428 * Returns the parsed query components.
1429 *
1430 * @param string $select_fields
1431 * @param string $from_table
1432 * @param string $where_clause
1433 * @param string $groupBy
1434 * @param string $orderBy
1435 * @param string $limit
1436 * @throws \InvalidArgumentException
1437 * @return array
1438 */
1439 protected function getQueryComponents($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit) {
1440 $queryComponents = array(
1441 'SELECT' => '',
1442 'FROM' => '',
1443 'WHERE' => '',
1444 'GROUPBY' => '',
1445 'ORDERBY' => '',
1446 'LIMIT' => '',
1447 'parameters' => array()
1448 );
1449 $this->lastHandlerKey = $this->handler_getFromTableList($from_table);
1450 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
1451 if ($hType === 'adodb' && $this->runningADOdbDriver('postgres')) {
1452 // Possibly rewrite the LIMIT to be PostgreSQL-compatible
1453 $splitLimit = GeneralUtility::intExplode(',', $limit);
1454 // Splitting the limit values:
1455 if ($splitLimit[1]) {
1456 // If there are two parameters, do mapping differently than otherwise:
1457 $numrows = $splitLimit[1];
1458 $offset = $splitLimit[0];
1459 $limit = $numrows . ' OFFSET ' . $offset;
1460 }
1461 }
1462 $queryComponents['LIMIT'] = $limit;
1463 $queryComponents['SELECT'] = $this->SQLparser->parseFieldList($select_fields);
1464 if ($this->SQLparser->parse_error) {
1465 throw new \InvalidArgumentException($this->SQLparser->parse_error, 1310027408);
1466 }
1467 $queryComponents['FROM'] = $this->SQLparser->parseFromTables($from_table);
1468 $queryComponents['WHERE'] = $this->SQLparser->parseWhereClause($where_clause, '', $queryComponents['parameters']);
1469 if (!is_array($queryComponents['WHERE'])) {
1470 throw new \InvalidArgumentException('Could not parse where clause', 1310027427);
1471 }
1472 $queryComponents['GROUPBY'] = $this->SQLparser->parseFieldList($groupBy);
1473 $queryComponents['ORDERBY'] = $this->SQLparser->parseFieldList($orderBy);
1474 // Return the query components
1475 return $queryComponents;
1476 }
1477
1478 /**
1479 * Precompiles a SELECT prepared SQL statement.
1480 *
1481 * @param array $components
1482 * @return array Precompiled SQL statement
1483 */
1484 protected function precompileSELECTquery(array $components) {
1485 $parameterWrap = '__' . dechex(time()) . '__';
1486 foreach ($components['parameters'] as $key => $params) {
1487 if ($key === '?') {
1488 foreach ($params as $index => $param) {
1489 $components['parameters'][$key][$index][0] = $parameterWrap . $param[0] . $parameterWrap;
1490 }
1491 } else {
1492 $components['parameters'][$key][0] = $parameterWrap . $params[0] . $parameterWrap;
1493 }
1494 }
1495 $select_fields = $this->SQLparser->compileFieldList($components['SELECT']);
1496 $from_table = $this->SQLparser->compileFromTables($components['FROM']);
1497 $where_clause = $this->SQLparser->compileWhereClause($components['WHERE']);
1498 $groupBy = $this->SQLparser->compileFieldList($components['GROUPBY']);
1499 $orderBy = $this->SQLparser->compileFieldList($components['ORDERBY']);
1500 $limit = $components['LIMIT'];
1501 $precompiledParts = array();
1502 $this->lastHandlerKey = $this->handler_getFromTableList($components['ORIG_tableName']);
1503 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
1504 $precompiledParts['handler'] = $hType;
1505 $precompiledParts['ORIG_tableName'] = $components['ORIG_tableName'];
1506 switch ($hType) {
1507 case 'native':
1508 $query = parent::SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
1509 $precompiledParts['queryParts'] = explode($parameterWrap, $query);
1510 break;
1511 case 'adodb':
1512 $query = parent::SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy);
1513 $precompiledParts['queryParts'] = explode($parameterWrap, $query);
1514 $precompiledParts['LIMIT'] = $limit;
1515 break;
1516 case 'userdefined':
1517 $precompiledParts['queryParts'] = array(
1518 'SELECT' => $select_fields,
1519 'FROM' => $from_table,
1520 'WHERE' => $where_clause,
1521 'GROUPBY' => $groupBy,
1522 'ORDERBY' => $orderBy,
1523 'LIMIT' => $limit
1524 );
1525 break;
1526 }
1527 return $precompiledParts;
1528 }
1529
1530 /**
1531 * Prepares a prepared query.
1532 *
1533 * @param string $query The query to execute
1534 * @param array $queryComponents The components of the query to execute
1535 * @return bool|\mysqli_statement|\TYPO3\CMS\Dbal\Database\AdodbPreparedStatement
1536 * @throws \RuntimeException
1537 * @internal This method may only be called by \TYPO3\CMS\Core\Database\PreparedStatement
1538 */
1539 public function prepare_PREPAREDquery($query, array $queryComponents) {
1540 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
1541 // Get handler key and select API:
1542 $preparedStatement = NULL;
1543 switch ($queryComponents['handler']) {
1544 case 'native':
1545 $this->lastQuery = $query;
1546 $preparedStatement = parent::prepare_PREPAREDquery($this->lastQuery, $queryComponents);
1547 $this->resourceIdToTableNameMap[serialize($preparedStatement)] = $queryComponents['ORIG_tableName'];
1548 break;
1549 case 'adodb':
1550 /** @var \TYPO3\CMS\Dbal\Database\AdodbPreparedStatement $preparedStatement */
1551 $preparedStatement = GeneralUtility::makeInstance(\TYPO3\CMS\Dbal\Database\AdodbPreparedStatement::class, $query, $queryComponents, $this);
1552 if (!$preparedStatement->prepare()) {
1553 $preparedStatement = FALSE;
1554 }
1555 break;
1556 case 'userdefined':
1557 throw new \RuntimeException('prepare_PREPAREDquery is not implemented for userdefined handlers', 1394620167);
1558 /*
1559 $queryParts = $queryComponents['queryParts'];
1560 $preparedStatement = $this->handlerInstance[$this->lastHandlerKey]->exec_SELECTquery($queryParts['SELECT'], $queryParts['FROM'], $queryParts['WHERE'], $queryParts['GROUPBY'], $queryParts['ORDERBY'], $queryParts['LIMIT']);
1561 if (is_object($preparedStatement)) {
1562 $preparedStatement->TYPO3_DBAL_handlerType = 'userdefined';
1563 // Setting handler type in result object (for later recognition!)
1564 $preparedStatement->TYPO3_DBAL_tableList = $queryComponents['ORIG_tableName'];
1565 }
1566 break;
1567 */
1568 }
1569 if ($this->printErrors && $this->sql_error()) {
1570 debug(array($this->lastQuery, $this->sql_error()));
1571 }
1572 if ($this->debug) {
1573 $data = array(
1574 'handlerType' => $queryComponents['handler'],
1575 'args' => $queryComponents,
1576 'ORIG_from_table' => $queryComponents['ORIG_tableName']
1577 );
1578 $this->debugHandler('prepare_PREPAREDquery', GeneralUtility::milliseconds() - $pt, $data);
1579 }
1580 // Return result handler.
1581 return $preparedStatement;
1582 }
1583
1584 /**************************************
1585 *
1586 * Functions for quoting table/field names
1587 *
1588 **************************************/
1589 /**
1590 * Quotes components of a SELECT subquery.
1591 *
1592 * @param array $components Array of SQL query components
1593 * @return array
1594 */
1595 protected function quoteSELECTsubquery(array $components) {
1596 $components['SELECT'] = $this->_quoteFieldNames($components['SELECT']);
1597 $components['FROM'] = $this->_quoteFromTables($components['FROM']);
1598 $components['WHERE'] = $this->_quoteWhereClause($components['WHERE']);
1599 return $components;
1600 }
1601
1602 /**
1603 * Quotes field (and table) names with the quote character suitable for the DB being used
1604 *
1605 * @param string $select_fields List of fields to be used in query to DB
1606 * @throws \InvalidArgumentException
1607 * @return string Quoted list of fields to be in query to DB
1608 */
1609 public function quoteFieldNames($select_fields) {
1610 if ($select_fields == '') {
1611 return '';
1612 }
1613 if ($this->runningNative()) {
1614 return $select_fields;
1615 }
1616 $select_fields = $this->SQLparser->parseFieldList($select_fields);
1617 if ($this->SQLparser->parse_error) {
1618 throw new \InvalidArgumentException($this->SQLparser->parse_error, 1310027490);
1619 }
1620 $select_fields = $this->_quoteFieldNames($select_fields);
1621 return $this->SQLparser->compileFieldList($select_fields);
1622 }
1623
1624 /**
1625 * Quotes field (and table) names in a SQL SELECT clause according to DB rules
1626 *
1627 * @param array $select_fields The parsed fields to quote
1628 * @return array
1629 * @see quoteFieldNames()
1630 */
1631 protected function _quoteFieldNames(array $select_fields) {
1632 foreach ($select_fields as $k => $v) {
1633 if ($select_fields[$k]['field'] != '' && $select_fields[$k]['field'] != '*' && !is_numeric($select_fields[$k]['field'])) {
1634 $select_fields[$k]['field'] = $this->quoteName($select_fields[$k]['field']);
1635 }
1636 if ($select_fields[$k]['table'] != '' && !is_numeric($select_fields[$k]['table'])) {
1637 $select_fields[$k]['table'] = $this->quoteName($select_fields[$k]['table']);
1638 }
1639 if ($select_fields[$k]['as'] != '') {
1640 $select_fields[$k]['as'] = $this->quoteName($select_fields[$k]['as']);
1641 }
1642 if (isset($select_fields[$k]['func_content.']) && $select_fields[$k]['func_content.'][0]['func_content'] != '*') {
1643 $select_fields[$k]['func_content.'][0]['func_content'] = $this->quoteFieldNames($select_fields[$k]['func_content.'][0]['func_content']);
1644 $select_fields[$k]['func_content'] = $this->quoteFieldNames($select_fields[$k]['func_content']);
1645 }
1646 if (isset($select_fields[$k]['flow-control'])) {
1647 // Quoting flow-control statements
1648 if ($select_fields[$k]['flow-control']['type'] === 'CASE') {
1649 if (isset($select_fields[$k]['flow-control']['case_field'])) {
1650 $select_fields[$k]['flow-control']['case_field'] = $this->quoteFieldNames($select_fields[$k]['flow-control']['case_field']);
1651 }
1652 foreach ($select_fields[$k]['flow-control']['when'] as $key => $when) {
1653 $select_fields[$k]['flow-control']['when'][$key]['when_value'] = $this->_quoteWhereClause($when['when_value']);
1654 }
1655 }
1656 }
1657 }
1658 return $select_fields;
1659 }
1660
1661 /**
1662 * Quotes table names with the quote character suitable for the DB being used
1663 *
1664 * @param string $from_table List of tables to be selected from DB
1665 * @return string Quoted list of tables to be selected from DB
1666 */
1667 public function quoteFromTables($from_table) {
1668 if ($from_table === '') {
1669 return '';
1670 }
1671 if ($this->runningNative()) {
1672 return $from_table;
1673 }
1674 $from_table = $this->SQLparser->parseFromTables($from_table);
1675 $from_table = $this->_quoteFromTables($from_table);
1676 return $this->SQLparser->compileFromTables($from_table);
1677 }
1678
1679 /**
1680 * Quotes table names in a SQL FROM clause according to DB rules
1681 *
1682 * @param array $from_table The parsed FROM clause to quote
1683 * @return array
1684 * @see quoteFromTables()
1685 */
1686 protected function _quoteFromTables(array $from_table) {
1687 foreach ($from_table as $k => $v) {
1688 $from_table[$k]['table'] = $this->quoteName($from_table[$k]['table']);
1689 if ($from_table[$k]['as'] != '') {
1690 $from_table[$k]['as'] = $this->quoteName($from_table[$k]['as']);
1691 }
1692 if (is_array($v['JOIN'])) {
1693 foreach ($v['JOIN'] as $joinCnt => $join) {
1694 $from_table[$k]['JOIN'][$joinCnt]['withTable'] = $this->quoteName($join['withTable']);
1695 $from_table[$k]['JOIN'][$joinCnt]['as'] = $join['as'] ? $this->quoteName($join['as']) : '';
1696 foreach ($from_table[$k]['JOIN'][$joinCnt]['ON'] as &$condition) {
1697 $condition['left']['table'] = $condition['left']['table'] ? $this->quoteName($condition['left']['table']) : '';
1698 $condition['left']['field'] = $this->quoteName($condition['left']['field']);
1699 $condition['right']['table'] = $condition['right']['table'] ? $this->quoteName($condition['right']['table']) : '';
1700 $condition['right']['field'] = $this->quoteName($condition['right']['field']);
1701 }
1702 }
1703 }
1704 }
1705 return $from_table;
1706 }
1707
1708 /**
1709 * Quotes the field (and table) names within a where clause with the quote character suitable for the DB being used
1710 *
1711 * @param string $where_clause A where clause that can be parsed by parseWhereClause
1712 * @throws \InvalidArgumentException
1713 * @return string Usable where clause with quoted field/table names
1714 */
1715 public function quoteWhereClause($where_clause) {
1716 if ($where_clause === '' || $this->runningNative()) {
1717 return $where_clause;
1718 }
1719 $where_clause = $this->SQLparser->parseWhereClause($where_clause);
1720 if (is_array($where_clause)) {
1721 $where_clause = $this->_quoteWhereClause($where_clause);
1722 $where_clause = $this->SQLparser->compileWhereClause($where_clause);
1723 } else {
1724 throw new \InvalidArgumentException('Could not parse where clause', 1310027511);
1725 }
1726 return $where_clause;
1727 }
1728
1729 /**
1730 * Quotes field names in a SQL WHERE clause according to DB rules
1731 *
1732 * @param array $where_clause The parsed WHERE clause to quote
1733 * @return array
1734 * @see quoteWhereClause()
1735 */
1736 protected function _quoteWhereClause(array $where_clause) {
1737 foreach ($where_clause as $k => $v) {
1738 // Look for sublevel:
1739 if (is_array($where_clause[$k]['sub'])) {
1740 $where_clause[$k]['sub'] = $this->_quoteWhereClause($where_clause[$k]['sub']);
1741 } elseif (isset($v['func'])) {
1742 switch ($where_clause[$k]['func']['type']) {
1743 case 'EXISTS':
1744 $where_clause[$k]['func']['subquery'] = $this->quoteSELECTsubquery($v['func']['subquery']);
1745 break;
1746 case 'FIND_IN_SET':
1747 // quoteStr that will be used for Oracle
1748 $pattern = str_replace($where_clause[$k]['func']['str'][1], '\\' . $where_clause[$k]['func']['str'][1], $where_clause[$k]['func']['str'][0]);
1749 // table is not really needed and may in fact be empty in real statements
1750 // but it's not overridden from \TYPO3\CMS\Core\Database\DatabaseConnection at the moment...
1751 $patternForLike = $this->escapeStrForLike($pattern, $where_clause[$k]['func']['table']);
1752 $where_clause[$k]['func']['str_like'] = $patternForLike;
1753 // Intentional fallthrough
1754 case 'IFNULL':
1755 // Intentional fallthrough
1756 case 'LOCATE':
1757 if ($where_clause[$k]['func']['table'] != '') {
1758 $where_clause[$k]['func']['table'] = $this->quoteName($v['func']['table']);
1759 }
1760 if ($where_clause[$k]['func']['field'] != '') {
1761 $where_clause[$k]['func']['field'] = $this->quoteName($v['func']['field']);
1762 }
1763 break;
1764 }
1765 } else {
1766 if ($where_clause[$k]['table'] != '') {
1767 $where_clause[$k]['table'] = $this->quoteName($where_clause[$k]['table']);
1768 }
1769 if (!is_numeric($where_clause[$k]['field'])) {
1770 $where_clause[$k]['field'] = $this->quoteName($where_clause[$k]['field']);
1771 }
1772 if (isset($where_clause[$k]['calc_table'])) {
1773 if ($where_clause[$k]['calc_table'] != '') {
1774 $where_clause[$k]['calc_table'] = $this->quoteName($where_clause[$k]['calc_table']);
1775 }
1776 if ($where_clause[$k]['calc_field'] != '') {
1777 $where_clause[$k]['calc_field'] = $this->quoteName($where_clause[$k]['calc_field']);
1778 }
1779 }
1780 }
1781 if ($where_clause[$k]['comparator']) {
1782 if (isset($v['value']['operator'])) {
1783 foreach ($where_clause[$k]['value']['args'] as $argK => $fieldDef) {
1784 $where_clause[$k]['value']['args'][$argK]['table'] = $this->quoteName($fieldDef['table']);
1785 $where_clause[$k]['value']['args'][$argK]['field'] = $this->quoteName($fieldDef['field']);
1786 }
1787 } else {
1788 // Detecting value type; list or plain:
1789 if (GeneralUtility::inList('NOTIN,IN', strtoupper(str_replace(array(' ', '
1790 ', '
1791 ', ' '), '', $where_clause[$k]['comparator'])))) {
1792 if (isset($v['subquery'])) {
1793 $where_clause[$k]['subquery'] = $this->quoteSELECTsubquery($v['subquery']);
1794 }
1795 } else {
1796 if (
1797 (!isset($where_clause[$k]['value'][1]) || $where_clause[$k]['value'][1] == '')
1798 && is_string($where_clause[$k]['value'][0]) && strstr($where_clause[$k]['value'][0], '.')
1799 ) {
1800 $where_clause[$k]['value'][0] = $this->quoteFieldNames($where_clause[$k]['value'][0]);
1801 }
1802 }
1803 }
1804 }
1805 }
1806 return $where_clause;
1807 }
1808
1809 /**
1810 * Quotes the field (and table) names within a group by clause with the quote
1811 * character suitable for the DB being used
1812 *
1813 * @param string $groupBy A group by clause that can by parsed by parseFieldList
1814 * @return string Usable group by clause with quoted field/table names
1815 */
1816 protected function quoteGroupBy($groupBy) {
1817 if ($groupBy === '') {
1818 return '';
1819 }
1820 if ($this->runningNative()) {
1821 return $groupBy;
1822 }
1823 $groupBy = $this->SQLparser->parseFieldList($groupBy);
1824 $groupBy = $this->_quoteGroupBy($groupBy);
1825 return $this->SQLparser->compileFieldList($groupBy);
1826 }
1827
1828 /**
1829 * Quotes field names in a SQL GROUP BY clause according to DB rules
1830 *
1831 * @param array $groupBy The parsed GROUP BY clause to quote
1832 * @return array
1833 * @see quoteGroupBy()
1834 */
1835 protected function _quoteGroupBy(array $groupBy) {
1836 foreach ($groupBy as $k => $v) {
1837 $groupBy[$k]['field'] = $this->quoteName($groupBy[$k]['field']);
1838 if ($groupBy[$k]['table'] != '') {
1839 $groupBy[$k]['table'] = $this->quoteName($groupBy[$k]['table']);
1840 }
1841 }
1842 return $groupBy;
1843 }
1844
1845 /**
1846 * Quotes the field (and table) names within an order by clause with the quote
1847 * character suitable for the DB being used
1848 *
1849 * @param string $orderBy An order by clause that can by parsed by parseFieldList
1850 * @return string Usable order by clause with quoted field/table names
1851 */
1852 protected function quoteOrderBy($orderBy) {
1853 if ($orderBy === '') {
1854 return '';
1855 }
1856 if ($this->runningNative()) {
1857 return $orderBy;
1858 }
1859 $orderBy = $this->SQLparser->parseFieldList($orderBy);
1860 $orderBy = $this->_quoteOrderBy($orderBy);
1861 return $this->SQLparser->compileFieldList($orderBy);
1862 }
1863
1864 /**
1865 * Quotes field names in a SQL ORDER BY clause according to DB rules
1866 *
1867 * @param array $orderBy The parsed ORDER BY clause to quote
1868 * @return array
1869 * @see quoteOrderBy()
1870 */
1871 protected function _quoteOrderBy(array $orderBy) {
1872 foreach ($orderBy as $k => $v) {
1873 if ($orderBy[$k]['table'] === '' && $v['field'] !== '' && ctype_digit($v['field'])) {
1874 continue;
1875 }
1876 $orderBy[$k]['field'] = $this->quoteName($orderBy[$k]['field']);
1877 if ($orderBy[$k]['table'] !== '') {
1878 $orderBy[$k]['table'] = $this->quoteName($orderBy[$k]['table']);
1879 }
1880 }
1881 return $orderBy;
1882 }
1883
1884 /**************************************
1885 *
1886 * Various helper functions
1887 *
1888 **************************************/
1889 /**
1890 * Escaping and quoting values for SQL statements.
1891 *
1892 * @param string $str Input string
1893 * @param string $table Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
1894 * @param bool $allowNull Whether to allow NULL values
1895 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
1896 * @see quoteStr()
1897 */
1898 public function fullQuoteStr($str, $table, $allowNull = FALSE) {
1899 if ($allowNull && $str === NULL) {
1900 return 'NULL';
1901 }
1902 return '\'' . $this->quoteStr($str, $table) . '\'';
1903 }
1904
1905 /**
1906 * Substitution for PHP function "addslashes()"
1907 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
1908 * NOTICE: You must wrap the output of this function in SINGLE QUOTES to be DBAL compatible. Unless you have to apply the single quotes yourself you should rather use ->fullQuoteStr()!
1909 *
1910 * @param string $str Input string
1911 * @param string $table Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
1912 * @throws \RuntimeException
1913 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
1914 * @see quoteStr()
1915 */
1916 public function quoteStr($str, $table) {
1917 $this->lastHandlerKey = $this->handler_getFromTableList($table);
1918 switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
1919 case 'native':
1920 if ($this->handlerInstance[$this->lastHandlerKey]['link']) {
1921 if (!$this->isConnected()) {
1922 $this->connectDB();
1923 }
1924 $str = $this->handlerInstance[$this->lastHandlerKey]['link']->real_escape_string($str);
1925 } else {
1926 // link may be null when unit testing DBAL
1927 $str = str_replace('\'', '\\\'', $str);
1928 }
1929 break;
1930 case 'adodb':
1931 if (!$this->isConnected()) {
1932 $this->connectDB();
1933 }
1934 $str = substr($this->handlerInstance[$this->lastHandlerKey]->qstr($str), 1, -1);
1935 break;
1936 case 'userdefined':
1937 $str = $this->handlerInstance[$this->lastHandlerKey]->quoteStr($str);
1938 break;
1939 default:
1940 throw new \RuntimeException('No handler found!!!', 1310027655);
1941 }
1942 return $str;
1943 }
1944
1945 /**
1946 * Quotes an object name (table name, field, ...)
1947 *
1948 * @param string $name Object's name
1949 * @param string $handlerKey Handler key
1950 * @param bool $useBackticks If method NameQuote() is not used, whether to use backticks instead of driver-specific quotes
1951 * @return string Properly-quoted object's name
1952 */
1953 public function quoteName($name, $handlerKey = NULL, $useBackticks = FALSE) {
1954 $handlerKey = $handlerKey ? $handlerKey : $this->lastHandlerKey;
1955 $useNameQuote = isset($this->handlerCfg[$handlerKey]['config']['useNameQuote']) ? $this->handlerCfg[$handlerKey]['config']['useNameQuote'] : FALSE;
1956 if ($useNameQuote) {
1957 // Sometimes DataDictionary is not properly instantiated
1958 if (!is_object($this->handlerInstance[$handlerKey]->DataDictionary)) {
1959 $this->handlerInstance[$handlerKey]->DataDictionary = NewDataDictionary($this->handlerInstance[$handlerKey]);
1960 }
1961 return $this->handlerInstance[$handlerKey]->DataDictionary->NameQuote($name);
1962 } else {
1963 $quote = $useBackticks ? '`' : $this->handlerInstance[$handlerKey]->nameQuote;
1964 return $quote . $name . $quote;
1965 }
1966 }
1967
1968 /**
1969 * Return MetaType for native field type (ADOdb only!)
1970 *
1971 * @param string $type Native type as reported by admin_get_fields()
1972 * @param string $table Table name for which query type string. Important for detection of DBMS handler of the query!
1973 * @param int $maxLength
1974 * @throws \RuntimeException
1975 * @return string Meta type (currently ADOdb syntax only, http://phplens.com/lens/adodb/docs-adodb.htm#metatype)
1976 */
1977 public function MetaType($type, $table, $maxLength = -1) {
1978 $this->lastHandlerKey = $this->handler_getFromTableList($table);
1979 $str = '';
1980 switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
1981 case 'native':
1982 $str = $type;
1983 break;
1984 case 'adodb':
1985 if (in_array($table, $this->cache_fieldType)) {
1986 $rs = $this->handlerInstance[$this->lastHandlerKey]->SelectLimit('SELECT * FROM ' . $this->quoteFromTables($table), 1);
1987 $str = $rs->MetaType($type, $maxLength);
1988 }
1989 break;
1990 case 'userdefined':
1991 $str = $this->handlerInstance[$this->lastHandlerKey]->MetaType($str, $table, $maxLength);
1992 break;
1993 default:
1994 throw new \RuntimeException('No handler found!!!', 1310027685);
1995 }
1996 return $str;
1997 }
1998
1999 /**
2000 * Return MetaType for native MySQL field type
2001 *
2002 * @param string $t native type as reported as in mysqldump files
2003 * @return string Meta type (currently ADOdb syntax only, http://phplens.com/lens/adodb/docs-adodb.htm#metatype)
2004 */
2005 public function MySQLMetaType($t) {
2006 switch (strtoupper($t)) {
2007 case 'STRING':
2008
2009 case 'CHAR':
2010
2011 case 'VARCHAR':
2012
2013 case 'TINYBLOB':
2014
2015 case 'TINYTEXT':
2016
2017 case 'ENUM':
2018
2019 case 'SET':
2020 return 'C';
2021 case 'TEXT':
2022
2023 case 'LONGTEXT':
2024
2025 case 'MEDIUMTEXT':
2026 return 'XL';
2027 case 'IMAGE':
2028
2029 case 'LONGBLOB':
2030
2031 case 'BLOB':
2032
2033 case 'MEDIUMBLOB':
2034 return 'B';
2035 case 'YEAR':
2036
2037 case 'DATE':
2038 return 'D';
2039 case 'TIME':
2040
2041 case 'DATETIME':
2042
2043 case 'TIMESTAMP':
2044 return 'T';
2045 case 'FLOAT':
2046
2047 case 'DOUBLE':
2048 return 'F';
2049 case 'INT':
2050
2051 case 'INTEGER':
2052
2053 case 'TINYINT':
2054
2055 case 'SMALLINT':
2056
2057 case 'MEDIUMINT':
2058
2059 case 'BIGINT':
2060 return 'I8';
2061 default:
2062 return 'N';
2063 }
2064 }
2065
2066 /**
2067 * Return actual MySQL type for meta field type
2068 *
2069 * @param string $meta Meta type (currenly ADOdb syntax only, http://phplens.com/lens/adodb/docs-adodb.htm#metatype)
2070 * @return string Native type as reported as in mysqldump files, uppercase
2071 */
2072 public function MySQLActualType($meta) {
2073 switch (strtoupper($meta)) {
2074 case 'C':
2075 return 'VARCHAR';
2076 case 'XL':
2077
2078 case 'X':
2079 return 'LONGTEXT';
2080 case 'C2':
2081 return 'VARCHAR';
2082 case 'X2':
2083 return 'LONGTEXT';
2084 case 'B':
2085 return 'LONGBLOB';
2086 case 'D':
2087 return 'DATE';
2088 case 'T':
2089 return 'DATETIME';
2090 case 'L':
2091 return 'TINYINT';
2092 case 'I':
2093
2094 case 'I1':
2095
2096 case 'I2':
2097
2098 case 'I4':
2099
2100 case 'I8':
2101 return 'BIGINT';
2102 case 'F':
2103 return 'DOUBLE';
2104 case 'N':
2105 return 'NUMERIC';
2106 default:
2107 return $meta;
2108 }
2109 }
2110
2111 /**************************************
2112 *
2113 * SQL wrapper functions (Overriding parent methods)
2114 * (For use in your applications)
2115 *
2116 **************************************/
2117 /**
2118 * Returns the error status on the last query() execution
2119 *
2120 * @return string MySQLi error string.
2121 */
2122 public function sql_error() {
2123 $output = '';
2124 switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
2125 case 'native':
2126 $output = $this->handlerInstance[$this->lastHandlerKey]['link']->error;
2127 break;
2128 case 'adodb':
2129 $output = $this->handlerInstance[$this->lastHandlerKey]->ErrorMsg();
2130 break;
2131 case 'userdefined':
2132 $output = $this->handlerInstance[$this->lastHandlerKey]->sql_error();
2133 break;
2134 }
2135 return $output;
2136 }
2137
2138 /**
2139 * Returns the error number on the last query() execution
2140 *
2141 * @return int MySQLi error number
2142 */
2143 public function sql_errno() {
2144 $output = 0;
2145 switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
2146 case 'native':
2147 $output = $this->handlerInstance[$this->lastHandlerKey]['link']->errno;
2148 break;
2149 case 'adodb':
2150 $output = $this->handlerInstance[$this->lastHandlerKey]->ErrorNo();
2151 break;
2152 case 'userdefined':
2153 $output = $this->handlerInstance[$this->lastHandlerKey]->sql_errno();
2154 break;
2155 }
2156 return $output;
2157 }
2158
2159 /**
2160 * Returns the number of selected rows.
2161 *
2162 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
2163 * @return int Number of resulting rows
2164 */
2165 public function sql_num_rows($res) {
2166 if ($res === FALSE) {
2167 return FALSE;
2168 }
2169 $handlerType = $this->determineHandlerType($res);
2170 $output = 0;
2171 switch ($handlerType) {
2172 case 'native':
2173 $output = $res->num_rows;
2174 break;
2175 case 'adodb':
2176 $output = method_exists($res, 'RecordCount') ? $res->RecordCount() : 0;
2177 break;
2178 case 'userdefined':
2179 $output = $res->sql_num_rows();
2180 break;
2181 }
2182 return $output;
2183 }
2184
2185 /**
2186 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
2187 * MySQLi fetch_assoc() wrapper function
2188 *
2189 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
2190 * @return array|boolean Associative array of result row.
2191 */
2192 public function sql_fetch_assoc($res) {
2193 $tableList = '';
2194 $output = FALSE;
2195 switch ($this->determineHandlerType($res)) {
2196 case 'native':
2197 $output = $res->fetch_assoc();
2198 $key = serialize($res);
2199 $tableList = $this->resourceIdToTableNameMap[$key];
2200 unset($this->resourceIdToTableNameMap[$key]);
2201 // Reading list of tables from SELECT query:
2202 break;
2203 case 'adodb':
2204 // Check if method exists for the current $res object.
2205 // If a table exists in TCA but not in the db, a error
2206 // occurred because $res is not a valid object.
2207 if (method_exists($res, 'FetchRow')) {
2208 $output = $res->FetchRow();
2209 $tableList = $res->TYPO3_DBAL_tableList;
2210 // Reading list of tables from SELECT query:
2211 // Removing all numeric/integer keys.
2212 // A workaround because in ADOdb we would need to know what we want before executing the query...
2213 // MSSQL does not support ADODB_FETCH_BOTH and always returns an assoc. array instead. So
2214 // we don't need to remove anything.
2215 if (is_array($output)) {
2216 if ($this->runningADOdbDriver('mssql')) {
2217 // MSSQL does not know such thing as an empty string. So it returns one space instead, which we must fix.
2218 foreach ($output as $key => $value) {
2219 if ($value === ' ') {
2220 $output[$key] = '';
2221 }
2222 }
2223 } else {
2224 foreach ($output as $key => $value) {
2225 if (is_integer($key)) {
2226 unset($output[$key]);
2227 }
2228 }
2229 }
2230 }
2231 }
2232 break;
2233 case 'userdefined':
2234 $output = $res->sql_fetch_assoc();
2235 $tableList = $res->TYPO3_DBAL_tableList;
2236 // Reading list of tables from SELECT query:
2237 break;
2238 }
2239 // Table/Fieldname mapping:
2240 if (is_array($output)) {
2241 if ($tables = $this->map_needMapping($tableList, TRUE)) {
2242 $output = $this->map_assocArray($output, $tables, 1);
2243 }
2244 }
2245 if ($output === NULL) {
2246 // Needed for compatibility
2247 $output = FALSE;
2248 }
2249 // Return result:
2250 return $output;
2251 }
2252
2253 /**
2254 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
2255 * The array contains the values in numerical indices.
2256 * MySQLi fetch_row() wrapper function
2257 *
2258 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
2259 * @return array|boolean Array with result rows.
2260 */
2261 public function sql_fetch_row($res) {
2262 $output = FALSE;
2263 switch ($this->determineHandlerType($res)) {
2264 case 'native':
2265 $output = $res->fetch_row();
2266 if ($output === NULL) {
2267 // Needed for compatibility
2268 $output = FALSE;
2269 }
2270 break;
2271 case 'adodb':
2272 // Check if method exists for the current $res object.
2273 // If a table exists in TCA but not in the db, a error
2274 // occurred because $res is not a valid object.
2275 if (method_exists($res, 'FetchRow')) {
2276 $output = $res->FetchRow();
2277 // Removing all assoc. keys.
2278 // A workaround because in ADOdb we would need to know what we want before executing the query...
2279 // MSSQL does not support ADODB_FETCH_BOTH and always returns an assoc. array instead. So
2280 // we need to convert resultset.
2281 if (is_array($output)) {
2282 $keyIndex = 0;
2283 foreach ($output as $key => $value) {
2284 unset($output[$key]);
2285 if (is_integer($key) || $this->runningADOdbDriver('mssql')) {
2286 $output[$keyIndex] = $value;
2287 if ($value === ' ') {
2288 // MSSQL does not know such thing as an empty string. So it returns one space instead, which we must fix.
2289 $output[$keyIndex] = '';
2290 }
2291 $keyIndex++;
2292 }
2293 }
2294 }
2295 }
2296 break;
2297 case 'userdefined':
2298 $output = $res->sql_fetch_row();
2299 break;
2300 }
2301 if ($output === NULL) {
2302 // Needed for compatibility
2303 $output = FALSE;
2304 }
2305 return $output;
2306 }
2307
2308 /**
2309 * Free result memory
2310 * free_result() wrapper function
2311 *
2312 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
2313 * @return bool Returns TRUE on success or FALSE on failure.
2314 */
2315 public function sql_free_result($res) {
2316 if ($res === FALSE) {
2317 return FALSE;
2318 }
2319 $output = TRUE;
2320 switch ($this->determineHandlerType($res)) {
2321 case 'native':
2322 $res->free();
2323 break;
2324 case 'adodb':
2325 if (method_exists($res, 'Close')) {
2326 $res->Close();
2327 unset($res);
2328 $output = TRUE;
2329 } else {
2330 $output = FALSE;
2331 }
2332 break;
2333 case 'userdefined':
2334 unset($res);
2335 break;
2336 }
2337 return $output;
2338 }
2339
2340 /**
2341 * Determine handler type by result set
2342 *
2343 * @param bool|\mysqli_result|object $res MySQLi result set / DBAL Object
2344 * @return bool|string
2345 */
2346 protected function determineHandlerType($res) {
2347 if (is_object($res) && !$res instanceof \mysqli_result) {
2348 $handlerType = $res->TYPO3_DBAL_handlerType;
2349 } elseif ($res instanceof \mysqli_result) {
2350 $handlerType = 'native';
2351 } else {
2352 $handlerType = FALSE;
2353 }
2354 return $handlerType;
2355 }
2356
2357 /**
2358 * Get the ID generated from the previous INSERT operation
2359 *
2360 * @return int The uid of the last inserted record.
2361 */
2362 public function sql_insert_id() {
2363 $output = 0;
2364 switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
2365 case 'native':
2366 $output = $this->handlerInstance[$this->lastHandlerKey]['link']->insert_id;
2367 break;
2368 case 'adodb':
2369 $output = $this->handlerInstance[$this->lastHandlerKey]->last_insert_id;
2370 break;
2371 case 'userdefined':
2372 $output = $this->handlerInstance[$this->lastHandlerKey]->sql_insert_id();
2373 break;
2374 }
2375 return $output;
2376 }
2377
2378 /**
2379 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
2380 *
2381 * @return int Number of rows affected by last query
2382 */
2383 public function sql_affected_rows() {
2384 $output = 0;
2385 switch ($this->handlerCfg[$this->lastHandlerKey]['type']) {
2386 case 'native':
2387 $output = $this->handlerInstance[$this->lastHandlerKey]['link']->affected_rows;
2388 break;
2389 case 'adodb':
2390 $output = $this->handlerInstance[$this->lastHandlerKey]->Affected_Rows();
2391 break;
2392 case 'userdefined':
2393 $output = $this->handlerInstance[$this->lastHandlerKey]->sql_affected_rows();
2394 break;
2395 }
2396 return $output;
2397 }
2398
2399 /**
2400 * Move internal result pointer
2401 *
2402 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
2403 * @param int $seek Seek result number.
2404 * @return bool Returns TRUE on success or FALSE on failure.
2405 */
2406 public function sql_data_seek($res, $seek) {
2407 $output = TRUE;
2408 switch ($this->determineHandlerType($res)) {
2409 case 'native':
2410 $output = $res->data_seek($seek);
2411 break;
2412 case 'adodb':
2413 $output = $res->Move($seek);
2414 break;
2415 case 'userdefined':
2416 $output = $res->sql_data_seek($seek);
2417 break;
2418 }
2419 return $output;
2420 }
2421
2422 /**
2423 * Get the type of the specified field in a result
2424 *
2425 * If the first parameter is a string, it is used as table name for the lookup.
2426 *
2427 * @param string $table MySQL result pointer (of SELECT query) / DBAL object / table name
2428 * @param int $field Field index. In case of ADOdb a string (field name!)
2429 * @return string Returns the type of the specified field index
2430 */
2431 public function sql_field_metatype($table, $field) {
2432 // If $table and/or $field are mapped, use the original names instead
2433 foreach ($this->mapping as $tableName => $tableMapInfo) {
2434 if (isset($tableMapInfo['mapFieldNames'])) {
2435 foreach ($tableMapInfo['mapFieldNames'] as $fieldName => $fieldMapInfo) {
2436 if ($fieldMapInfo === $field) {
2437 // Field name is mapped => use original name
2438 $field = $fieldName;
2439 }
2440 }
2441 }
2442 }
2443 return $this->cache_fieldType[$table][$field]['metaType'];
2444 }
2445
2446 /**
2447 * Get the type of the specified field in a result
2448 * mysql_field_type() wrapper function
2449 *
2450 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
2451 * @param int $pointer Field index.
2452 * @return string Returns the name of the specified field index, or FALSE on error
2453 */
2454 public function sql_field_type($res, $pointer) {
2455 if ($res === NULL) {
2456 debug(array('no res in sql_field_type!'));
2457 return 'text';
2458 } elseif (is_string($res)) {
2459 if ($res === 'tx_dbal_debuglog') {
2460 return 'text';
2461 }
2462 $handlerType = 'adodb';
2463 } else {
2464 $handlerType = $this->determineHandlerType($res);
2465 }
2466 $output = '';
2467 switch ($handlerType) {
2468 case 'native':
2469 $metaInfo = $res->fetch_field_direct($pointer);
2470 if ($metaInfo) {
2471 $output = $this->mysqlDataTypeMapping[$metaInfo->type];
2472 } else {
2473 $output = '';
2474 }
2475 break;
2476 case 'adodb':
2477 if (is_string($pointer)) {
2478 $output = $this->cache_fieldType[$res][$pointer]['type'];
2479 }
2480 break;
2481 case 'userdefined':
2482 $output = $res->sql_field_type($pointer);
2483 break;
2484 }
2485 return $output;
2486 }
2487
2488 /**********
2489 *
2490 * Legacy functions, bound to _DEFAULT handler. (Overriding parent methods)
2491 * Deprecated or still experimental.
2492 *
2493 **********/
2494 /**
2495 * Executes query
2496 *
2497 * EXPERIMENTAL - This method will make its best to handle the query correctly
2498 * but if it cannot, it will simply pass the query to DEFAULT handler.
2499 *
2500 * You should use exec_* function from this class instead!
2501 * If you don't, anything that does not use the _DEFAULT handler will probably break!
2502 *
2503 * MySQLi query() wrapper function
2504 * Beware: Use of this method should be avoided as it is experimentally supported by DBAL. You should consider
2505 * using exec_SELECTquery() and similar methods instead.
2506 *
2507 * @param string $query Query to execute
2508 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
2509 */
2510 public function sql_query($query) {
2511 $globalConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['dbal']);
2512 if ($globalConfig['sql_query.']['passthrough']) {
2513 return parent::sql_query($query);
2514 }
2515 // This method is heavily used by Extbase, try to handle it with DBAL-native methods
2516 $queryParts = $this->SQLparser->parseSQL($query);
2517 if (is_array($queryParts) && GeneralUtility::inList('SELECT,UPDATE,INSERT,DELETE', $queryParts['type'])) {
2518 return $this->exec_query($queryParts);
2519 }
2520 $sqlResult = NULL;
2521 switch ($this->handlerCfg['_DEFAULT']['type']) {
2522 case 'native':
2523 if (!$this->isConnected()) {
2524 $this->connectDB();
2525 }
2526 $sqlResult = $this->handlerInstance['_DEFAULT']['link']->query($query);
2527 break;
2528 case 'adodb':
2529 $sqlResult = $this->handlerInstance['_DEFAULT']->Execute($query);
2530 $sqlResult->TYPO3_DBAL_handlerType = 'adodb';
2531 break;
2532 case 'userdefined':
2533 $sqlResult = $this->handlerInstance['_DEFAULT']->sql_query($query);
2534 $sqlResult->TYPO3_DBAL_handlerType = 'userdefined';
2535 break;
2536 }
2537 $this->lastHandlerKey = '_DEFAULT';
2538 if ($this->printErrors && $this->sql_error()) {
2539 debug(array($this->lastQuery, $this->sql_error()));
2540 }
2541 return $sqlResult;
2542 }
2543
2544 /**
2545 * Open a (persistent) connection to a MySQL server
2546 *
2547 * @return bool|void
2548 */
2549 public function sql_pconnect() {
2550 return $this->handler_init('_DEFAULT');
2551 }
2552
2553 /**
2554 * Select a SQL database
2555 *
2556 * @return bool Returns TRUE on success or FALSE on failure.
2557 */
2558 public function sql_select_db() {
2559 $databaseName = $this->handlerCfg[$this->lastHandlerKey]['config']['database'];
2560 $ret = TRUE;
2561 if ((string)$this->handlerCfg[$this->lastHandlerKey]['type'] === 'native') {
2562 $ret = $this->handlerInstance[$this->lastHandlerKey]['link']->select_db($databaseName);
2563 }
2564 if (!$ret) {
2565 GeneralUtility::sysLog(
2566 'Could not select MySQL database ' . $databaseName . ': ' . $this->sql_error(),
2567 'Core',
2568 GeneralUtility::SYSLOG_SEVERITY_FATAL
2569 );
2570 }
2571 return $ret;
2572 }
2573
2574 /**************************************
2575 *
2576 * SQL admin functions
2577 * (For use in the Install Tool and Extension Manager)
2578 *
2579 **************************************/
2580 /**
2581 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
2582 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
2583 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
2584 * Use in Install Tool only!
2585 *
2586 * @return array Each entry represents a database name
2587 * @throws \RuntimeException
2588 */
2589 public function admin_get_dbs() {
2590 $dbArr = array();
2591 $this->lastHandlerKey = '_DEFAULT';
2592 switch ($this->handlerCfg['_DEFAULT']['type']) {
2593 case 'native':
2594 /** @var \mysqli_result $db_list */
2595 $db_list = $this->query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA");
2596 $oldDb = $this->handlerCfg[$this->lastHandlerKey]['config']['database'];
2597 while ($row = $db_list->fetch_object()) {
2598 $this->handlerCfg[$this->lastHandlerKey]['config']['database'] = $row->SCHEMA_NAME;
2599 if ($this->sql_select_db()) {
2600 $dbArr[] = $row->SCHEMA_NAME;
2601 }
2602 }
2603 $this->handlerCfg[$this->lastHandlerKey]['config']['database'] = $oldDb;
2604 $db_list->free();
2605 break;
2606 case 'adodb':
2607 // check needed for install tool - otherwise it will just die because the call to
2608 // MetaDatabases is done on a stdClass instance
2609 if (method_exists($this->handlerInstance['_DEFAULT'], 'MetaDatabases')) {
2610 $sqlDBs = $this->handlerInstance['_DEFAULT']->MetaDatabases();
2611 if (is_array($sqlDBs)) {
2612 foreach ($sqlDBs as $k => $theDB) {
2613 $dbArr[] = $theDB;
2614 }
2615 }
2616 }
2617 break;
2618 case 'userdefined':
2619 $dbArr = $this->handlerInstance['_DEFAULT']->admin_get_tables();
2620 break;
2621 }
2622 return $dbArr;
2623 }
2624
2625 /**
2626 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
2627 * In a DBAL this method should 1) look up all tables from the DBMS of
2628 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
2629 *
2630 * @return array Array with tablenames as key and arrays with status information as value
2631 */
2632 public function admin_get_tables() {
2633 $whichTables = array();
2634 // Getting real list of tables:
2635 switch ($this->handlerCfg['_DEFAULT']['type']) {
2636 case 'native':
2637 $tables_result = $this->query('SHOW TABLE STATUS FROM `' . TYPO3_db . '`');
2638 if (!$this->sql_error()) {
2639 while ($theTable = $this->sql_fetch_assoc($tables_result)) {
2640 $whichTables[$theTable['Name']] = $theTable;
2641 }
2642 }
2643 $tables_result->free();
2644 break;
2645 case 'adodb':
2646 // check needed for install tool - otherwise it will just die because the call to
2647 // MetaTables is done on a stdClass instance
2648 if (method_exists($this->handlerInstance['_DEFAULT'], 'MetaTables')) {
2649 $sqlTables = $this->handlerInstance['_DEFAULT']->MetaTables('TABLES');
2650 foreach ($sqlTables as $k => $theTable) {
2651 if (preg_match('/BIN\\$/', $theTable)) {
2652 // Skip tables from the Oracle 10 Recycle Bin
2653 continue;
2654 }
2655 $whichTables[$theTable] = $theTable;
2656 }
2657 }
2658 break;
2659 case 'userdefined':
2660 $whichTables = $this->handlerInstance['_DEFAULT']->admin_get_tables();
2661 break;
2662 }
2663 // Check mapping:
2664 if (is_array($this->mapping) && count($this->mapping)) {
2665 // Mapping table names in reverse, first getting list of real table names:
2666 $tMap = array();
2667 foreach ($this->mapping as $tN => $tMapInfo) {
2668 if (isset($tMapInfo['mapTableName'])) {
2669 $tMap[$tMapInfo['mapTableName']] = $tN;
2670 }
2671 }
2672 // Do mapping:
2673 $newList = array();
2674 foreach ($whichTables as $tN => $tDefinition) {
2675 if (isset($tMap[$tN])) {
2676 $tN = $tMap[$tN];
2677 }
2678 $newList[$tN] = $tDefinition;
2679 }
2680 $whichTables = $newList;
2681 }
2682 // Adding tables configured to reside in other DBMS (handler by other handlers than the default):
2683 if (is_array($this->table2handlerKeys)) {
2684 foreach ($this->table2handlerKeys as $key => $handlerKey) {
2685 $whichTables[$key] = $key;
2686 }
2687 }
2688 return $whichTables;
2689 }
2690
2691 /**
2692 * Returns information about each field in the $table (quering the DBMS)
2693 * In a DBAL this should look up the right handler for the table and return compatible information
2694 * This function is important not only for the Install Tool but probably for
2695 * DBALs as well since they might need to look up table specific information
2696 * in order to construct correct queries. In such cases this information should
2697 * probably be cached for quick delivery.
2698 *
2699 * @param string $tableName Table name
2700 * @return array Field information in an associative array with fieldname => field row
2701 */
2702 public function admin_get_fields($tableName) {
2703 $output = array();
2704 // Do field mapping if needed:
2705 $ORIG_tableName = $tableName;
2706 if ($tableArray = $this->map_needMapping($tableName)) {
2707 // Table name:
2708 if ($this->mapping[$tableName]['mapTableName']) {
2709 $tableName = $this->mapping[$tableName]['mapTableName'];
2710 }
2711 }
2712 // Find columns
2713 $this->lastHandlerKey = $this->handler_getFromTableList($tableName);
2714 switch ((string)$this->handlerCfg[$this->lastHandlerKey]['type']) {
2715 case 'native':
2716 /** @var \mysqli_result $columns_res */
2717 $columns_res = $this->query('SHOW columns FROM ' . $tableName);
2718 while ($fieldRow = $columns_res->fetch_assoc()) {
2719 $output[$fieldRow['Field']] = $fieldRow;
2720 }
2721 $columns_res->free();
2722 break;
2723 case 'adodb':
2724 $fieldRows = $this->handlerInstance[$this->lastHandlerKey]->MetaColumns($tableName, FALSE);
2725 if (is_array($fieldRows)) {
2726 foreach ($fieldRows as $k => $fieldRow) {
2727 settype($fieldRow, 'array');
2728 $fieldRow['Field'] = $fieldRow['name'];
2729 $ntype = $this->MySQLActualType($this->MetaType($fieldRow['type'], $tableName));
2730 $ntype .= $fieldRow['max_length'] != -1 ? ($ntype == 'INT' ? '(11)' : '(' . $fieldRow['max_length'] . ')') : '';
2731 $fieldRow['Type'] = strtolower($ntype);
2732 $fieldRow['Null'] = '';
2733 $fieldRow['Key'] = '';
2734 $fieldRow['Default'] = $fieldRow['default_value'];
2735 $fieldRow['Extra'] = '';
2736 $output[$fieldRow['name']] = $fieldRow;
2737 }
2738 }
2739 break;
2740 case 'userdefined':
2741 $output = $this->handlerInstance[$this->lastHandlerKey]->admin_get_fields($tableName);
2742 break;
2743 }
2744 // mapping should be done:
2745 if (is_array