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