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