2 namespace TYPO3\CMS\Core\Database
;
5 * This file is part of the TYPO3 CMS project.
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.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use TYPO3\CMS\Core\Utility\GeneralUtility
;
18 use TYPO3\CMS\Core\Utility\StringUtility
;
21 * Contains the class "DatabaseConnection" containing functions for building SQL queries
22 * and mysqli wrappers, thus providing a foundational API to all database
24 * This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
26 * TYPO3 "database wrapper" class (new in 3.6.0)
28 * - abstraction functions for executing INSERT/UPDATE/DELETE/SELECT queries ("Query execution"; These are REQUIRED for all future connectivity to the database, thus ensuring DBAL compliance!)
29 * - functions for building SQL queries (INSERT/UPDATE/DELETE/SELECT) ("Query building"); These are transitional functions for building SQL queries in a more automated way. Use these to build queries instead of doing it manually in your code!
30 * - mysqli wrapper functions; These are transitional functions. By a simple search/replace you should be able to substitute all mysql*() calls with $GLOBALS['TYPO3_DB']->sql*() and your application will work out of the box. YOU CANNOT (legally) use any mysqli functions not found as wrapper functions in this class!
31 * See the Project Coding Guidelines (doc_core_cgl) for more instructions on best-practise
33 * This class is not in itself a complete database abstraction layer but can be extended to be a DBAL (by extensions, see "dbal" for example)
34 * ALL connectivity to the database in TYPO3 must be done through this class!
35 * The points of this class are:
36 * - To direct all database calls through this class so it becomes possible to implement DBAL with extensions.
37 * - To keep it very easy to use for developers used to MySQL in PHP - and preserve as much performance as possible when TYPO3 is used with MySQL directly...
38 * - To create an interface for DBAL implemented by extensions; (Eg. making possible escaping characters, clob/blob handling, reserved words handling)
39 * - Benchmarking the DB bottleneck queries will become much easier; Will make it easier to find optimization possibilities.
42 * In all TYPO3 scripts the global variable $TYPO3_DB is an instance of this class. Use that.
43 * Eg. $GLOBALS['TYPO3_DB']->sql_fetch_assoc()
45 class DatabaseConnection
48 * The AND constraint in where clause
52 const AND_Constraint
= 'AND';
55 * The OR constraint in where clause
59 const OR_Constraint
= 'OR';
62 * Set "TRUE" or "1" if you want database errors outputted. Set to "2" if you also want successful database actions outputted.
66 public $debugOutput = false;
69 * Internally: Set to last built query (not necessarily executed...)
73 public $debug_lastBuiltQuery = '';
76 * Set "TRUE" if you want the last built query to be stored in $debug_lastBuiltQuery independent of $this->debugOutput
80 public $store_lastBuiltQuery = false;
83 * Set this to 1 to get queries explained (devIPmask must match). Set the value to 2 to the same but disregarding the devIPmask.
84 * There is an alternative option to enable explain output in the admin panel under "TypoScript", which will produce much nicer output, but only works in FE.
88 public $explainOutput = 0;
91 * @var string Database host to connect to
93 protected $databaseHost = '';
96 * @var int Database port to connect to
98 protected $databasePort = 3306;
101 * @var string|NULL Database socket to connect to
103 protected $databaseSocket = null;
106 * @var string Database name to connect to
108 protected $databaseName = '';
111 * @var string Database user to connect with
113 protected $databaseUsername = '';
116 * @var string Database password to connect with
118 protected $databaseUserPassword = '';
121 * @var bool TRUE if database connection should be persistent
122 * @see http://php.net/manual/de/mysqli.persistconns.php
124 protected $persistentDatabaseConnection = false;
127 * @var bool TRUE if connection between client and sql server is compressed
129 protected $connectionCompression = false;
132 * The charset for the connection; will be passed on to
133 * mysqli_set_charset during connection initialization.
137 protected $connectionCharset = 'utf8';
140 * @var array List of commands executed after connection was established
142 protected $initializeCommandsAfterConnect = array();
145 * @var bool TRUE if database connection is established
147 protected $isConnected = false;
150 * @var \mysqli $link Default database link object
152 protected $link = null;
155 * Default character set, applies unless character set or collation are explicitly set
159 public $default_charset = 'utf8';
162 * @var array<PostProcessQueryHookInterface>
164 protected $preProcessHookObjects = array();
167 * @var array<PreProcessQueryHookInterface>
169 protected $postProcessHookObjects = array();
172 * the date and time formats compatible with the database in general
176 protected static $dateTimeFormats = array(
178 'empty' => '0000-00-00',
182 'empty' => '0000-00-00 00:00:00',
183 'format' => 'Y-m-d H:i:s'
188 * Initialize the database connection
192 public function initialize()
194 // Intentionally blank as this will be overloaded by DBAL
197 /************************************
201 * These functions are the RECOMMENDED DBAL functions for use in your applications
202 * Using these functions will allow the DBAL to use alternative ways of accessing data (contrary to if a query is returned!)
203 * They compile a query AND execute it immediately and then return the result
204 * This principle heightens our ability to create various forms of DBAL of the functions.
205 * Generally: We want to return a result pointer/object, never queries.
206 * Also, having the table name together with the actual query execution allows us to direct the request to other databases.
208 **************************************/
211 * Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
212 * Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
214 * @param string $table Table name
215 * @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.
216 * @param bool|array|string $no_quote_fields See fullQuoteArray()
217 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
219 public function exec_INSERTquery($table, $fields_values, $no_quote_fields = false)
221 $res = $this->query($this->INSERTquery($table, $fields_values, $no_quote_fields));
222 if ($this->debugOutput
) {
223 $this->debug('exec_INSERTquery');
225 foreach ($this->postProcessHookObjects
as $hookObject) {
226 /** @var $hookObject PostProcessQueryHookInterface */
227 $hookObject->exec_INSERTquery_postProcessAction($table, $fields_values, $no_quote_fields, $this);
233 * Creates and executes an INSERT SQL-statement for $table with multiple rows.
235 * @param string $table Table name
236 * @param array $fields Field names
237 * @param array $rows Table rows. Each row should be an array with field values mapping to $fields
238 * @param bool|array|string $no_quote_fields See fullQuoteArray()
239 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
241 public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = false)
243 $res = $this->query($this->INSERTmultipleRows($table, $fields, $rows, $no_quote_fields));
244 if ($this->debugOutput
) {
245 $this->debug('exec_INSERTmultipleRows');
247 foreach ($this->postProcessHookObjects
as $hookObject) {
248 /** @var $hookObject PostProcessQueryHookInterface */
249 $hookObject->exec_INSERTmultipleRows_postProcessAction($table, $fields, $rows, $no_quote_fields, $this);
255 * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
256 * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
258 * @param string $table Database tablename
259 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
260 * @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.
261 * @param bool|array|string $no_quote_fields See fullQuoteArray()
262 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
264 public function exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields = false)
266 $res = $this->query($this->UPDATEquery($table, $where, $fields_values, $no_quote_fields));
267 if ($this->debugOutput
) {
268 $this->debug('exec_UPDATEquery');
270 foreach ($this->postProcessHookObjects
as $hookObject) {
271 /** @var $hookObject PostProcessQueryHookInterface */
272 $hookObject->exec_UPDATEquery_postProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
278 * Creates and executes a DELETE SQL-statement for $table where $where-clause
280 * @param string $table Database tablename
281 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
282 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
284 public function exec_DELETEquery($table, $where)
286 $res = $this->query($this->DELETEquery($table, $where));
287 if ($this->debugOutput
) {
288 $this->debug('exec_DELETEquery');
290 foreach ($this->postProcessHookObjects
as $hookObject) {
291 /** @var $hookObject PostProcessQueryHookInterface */
292 $hookObject->exec_DELETEquery_postProcessAction($table, $where, $this);
298 * Creates and executes a SELECT SQL-statement
299 * Using this function specifically allow us to handle the LIMIT feature independently of DB.
301 * @param string $select_fields List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
302 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
303 * @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!
304 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
305 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
306 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
307 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
309 public function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '')
311 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
312 $res = $this->query($query);
313 if ($this->debugOutput
) {
314 $this->debug('exec_SELECTquery');
316 if ($this->explainOutput
) {
317 $this->explain($query, $from_table, $res->num_rows
);
319 foreach ($this->postProcessHookObjects
as $hookObject) {
320 /** @var $hookObject PostProcessQueryHookInterface */
321 $hookObject->exec_SELECTquery_postProcessAction($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', $this);
327 * Creates and executes a SELECT query, selecting fields ($select) from two/three tables joined
328 * Use $mm_table together with $local_table or $foreign_table to select over two tables. Or use all three tables to select the full MM-relation.
329 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
330 * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $GLOBALS['TCA'] in Inside TYPO3 for more details.
332 * @param string $select Field list for SELECT
333 * @param string $local_table Tablename, local table
334 * @param string $mm_table Tablename, relation table
335 * @param string $foreign_table Tablename, foreign table
336 * @param string $whereClause Optional 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! You have to prepend 'AND ' to this parameter yourself!
337 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
338 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
339 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
340 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
341 * @see exec_SELECTquery()
343 public function exec_SELECT_mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
345 $queryParts = $this->getSelectMmQueryParts($select, $local_table, $mm_table, $foreign_table, $whereClause, $groupBy, $orderBy, $limit);
346 return $this->exec_SELECT_queryArray($queryParts);
350 * Executes a select based on input query parts array
352 * @param array $queryParts Query parts array
353 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
354 * @see exec_SELECTquery()
356 public function exec_SELECT_queryArray($queryParts)
358 return $this->exec_SELECTquery($queryParts['SELECT'], $queryParts['FROM'], $queryParts['WHERE'], $queryParts['GROUPBY'], $queryParts['ORDERBY'], $queryParts['LIMIT']);
362 * Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
364 * @param string $select_fields List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
365 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
366 * @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!
367 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
368 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
369 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
370 * @param string $uidIndexField If set, the result array will carry this field names value as index. Requires that field to be selected of course!
371 * @return array|NULL Array of rows, or NULL in case of SQL error
372 * @see exec_SELECTquery()
373 * @throws \InvalidArgumentException
375 public function exec_SELECTgetRows($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', $uidIndexField = '')
377 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
378 if ($this->sql_error()) {
379 $this->sql_free_result($res);
384 while ($record = $this->sql_fetch_assoc($res)) {
385 if ($uidIndexField) {
387 $firstRecord = false;
388 if (!array_key_exists($uidIndexField, $record)) {
389 $this->sql_free_result($res);
390 throw new \
InvalidArgumentException('The given $uidIndexField "' . $uidIndexField . '" is not available in the result.', 1432933855);
393 $output[$record[$uidIndexField]] = $record;
398 $this->sql_free_result($res);
403 * Creates and executes a SELECT SQL-statement AND gets a result set and returns an array with a single record in.
404 * LIMIT is automatically set to 1 and can not be overridden.
406 * @param string $select_fields List of fields to select from the table.
407 * @param string $from_table Table(s) from which to select.
408 * @param string $where_clause Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
409 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
410 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
411 * @param bool $numIndex If set, the result will be fetched with sql_fetch_row, otherwise sql_fetch_assoc will be used.
412 * @return array|FALSE|NULL Single row, FALSE on empty result, NULL on error
414 public function exec_SELECTgetSingleRow($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $numIndex = false)
416 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, '1');
418 if ($res !== false) {
420 $output = $this->sql_fetch_row($res);
422 $output = $this->sql_fetch_assoc($res);
424 $this->sql_free_result($res);
430 * Counts the number of rows in a table.
432 * @param string $field Name of the field to use in the COUNT() expression (e.g. '*')
433 * @param string $table Name of the table to count rows for
434 * @param string $where (optional) WHERE statement of the query
435 * @return mixed Number of rows counter (int) or FALSE if something went wrong (bool)
437 public function exec_SELECTcountRows($field, $table, $where = '1=1')
440 $resultSet = $this->exec_SELECTquery('COUNT(' . $field . ')', $table, $where);
441 if ($resultSet !== false) {
442 list($count) = $this->sql_fetch_row($resultSet);
443 $count = (int)$count;
444 $this->sql_free_result($resultSet);
452 * @param string $table Database tablename
453 * @return mixed Result from handler
455 public function exec_TRUNCATEquery($table)
457 $res = $this->query($this->TRUNCATEquery($table));
458 if ($this->debugOutput
) {
459 $this->debug('exec_TRUNCATEquery');
461 foreach ($this->postProcessHookObjects
as $hookObject) {
462 /** @var $hookObject PostProcessQueryHookInterface */
463 $hookObject->exec_TRUNCATEquery_postProcessAction($table, $this);
469 * Central query method. Also checks if there is a database connection.
470 * Use this to execute database queries instead of directly calling $this->link->query()
472 * @param string $query The query to send to the database
473 * @return bool|\mysqli_result
475 protected function query($query)
477 if (!$this->isConnected
) {
480 return $this->link
->query($query);
483 /**************************************
487 **************************************/
489 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
491 * @param string $table See exec_INSERTquery()
492 * @param array $fields_values See exec_INSERTquery()
493 * @param bool|array|string $no_quote_fields See fullQuoteArray()
494 * @return string|NULL Full SQL query for INSERT, NULL if $fields_values is empty
496 public function INSERTquery($table, $fields_values, $no_quote_fields = false)
498 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
499 // function (contrary to values in the arrays which may be insecure).
500 if (!is_array($fields_values) ||
empty($fields_values)) {
503 foreach ($this->preProcessHookObjects
as $hookObject) {
504 $hookObject->INSERTquery_preProcessAction($table, $fields_values, $no_quote_fields, $this);
506 // Quote and escape values
507 $fields_values = $this->fullQuoteArray($fields_values, $table, $no_quote_fields, true);
509 $query = 'INSERT INTO ' . $table . ' (' . implode(',', array_keys($fields_values)) . ') VALUES ' . '(' . implode(',', $fields_values) . ')';
511 if ($this->debugOutput ||
$this->store_lastBuiltQuery
) {
512 $this->debug_lastBuiltQuery
= $query;
518 * Creates an INSERT SQL-statement for $table with multiple rows.
520 * @param string $table Table name
521 * @param array $fields Field names
522 * @param array $rows Table rows. Each row should be an array with field values mapping to $fields
523 * @param bool|array|string $no_quote_fields See fullQuoteArray()
524 * @return string|NULL Full SQL query for INSERT, NULL if $rows is empty
526 public function INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = false)
528 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
529 // function (contrary to values in the arrays which may be insecure).
533 foreach ($this->preProcessHookObjects
as $hookObject) {
534 /** @var $hookObject PreProcessQueryHookInterface */
535 $hookObject->INSERTmultipleRows_preProcessAction($table, $fields, $rows, $no_quote_fields, $this);
538 $query = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES ';
540 foreach ($rows as $row) {
541 // Quote and escape values
542 $row = $this->fullQuoteArray($row, $table, $no_quote_fields);
543 $rowSQL[] = '(' . implode(', ', $row) . ')';
545 $query .= implode(', ', $rowSQL);
547 if ($this->debugOutput ||
$this->store_lastBuiltQuery
) {
548 $this->debug_lastBuiltQuery
= $query;
554 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
557 * @param string $table See exec_UPDATEquery()
558 * @param string $where See exec_UPDATEquery()
559 * @param array $fields_values See exec_UPDATEquery()
560 * @param bool|array|string $no_quote_fields See fullQuoteArray()
561 * @throws \InvalidArgumentException
562 * @return string Full SQL query for UPDATE
564 public function UPDATEquery($table, $where, $fields_values, $no_quote_fields = false)
566 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
567 // function (contrary to values in the arrays which may be insecure).
568 if (is_string($where)) {
569 foreach ($this->preProcessHookObjects
as $hookObject) {
570 /** @var $hookObject PreProcessQueryHookInterface */
571 $hookObject->UPDATEquery_preProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
574 if (is_array($fields_values) && !empty($fields_values)) {
575 // Quote and escape values
576 $nArr = $this->fullQuoteArray($fields_values, $table, $no_quote_fields, true);
577 foreach ($nArr as $k => $v) {
578 $fields[] = $k . '=' . $v;
582 $query = 'UPDATE ' . $table . ' SET ' . implode(',', $fields) . ((string)$where !== '' ?
' WHERE ' . $where : '');
583 if ($this->debugOutput ||
$this->store_lastBuiltQuery
) {
584 $this->debug_lastBuiltQuery
= $query;
588 throw new \
InvalidArgumentException('TYPO3 Fatal Error: "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !', 1270853880);
593 * Creates a DELETE SQL-statement for $table where $where-clause
595 * @param string $table See exec_DELETEquery()
596 * @param string $where See exec_DELETEquery()
597 * @return string Full SQL query for DELETE
598 * @throws \InvalidArgumentException
600 public function DELETEquery($table, $where)
602 if (is_string($where)) {
603 foreach ($this->preProcessHookObjects
as $hookObject) {
604 /** @var $hookObject PreProcessQueryHookInterface */
605 $hookObject->DELETEquery_preProcessAction($table, $where, $this);
607 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
608 $query = 'DELETE FROM ' . $table . ((string)$where !== '' ?
' WHERE ' . $where : '');
609 if ($this->debugOutput ||
$this->store_lastBuiltQuery
) {
610 $this->debug_lastBuiltQuery
= $query;
614 throw new \
InvalidArgumentException('TYPO3 Fatal Error: "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !', 1270853881);
619 * Creates a SELECT SQL-statement
621 * @param string $select_fields See exec_SELECTquery()
622 * @param string $from_table See exec_SELECTquery()
623 * @param string $where_clause See exec_SELECTquery()
624 * @param string $groupBy See exec_SELECTquery()
625 * @param string $orderBy See exec_SELECTquery()
626 * @param string $limit See exec_SELECTquery()
627 * @return string Full SQL query for SELECT
629 public function SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '')
631 foreach ($this->preProcessHookObjects
as $hookObject) {
632 /** @var $hookObject PreProcessQueryHookInterface */
633 $hookObject->SELECTquery_preProcessAction($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit, $this);
635 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
637 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table . ((string)$where_clause !== '' ?
' WHERE ' . $where_clause : '');
639 $query .= (string)$groupBy !== '' ?
' GROUP BY ' . $groupBy : '';
641 $query .= (string)$orderBy !== '' ?
' ORDER BY ' . $orderBy : '';
643 $query .= (string)$limit !== '' ?
' LIMIT ' . $limit : '';
645 if ($this->debugOutput ||
$this->store_lastBuiltQuery
) {
646 $this->debug_lastBuiltQuery
= $query;
652 * Creates a SELECT SQL-statement to be used as subquery within another query.
653 * BEWARE: This method should not be overriden within DBAL to prevent quoting from happening.
655 * @param string $select_fields List of fields to select from the table.
656 * @param string $from_table Table from which to select.
657 * @param string $where_clause Conditional WHERE statement
658 * @return string Full SQL query for SELECT
660 public function SELECTsubquery($select_fields, $from_table, $where_clause)
662 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
663 // Build basic query:
664 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table . ((string)$where_clause !== '' ?
' WHERE ' . $where_clause : '');
666 if ($this->debugOutput ||
$this->store_lastBuiltQuery
) {
667 $this->debug_lastBuiltQuery
= $query;
673 * Creates a SELECT query, selecting fields ($select) from two/three tables joined
674 * Use $mm_table together with $local_table or $foreign_table to select over two tables. Or use all three tables to select the full MM-relation.
675 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
676 * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $GLOBALS['TCA'] in Inside TYPO3 for more details.
678 * @param string $select See exec_SELECT_mm_query()
679 * @param string $local_table See exec_SELECT_mm_query()
680 * @param string $mm_table See exec_SELECT_mm_query()
681 * @param string $foreign_table See exec_SELECT_mm_query()
682 * @param string $whereClause See exec_SELECT_mm_query()
683 * @param string $groupBy See exec_SELECT_mm_query()
684 * @param string $orderBy See exec_SELECT_mm_query()
685 * @param string $limit See exec_SELECT_mm_query()
686 * @return string Full SQL query for SELECT
689 public function SELECT_mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
691 $queryParts = $this->getSelectMmQueryParts($select, $local_table, $mm_table, $foreign_table, $whereClause, $groupBy, $orderBy, $limit);
692 return $this->SELECTquery($queryParts['SELECT'], $queryParts['FROM'], $queryParts['WHERE'], $queryParts['GROUPBY'], $queryParts['ORDERBY'], $queryParts['LIMIT']);
696 * Creates a TRUNCATE TABLE SQL-statement
698 * @param string $table See exec_TRUNCATEquery()
699 * @return string Full SQL query for TRUNCATE TABLE
701 public function TRUNCATEquery($table)
703 foreach ($this->preProcessHookObjects
as $hookObject) {
704 /** @var $hookObject PreProcessQueryHookInterface */
705 $hookObject->TRUNCATEquery_preProcessAction($table, $this);
707 // Table should be "SQL-injection-safe" when supplied to this function
708 // Build basic query:
709 $query = 'TRUNCATE TABLE ' . $table;
711 if ($this->debugOutput ||
$this->store_lastBuiltQuery
) {
712 $this->debug_lastBuiltQuery
= $query;
718 * Returns a WHERE clause that can find a value ($value) in a list field ($field)
719 * For instance a record in the database might contain a list of numbers,
720 * "34,234,5" (with no spaces between). This query would be able to select that
721 * record based on the value "34", "234" or "5" regardless of their position in
722 * the list (left, middle or right).
723 * The value must not contain a comma (,)
724 * Is nice to look up list-relations to records or files in TYPO3 database tables.
726 * @param string $field Field name
727 * @param string $value Value to find in list
728 * @param string $table Table in which we are searching (for DBAL detection of quoteStr() method)
729 * @return string WHERE clause for a query
730 * @throws \InvalidArgumentException
732 public function listQuery($field, $value, $table)
734 $value = (string)$value;
735 if (strpos($value, ',') !== false) {
736 throw new \
InvalidArgumentException('$value must not contain a comma (,) in $this->listQuery() !', 1294585862);
738 $pattern = $this->quoteStr($value, $table);
739 $where = 'FIND_IN_SET(\'' . $pattern . '\',' . $field . ')';
744 * Returns a WHERE clause which will make an AND or OR search for the words in the $searchWords array in any of the fields in array $fields.
746 * @param array $searchWords Array of search words
747 * @param array $fields Array of fields
748 * @param string $table Table in which we are searching (for DBAL detection of quoteStr() method)
749 * @param string $constraint How multiple search words have to match ('AND' or 'OR')
750 * @return string WHERE clause for search
752 public function searchQuery($searchWords, $fields, $table, $constraint = self
::AND_Constraint
)
754 switch ($constraint) {
755 case self
::OR_Constraint
:
762 $queryParts = array();
763 foreach ($searchWords as $sw) {
764 $like = ' LIKE \'%' . $this->quoteStr($this->escapeStrForLike($sw, $table), $table) . '%\'';
765 $queryParts[] = $table . '.' . implode(($like . ' OR ' . $table . '.'), $fields) . $like;
767 $query = '(' . implode(') ' . $constraint . ' (', $queryParts) . ')';
772 /**************************************
774 * Prepared Query Support
776 **************************************/
778 * Creates a SELECT prepared SQL statement.
780 * @param string $select_fields See exec_SELECTquery()
781 * @param string $from_table See exec_SELECTquery()
782 * @param string $where_clause See exec_SELECTquery()
783 * @param string $groupBy See exec_SELECTquery()
784 * @param string $orderBy See exec_SELECTquery()
785 * @param string $limit See exec_SELECTquery()
786 * @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.
787 * @return \TYPO3\CMS\Core\Database\PreparedStatement Prepared statement
789 public function prepare_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', array $input_parameters = array())
791 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
792 /** @var $preparedStatement \TYPO3\CMS\Core\Database\PreparedStatement */
793 $preparedStatement = GeneralUtility
::makeInstance(\TYPO3\CMS\Core\Database\PreparedStatement
::class, $query, $from_table, array());
794 // Bind values to parameters
795 foreach ($input_parameters as $key => $value) {
796 $preparedStatement->bindValue($key, $value, PreparedStatement
::PARAM_AUTOTYPE
);
798 // Return prepared statement
799 return $preparedStatement;
803 * Creates a SELECT prepared SQL statement based on input query parts array
805 * @param array $queryParts Query parts array
806 * @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.
807 * @return \TYPO3\CMS\Core\Database\PreparedStatement Prepared statement
809 public function prepare_SELECTqueryArray(array $queryParts, array $input_parameters = array())
811 return $this->prepare_SELECTquery($queryParts['SELECT'], $queryParts['FROM'], $queryParts['WHERE'], $queryParts['GROUPBY'], $queryParts['ORDERBY'], $queryParts['LIMIT'], $input_parameters);
815 * Prepares a prepared query.
817 * @param string $query The query to execute
818 * @param array $queryComponents The components of the query to execute
819 * @return \mysqli_stmt|object MySQLi statement / DBAL object
820 * @internal This method may only be called by \TYPO3\CMS\Core\Database\PreparedStatement
822 public function prepare_PREPAREDquery($query, array $queryComponents)
824 if (!$this->isConnected
) {
827 $stmt = $this->link
->stmt_init();
828 $success = $stmt->prepare($query);
829 if ($this->debugOutput
) {
830 $this->debug('stmt_execute', $query);
832 return $success ?
$stmt : null;
835 /**************************************
837 * Various helper functions
839 * Functions recommended to be used for
841 * - cleaning lists of values,
842 * - stripping of excess ORDER BY/GROUP BY keywords
844 **************************************/
846 * Escaping and quoting values for SQL statements.
848 * @param string $str Input string
849 * @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!).
850 * @param bool $allowNull Whether to allow NULL values
851 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
854 public function fullQuoteStr($str, $table, $allowNull = false)
856 if (!$this->isConnected
) {
859 if ($allowNull && $str === null) {
866 return '\'' . $this->link
->real_escape_string($str) . '\'';
870 * Will fullquote all values in the one-dimensional array so they are ready to "implode" for an sql query.
872 * @param array $arr Array with values (either associative or non-associative array)
873 * @param string $table Table name for which to quote
874 * @param bool|array|string $noQuote List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
875 * @param bool $allowNull Whether to allow NULL values
876 * @return array The input array with the values quoted
877 * @see cleanIntArray()
879 public function fullQuoteArray($arr, $table, $noQuote = false, $allowNull = false)
881 if (is_string($noQuote)) {
882 $noQuote = explode(',', $noQuote);
883 } elseif (!is_array($noQuote)) {
884 $noQuote = (bool)$noQuote;
886 if ($noQuote === true) {
889 foreach ($arr as $k => $v) {
890 if ($noQuote === false ||
!in_array($k, $noQuote)) {
891 $arr[$k] = $this->fullQuoteStr($v, $table, $allowNull);
898 * Substitution for PHP function "addslashes()"
899 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
900 * 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()!
902 * @param string $str Input string
903 * @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!).
904 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
907 public function quoteStr($str, $table)
909 if (!$this->isConnected
) {
912 return $this->link
->real_escape_string($str);
916 * Escaping values for SQL LIKE statements.
918 * @param string $str Input string
919 * @param string $table Table name for which to escape 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!).
920 * @return string Output string; % and _ will be escaped with \ (or otherwise based on DBAL handler)
923 public function escapeStrForLike($str, $table)
925 return addcslashes($str, '_%');
929 * Will convert all values in the one-dimensional array to integers.
930 * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
932 * @param array $arr Array with values
933 * @return array The input array with all values cast to (int)
934 * @see cleanIntList()
936 public function cleanIntArray($arr)
938 return array_map('intval', $arr);
942 * Will force all entries in the input comma list to integers
943 * Useful when you want to make sure a commalist of supposed integers really contain only integers; You want to know that when you don't trust content that could go into an SQL statement.
945 * @param string $list List of comma-separated values which should be integers
946 * @return string The input list but with every value cast to (int)
947 * @see cleanIntArray()
949 public function cleanIntList($list)
951 return implode(',', GeneralUtility
::intExplode(',', $list));
955 * Removes the prefix "ORDER BY" from the input string.
956 * This function is used when you call the exec_SELECTquery() function and want to pass the ORDER BY parameter by can't guarantee that "ORDER BY" is not prefixed.
957 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
959 * @param string $str eg. "ORDER BY title, uid
960 * @return string eg. "title, uid
961 * @see exec_SELECTquery(), stripGroupBy()
963 public function stripOrderBy($str)
965 return preg_replace('/^(?:ORDER[[:space:]]*BY[[:space:]]*)+/i', '', trim($str));
969 * Removes the prefix "GROUP BY" from the input string.
970 * This function is used when you call the SELECTquery() function and want to pass the GROUP BY parameter by can't guarantee that "GROUP BY" is not prefixed.
971 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
973 * @param string $str eg. "GROUP BY title, uid
974 * @return string eg. "title, uid
975 * @see exec_SELECTquery(), stripOrderBy()
977 public function stripGroupBy($str)
979 return preg_replace('/^(?:GROUP[[:space:]]*BY[[:space:]]*)+/i', '', trim($str));
983 * Returns the date and time formats compatible with the given database table.
985 * @param string $table Table name for which to return an empty date. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how date and time should be formatted).
988 public function getDateTimeFormats($table)
990 return self
::$dateTimeFormats;
994 * Creates SELECT query components for selecting fields ($select) from two/three tables joined
995 * Use $mm_table together with $local_table or $foreign_table to select over two tables. Or use all three tables to select the full MM-relation.
996 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
997 * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $GLOBALS['TCA'] in Inside TYPO3 for more details.
999 * @param string $select See exec_SELECT_mm_query()
1000 * @param string $local_table See exec_SELECT_mm_query()
1001 * @param string $mm_table See exec_SELECT_mm_query()
1002 * @param string $foreign_table See exec_SELECT_mm_query()
1003 * @param string $whereClause See exec_SELECT_mm_query()
1004 * @param string $groupBy See exec_SELECT_mm_query()
1005 * @param string $orderBy See exec_SELECT_mm_query()
1006 * @param string $limit See exec_SELECT_mm_query()
1007 * @return array SQL query components
1009 protected function getSelectMmQueryParts($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
1011 $foreign_table_as = $foreign_table == $local_table ?
$foreign_table . StringUtility
::getUniqueId('_join') : '';
1012 $mmWhere = $local_table ?
$local_table . '.uid=' . $mm_table . '.uid_local' : '';
1013 $mmWhere .= ($local_table and $foreign_table) ?
' AND ' : '';
1014 $tables = ($local_table ?
$local_table . ',' : '') . $mm_table;
1015 if ($foreign_table) {
1016 $mmWhere .= ($foreign_table_as ?
: $foreign_table) . '.uid=' . $mm_table . '.uid_foreign';
1017 $tables .= ',' . $foreign_table . ($foreign_table_as ?
' AS ' . $foreign_table_as : '');
1020 'SELECT' => $select,
1022 'WHERE' => $mmWhere . ' ' . $whereClause,
1023 'GROUPBY' => $groupBy,
1024 'ORDERBY' => $orderBy,
1029 /**************************************
1031 * MySQL(i) wrapper functions
1032 * (For use in your applications)
1034 **************************************/
1037 * MySQLi query() wrapper function
1038 * Beware: Use of this method should be avoided as it is experimentally supported by DBAL. You should consider
1039 * using exec_SELECTquery() and similar methods instead.
1041 * @param string $query Query to execute
1042 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
1044 public function sql_query($query)
1046 $res = $this->query($query);
1047 if ($this->debugOutput
) {
1048 $this->debug('sql_query', $query);
1054 * Returns the error status on the last query() execution
1056 * @return string MySQLi error string.
1058 public function sql_error()
1060 return $this->link
->error
;
1064 * Returns the error number on the last query() execution
1066 * @return int MySQLi error number
1068 public function sql_errno()
1070 return $this->link
->errno
;
1074 * Returns the number of selected rows.
1076 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
1077 * @return int Number of resulting rows
1079 public function sql_num_rows($res)
1081 if ($this->debug_check_recordset($res)) {
1082 return $res->num_rows
;
1089 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
1090 * MySQLi fetch_assoc() wrapper function
1092 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
1093 * @return array|bool Associative array of result row.
1095 public function sql_fetch_assoc($res)
1097 if ($this->debug_check_recordset($res)) {
1098 $result = $res->fetch_assoc();
1099 if ($result === null) {
1100 // Needed for compatibility
1110 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
1111 * The array contains the values in numerical indices.
1112 * MySQLi fetch_row() wrapper function
1114 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
1115 * @return array|bool Array with result rows.
1117 public function sql_fetch_row($res)
1119 if ($this->debug_check_recordset($res)) {
1120 $result = $res->fetch_row();
1121 if ($result === null) {
1122 // Needed for compatibility
1132 * Free result memory
1133 * free_result() wrapper function
1135 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
1136 * @return bool Returns TRUE on success or FALSE on failure.
1138 public function sql_free_result($res)
1140 if ($this->debug_check_recordset($res) && is_object($res)) {
1149 * Get the ID generated from the previous INSERT operation
1151 * @return int The uid of the last inserted record.
1153 public function sql_insert_id()
1155 return $this->link
->insert_id
;
1159 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
1161 * @return int Number of rows affected by last query
1163 public function sql_affected_rows()
1165 return $this->link
->affected_rows
;
1169 * Move internal result pointer
1171 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
1172 * @param int $seek Seek result number.
1173 * @return bool Returns TRUE on success or FALSE on failure.
1175 public function sql_data_seek($res, $seek)
1177 if ($this->debug_check_recordset($res)) {
1178 return $res->data_seek($seek);
1185 * Get the type of the specified field in a result
1186 * mysql_field_type() wrapper function
1188 * @param bool|\mysqli_result|object $res MySQLi result object / DBAL object
1189 * @param int $pointer Field index.
1190 * @return string Returns the name of the specified field index, or FALSE on error
1192 public function sql_field_type($res, $pointer)
1194 // mysql_field_type compatibility map
1195 // taken from: http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php#89117
1196 // Constant numbers see http://php.net/manual/en/mysqli.constants.php
1197 $mysql_data_type_hash = array(
1211 //252 is currently mapped to all text and blob types (MySQL 5.0.51a)
1216 if ($this->debug_check_recordset($res)) {
1217 $metaInfo = $res->fetch_field_direct($pointer);
1218 if ($metaInfo === false) {
1221 return $mysql_data_type_hash[$metaInfo->type
];
1228 * Open a (persistent) connection to a MySQL server
1231 * @throws \RuntimeException
1233 public function sql_pconnect()
1235 if ($this->isConnected
) {
1239 if (!extension_loaded('mysqli')) {
1240 throw new \
RuntimeException(
1241 'Database Error: PHP mysqli extension not loaded. This is a must have for TYPO3 CMS!',
1246 $host = $this->persistentDatabaseConnection
1247 ?
'p:' . $this->databaseHost
1248 : $this->databaseHost
;
1250 $this->link
= mysqli_init();
1251 $connected = $this->link
->real_connect(
1253 $this->databaseUsername
,
1254 $this->databaseUserPassword
,
1256 (int)$this->databasePort
,
1257 $this->databaseSocket
,
1258 $this->connectionCompression ? MYSQLI_CLIENT_COMPRESS
: 0
1262 $this->isConnected
= true;
1264 if ($this->link
->set_charset($this->connectionCharset
) === false) {
1265 GeneralUtility
::sysLog(
1266 'Error setting connection charset to "' . $this->connectionCharset
. '"',
1268 GeneralUtility
::SYSLOG_SEVERITY_ERROR
1272 foreach ($this->initializeCommandsAfterConnect
as $command) {
1273 if ($this->query($command) === false) {
1274 GeneralUtility
::sysLog(
1275 'Could not initialize DB connection with query "' . $command . '": ' . $this->sql_error(),
1277 GeneralUtility
::SYSLOG_SEVERITY_ERROR
1281 $this->checkConnectionCharset();
1283 // @todo This should raise an exception. Would be useful especially to work during installation.
1284 $error_msg = $this->link
->connect_error
;
1286 GeneralUtility
::sysLog(
1287 'Could not connect to MySQL server ' . $host . ' with user ' . $this->databaseUsername
. ': ' . $error_msg,
1289 GeneralUtility
::SYSLOG_SEVERITY_FATAL
1296 * Select a SQL database
1298 * @return bool Returns TRUE on success or FALSE on failure.
1300 public function sql_select_db()
1302 if (!$this->isConnected
) {
1306 $ret = $this->link
->select_db($this->databaseName
);
1308 GeneralUtility
::sysLog(
1309 'Could not select MySQL database ' . $this->databaseName
. ': ' . $this->sql_error(),
1311 GeneralUtility
::SYSLOG_SEVERITY_FATAL
1317 /**************************************
1319 * SQL admin functions
1320 * (For use in the Install Tool and Extension Manager)
1322 **************************************/
1324 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
1325 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
1326 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
1327 * Use in Install Tool only!
1329 * @return array Each entry represents a database name
1330 * @throws \RuntimeException
1332 public function admin_get_dbs()
1335 $db_list = $this->query('SELECT SCHEMA_NAME FROM information_schema.SCHEMATA');
1336 if ($db_list === false) {
1337 throw new \
RuntimeException(
1338 'MySQL Error: Cannot get tablenames: "' . $this->sql_error() . '"!',
1342 while ($row = $db_list->fetch_object()) {
1344 $this->setDatabaseName($row->SCHEMA_NAME
);
1345 if ($this->sql_select_db()) {
1346 $dbArr[] = $row->SCHEMA_NAME
;
1348 } catch (\RuntimeException
$exception) {
1349 // The exception happens if we cannot connect to the database
1350 // (usually due to missing permissions). This is ok here.
1351 // We catch the exception, skip the database and continue.
1359 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
1360 * In a DBAL this method should 1) look up all tables from the DBMS of
1361 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
1363 * @return array Array with tablenames as key and arrays with status information as value
1365 public function admin_get_tables()
1367 $whichTables = array();
1368 $tables_result = $this->query('SHOW TABLE STATUS FROM `' . $this->databaseName
. '`');
1369 if ($tables_result !== false) {
1370 while ($theTable = $tables_result->fetch_assoc()) {
1371 $whichTables[$theTable['Name']] = $theTable;
1373 $tables_result->free();
1375 return $whichTables;
1379 * Returns information about each field in the $table (quering the DBMS)
1380 * In a DBAL this should look up the right handler for the table and return compatible information
1381 * This function is important not only for the Install Tool but probably for
1382 * DBALs as well since they might need to look up table specific information
1383 * in order to construct correct queries. In such cases this information should
1384 * probably be cached for quick delivery.
1386 * @param string $tableName Table name
1387 * @return array Field information in an associative array with fieldname => field row
1389 public function admin_get_fields($tableName)
1392 $columns_res = $this->query('SHOW FULL COLUMNS FROM `' . $tableName . '`');
1393 if ($columns_res !== false) {
1394 while ($fieldRow = $columns_res->fetch_assoc()) {
1395 $output[$fieldRow['Field']] = $fieldRow;
1397 $columns_res->free();
1403 * Returns information about each index key in the $table (quering the DBMS)
1404 * In a DBAL this should look up the right handler for the table and return compatible information
1406 * @param string $tableName Table name
1407 * @return array Key information in a numeric array
1409 public function admin_get_keys($tableName)
1412 $keyRes = $this->query('SHOW KEYS FROM `' . $tableName . '`');
1413 if ($keyRes !== false) {
1414 while ($keyRow = $keyRes->fetch_assoc()) {
1415 $output[] = $keyRow;
1423 * Returns information about the character sets supported by the current DBM
1424 * This function is important not only for the Install Tool but probably for
1425 * DBALs as well since they might need to look up table specific information
1426 * in order to construct correct queries. In such cases this information should
1427 * probably be cached for quick delivery.
1429 * This is used by the Install Tool to convert tables with non-UTF8 charsets
1430 * Use in Install Tool only!
1432 * @return array Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
1434 public function admin_get_charsets()
1437 $columns_res = $this->query('SHOW CHARACTER SET');
1438 if ($columns_res !== false) {
1439 while ($row = $columns_res->fetch_assoc()) {
1440 $output[$row['Charset']] = $row;
1442 $columns_res->free();
1448 * mysqli() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
1450 * @param string $query Query to execute
1451 * @return bool|\mysqli_result|object MySQLi result object / DBAL object
1453 public function admin_query($query)
1455 $res = $this->query($query);
1456 if ($this->debugOutput
) {
1457 $this->debug('admin_query', $query);
1462 /******************************
1466 ******************************/
1471 * @param string $host
1473 public function setDatabaseHost($host = 'localhost')
1475 $this->disconnectIfConnected();
1476 $this->databaseHost
= $host;
1484 public function setDatabasePort($port = 3306)
1486 $this->disconnectIfConnected();
1487 $this->databasePort
= (int)$port;
1491 * Set database socket
1493 * @param string|NULL $socket
1495 public function setDatabaseSocket($socket = null)
1497 $this->disconnectIfConnected();
1498 $this->databaseSocket
= $socket;
1504 * @param string $name
1506 public function setDatabaseName($name)
1508 $this->disconnectIfConnected();
1509 $this->databaseName
= $name;
1513 * Set database username
1515 * @param string $username
1517 public function setDatabaseUsername($username)
1519 $this->disconnectIfConnected();
1520 $this->databaseUsername
= $username;
1524 * Set database password
1526 * @param string $password
1528 public function setDatabasePassword($password)
1530 $this->disconnectIfConnected();
1531 $this->databaseUserPassword
= $password;
1535 * Set persistent database connection
1537 * @param bool $persistentDatabaseConnection
1538 * @see http://php.net/manual/de/mysqli.persistconns.php
1540 public function setPersistentDatabaseConnection($persistentDatabaseConnection)
1542 $this->disconnectIfConnected();
1543 $this->persistentDatabaseConnection
= (bool)$persistentDatabaseConnection;
1547 * Set connection compression. Might be an advantage, if SQL server is not on localhost
1549 * @param bool $connectionCompression TRUE if connection should be compressed
1551 public function setConnectionCompression($connectionCompression)
1553 $this->disconnectIfConnected();
1554 $this->connectionCompression
= (bool)$connectionCompression;
1558 * Set commands to be fired after connection was established
1560 * @param array $commands List of SQL commands to be executed after connect
1562 public function setInitializeCommandsAfterConnect(array $commands)
1564 $this->disconnectIfConnected();
1565 $this->initializeCommandsAfterConnect
= $commands;
1569 * Set the charset that should be used for the MySQL connection.
1570 * The given value will be passed on to mysqli_set_charset().
1572 * The default value of this setting is utf8.
1574 * @param string $connectionCharset The connection charset that will be passed on to mysqli_set_charset() when connecting the database. Default is utf8.
1577 public function setConnectionCharset($connectionCharset = 'utf8')
1579 $this->disconnectIfConnected();
1580 $this->connectionCharset
= $connectionCharset;
1584 * Connects to database for TYPO3 sites:
1586 * @throws \RuntimeException
1587 * @throws \UnexpectedValueException
1590 public function connectDB()
1592 // Early return if connected already
1593 if ($this->isConnected
) {
1597 if (!$this->databaseName
) {
1598 throw new \
RuntimeException(
1599 'TYPO3 Fatal Error: No database selected!',
1604 if ($this->sql_pconnect()) {
1605 if (!$this->sql_select_db()) {
1606 throw new \
RuntimeException(
1607 'TYPO3 Fatal Error: Cannot connect to the current database, "' . $this->databaseName
. '"!',
1612 throw new \
RuntimeException(
1613 'TYPO3 Fatal Error: The current username, password or host was not accepted when the connection to the database was attempted to be established!',
1618 // Prepare user defined objects (if any) for hooks which extend query methods
1619 $this->preProcessHookObjects
= array();
1620 $this->postProcessHookObjects
= array();
1621 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'])) {
1622 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'] as $classRef) {
1623 $hookObject = GeneralUtility
::getUserObj($classRef);
1625 $hookObject instanceof PreProcessQueryHookInterface
1626 ||
$hookObject instanceof PostProcessQueryHookInterface
1628 throw new \
UnexpectedValueException(
1629 '$hookObject must either implement interface TYPO3\\CMS\\Core\\Database\\PreProcessQueryHookInterface or interface TYPO3\\CMS\\Core\\Database\\PostProcessQueryHookInterface',
1633 if ($hookObject instanceof PreProcessQueryHookInterface
) {
1634 $this->preProcessHookObjects
[] = $hookObject;
1636 if ($hookObject instanceof PostProcessQueryHookInterface
) {
1637 $this->postProcessHookObjects
[] = $hookObject;
1644 * Checks if database is connected
1648 public function isConnected()
1650 // We think we're still connected
1651 if ($this->isConnected
) {
1652 // Check if this is really the case or if the database server has gone away for some reason
1653 // Using mysqlnd ping() does not reconnect (which we would not want anyway since charset etc would not be reinitialized that way)
1654 $this->isConnected
= $this->link
->ping();
1656 return $this->isConnected
;
1660 * Checks if the current connection character set has the same value
1661 * as the connectionCharset variable.
1663 * To determine the character set these MySQL session variables are
1664 * checked: character_set_client, character_set_results and
1665 * character_set_connection.
1667 * If the character set does not match or if the session variables
1668 * can not be read a RuntimeException is thrown.
1671 * @throws \RuntimeException
1673 protected function checkConnectionCharset()
1675 $sessionResult = $this->sql_query('SHOW SESSION VARIABLES LIKE \'character_set%\'');
1677 if ($sessionResult === false) {
1678 GeneralUtility
::sysLog(
1679 'Error while retrieving the current charset session variables from the database: ' . $this->sql_error(),
1681 GeneralUtility
::SYSLOG_SEVERITY_ERROR
1683 throw new \
RuntimeException(
1684 'TYPO3 Fatal Error: Could not determine the current charset of the database.',
1689 $charsetVariables = array();
1690 while (($row = $this->sql_fetch_row($sessionResult)) !== false) {
1691 $variableName = $row[0];
1692 $variableValue = $row[1];
1693 $charsetVariables[$variableName] = $variableValue;
1695 $this->sql_free_result($sessionResult);
1697 // These variables are set with the "Set names" command which was
1698 // used in the past. This is why we check them.
1699 $charsetRequiredVariables = array(
1700 'character_set_client',
1701 'character_set_results',
1702 'character_set_connection',
1705 $hasValidCharset = true;
1706 foreach ($charsetRequiredVariables as $variableName) {
1707 if (empty($charsetVariables[$variableName])) {
1708 GeneralUtility
::sysLog(
1709 'A required session variable is missing in the current MySQL connection: ' . $variableName,
1711 GeneralUtility
::SYSLOG_SEVERITY_ERROR
1713 throw new \
RuntimeException(
1714 'TYPO3 Fatal Error: Could not determine the value of the database session variable: ' . $variableName,
1719 if ($charsetVariables[$variableName] !== $this->connectionCharset
) {
1720 $hasValidCharset = false;
1725 if (!$hasValidCharset) {
1726 throw new \
RuntimeException(
1727 'It looks like the character set ' . $this->connectionCharset
. ' is not used for this connection even though it is configured as connection charset. ' .
1728 'This TYPO3 installation is using the $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'setDBinit\'] property with the following value: "' .
1729 $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'] . '". Please make sure that this command does not overwrite the configured charset. ' .
1730 'Please note that for the TYPO3 database everything other than utf8 is unsupported since version 4.7.',
1737 * Disconnect from database if connected
1741 protected function disconnectIfConnected()
1743 if ($this->isConnected
) {
1744 $this->link
->close();
1745 $this->isConnected
= false;
1750 * Returns current database handle
1752 * @return \mysqli|NULL
1754 public function getDatabaseHandle()
1760 * Set current database handle, usually \mysqli
1762 * @param \mysqli $handle
1764 public function setDatabaseHandle($handle)
1766 $this->link
= $handle;
1770 * Get the MySQL server version
1774 public function getServerVersion()
1776 return $this->link
->server_info
;
1779 /******************************
1783 ******************************/
1785 * Debug function: Outputs error if any
1787 * @param string $func Function calling debug()
1788 * @param string $query Last query if not last built query
1791 public function debug($func, $query = '')
1793 $error = $this->sql_error();
1794 if ($error ||
(int)$this->debugOutput
=== 2) {
1795 \TYPO3\CMS\Core\Utility\DebugUtility
::debug(
1797 'caller' => \TYPO3\CMS\Core\Database\DatabaseConnection
::class . '::' . $func,
1799 'lastBuiltQuery' => $query ?
$query : $this->debug_lastBuiltQuery
,
1800 'debug_backtrace' => \TYPO3\CMS\Core\Utility\DebugUtility
::debugTrail()
1803 is_object($GLOBALS['error']) && @is_callable
(array($GLOBALS['error'], 'debug'))
1811 * Checks if record set is valid and writes debugging information into devLog if not.
1813 * @param bool|\mysqli_result|object MySQLi result object / DBAL object
1814 * @return bool TRUE if the record set is valid, FALSE otherwise
1816 public function debug_check_recordset($res)
1818 if ($res !== false) {
1821 $trace = debug_backtrace(0);
1822 array_shift($trace);
1823 $msg = 'Invalid database result detected: function TYPO3\\CMS\\Core\\Database\\DatabaseConnection->'
1824 . $trace[0]['function'] . ' called from file ' . substr($trace[0]['file'], (strlen(PATH_site
) +
2))
1825 . ' in line ' . $trace[0]['line'] . '.';
1826 GeneralUtility
::sysLog(
1827 $msg . ' Use a devLog extension to get more details.',
1829 GeneralUtility
::SYSLOG_SEVERITY_ERROR
1831 // Send to devLog if enabled
1833 $debugLogData = array(
1834 'SQL Error' => $this->sql_error(),
1835 'Backtrace' => $trace
1837 if ($this->debug_lastBuiltQuery
) {
1838 $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery
) +
$debugLogData;
1840 GeneralUtility
::devLog($msg, 'Core/t3lib_db', 3, $debugLogData);
1846 * Explain select queries
1847 * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
1848 * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
1850 * @todo Feature is not DBAL-compliant
1852 * @param string $query SQL query
1853 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
1854 * @param int $row_count Number of resulting rows
1855 * @return bool TRUE if explain was run, FALSE otherwise
1857 protected function explain($query, $from_table, $row_count)
1859 $debugAllowedForIp = GeneralUtility
::cmpIP(
1860 GeneralUtility
::getIndpEnv('REMOTE_ADDR'),
1861 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1864 (int)$this->explainOutput
== 1
1865 ||
((int)$this->explainOutput
== 2 && $debugAllowedForIp)
1869 } elseif ((int)$this->explainOutput
== 3 && is_object($GLOBALS['TT'])) {
1870 // Embed the output into the TS admin panel
1875 $error = $this->sql_error();
1876 $trail = \TYPO3\CMS\Core\Utility\DebugUtility
::debugTrail();
1877 $explain_tables = array();
1878 $explain_output = array();
1879 $res = $this->sql_query('EXPLAIN ' . $query, $this->link
);
1880 if (is_a($res, '\\mysqli_result')) {
1881 while ($tempRow = $this->sql_fetch_assoc($res)) {
1882 $explain_output[] = $tempRow;
1883 $explain_tables[] = $tempRow['table'];
1885 $this->sql_free_result($res);
1887 $indices_output = array();
1888 // Notice: Rows are skipped if there is only one result, or if no conditions are set
1889 if ($explain_output[0]['rows'] > 1 ||
$explain_output[0]['type'] === 'ALL') {
1890 // Only enable output if it's really useful
1892 foreach ($explain_tables as $table) {
1893 $tableRes = $this->sql_query('SHOW TABLE STATUS LIKE \'' . $table . '\'');
1894 $isTable = $this->sql_num_rows($tableRes);
1896 $res = $this->sql_query('SHOW INDEX FROM ' . $table, $this->link
);
1897 if (is_a($res, '\\mysqli_result')) {
1898 while ($tempRow = $this->sql_fetch_assoc($res)) {
1899 $indices_output[] = $tempRow;
1901 $this->sql_free_result($res);
1904 $this->sql_free_result($tableRes);
1912 $data['query'] = $query;
1913 $data['trail'] = $trail;
1914 $data['row_count'] = $row_count;
1916 $data['error'] = $error;
1918 if (!empty($explain_output)) {
1919 $data['explain'] = $explain_output;
1921 if (!empty($indices_output)) {
1922 $data['indices'] = $indices_output;
1924 if ($explainMode == 1) {
1925 \TYPO3\CMS\Core\Utility\DebugUtility
::debug($data, 'Tables: ' . $from_table, 'DB SQL EXPLAIN');
1926 } elseif ($explainMode == 2) {
1927 $GLOBALS['TT']->setTSselectQuery($data);
1936 * Serialize destructs current connection
1938 * @return array All protected properties that should be saved
1940 public function __sleep()
1942 $this->disconnectIfConnected();
1951 'databaseUserPassword',
1952 'persistentDatabaseConnection',
1953 'connectionCompression',
1954 'initializeCommandsAfterConnect',