📄 class.ux_t3lib_db.php
字号:
<?php/**************************************************************** Copyright notice** (c) 2004-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)* All rights reserved** This script is part of the TYPO3 project. The TYPO3 project is* free software; you can redistribute it and/or modify* it under the terms of the GNU General Public License as published by* the Free Software Foundation; either version 2 of the License, or* (at your option) any later version.** The GNU General Public License can be found at* http://www.gnu.org/copyleft/gpl.html.* A copy is found in the textfile GPL.txt and important notices to the license* from the author is found in LICENSE.txt distributed with these scripts.*** This script is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the* GNU General Public License for more details.** This copyright notice MUST APPEAR in all copies of the script!***************************************************************//** * Contains a database abstraction layer class for TYPO3 * * $Id: class.ux_t3lib_db.php 2013 2007-02-07 00:09:25Z mundaun $ * * @author Kasper Skaarhoj <kasper@typo3.com> * @author Karsten Dambekalns <k.dambekalns@fishfarm.de> *//** * [CLASS/FUNCTION INDEX of SCRIPT] * * * * 123: class ux_t3lib_DB extends t3lib_DB * 169: function ux_t3lib_DB() * 184: function initInternalVariables() * * SECTION: Query Building (Overriding parent methods) * 217: function exec_INSERTquery($table,$fields_values) * 275: function exec_UPDATEquery($table,$where,$fields_values) * 334: function exec_DELETEquery($table,$where) * 387: function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='') * * SECTION: Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values. * 533: function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='') * 556: function quoteSelectFields(&$select_fields) * 573: function quoteFromTables(&$from_table) * 595: function quoteWhereClause(&$where_clause) * 620: function quoteGroupBy(&$groupBy) * 637: function quoteOrderBy(&$orderBy) * * SECTION: Various helper functions * 663: function quoteStr($str, $table) * * SECTION: SQL wrapper functions (Overriding parent methods) * 707: function sql_error() * 734: function sql_num_rows(&$res) * 760: function sql_fetch_assoc(&$res) * 808: function sql_fetch_row(&$res) * 842: function sql_free_result(&$res) * 868: function sql_insert_id() * 893: function sql_affected_rows() * 919: function sql_data_seek(&$res,$seek) * 946: function sql_field_type(&$res,$pointer) * * SECTION: Legacy functions, bound to _DEFAULT handler. (Overriding parent methods) * 987: function sql($db,$query) * 999: function sql_query($query) * 1035: function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) * 1055: function sql_select_db($TYPO3_db) * * SECTION: SQL admin functions * 1086: function admin_get_tables() * 1149: function admin_get_fields($tableName) * 1210: function admin_get_keys($tableName) * 1270: function admin_query($query) * * SECTION: Handler management * 1333: function handler_getFromTableList($tableList) * 1379: function handler_init($handlerKey) * * SECTION: Table/Field mapping * 1488: function map_needMapping($tableList,$fieldMappingOnly=FALSE) * 1524: function map_assocArray($input,$tables,$rev=FALSE) * 1573: function map_remapSELECTQueryParts(&$select_fields,&$from_table,&$where_clause,&$groupBy,&$orderBy) * 1615: function map_sqlParts(&$sqlPartArray, $defaultTable) * 1650: function map_genericQueryParsed(&$parsedQuery) * 1717: function map_fieldNamesInArray($table,&$fieldArray) * * SECTION: Debugging * 1758: function debugHandler($function,$execTime,$inData) * 1823: function debug_log($query,$ms,$data,$join,$errorFlag) * 1849: function debug_explain($query) * * TOTAL FUNCTIONS: 41 * (This index is automatically created/updated by the extension "extdeveval") * */require_once(PATH_t3lib.'class.t3lib_sqlengine.php');require_once(PATH_t3lib.'class.t3lib_install.php');/** * TYPO3 database abstraction layer * * @author Kasper Skaarhoj <kasper@typo3.com> * @author Karsten Dambekalns <k.dambekalns@fishfarm.de> * @package TYPO3 * @subpackage tx_dbal */class ux_t3lib_DB extends t3lib_DB { // Internal, static: var $printErrors = false; // Enable output of SQL errors after query executions. Set through TYPO3_CONF_VARS, see init() var $debug = false; // Enable debug mode. Set through TYPO3_CONF_VARS, see init() var $conf = array(); // Configuration array, copied from TYPO3_CONF_VARS in constructor. var $mapping = array(); // See manual. var $table2handlerKeys = array(); // See manual. var $handlerCfg = array ( // See manual. '_DEFAULT' => array ( 'type' => 'native', 'config' => array( 'username' => '', // Set by default (overridden) 'password' => '', // Set by default (overridden) 'host' => '', // Set by default (overridden) 'database' => '', // Set by default (overridden) 'driver' => '', // ONLY "adodb" type; eg. "mysql" 'sequenceStart' => 1 // ONLY "adodb", first number in sequences/serials/... ) ), ); // Internal, dynamic: var $handlerInstance = array(); // Contains instance of the handler objects as they are created. Exception is the native mySQL calls which are registered as an array with keys "handlerType" = "native" and "link" pointing to the link resource for the connection. var $lastHandlerKey = ''; // Storage of the handler key of last ( SELECT) query - used for subsequent fetch-row calls etc. var $lastQuery = ''; // Storage of last SELECT query var $lastParsedAndMappedQueryArray = array(); // Query array, the last one parsed var $resourceIdToTableNameMap = array(); // Mapping of resource ids to table names. // Internal, caching: var $cache_handlerKeyFromTableList = array(); // Caching handlerKeys for table lists var $cache_mappingFromTableList = array(); // Caching mapping information for table lists var $cache_autoIncFields = array(); // parsed SQL from standard DB dump file var $cache_fieldType = array(); // field types for tables/fields var $cache_primaryKeys = array(); // primary keys /** * Constructor. * Creates SQL parser object and imports configuration from $TYPO3_CONF_VARS['EXTCONF']['dbal'] * * @return void */ function ux_t3lib_DB() { // Set SQL parser object for internal use: $this->SQLparser = t3lib_div::makeInstance('t3lib_sqlengine'); $this->Installer = t3lib_div::makeInstance('t3lib_install'); // Set internal variables with configuration: $this->conf = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal']; $this->initInternalVariables(); } /** * Setting internal variables from $this->conf * * @return void */ function initInternalVariables() { // Set outside configuration: if (isset($this->conf['mapping'])) $this->mapping = $this->conf['mapping']; if (isset($this->conf['table2handlerKeys'])) $this->table2handlerKeys = $this->conf['table2handlerKeys']; if (isset($this->conf['handlerCfg'])) $this->handlerCfg = $this->conf['handlerCfg']; $this->cacheFieldInfo(); // Debugging settings: $this->printErrors = $this->conf['debugOptions']['printErrors'] ? TRUE : FALSE; $this->debug = $this->conf['debugOptions']['enabled'] ? TRUE : FALSE; } function clearCachedFieldInfo() { if(file_exists(PATH_typo3conf.'temp_fieldInfo.php')) unlink(PATH_typo3conf.'temp_fieldInfo.php'); } function cacheFieldInfo() { global $TYPO3_LOADED_EXT; $extSQL = ''; $parsedExtSQL = array(); // try to fetch cached file first // file is removed when admin_query() is called if(file_exists(PATH_typo3conf.'temp_fieldInfo.php')) { $fdata = unserialize(t3lib_div::getUrl(PATH_typo3conf.'temp_fieldInfo.php')); $this->cache_autoIncFields = $fdata['incFields']; $this->cache_fieldType = $fdata['fieldTypes']; $this->cache_primaryKeys = $fdata['primaryKeys']; } else { // handle stddb.sql, parse and analyze $extSQL = t3lib_div::getUrl(PATH_site.'t3lib/stddb/tables.sql'); $parsedExtSQL = $this->Installer->getFieldDefinitions_sqlContent($extSQL); $this->analyzeFields($parsedExtSQL); // loop over all installed extensions foreach($TYPO3_LOADED_EXT as $ext => $v) { if(!is_array($v) || !isset($v['ext_tables.sql'])) continue; // fetch db dump (if any) and parse it, then analyze $extSQL = t3lib_div::getUrl($v['ext_tables.sql']); $parsedExtSQL = $this->Installer->getFieldDefinitions_sqlContent($extSQL); $this->analyzeFields($parsedExtSQL); } $cachedFieldInfo = array('incFields' => $this->cache_autoIncFields, 'fieldTypes' => $this->cache_fieldType, 'primaryKeys' => $this->cache_primaryKeys); $cachedFieldInfo = serialize($this->mapCachedFieldInfo($cachedFieldInfo)); // write serialized content to file t3lib_div::writeFile(PATH_typo3conf."temp_fieldInfo.php", $cachedFieldInfo); if (strcmp(t3lib_div::getUrl(PATH_typo3conf."temp_fieldInfo.php"), $cachedFieldInfo)) { die('typo3temp/temp_incfields.php was NOT updated properly (written content didn\'t match file content) - maybe write access problem?'); } } } /** * Analyzes fields and adds the extracted information to the field type, auto increment and primary key info caches. * * @param array $parsedExtSQL The output produced by t3lib_install::getFieldDefinitions_sqlContent() * @return void * @see t3lib_install::getFieldDefinitions_sqlContent() */ function analyzeFields($parsedExtSQL) { foreach($parsedExtSQL as $table => $tdef) { if (is_array($tdef['fields'])) { foreach($tdef['fields'] as $field => $fdef) { $fdef = $this->SQLparser->parseFieldDef($fdef); $this->cache_fieldType[$table][$field]['type'] = $fdef['fieldType']; $this->cache_fieldType[$table][$field]['metaType'] = $this->MySQLMetaType($fdef['fieldType']); $this->cache_fieldType[$table][$field]['notnull'] = (isset($fdef['featureIndex']['NOTNULL']) && !$this->SQLparser->checkEmptyDefaultValue($fdef['featureIndex'])) ? 1 : 0; if(isset($fdef['featureIndex']['AUTO_INCREMENT'])) { $this->cache_autoIncFields[$table] = $field; } if(isset($tdef['keys']['PRIMARY'])) { $this->cache_primaryKeys[$table] = substr($tdef['keys']['PRIMARY'], 13, -1); } } } } } /** * This function builds all definitions for mapped tables and fields * @see cacheFieldInfo() */ function mapCachedFieldInfo($fieldInfo){ global $TYPO3_CONF_VARS; if(is_array($TYPO3_CONF_VARS['EXTCONF']['dbal']['mapping'])) { foreach($TYPO3_CONF_VARS['EXTCONF']['dbal']['mapping'] as $mappedTable => $mappedConf){ if(array_key_exists($mappedTable, $fieldInfo['incFields'])) { $mappedTableAlias = $mappedConf['mapTableName']; $fieldInfo['incFields'][$mappedTableAlias] = isset($mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]]) ? $mappedConf['mapFieldNames'][$fieldInfo['incFields'][$mappedTable]] : $fieldInfo['incFields'][$mappedTable]; } if(array_key_exists($mappedTable, $fieldInfo['fieldTypes'])) { foreach($fieldInfo['fieldTypes'][$mappedTable] as $field => $fieldConf){ $tempMappedFieldConf[$mappedConf['mapFieldNames'][$field]] = $fieldConf; } $fieldInfo['fieldTypes'][$mappedConf['mapTableName']] = $tempMappedFieldConf; } if(array_key_exists($mappedTable, $fieldInfo['primaryKeys'])) { $mappedTableAlias = $mappedConf['mapTableName']; $fieldInfo['primaryKeys'][$mappedTableAlias] = isset($mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]]) ? $mappedConf['mapFieldNames'][$fieldInfo['primaryKeys'][$mappedTable]] : $fieldInfo['primaryKeys'][$mappedTable]; } } } return $fieldInfo; } /************************************ * * Query Building (Overriding parent methods) * These functions are extending counterparts in the parent class. * **************************************/ /* From the ADOdb documentation, this is what we do (_Execute for SELECT, _query for the other actions) Execute() is the default way to run queries. You can use the low-level functions _Execute() and _query() to reduce query overhead. Both these functions share the same parameters as Execute(). If you do not have any bind parameters or your database supports binding (without emulation), then you can call _Execute() directly. Calling this function bypasses bind emulation. Debugging is still supported in _Execute(). If you do not require debugging facilities nor emulated binding, and do not require a recordset to be returned, then you can call _query. This is great for inserts, updates and deletes. Calling this function bypasses emulated binding, debugging, and recordset handling. Either the resultid, true or false are returned by _query(). */ /** * Inserts a record for $table from the array with field/value pairs $fields_values. * * @param string Table name * @param array 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. * @param mixed List/array of keys NOT to quote (eg. SQL functions) * @return mixed Result from handler, usually TRUE when success and FALSE on failure */ function exec_INSERTquery($table,$fields_values,$no_quote_fields='') { if ($this->debug) $pt = t3lib_div::milliseconds(); // Do field mapping if needed: $ORIG_tableName = $table; if ($tableArray = $this->map_needMapping($table)) { // Field mapping of array: $fields_values = $this->map_assocArray($fields_values,$tableArray); // Table name: if ($this->mapping[$table]['mapTableName']) { $table = $this->mapping[$table]['mapTableName']; } } // Select API: $this->lastHandlerKey = $this->handler_getFromTableList($ORIG_tableName); switch((string)$this->handlerCfg[$this->lastHandlerKey]['type']) { case 'native': $this->lastQuery = $this->INSERTquery($table,$fields_values,$no_quote_fields); if(is_string($this->lastQuery)) { $sqlResult = mysql_query($this->lastQuery, $this->handlerInstance[$this->lastHandlerKey]['link']); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -