[TASK] DBAL: Log error if query fails
[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 = 't3lib_db_fieldInfo';
148
149 /**
150 * SQL parser
151 *
152 * @var \TYPO3\CMS\Core\Database\SqlParser
153 * @todo Define visibility
154 */
155 public $SQLparser;
156
157 /**
158 * @var \TYPO3\CMS\Install\Service\SqlSchemaMigrationService
159 */
160 protected $installerSql = NULL;
161
162 /**
163 * Cache for queries
164 *
165 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
166 */
167 protected $queryCache;
168
169 /**
170 * mysql_field_type compatibility map
171 * taken from: http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php#89117
172 * Constant numbers see http://php.net/manual/en/mysqli.constants.php
173 *
174 * @var array
175 */
176 protected $mysqlDataTypeMapping = array(
177 MYSQLI_TYPE_TINY => 'tinyint',
178 MYSQLI_TYPE_CHAR => 'tinyint',
179 MYSQLI_TYPE_SHORT => 'smallint',
180 MYSQLI_TYPE_LONG => 'int',
181 MYSQLI_TYPE_FLOAT => 'float',
182 MYSQLI_TYPE_DOUBLE => 'double',
183 MYSQLI_TYPE_TIMESTAMP => 'timestamp',
184 MYSQLI_TYPE_LONGLONG => 'bigint',
185 MYSQLI_TYPE_INT24 => 'mediumint',
186 MYSQLI_TYPE_DATE => 'date',
187 MYSQLI_TYPE_NEWDATE => 'date',
188 MYSQLI_TYPE_TIME => 'time',
189 MYSQLI_TYPE_DATETIME => 'datetime',
190 MYSQLI_TYPE_YEAR => 'year',
191 MYSQLI_TYPE_BIT => 'bit',
192 MYSQLI_TYPE_INTERVAL => 'interval',
193 MYSQLI_TYPE_ENUM => 'enum',
194 MYSQLI_TYPE_SET => 'set',
195 MYSQLI_TYPE_TINY_BLOB => 'blob',
196 MYSQLI_TYPE_MEDIUM_BLOB => 'blob',
197 MYSQLI_TYPE_LONG_BLOB => 'blob',
198 MYSQLI_TYPE_BLOB => 'blob',
199 MYSQLI_TYPE_VAR_STRING => 'varchar',
200 MYSQLI_TYPE_STRING => 'char',
201 MYSQLI_TYPE_DECIMAL => 'decimal',
202 MYSQLI_TYPE_NEWDECIMAL => 'decimal',
203 MYSQLI_TYPE_GEOMETRY => 'geometry'
204 );
205
206 /**
207 * @var Specifics\AbstractSpecifics
208 */
209 protected $dbmsSpecifics;
210
211 /**
212 * Constructor.
213 * Creates SQL parser object and imports configuration from $TYPO3_CONF_VARS['EXTCONF']['dbal']
214 */
215 public function __construct() {
216 // Set SQL parser object for internal use:
217 $this->SQLparser = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\SqlParser', $this);
218 $this->installerSql = GeneralUtility::makeInstance('TYPO3\\CMS\\Install\\Service\\SqlSchemaMigrationService');
219 $this->queryCache = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('dbal');
220 // Set internal variables with configuration:
221 $this->conf = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal'];
222 }
223
224 /**
225 * Initialize the database connection
226 *
227 * @return void
228 */
229 public function initialize() {
230 // Set outside configuration:
231 if (isset($this->conf['mapping'])) {
232 $this->mapping = $this->conf['mapping'];
233 }
234 if (isset($this->conf['table2handlerKeys'])) {
235 $this->table2handlerKeys = $this->conf['table2handlerKeys'];
236 }
237 if (isset($this->conf['handlerCfg'])) {
238 $this->handlerCfg = $this->conf['handlerCfg'];
239
240 if (isset($this->handlerCfg['_DEFAULT']['config']['driver'])) {
241 // load DBMS specifics
242 $driver = $this->handlerCfg['_DEFAULT']['config']['driver'];
243 $className = 'TYPO3\\CMS\\Dbal\\Database\\Specifics\\' . ucfirst(strtolower($driver));
244 if (class_exists($className)) {
245 if (!is_subclass_of($className, 'TYPO3\\CMS\\Dbal\\Database\\Specifics\\AbstractSpecifics')) {
246 throw new \InvalidArgumentException($className . ' must inherit from \\TYPO3\\CMS\\Dbal\\Database\\Specifics\\AbstractSpecifics', 1416919866);
247 }
248 $this->dbmsSpecifics = GeneralUtility::makeInstance($className);
249 }
250 }
251 }
252 $this->cacheFieldInfo();
253 // Debugging settings:
254 $this->printErrors = !empty($this->conf['debugOptions']['printErrors']);
255 $this->debug = !empty($this->conf['debugOptions']['enabled']);
256 }
257
258 /**
259 * Gets the DBMS specifics object
260 *
261 * @return Specifics\AbstractSpecifics
262 */
263 public function getSpecifics() {
264 return $this->dbmsSpecifics;
265 }
266
267 /**
268 * @return \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend
269 */
270 protected function getFieldInfoCache() {
271 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('cache_phpcode');
272 }
273
274 /**
275 * Clears the cached field information file.
276 *
277 * @return void
278 */
279 public function clearCachedFieldInfo() {
280 $this->getFieldInfoCache()->flushByTag('t3lib_db');
281 }
282
283 /**
284 * Caches the field information.
285 *
286 * @return void
287 */
288 public function cacheFieldInfo() {
289 $phpCodeCache = $this->getFieldInfoCache();
290 // try to fetch cache
291 // cache is flushed when admin_query() is called
292 if ($phpCodeCache->has($this->cacheIdentifier)) {
293 $fieldInformation = $phpCodeCache->requireOnce($this->cacheIdentifier);
294 $this->cache_autoIncFields = $fieldInformation['incFields'];
295 $this->cache_fieldType = $fieldInformation['fieldTypes'];
296 $this->cache_primaryKeys = $fieldInformation['primaryKeys'];
297 } else {
298 $this->analyzeCachingTables();
299 $this->analyzeExtensionTables();
300 $completeFieldInformation = $this->getCompleteFieldInformation();
301 $phpCodeCache->set($this->cacheIdentifier, $this->getCacheableString($completeFieldInformation), array('t3lib_db'));
302 }
303 }
304
305 /**
306 * Loop through caching configurations
307 * to find the usage of database backends and
308 * parse and analyze table definitions
309 *
310 * @return void
311 */
312 protected function analyzeCachingTables() {
313 $this->parseAndAnalyzeSql(\TYPO3\CMS\Core\Cache\Cache::getDatabaseTableDefinitions());
314 }
315
316 /**
317 * Loop over all installed extensions
318 * parse and analyze table definitions (if any)
319 *
320 * @return void
321 */
322 protected function analyzeExtensionTables() {
323 if (isset($GLOBALS['TYPO3_LOADED_EXT']) && (is_array($GLOBALS['TYPO3_LOADED_EXT']) || $GLOBALS['TYPO3_LOADED_EXT'] instanceof \ArrayAccess)) {
324 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extensionConfiguration) {
325 $isArray = (is_array($extensionConfiguration) || $extensionConfiguration instanceof \ArrayAccess);
326 if (!$isArray || ($isArray && !isset($extensionConfiguration['ext_tables.sql']))) {
327 continue;
328 }
329 $extensionsSql = file_get_contents($extensionConfiguration['ext_tables.sql']);
330 $this->parseAndAnalyzeSql($extensionsSql);
331 }
332 }
333 }
334
335 /**
336 * Parse and analyze given SQL string
337 *
338 * @param $sql
339 * @return void
340 */
341 protected function parseAndAnalyzeSql($sql) {
342 $parsedSql = $this->installerSql->getFieldDefinitions_fileContent($sql);
343 $this->analyzeFields($parsedSql);
344 }
345
346 /**
347 * Returns all field information gathered during
348 * analyzing all tables and fields.
349 *
350 * @return array
351 */
352 protected function getCompleteFieldInformation() {
353 return array('incFields' => $this->cache_autoIncFields, 'fieldTypes' => $this->cache_fieldType, 'primaryKeys' => $this->cache_primaryKeys);
354 }
355
356 /**
357 * Creates a PHP code representation of the array that can be cached
358 * in the PHP code cache.
359 *
360 * @param array $fieldInformation
361 * @return string
362 */
363 protected function getCacheableString(array $fieldInformation) {
364 $cacheString = 'return ';
365 $cacheString .= var_export($fieldInformation, TRUE);
366 $cacheString .= ';';
367 return $cacheString;
368 }
369
370 /**
371 * Analyzes fields and adds the extracted information to the field type, auto increment and primary key info caches.
372 *
373 * @param array $parsedExtSQL The output produced by \TYPO3\CMS\Install\Service\SqlSchemaMigrationService->getFieldDefinitions_fileContent()
374 * @return void
375 */
376 protected function analyzeFields($parsedExtSQL) {
377 foreach ($parsedExtSQL as $table => $tdef) {
378 // check if table is mapped
379 if (isset($this->mapping[$table])) {
380 $table = $this->mapping[$table]['mapTableName'];
381 }
382 if (is_array($tdef['fields'])) {
383 foreach ($tdef['fields'] as $field => $fdefString) {
384 $fdef = $this->SQLparser->parseFieldDef($fdefString);
385 $fieldType = isset($fdef['fieldType']) ? $fdef['fieldType'] : '';
386 $this->cache_fieldType[$table][$field]['type'] = $fieldType;
387 $this->cache_fieldType[$table][$field]['metaType'] = $this->MySQLMetaType($fieldType);
388 $this->cache_fieldType[$table][$field]['notnull'] = isset($fdef['featureIndex']['NOTNULL']) && !$this->SQLparser->checkEmptyDefaultValue($fdef['featureIndex']) ? 1 : 0;
389 if (isset($fdef['featureIndex']['DEFAULT'])) {
390 $default = $fdef['featureIndex']['DEFAULT']['value'][0];
391 if (isset($fdef['featureIndex']['DEFAULT']['value'][1])) {
392 $default = $fdef['featureIndex']['DEFAULT']['value'][1] . $default . $fdef['featureIndex']['DEFAULT']['value'][1];
393 }
394 $this->cache_fieldType[$table][$field]['default'] = $default;
395 }
396 if (isset($fdef['featureIndex']['AUTO_INCREMENT'])) {
397 $this->cache_autoIncFields[$table] = $field;
398 }
399 if (isset($tdef['keys']['PRIMARY'])) {
400 $this->cache_primaryKeys[$table] = substr($tdef['keys']['PRIMARY'], 13, -1);
401 }
402 }
403 }
404 }
405 }
406
407 /**
408 * This function builds all definitions for mapped tables and fields
409 *
410 * @param array $fieldInfo
411 * @return array
412 *
413 * @see cacheFieldInfo()
414 */
415 protected function mapCachedFieldInfo(array $fieldInfo) {
416 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['mapping'])) {
417 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']['mapping'] as $mappedTable => $mappedConf) {
418 if (array_key_exists($mappedTable, $fieldInfo['incFields'])) {
419 $mappedTableAlias = $mappedConf['mapTableName'];
420 if (isset($mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]])) {
421 $fieldInfo['incFields'][$mappedTableAlias] = $mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]];
422 } else {
423 $fieldInfo['incFields'][$mappedTableAlias] = $fieldInfo['incFields'][$mappedTable];
424 }
425 }
426 if (array_key_exists($mappedTable, $fieldInfo['fieldTypes'])) {
427 $tempMappedFieldConf = array();
428 foreach ($fieldInfo['fieldTypes'][$mappedTable] as $field => $fieldConf) {
429 $tempMappedFieldConf[$mappedConf['mapFieldNames'][$field]] = $fieldConf;
430 }
431 $fieldInfo['fieldTypes'][$mappedConf['mapTableName']] = $tempMappedFieldConf;
432 }
433 if (array_key_exists($mappedTable, $fieldInfo['primaryKeys'])) {
434 $mappedTableAlias = $mappedConf['mapTableName'];
435 if (isset($mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]])) {
436 $fieldInfo['primaryKeys'][$mappedTableAlias] = $mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]];
437 } else {
438 $fieldInfo['primaryKeys'][$mappedTableAlias] = $fieldInfo['primaryKeys'][$mappedTable];
439 }
440 }
441 }
442 }
443 return $fieldInfo;
444 }
445
446 /************************************
447 *
448 * Query Building (Overriding parent methods)
449 * These functions are extending counterparts in the parent class.
450 *
451 **************************************/
452 /*
453 * From the ADOdb documentation, this is what we do (_Execute for SELECT, _query for the other actions)Execute()
454 * is the default way to run queries. You can use the low-level functions _Execute() and _query() to reduce query overhead.
455 * Both these functions share the same parameters as Execute().If you do not have any bind parameters or your database
456 * supports binding (without emulation), then you can call _Execute() directly.
457 * Calling this function bypasses bind emulation. Debugging is still supported in _Execute().If you do not require
458 * debugging facilities nor emulated binding, and do not require a recordset to be returned, then you can call _query.
459 * This is great for inserts, updates and deletes. Calling this function bypasses emulated binding, debugging,
460 * and recordset handling. Either the resultid, TRUE or FALSE are returned by _query().
461 */
462
463 /**
464 * Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
465 * Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
466 *
467 * @param string $table Table name
468 * @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.
469 * @param bool $no_quote_fields See fullQuoteArray()
470 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
471 * @throws \RuntimeException
472 */
473 public function exec_INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
474 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
475 // Do field mapping if needed:
476 $ORIG_tableName = $table;
477 if ($tableArray = $this->map_needMapping($table)) {
478 // Field mapping of array:
479 $fields_values = $this->map_assocArray($fields_values, $tableArray);
480 // Table name:
481 if ($this->mapping[$table]['mapTableName']) {
482 $table = $this->mapping[$table]['mapTableName'];
483 }
484 }
485 // Select API:
486 $this->lastHandlerKey = $this->handler_getFromTableList($table);
487 $hType = (string)$this->handlerCfg[$this->lastHandlerKey]['type'];
488 $sqlResult = NULL;
489 switch ($hType) {
490 case 'native':
491 $this->lastQuery = $this->INSERTquery($table, $fields_values, $no_quote_fields);
492 if (is_string($this->lastQuery)) {
493 $sqlResult = $this->query($this->lastQuery);
494 } else {
495 $sqlResult = $this->query($this->lastQuery[0]);
496 $new_id = $this->sql_insert_id();
497 $where = $this->cache_autoIncFields[$table] . '=' . $new_id;
498 foreach ($this->lastQuery[1] as $field => $content) {
499 $stmt = 'UPDATE ' . $this->quoteFromTables($table) . ' SET ' . $this->quoteFromTables($field) . '=' . $this->fullQuoteStr($content, $table) . ' WHERE ' . $this->quoteWhereClause($where);
500 $this->query($stmt);
501 }
502 }
503 break;
504 case 'adodb':
505 // auto generate ID for auto_increment fields if not present (static import needs this!)
506 // should we check the table name here (static_*)?
507 if (isset($this->cache_autoIncFields[$table])) {
508 if (isset($fields_values[$this->cache_autoIncFields[$table]])) {
509 $new_id = $fields_values[$this->cache_autoIncFields[$table]];
510 if ($table != 'tx_dbal_debuglog') {
511 $this->handlerInstance[$this->lastHandlerKey]->last_insert_id = $new_id;
512 }
513 } else {
514 $new_id = $this->handlerInstance[$this->lastHandlerKey]->GenID($table . '_' . $this->cache_autoIncFields[$table], $this->handlerInstance[$this->lastHandlerKey]->sequenceStart);
515 $fields_values[$this->cache_autoIncFields[$table]] = $new_id;
516 if ($table != 'tx_dbal_debuglog') {
517 $this->handlerInstance[$this->lastHandlerKey]->last_insert_id = $new_id;
518 }
519 }
520 }
521 $this->lastQuery = $this->INSERTquery($table, $fields_values, $no_quote_fields);
522 if (is_string($this->lastQuery)) {
523 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
524 } else {
525 $this->handlerInstance[$this->lastHandlerKey]->StartTrans();
526 if (strlen($this->lastQuery[0])) {
527 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery[0], FALSE);
528 }
529 if (is_array($this->lastQuery[1])) {
530 foreach ($this->lastQuery[1] as $field => $content) {
531 if (empty($content)) {
532 continue;
533 }
534 if (isset($this->cache_autoIncFields[$table]) && isset($new_id)) {
535 $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($this->cache_autoIncFields[$table] . '=' . $new_id));
536 } elseif (isset($this->cache_primaryKeys[$table])) {
537 $where = '';
538 $pks = explode(',', $this->cache_primaryKeys[$table]);
539 foreach ($pks as $pk) {
540 if (isset($fields_values[$pk])) {
541 $where .= $pk . '=' . $this->fullQuoteStr($fields_values[$pk], $table) . ' AND ';
542 }
543 }
544 $where = $this->quoteWhereClause($where . '1=1');
545 $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table), $field, $content, $where);
546 } else {
547 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans(FALSE);
548 // Should never ever happen
549 throw new \RuntimeException('Could not update BLOB >>>> no WHERE clause found!', 1321860519);
550 }
551 }
552 }
553 if (is_array($this->lastQuery[2])) {
554 foreach ($this->lastQuery[2] as $field => $content) {
555 if (empty($content)) {
556 continue;
557 }
558 if (isset($this->cache_autoIncFields[$table]) && isset($new_id)) {
559 $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($this->cache_autoIncFields[$table] . '=' . $new_id));
560 } elseif (isset($this->cache_primaryKeys[$table])) {
561 $where = '';
562 $pks = explode(',', $this->cache_primaryKeys[$table]);
563 foreach ($pks as $pk) {
564 if (isset($fields_values[$pk])) {
565 $where .= $pk . '=' . $this->fullQuoteStr($fields_values[$pk], $table) . ' AND ';
566 }
567 }
568 $where = $this->quoteWhereClause($where . '1=1');
569 $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table), $field, $content, $where);
570 } else {
571 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans(FALSE);
572 // Should never ever happen
573 throw new \RuntimeException('Could not update CLOB >>>> no WHERE clause found!', 1310027337);
574 }
575 }
576 }
577 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans();
578 }
579 break;
580 case 'userdefined':
581 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_INSERTquery($table, $fields_values, $no_quote_fields);
582 break;
583 }
584 if ($this->printErrors && $this->sql_error()) {
585 debug(array($this->lastQuery, $this->sql_error()));
586 }
587 if ($this->debug) {
588 $this->debugHandler('exec_INSERTquery', GeneralUtility::milliseconds() - $pt, array(
589 'handlerType' => $hType,
590 'args' => array($table, $fields_values),
591 'ORIG_tablename' => $ORIG_tableName
592 ));
593 }
594 foreach ($this->postProcessHookObjects as $hookObject) {
595 $hookObject->exec_INSERTquery_postProcessAction($table, $fields_values, $no_quote_fields, $this);
596 }
597 // Return output:
598 return $sqlResult;
599 }
600
601 /**
602 * Creates and executes an INSERT SQL-statement for $table with multiple rows.
603 *
604 * @param string $table Table name
605 * @param array $fields Field names
606 * @param array $rows Table rows. Each row should be an array with field values mapping to $fields
607 * @param bool $no_quote_fields See fullQuoteArray()
608 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
609 */
610 public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
611 $res = NULL;
612 if ((string)$this->handlerCfg[$this->lastHandlerKey]['type'] === 'native') {
613 $this->lastHandlerKey = $this->handler_getFromTableList($table);
614 $res = $this->query(parent::INSERTmultipleRows($table, $fields, $rows, $no_quote_fields));
615 } else {
616 foreach ($rows as $row) {
617 $fields_values = array();
618 foreach ($fields as $key => $value) {
619 $fields_values[$value] = $row[$key];
620 }
621 $res = $this->exec_INSERTquery($table, $fields_values, $no_quote_fields);
622 }
623 }
624 foreach ($this->postProcessHookObjects as $hookObject) {
625 $hookObject->exec_INSERTmultipleRows_postProcessAction($table, $fields, $rows, $no_quote_fields, $this);
626 }
627 return $res;
628 }
629
630 /**
631 * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
632 * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
633 *
634 * @param string $table Database tablename
635 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
636 * @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.
637 * @param bool $no_quote_fields See fullQuoteArray()
638 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
639 */
640 public function exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
641 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
642 // Do table/field mapping:
643 $ORIG_tableName = $table;
644 if ($tableArray = $this->map_needMapping($table)) {
645 // Field mapping of array:
646 $fields_values = $this->map_assocArray($fields_values, $tableArray);
647 // Where clause table and field mapping:
648 $whereParts = $this->SQLparser->parseWhereClause($where);
649 $this->map_sqlParts($whereParts, $tableArray[0]['table']);
650 $where = $this->SQLparser->compileWhereClause($whereParts, FALSE);
651 // Table name:
652 if ($this->mapping[$table]['mapTableName']) {
653 $table = $this->mapping[$table]['mapTableName'];
654 }
655 }
656 // Select API
657 $this->lastHandlerKey = $this->handler_getFromTableList($table);
658 $hType = (string) $this->handlerCfg[$this->lastHandlerKey]['type'];
659 $sqlResult = NULL;
660 switch ($hType) {
661 case 'native':
662 $this->lastQuery = $this->UPDATEquery($table, $where, $fields_values, $no_quote_fields);
663 if (is_string($this->lastQuery)) {
664 $sqlResult = $this->query($this->lastQuery);
665 } else {
666 $sqlResult = $this->query($this->lastQuery[0]);
667 foreach ($this->lastQuery[1] as $field => $content) {
668 $stmt = 'UPDATE ' . $this->quoteFromTables($table) . ' SET ' . $this->quoteFromTables($field) . '=' . $this->fullQuoteStr($content, $table) . ' WHERE ' . $this->quoteWhereClause($where);
669 $this->query($stmt);
670 }
671 }
672 break;
673 case 'adodb':
674 $this->lastQuery = $this->UPDATEquery($table, $where, $fields_values, $no_quote_fields);
675 if (is_string($this->lastQuery)) {
676 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
677 } else {
678 $this->handlerInstance[$this->lastHandlerKey]->StartTrans();
679 if (strlen($this->lastQuery[0])) {
680 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery[0], FALSE);
681 }
682 if (is_array($this->lastQuery[1])) {
683 foreach ($this->lastQuery[1] as $field => $content) {
684 $this->handlerInstance[$this->lastHandlerKey]->UpdateBlob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($where));
685 }
686 }
687 if (is_array($this->lastQuery[2])) {
688 foreach ($this->lastQuery[2] as $field => $content) {
689 $this->handlerInstance[$this->lastHandlerKey]->UpdateClob($this->quoteFromTables($table), $field, $content, $this->quoteWhereClause($where));
690 }
691 }
692 $this->handlerInstance[$this->lastHandlerKey]->CompleteTrans();
693 }
694 break;
695 case 'userdefined':
696 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields);
697 break;
698 }
699 if ($this->printErrors && $this->sql_error()) {
700 debug(array($this->lastQuery, $this->sql_error()));
701 }
702 if ($this->debug) {
703 $this->debugHandler('exec_UPDATEquery', GeneralUtility::milliseconds() - $pt, array(
704 'handlerType' => $hType,
705 'args' => array($table, $where, $fields_values),
706 'ORIG_from_table' => $ORIG_tableName
707 ));
708 }
709 foreach ($this->postProcessHookObjects as $hookObject) {
710 $hookObject->exec_UPDATEquery_postProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
711 }
712 // Return result:
713 return $sqlResult;
714 }
715
716 /**
717 * Creates and executes a DELETE SQL-statement for $table where $where-clause
718 *
719 * @param string $table Database tablename
720 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
721 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
722 */
723 public function exec_DELETEquery($table, $where) {
724 $pt = $this->debug ? GeneralUtility::milliseconds() : 0;
725 // Do table/field mapping:
726 $ORIG_tableName = $table;
727 if ($tableArray = $this->map_needMapping($table)) {
728 // Where clause:
729 $whereParts = $this->SQLparser->parseWhereClause($where);
730 $this->map_sqlParts($whereParts, $tableArray[0]['table']);
731 $where = $this->SQLparser->compileWhereClause($whereParts, FALSE);
732 // Table name:
733 if ($this->mapping[$table]['mapTableName']) {
734 $table = $this->mapping[$table]['mapTableName'];
735 }
736 }
737 // Select API
738 $this->lastHandlerKey = $this->handler_getFromTableList($table);
739 $hType = (string) $this->handlerCfg[$this->lastHandlerKey]['type'];
740 $sqlResult = NULL;
741 switch ($hType) {
742 case 'native':
743 $this->lastQuery = $this->DELETEquery($table, $where);
744 $sqlResult = $this->query($this->lastQuery);
745 break;
746 case 'adodb':
747 $this->lastQuery = $this->DELETEquery($table, $where);
748 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->_query($this->lastQuery, FALSE);
749 break;
750 case 'userdefined':
751 $sqlResult = $this->handlerInstance[$this->lastHandlerKey]->exec_DELETEquery($table, $where);
752 break;
753 }
754 if ($this->printErrors && $this->sql_error()) {
755 debug(array($this->lastQuery, $this->sql_error()));
756 }
757 if ($this->debug) {
758 $this->debugHandler('exec_DELETEquery', GeneralUtility::milliseconds() - $pt, array(
759 'handlerType' => $hType,
760 'args' => array($table, $where),
761 'ORIG_from_table' => $ORIG_tableName
762 ));
763 }
764 foreach ($this->postProcessHookObjects as $hookObject) {
765 $hookObject->exec_DELETEquery_postProcessAction($table, $where, $this);
766 }
767 // Return result:
768 return $sqlResult;
769 }
770
771 /**
772 * Creates and executes a SELECT SQL-statement
773 * Using this function specifically allow us to handle the LIMIT feature independently of DB.
774 *
775 * @param string $select_fields List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
776 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
777 * @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!
778 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
779 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
780 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
781 * @return boolean|\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 debug(array($this->lastQuery, $this->sql_error()));
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', '', $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 boolean|\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', $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 integer 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 boolean|\mysqli_result|object $res MySQLi result object / DBAL object
2154 * @return integer 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 boolean|\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 boolean|\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 boolean|\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 integer 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 integer 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 boolean|\mysqli_result|object $res MySQLi result object / DBAL object
2394 * @param integer $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 integer $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 boolean|\mysqli_result|object $res MySQLi result object / DBAL object
2442 * @param integer $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 boolean|\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 * @param string $host Deprecated since 6.1, will be removed in two versions. Database host IP/domain[:port]
2539 * @param string $username Deprecated since 6.1, will be removed in two versions. Username to connect with.
2540 * @param string $password Deprecated since 6.1, will be removed in two versions. Password to connect with.
2541 * @return boolean|void
2542 * @throws \RuntimeException
2543 */
2544 public function sql_pconnect($host = NULL, $username = NULL, $password = NULL) {
2545 if ($host || $username || $password) {
2546 $this->handleDeprecatedConnectArguments($host, $username, $password);
2547 }
2548
2549 // Initializing and output value:
2550 $sqlResult = $this->handler_init('_DEFAULT');
2551 return $sqlResult;
2552 }
2553
2554 /**
2555 * Select a SQL database
2556 *
2557 * @param string $TYPO3_db Deprecated since 6.1, will be removed in two versions. Database to connect to.
2558 * @return bool Returns TRUE on success or FALSE on failure.
2559 */
2560 public function sql_select_db($TYPO3_db = NULL) {
2561 if (!$TYPO3_db) {
2562 $TYPO3_db = $this->handlerCfg[$this->lastHandlerKey]['config']['database'];
2563 }
2564 $ret = TRUE;
2565 if ((string)$this->handlerCfg[$this->lastHandlerKey]['type'] === 'native') {
2566 $ret = $this->handlerInstance[$this->lastHandlerKey]['link']->select_db($TYPO3_db);
2567 }
2568 if (!$ret) {
2569 GeneralUtility::sysLog(
2570 'Could not select MySQL database ' . $TYPO3_db . ': ' . $this->sql_error(),
2571 'Core',
2572 GeneralUtility::SYSLOG_SEVERITY_FATAL
2573 );
2574 }
2575 return $ret;
2576 }
2577
2578 /**************************************
2579 *
2580 * SQL admin functions
2581 * (For use in the Install Tool and Extension Manager)
2582 *
2583 **************************************/
2584 /**
2585 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
2586 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
2587 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
2588 * Use in Install Tool only!
2589 *
2590 * @return array Each entry represents a database name
2591 * @throws \RuntimeException
2592 */
2593 public function admin_get_dbs() {
2594 $dbArr = array();
2595 $this->lastHandlerKey = '_DEFAULT';
2596 switch ($this->handlerCfg['_DEFAULT']['type']) {
2597 case 'native':
2598 /** @var \mysqli_result $db_list */
2599 $db_list = $this->query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA");
2600 while ($row = $db_list->fetch_object()) {
2601 if ($this->sql_select_db($row->SCHEMA_NAME)) {
2602 $dbArr[] = $row->SCHEMA_NAME;
2603 }
2604 }
2605 $db_list->free();
2606 break;
2607 case 'adodb':
2608 // check needed for install tool - otherwise it will just die because the call to
2609 // MetaDatabases is done on a stdClass instance
2610 if (method_exists($this->handlerInstance['_DEFAULT'], 'MetaDatabases')) {
2611 $sqlDBs = $this->handlerInstance['_DEFAULT']->MetaDatabases();
2612 if (is_array($sqlDBs)) {
2613 foreach ($sqlDBs as $k => $theDB) {
2614 $dbArr[] = $theDB;
2615 }
2616 }
2617 }
2618 break;
2619 case 'userdefined':
2620 $dbArr = $this->handlerInstance['_DEFAULT']->admin_get_tables();
2621 break;
2622 }
2623 return $dbArr;
2624 }
2625
2626 /**
2627 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
2628 * In a DBAL this method should 1) look up all tables from the DBMS of
2629 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
2630 *
2631 * @return array Array with tablenames as key and arrays with status information as value
2632 */
2633 public function admin_get_tables() {
2634 $whichTables = array();
2635 // Getting real list of tables:
2636 switch ($this->handlerCfg['_DEFAULT']['type']) {
2637 case 'native':
2638 $tables_result = $this->query('SHOW TABLE STATUS FROM `' . TYPO3_db . '`');
2639 if (!$this->sql_error()) {
2640 while ($theTable = $this->sql_fetch_assoc($tables_result)) {
2641 $whichTables[$theTable['Name']] = $theTable;
2642 }
2643 }
2644 $tables_result->free();
2645 break;
2646 case 'adodb':
2647 // check needed for install tool - otherwise it will just die because the call to
2648 // MetaTables is done on a stdClass instance
2649 if (method_exists($this->handlerInstance['_DEFAULT'], 'MetaTables')) {
2650 $sqlTables = $this->handlerInstance['_DEFAULT']->MetaTables('TABLES');
2651 foreach ($sqlTables as $k => $theTable) {
2652 if (preg_match('/BIN\\$/', $theTable)) {
2653 // Skip tables from the Oracle 10 Recycle Bin
2654 continue;
2655 }
2656 $whichTables[$theTable] = $theTable;
2657 }
2658 }
2659 break;
2660 case 'userdefined':
2661 $whichTables = $this->handlerInstance['_DEFAULT']->admin_get_tables();
2662 break;
2663 }
2664 // Check mapping:
2665 if (is_array($this->mapping) && count($this->mapping)) {
2666 // Mapping table names in reverse, first getting list of real table names:
2667 $tMap = array();
2668 foreach ($this->mapping as $tN => $tMapInfo) {
2669 if (isset($tMapInfo['mapTableName'])) {
2670 $tMap[$tMapInfo['mapTableName']] = $tN;
2671 }
2672 }
2673 // Do mapping:
2674 $newList = array();
2675 foreach ($whichTables as $tN => $tDefinition) {
2676 if (isset($tMap[$tN])) {
2677 $tN = $tMap[$tN];
2678 }
2679 $newList[$tN] = $tDefinition;
2680 }
2681 $whichTables = $newList;
2682 }
2683 // Adding tables configured to reside in other DBMS (handler by other handlers than the default):
2684 if (is_array($this->table2handlerKeys)) {
2685 foreach ($this->table2handlerKeys as $key => $handlerKey) {
2686 $whichTables[$key] = $key;
2687 }
2688 }
2689 return $whichTables;
2690 }
2691
2692 /**
2693 * Returns information about each field in the $table (quering the DBMS)
2694 * In a DBAL this should look up the right handler for the table and return compatible information
2695 * This function is important not only for the Install Tool but probably for
2696 * DBALs as well since they might need to look up table specific information
2697 * in order to construct correct queries. In such cases this information should
2698 * probably be cached for quick delivery.
2699 *
2700 * @param string $tableName Table name
2701 * @return array Field information in an associative array with fieldname => field row
2702 */
2703 public function admin_get_fields($tableName) {
2704 $output = array();
2705 // Do field mapping if needed:
2706 $ORIG_tableName = $tableName;
2707 if ($tableArray = $this->map_needMapping($tableName)) {
2708 // Table name:
2709 if ($this->mapping[$tableName]['mapTableName']) {
2710 $tableName = $this->mapping[$tableName]['mapTableName'];
2711 }
2712 }
2713 // Find columns
2714 $this->lastHandlerKey = $this->handler_getFromTableList($tableName);
2715 switch ((string) $this->handlerCfg[$this->lastHandlerKey]['type']) {
2716 case 'native':
2717 /** @var \mysqli_result $columns_res */
2718 $columns_res = $this->query('SHOW columns FROM ' . $tableName);
2719 while ($fieldRow = $columns_res->fetch_assoc()) {
2720 $output[$fieldRow['Field']] = $fieldRow;
2721 }
2722 $columns_res->free();
2723 break;
2724 case 'adodb':
2725 $fieldRows = $this->handlerInstance[$this->lastHandlerKey]->MetaColumns($tableName, FALSE);
2726 if (is_array($fieldRows)) {
2727 foreach ($fieldRows as $k => $fieldRow) {
2728 settype($fieldRow, 'array');
2729 $fieldRow['Field'] = $fieldRow['name'];
2730 $ntype = $this->MySQLActualType($this->MetaType($fieldRow['type'], $tableName));
2731 $ntype .= $fieldRow['max_length'] != -1 ? ($ntype == 'INT' ? '(11)' : '(' . $fieldRow['max_length'] . ')') : '';
2732 $fieldRow['Type'] = strtolower($ntype);
2733 $fieldRow['Null'] = '';
2734 $fieldRow['Key'] = '';
2735 $fieldRow['Default'] = $fieldRow['default_value'];
2736 $fieldRow['Extra'] = '';
2737 $output[$fieldRow['name']] = $fieldRow;
2738 }
2739 }
2740 break;
2741 case 'userdefined':
2742 $output = $this->handlerInstance[$this->lastHandlerKey]->admin_get_fields($tableName);
2743 break;
2744 }
2745 // mapping should be done:
2746 if (is_array($tableArray) && is_array($this->mapping[$ORIG_tableName]['mapFieldNames'])) {
2747 $revFields = array_flip($this->mapping[$ORIG_tableName]['mapFieldNames']);
2748 $newOutput = array();