/base/lib/flourishlib/fDatabase.php
PHP | 3242 lines | 2035 code | 420 blank | 787 comment | 515 complexity | 074f964f1e623036c3a68457a94dff53 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Provides a common API for different databases - will automatically use any installed extension
- *
- * This class is implemented to use the UTF-8 character encoding. Please see
- * http://flourishlib.com/docs/UTF-8 for more information.
- *
- * The following databases are supported:
- *
- * - [http://ibm.com/db2 DB2]
- * - [http://microsoft.com/sql/ MSSQL]
- * - [http://mysql.com MySQL]
- * - [http://oracle.com Oracle]
- * - [http://postgresql.org PostgreSQL]
- * - [http://sqlite.org SQLite]
- *
- * The class will automatically use the first of the following extensions it finds:
- *
- * - DB2
- * - [http://php.net/ibm_db2 ibm_db2]
- * - [http://php.net/pdo_ibm pdo_ibm]
- * - MSSQL
- * - [http://msdn.microsoft.com/en-us/library/cc296221.aspx sqlsrv]
- * - [http://php.net/pdo_dblib pdo_dblib]
- * - [http://php.net/mssql mssql] (or [http://php.net/sybase sybase])
- * - MySQL
- * - [http://php.net/mysql mysql]
- * - [http://php.net/mysqli mysqli]
- * - [http://php.net/pdo_mysql pdo_mysql]
- * - Oracle
- * - [http://php.net/oci8 oci8]
- * - [http://php.net/pdo_oci pdo_oci]
- * - PostgreSQL
- * - [http://php.net/pgsql pgsql]
- * - [http://php.net/pdo_pgsql pdo_pgsql]
- * - SQLite
- * - [http://php.net/pdo_sqlite pdo_sqlite] (for v3.x)
- * - [http://php.net/sqlite sqlite] (for v2.x)
- *
- * The `odbc` and `pdo_odbc` extensions are not supported due to character
- * encoding and stability issues on Windows, and functionality on non-Windows
- * operating systems.
- *
- * @copyright Copyright (c) 2007-2011 Will Bond
- * @author Will Bond [wb] <will@flourishlib.com>
- * @license http://flourishlib.com/license
- *
- * @package Flourish
- * @link http://flourishlib.com/fDatabase
- *
- * @version 1.0.0b37
- * @changes 1.0.0b37 Fixed usage of the mysqli extension to only call mysqli_set_charset() if it exists [wb, 2011-03-04]
- * @changes 1.0.0b36 Updated ::escape() and methods that use ::escape() to handle float values that don't contain a digit before or after the . [wb, 2011-02-01]
- * @changes 1.0.0b35 Updated the class to replace `LIMIT` and `OFFSET` value placeholders in the SQL with their values before translating since most databases that translate `LIMIT` statements need to move or add values together [wb, 2011-01-11]
- * @changes 1.0.0b34 Fixed a bug with creating translated prepared statements [wb, 2011-01-09]
- * @changes 1.0.0b33 Added code to explicitly set the connection encoding for the mysql and mysqli extensions since some PHP installs don't see to fully respect `SET NAMES` [wb, 2010-12-06]
- * @changes 1.0.0b32 Fixed handling auto-incrementing values for Oracle when the trigger was on `INSERT OR UPDATE` instead of just `INSERT` [wb, 2010-12-04]
- * @changes 1.0.0b31 Fixed handling auto-incrementing values for MySQL when the `INTO` keyword is left out of an `INSERT` statement [wb, 2010-11-04]
- * @changes 1.0.0b30 Fixed the pgsql, mssql and mysql extensions to force a new connection instead of reusing an existing one [wb, 2010-08-17]
- * @changes 1.0.0b29 Backwards Compatibility Break - removed ::enableSlowQueryWarnings(), added ability to replicate via ::registerHookCallback() [wb, 2010-08-10]
- * @changes 1.0.0b28 Backwards Compatibility Break - removed ODBC support. Added support for the `pdo_ibm` extension. [wb, 2010-07-31]
- * @changes 1.0.0b27 Fixed a bug with running multiple copies of a SQL statement with string values through a single ::translatedQuery() call [wb, 2010-07-14]
- * @changes 1.0.0b26 Updated the class to use new fCore functionality [wb, 2010-07-05]
- * @changes 1.0.0b25 Added IBM DB2 support [wb, 2010-04-13]
- * @changes 1.0.0b24 Fixed an auto-incrementing transaction bug with Oracle and debugging issues with all databases [wb, 2010-03-17]
- * @changes 1.0.0b23 Resolved another bug with capturing auto-incrementing values for PostgreSQL and Oracle [wb, 2010-03-15]
- * @changes 1.0.0b22 Changed ::clearCache() to also clear the cache on the fSQLTranslation [wb, 2010-03-09]
- * @changes 1.0.0b21 Added ::execute() for result-less SQL queries, ::prepare() and ::translatedPrepare() to create fStatement objects for prepared statements, support for prepared statements in ::query() and ::unbufferedQuery(), fixed default caching key for ::enableCaching() [wb, 2010-03-02]
- * @changes 1.0.0b20 Added a parameter to ::enableCaching() to provide a key token that will allow cached values to be shared between multiple databases with the same schema [wb, 2009-10-28]
- * @changes 1.0.0b19 Added support for escaping identifiers (column and table names) to ::escape(), added support for database schemas, rewrote internal SQL string spliting [wb, 2009-10-22]
- * @changes 1.0.0b18 Updated the class for the new fResult and fUnbufferedResult APIs, fixed ::unescape() to not touch NULLs [wb, 2009-08-12]
- * @changes 1.0.0b17 Added the ability to pass an array of all values as a single parameter to ::escape() instead of one value per parameter [wb, 2009-08-11]
- * @changes 1.0.0b16 Fixed PostgreSQL and Oracle from trying to get auto-incrementing values on inserts when explicit values were given [wb, 2009-08-06]
- * @changes 1.0.0b15 Fixed a bug where auto-incremented values would not be detected when table names were quoted [wb, 2009-07-15]
- * @changes 1.0.0b14 Changed ::determineExtension() and ::determineCharacterSet() to be protected instead of private [wb, 2009-07-08]
- * @changes 1.0.0b13 Updated ::escape() to accept arrays of values for insertion into full SQL strings [wb, 2009-07-06]
- * @changes 1.0.0b12 Updates to ::unescape() to improve performance [wb, 2009-06-15]
- * @changes 1.0.0b11 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
- * @changes 1.0.0b10 Changed date/time/timestamp escaping from `strtotime()` to fDate/fTime/fTimestamp for better localization support [wb, 2009-06-01]
- * @changes 1.0.0b9 Fixed a bug with ::escape() where floats that start with a . were encoded as `NULL` [wb, 2009-05-09]
- * @changes 1.0.0b8 Added Oracle support, change PostgreSQL code to no longer cause lastval() warnings, added support for arrays of values to ::escape() [wb, 2009-05-03]
- * @changes 1.0.0b7 Updated for new fCore API [wb, 2009-02-16]
- * @changes 1.0.0b6 Fixed a bug with executing transaction queries when using the mysqli extension [wb, 2009-02-12]
- * @changes 1.0.0b5 Changed @ error suppression operator to `error_reporting()` calls [wb, 2009-01-26]
- * @changes 1.0.0b4 Added a few error suppression operators back in so that developers don't get errors and exceptions [wb, 2009-01-14]
- * @changes 1.0.0b3 Removed some unnecessary error suppresion operators [wb, 2008-12-11]
- * @changes 1.0.0b2 Fixed a bug with PostgreSQL when using the PDO extension and executing an INSERT statement [wb, 2008-12-11]
- * @changes 1.0.0b The initial implementation [wb, 2007-09-25]
- */
- class fDatabase
- {
- /**
- * Composes text using fText if loaded
- *
- * @param string $message The message to compose
- * @param mixed $component A string or number to insert into the message
- * @param mixed ...
- * @return string The composed and possible translated message
- */
- static protected function compose($message)
- {
- $args = array_slice(func_get_args(), 1);
-
- if (class_exists('fText', FALSE)) {
- return call_user_func_array(
- array('fText', 'compose'),
- array($message, $args)
- );
- } else {
- return vsprintf($message, $args);
- }
- }
-
-
- /**
- * An fCache object to cache the schema info to
- *
- * @var fCache
- */
- private $cache;
-
- /**
- * The cache prefix to use for cache entries
- *
- * @var string
- */
- private $cache_prefix;
-
- /**
- * Database connection resource or PDO object
- *
- * @var mixed
- */
- private $connection;
-
- /**
- * The database name
- *
- * @var string
- */
- private $database;
-
- /**
- * If debugging is enabled
- *
- * @var boolean
- */
- private $debug;
-
- /**
- * A temporary error holder for the mssql extension
- *
- * @var string
- */
- private $error;
-
- /**
- * The extension to use for the database specified
- *
- * Options include:
- *
- * - `'ibm_db2'`
- * - `'mssql'`
- * - `'mysql'`
- * - `'mysqli'`
- * - `'oci8'`
- * - `'pgsql'`
- * - `'sqlite'`
- * - `'sqlsrv'`
- * - `'pdo'`
- *
- * @var string
- */
- protected $extension;
-
- /**
- * Hooks callbacks to be used for accessing and modifying queries
- *
- * This array will have the structure:
- *
- * {{{
- * array(
- * 'unmodified' => array({callbacks}),
- * 'extracted' => array({callbacks}),
- * 'run' => array({callbacks})
- * )
- * }}}
- *
- * @var array
- */
- private $hook_callbacks;
-
- /**
- * The host the database server is located on
- *
- * @var string
- */
- private $host;
-
- /**
- * If a transaction is in progress
- *
- * @var boolean
- */
- private $inside_transaction;
-
- /**
- * The password for the user specified
- *
- * @var string
- */
- private $password;
-
- /**
- * The port number for the host
- *
- * @var string
- */
- private $port;
-
- /**
- * The total number of seconds spent executing queries
- *
- * @var float
- */
- private $query_time;
-
- /**
- * A cache of database-specific code
- *
- * @var array
- */
- protected $schema_info;
-
- /**
- * The last executed fStatement object
- *
- * @var fStatement
- */
- private $statement;
-
- /**
- * The fSQLTranslation object for this database
- *
- * @var object
- */
- private $translation;
-
- /**
- * The database type: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, or `'sqlite'`
- *
- * @var string
- */
- private $type;
-
- /**
- * The unbuffered query instance
- *
- * @var fUnbufferedResult
- */
- private $unbuffered_result;
-
- /**
- * The user to connect to the database as
- *
- * @var string
- */
- private $username;
-
-
- /**
- * Configures the connection to a database - connection is not made until the first query is executed
- *
- * @param string $type The type of the database: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, `'sqlite'`
- * @param string $database Name of the database. If SQLite the path to the database file.
- * @param string $username Database username - not used for SQLite
- * @param string $password The password for the username specified - not used for SQLite
- * @param string $host Database server host or IP, defaults to localhost - not used for SQLite. MySQL socket connection can be made by entering `'sock:'` followed by the socket path. PostgreSQL socket connection can be made by passing just `'sock:'`.
- * @param integer $port The port to connect to, defaults to the standard port for the database type specified - not used for SQLite
- * @return fDatabase
- */
- public function __construct($type, $database, $username=NULL, $password=NULL, $host=NULL, $port=NULL)
- {
- $valid_types = array('db2', 'mssql', 'mysql', 'oracle', 'postgresql', 'sqlite');
- if (!in_array($type, $valid_types)) {
- throw new fProgrammerException(
- 'The database type specified, %1$s, is invalid. Must be one of: %2$s.',
- $type,
- join(', ', $valid_types)
- );
- }
-
- if (empty($database)) {
- throw new fProgrammerException('No database was specified');
- }
-
- if ($host === NULL) {
- $host = 'localhost';
- }
-
- $this->type = $type;
- $this->database = $database;
- $this->username = $username;
- $this->password = $password;
- $this->host = $host;
- $this->port = $port;
-
- $this->hook_callbacks = array(
- 'unmodified' => array(),
- 'extracted' => array(),
- 'run' => array()
- );
-
- $this->schema_info = array();
-
- $this->determineExtension();
- }
-
-
- /**
- * Closes the open database connection
- *
- * @internal
- *
- * @return void
- */
- public function __destruct()
- {
- if (!$this->connection) { return; }
-
- fCore::debug('Total query time: ' . $this->query_time . ' seconds', $this->debug);
- if ($this->extension == 'ibm_db2') {
- db2_close($this->connection);
- } elseif ($this->extension == 'mssql') {
- mssql_close($this->connection);
- } elseif ($this->extension == 'mysql') {
- mysql_close($this->connection);
- } elseif ($this->extension == 'mysqli') {
- mysqli_close($this->connection);
- } elseif ($this->extension == 'oci8') {
- oci_close($this->connection);
- } elseif ($this->extension == 'pgsql') {
- pg_close($this->connection);
- } elseif ($this->extension == 'sqlite') {
- sqlite_close($this->connection);
- } elseif ($this->extension == 'sqlsrv') {
- sqlsrv_close($this->connection);
- } elseif ($this->extension == 'pdo') {
- // PDO objects close their own connections when destroyed
- }
- }
-
-
- /**
- * All requests that hit this method should be requests for callbacks
- *
- * @internal
- *
- * @param string $method The method to create a callback for
- * @return callback The callback for the method requested
- */
- public function __get($method)
- {
- return array($this, $method);
- }
-
-
- /**
- * Checks to see if an SQL error occured
- *
- * @param fResult|fUnbufferedResult|boolean $result The result object for the query
- * @param mixed $extra_info The sqlite extension will pass a string error message, the oci8 extension will pass the statement resource
- * @param string $sql The SQL that was executed
- * @return void
- */
- private function checkForError($result, $extra_info=NULL, $sql=NULL)
- {
- if ($result === FALSE || $result->getResult() === FALSE) {
-
- if ($this->extension == 'ibm_db2') {
- if (is_resource($extra_info)) {
- $message = db2_stmt_errormsg($extra_info);
- } else {
- $message = db2_stmt_errormsg();
- }
- } elseif ($this->extension == 'mssql') {
- $message = $this->error;
- unset($this->error);
- } elseif ($this->extension == 'mysql') {
- $message = mysql_error($this->connection);
- } elseif ($this->extension == 'mysqli') {
- if (is_object($extra_info)) {
- $message = $extra_info->error;
- } else {
- $message = mysqli_error($this->connection);
- }
- } elseif ($this->extension == 'oci8') {
- $error_info = oci_error($extra_info);
- $message = $error_info['message'];
- } elseif ($this->extension == 'pgsql') {
- $message = pg_last_error($this->connection);
- } elseif ($this->extension == 'sqlite') {
- $message = $extra_info;
- } elseif ($this->extension == 'sqlsrv') {
- $error_info = sqlsrv_errors(SQLSRV_ERR_ALL);
- $message = $error_info[0]['message'];
- } elseif ($this->extension == 'pdo') {
- if ($extra_info instanceof PDOStatement) {
- $error_info = $extra_info->errorInfo();
- } else {
- $error_info = $this->connection->errorInfo();
- }
- if (empty($error_info[2])) {
- $error_info[2] = 'Unknown error - this usually indicates a bug in the PDO driver';
- }
- $message = $error_info[2];
- }
-
- $db_type_map = array(
- 'db2' => 'DB2',
- 'mssql' => 'MSSQL',
- 'mysql' => 'MySQL',
- 'oracle' => 'Oracle',
- 'postgresql' => 'PostgreSQL',
- 'sqlite' => 'SQLite'
- );
-
- throw new fSQLException(
- '%1$s error (%2$s) in %3$s',
- $db_type_map[$this->type],
- $message,
- is_object($result) ? $result->getSQL() : $sql
- );
- }
- }
-
-
- /**
- * Clears all of the schema info out of the object and, if set, the fCache object
- *
- * @return void
- */
- public function clearCache()
- {
- $this->schema_info = array();
- if ($this->cache) {
- $this->cache->delete($this->makeCachePrefix() . 'schema_info');
- }
- if ($this->type == 'mssql') {
- $this->determineCharacterSet();
- }
- if ($this->translation) {
- $this->translation->clearCache();
- }
- }
-
-
- /**
- * Connects to the database specified if no connection exists
- *
- * @return void
- */
- private function connectToDatabase()
- {
- // Don't try to reconnect if we are already connected
- if ($this->connection) { return; }
- // Establish a connection to the database
- if ($this->extension == 'pdo') {
- $username = $this->username;
- $password = $this->password;
-
- if ($this->type == 'db2') {
- if ($this->host === NULL && $this->port === NULL) {
- $dsn = 'ibm:DSN:' . $this->database;
- } else {
- $dsn = 'ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
- $dsn .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
- $dsn .= 'PROTOCOL=TCPIP;UID=' . $username . ';PWD=' . $password . ';';
- $username = NULL;
- $password = NULL;
- }
-
- } elseif ($this->type == 'mssql') {
- $separator = (fCore::checkOS('windows')) ? ',' : ':';
- $port = ($this->port) ? $separator . $this->port : '';
- $driver = (fCore::checkOs('windows')) ? 'mssql' : 'dblib';
- $dsn = $driver . ':host=' . $this->host . $port . ';dbname=' . $this->database;
-
- } elseif ($this->type == 'mysql') {
- if (substr($this->host, 0, 5) == 'sock:') {
- $dsn = 'mysql:unix_socket=' . substr($this->host, 5) . ';dbname=' . $this->database;
- } else {
- $port = ($this->port) ? ';port=' . $this->port : '';
- $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database . $port;
- }
-
- } elseif ($this->type == 'oracle') {
- $port = ($this->port) ? ':' . $this->port : '';
- $dsn = 'oci:dbname=' . $this->host . $port . '/' . $this->database . ';charset=AL32UTF8';
-
- } elseif ($this->type == 'postgresql') {
-
- $dsn = 'pgsql:dbname=' . $this->database;
- if ($this->host && $this->host != 'sock:') {
- $dsn .= ' host=' . $this->host;
- }
- if ($this->port) {
- $dsn .= ' port=' . $this->port;
- }
-
- } elseif ($this->type == 'sqlite') {
- $dsn = 'sqlite:' . $this->database;
- }
-
- try {
- $this->connection = new PDO($dsn, $username, $password);
- if ($this->type == 'mysql') {
- $this->connection->setAttribute(PDO::MYSQL_ATTR_DIRECT_QUERY, 1);
- }
- } catch (PDOException $e) {
- $this->connection = FALSE;
- }
- }
-
- if ($this->extension == 'sqlite') {
- $this->connection = sqlite_open($this->database);
- }
-
- if ($this->extension == 'ibm_db2') {
- $username = $this->username;
- $password = $this->password;
- if ($this->host === NULL && $this->port === NULL) {
- $connection_string = $this->database;
- } else {
- $connection_string = 'DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
- $connection_string .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
- $connection_string .= 'PROTOCOL=TCPIP;UID=' . $this->username . ';PWD=' . $this->password . ';';
- $username = NULL;
- $password = NULL;
- }
- $options = array(
- 'autocommit' => DB2_AUTOCOMMIT_ON,
- 'DB2_ATTR_CASE' => DB2_CASE_LOWER
- );
- $this->connection = db2_connect($connection_string, $username, $password, $options);
- }
-
- if ($this->extension == 'mssql') {
- $separator = (fCore::checkOS('windows')) ? ',' : ':';
- $this->connection = mssql_connect(($this->port) ? $this->host . $separator . $this->port : $this->host, $this->username, $this->password, TRUE);
- if ($this->connection !== FALSE && mssql_select_db($this->database, $this->connection) === FALSE) {
- $this->connection = FALSE;
- }
- }
-
- if ($this->extension == 'mysql') {
- if (substr($this->host, 0, 5) == 'sock:') {
- $host = substr($this->host, 4);
- } elseif ($this->port) {
- $host = $this->host . ':' . $this->port;
- } else {
- $host = $this->host;
- }
- $this->connection = mysql_connect($host, $this->username, $this->password, TRUE);
- if ($this->connection !== FALSE && mysql_select_db($this->database, $this->connection) === FALSE) {
- $this->connection = FALSE;
- }
- if ($this->connection && function_exists('mysql_set_charset') && !mysql_set_charset('utf8', $this->connection)) {
- throw new fConnectivityException(
- 'There was an error setting the database connection to use UTF-8'
- );
- }
- }
-
- if ($this->extension == 'mysqli') {
- if (substr($this->host, 0, 5) == 'sock:') {
- $this->connection = mysqli_connect('localhost', $this->username, $this->password, $this->database, $this->port, substr($this->host, 5));
- } elseif ($this->port) {
- $this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database, $this->port);
- } else {
- $this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
- }
- if ($this->connection && function_exists('mysqli_set_charset') && !mysqli_set_charset($this->connection, 'utf8')) {
- throw new fConnectivityException(
- 'There was an error setting the database connection to use UTF-8'
- );
- }
- }
-
- if ($this->extension == 'oci8') {
- $this->connection = oci_connect($this->username, $this->password, $this->host . ($this->port ? ':' . $this->port : '') . '/' . $this->database, 'AL32UTF8');
- }
-
- if ($this->extension == 'pgsql') {
- $connection_string = "dbname='" . addslashes($this->database) . "'";
- if ($this->host && $this->host != 'sock:') {
- $connection_string .= " host='" . addslashes($this->host) . "'";
- }
- if ($this->username) {
- $connection_string .= " user='" . addslashes($this->username) . "'";
- }
- if ($this->password) {
- $connection_string .= " password='" . addslashes($this->password) . "'";
- }
- if ($this->port) {
- $connection_string .= " port='" . $this->port . "'";
- }
- $this->connection = pg_connect($connection_string, PGSQL_CONNECT_FORCE_NEW);
- }
-
- if ($this->extension == 'sqlsrv') {
- $options = array(
- 'Database' => $this->database,
- 'UID' => $this->username,
- 'PWD' => $this->password
- );
- $this->connection = sqlsrv_connect($this->host . ',' . $this->port, $options);
- }
-
- // Ensure the connection was established
- if ($this->connection === FALSE) {
- throw new fConnectivityException(
- 'Unable to connect to database'
- );
- }
-
- // Make MySQL act more strict and use UTF-8
- if ($this->type == 'mysql') {
- $this->execute("SET SQL_MODE = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE'");
- $this->execute("SET NAMES 'utf8'");
- $this->execute("SET CHARACTER SET utf8");
- }
-
- // Make SQLite behave like other DBs for assoc arrays
- if ($this->type == 'sqlite') {
- $this->execute('PRAGMA short_column_names = 1');
- }
-
- // Fix some issues with mssql
- if ($this->type == 'mssql') {
- if (!isset($this->schema_info['character_set'])) {
- $this->determineCharacterSet();
- }
- $this->execute('SET TEXTSIZE 65536');
- $this->execute('SET QUOTED_IDENTIFIER ON');
- }
-
- // Make PostgreSQL use UTF-8
- if ($this->type == 'postgresql') {
- $this->execute("SET NAMES 'UTF8'");
- }
-
- // Oracle has different date and timestamp defaults
- if ($this->type == 'oracle') {
- $this->execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
- $this->execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'");
- $this->execute("ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS TZR'");
- $this->execute("ALTER SESSION SET NLS_TIME_FORMAT = 'HH24:MI:SS'");
- $this->execute("ALTER SESSION SET NLS_TIME_TZ_FORMAT = 'HH24:MI:SS TZR'");
- }
- }
-
-
- /**
- * Determines the character set of a SQL Server database
- *
- * @return void
- */
- protected function determineCharacterSet()
- {
- $this->schema_info['character_set'] = 'WINDOWS-1252';
- $this->schema_info['character_set'] = $this->query("SELECT 'WINDOWS-' + CONVERT(VARCHAR, COLLATIONPROPERTY(CONVERT(NVARCHAR, DATABASEPROPERTYEX(DB_NAME(), 'Collation')), 'CodePage')) AS charset")->fetchScalar();
- if ($this->cache) {
- $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
- }
- }
-
-
- /**
- * Figures out which extension to use for the database type selected
- *
- * @return void
- */
- protected function determineExtension()
- {
- switch ($this->type) {
-
- case 'db2':
-
- if (extension_loaded('ibm_db2')) {
- $this->extension = 'ibm_db2';
-
- } elseif (class_exists('PDO', FALSE) && in_array('ibm', PDO::getAvailableDrivers())) {
- $this->extension = 'pdo';
-
- } else {
- $type = 'DB2';
- $exts = 'ibm_db2, pdo_ibm';
- }
- break;
-
- case 'mssql':
-
- if (extension_loaded('sqlsrv')) {
- $this->extension = 'sqlsrv';
-
- } elseif (extension_loaded('mssql')) {
- $this->extension = 'mssql';
-
- } elseif (class_exists('PDO', FALSE) && (in_array('dblib', PDO::getAvailableDrivers()) || in_array('mssql', PDO::getAvailableDrivers()))) {
- $this->extension = 'pdo';
-
- } else {
- $type = 'MSSQL';
- $exts = 'mssql, sqlsrv, pdo_dblib (linux), pdo_mssql (windows)';
- }
- break;
-
-
- case 'mysql':
-
- if (extension_loaded('mysqli')) {
- $this->extension = 'mysqli';
-
- } elseif (class_exists('PDO', FALSE) && in_array('mysql', PDO::getAvailableDrivers())) {
- $this->extension = 'pdo';
-
- } elseif (extension_loaded('mysql')) {
- $this->extension = 'mysql';
-
- } else {
- $type = 'MySQL';
- $exts = 'mysql, pdo_mysql, mysqli';
- }
- break;
-
-
- case 'oracle':
-
- if (extension_loaded('oci8')) {
- $this->extension = 'oci8';
-
- } elseif (class_exists('PDO', FALSE) && in_array('oci', PDO::getAvailableDrivers())) {
- $this->extension = 'pdo';
-
- } else {
- $type = 'Oracle';
- $exts = 'oci8, pdo_oci';
- }
- break;
-
-
- case 'postgresql':
-
- if (extension_loaded('pgsql')) {
- $this->extension = 'pgsql';
-
- } elseif (class_exists('PDO', FALSE) && in_array('pgsql', PDO::getAvailableDrivers())) {
- $this->extension = 'pdo';
-
- } else {
- $type = 'PostgreSQL';
- $exts = 'pgsql, pdo_pgsql';
- }
- break;
-
-
- case 'sqlite':
-
- $sqlite_version = 0;
-
- if (file_exists($this->database)) {
-
- $database_handle = fopen($this->database, 'r');
- $database_version = fread($database_handle, 64);
- fclose($database_handle);
-
- if (strpos($database_version, 'SQLite format 3') !== FALSE) {
- $sqlite_version = 3;
- } elseif (strpos($database_version, '** This file contains an SQLite 2.1 database **') !== FALSE) {
- $sqlite_version = 2;
- } else {
- throw new fConnectivityException(
- 'The database specified does not appear to be a valid %1$s or %2$s database',
- 'SQLite v2.1',
- 'v3'
- );
- }
- }
-
- if ((!$sqlite_version || $sqlite_version == 3) && class_exists('PDO', FALSE) && in_array('sqlite', PDO::getAvailableDrivers())) {
- $this->extension = 'pdo';
-
- } elseif ($sqlite_version == 3 && (!class_exists('PDO', FALSE) || !in_array('sqlite', PDO::getAvailableDrivers()))) {
- throw new fEnvironmentException(
- 'The database specified is an %1$s database and the %2$s extension is not installed',
- 'SQLite v3',
- 'pdo_sqlite'
- );
-
- } elseif ((!$sqlite_version || $sqlite_version == 2) && extension_loaded('sqlite')) {
- $this->extension = 'sqlite';
-
- } elseif ($sqlite_version == 2 && !extension_loaded('sqlite')) {
- throw new fEnvironmentException(
- 'The database specified is an %1$s database and the %2$s extension is not installed',
- 'SQLite v2.1',
- 'sqlite'
- );
-
- } else {
- $type = 'SQLite';
- $exts = 'pdo_sqlite, sqlite';
- }
- break;
- }
-
- if (!$this->extension) {
- throw new fEnvironmentException(
- 'The server does not have any of the following extensions for %2$s support: %2$s',
- $type,
- $exts
- );
- }
- }
-
-
- /**
- * Sets the schema info to be cached to the fCache object specified
- *
- * @param fCache $cache The cache to cache to
- * @param string $key_token Internal use only! (this will be used in the cache key to uniquely identify the cache for this fDatabase object)
- * @return void
- */
- public function enableCaching($cache, $key_token=NULL)
- {
- $this->cache = $cache;
-
- if ($key_token !== NULL) {
- $this->cache_prefix = 'fDatabase::' . $this->type . '::' . $key_token . '::';
- }
-
- $this->schema_info = $this->cache->get($this->makeCachePrefix() . 'schema_info', array());
- }
-
-
- /**
- * Sets if debug messages should be shown
- *
- * @param boolean $flag If debugging messages should be shown
- * @return void
- */
- public function enableDebugging($flag)
- {
- $this->debug = (boolean) $flag;
- }
-
-
- /**
- * Escapes a value for insertion into SQL
- *
- * The valid data types are:
- *
- * - `'blob'`
- * - `'boolean'`
- * - `'date'`
- * - `'float'`
- * - `'identifier'`
- * - `'integer'`
- * - `'string'` (also varchar, char or text)
- * - `'varchar'`
- * - `'char'`
- * - `'text'`
- * - `'time'`
- * - `'timestamp'`
- *
- * In addition to being able to specify the data type, you can also pass
- * in an SQL statement with data type placeholders in the following form:
- *
- * - `%l` for a blob
- * - `%b` for a boolean
- * - `%d` for a date
- * - `%f` for a float
- * - `%r` for an indentifier (table or column name)
- * - `%i` for an integer
- * - `%s` for a string
- * - `%t` for a time
- * - `%p` for a timestamp
- *
- * Depending on what `$sql_or_type` and `$value` are, the output will be
- * slightly different. If `$sql_or_type` is a data type or a single
- * placeholder and `$value` is:
- *
- * - a scalar value - an escaped SQL string is returned
- * - an array - an array of escaped SQL strings is returned
- *
- * If `$sql_or_type` is a SQL string and `$value` is:
- *
- * - a scalar value - the escaped value is inserted into the SQL string
- * - an array - the escaped values are inserted into the SQL string separated by commas
- *
- * If `$sql_or_type` is a SQL string, it is also possible to pass an array
- * of all values as a single parameter instead of one value per parameter.
- * An example would look like the following:
- *
- * {{{
- * #!php
- * $db->escape(
- * "SELECT * FROM users WHERE status = %s AND authorization_level = %s",
- * array('Active', 'Admin')
- * );
- * }}}
- *
- * @param string $sql_or_type This can either be the data type to escape or an SQL string with a data type placeholder - see method description
- * @param mixed $value The value to escape - both single values and arrays of values are supported, see method description for details
- * @param mixed ...
- * @return mixed The escaped value/SQL or an array of the escaped values
- */
- public function escape($sql_or_type, $value)
- {
- $values = array_slice(func_get_args(), 1);
-
- if (sizeof($values) < 1) {
- throw new fProgrammerException(
- 'No value was specified to escape'
- );
- }
-
- // Convert all objects into strings
- $values = $this->scalarize($values);
-
- $value = array_shift($values);
-
- // Handle single value escaping
- $callback = NULL;
-
- switch ($sql_or_type) {
- case 'blob':
- case '%l':
- $callback = $this->escapeBlob;
- break;
- case 'boolean':
- case '%b':
- $callback = $this->escapeBoolean;
- break;
- case 'date':
- case '%d':
- $callback = $this->escapeDate;
- break;
- case 'float':
- case '%f':
- $callback = $this->escapeFloat;
- break;
- case 'identifier':
- case '%r':
- $callback = $this->escapeIdentifier;
- break;
- case 'integer':
- case '%i':
- $callback = $this->escapeInteger;
- break;
- case 'string':
- case 'varchar':
- case 'char':
- case 'text':
- case '%s':
- $callback = $this->escapeString;
- break;
- case 'time':
- case '%t':
- $callback = $this->escapeTime;
- break;
- case 'timestamp':
- case '%p':
- $callback = $this->escapeTimestamp;
- break;
- }
-
- if ($callback) {
- if (is_array($value)) {
- // If the values were passed as a single array, this handles that
- if (count($value) == 1 && is_array(current($value))) {
- $value = current($value);
- }
- return array_map($callback, $value);
- }
- return call_user_func($callback, $value);
- }
-
- // Fix \' in MySQL and PostgreSQL
- if(($this->type == 'mysql' || $this->type == 'postgresql') && strpos($sql_or_type, '\\') !== FALSE) {
- $sql_or_type = preg_replace("#(?<!\\\\)((\\\\{2})*)\\\\'#", "\\1''", $sql_or_type);
- }
-
- // Separate the SQL from quoted values
- $parts = $this->splitSQL($sql_or_type);
-
- $temp_sql = '';
- $strings = array();
-
- // Replace strings with a placeholder so they don't mess up the regex parsing
- foreach ($parts as $part) {
- if ($part[0] == "'") {
- $strings[] = $part;
- $part = ':string_' . (sizeof($strings)-1);
- }
- $temp_sql .= $part;
- }
-
- // If the values were passed as a single array, this handles that
- $placeholders = preg_match_all('#%[lbdfristp]\b#', $temp_sql, $trash);
- if (count($values) == 0 && is_array($value) && count($value) == $placeholders) {
- $values = $value;
- $value = array_shift($values);
- }
-
- array_unshift($values, $value);
-
- $sql = $this->escapeSQL($temp_sql, $values);
-
- $string_number = 0;
- foreach ($strings as $string) {
- $string = strtr($string, array('\\' => '\\\\', '$' => '\\$'));
- $sql = preg_replace('#:string_' . $string_number++ . '\b#', $string, $sql);
- }
-
- return $sql;
- }
-
-
- /**
- * Escapes a blob for use in SQL, includes surround quotes when appropriate
- *
- * A `NULL` value will be returned as `'NULL'`
- *
- * @param string $value The blob to escape
- * @return string The escaped blob
- */
- private function escapeBlob($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
-
- $this->connectToDatabase();
-
- if ($this->type == 'db2') {
- return "BLOB(X'" . bin2hex($value) . "')";
-
- } elseif ($this->type == 'mysql') {
- return "x'" . bin2hex($value) . "'";
-
- } elseif ($this->type == 'postgresql') {
- $output = '';
- for ($i=0; $i<strlen($value); $i++) {
- $output .= '\\\\' . str_pad(decoct(ord($value[$i])), 3, '0', STR_PAD_LEFT);
- }
- return "E'" . $output . "'";
-
- } elseif ($this->extension == 'sqlite') {
- return "'" . bin2hex($value) . "'";
-
- } elseif ($this->type == 'sqlite') {
- return "X'" . bin2hex($value) . "'";
-
- } elseif ($this->type == 'mssql') {
- return '0x' . bin2hex($value);
-
- } elseif ($this->type == 'oracle') {
- return "'" . bin2hex($value) . "'";
- }
- }
-
-
- /**
- * Escapes a boolean for use in SQL, includes surround quotes when appropriate
- *
- * A `NULL` value will be returned as `'NULL'`
- *
- * @param boolean $value The boolean to escape
- * @return string The database equivalent of the boolean passed
- */
- private function escapeBoolean($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
-
- if (in_array($this->type, array('postgresql', 'mysql'))) {
- return ($value) ? 'TRUE' : 'FALSE';
- } elseif (in_array($this->type, array('mssql', 'sqlite', 'db2'))) {
- return ($value) ? "'1'" : "'0'";
- } elseif ($this->type == 'oracle') {
- return ($value) ? '1' : '0';
- }
- }
-
-
- /**
- * Escapes a date for use in SQL, includes surrounding quotes
- *
- * A `NULL` or invalid value will be returned as `'NULL'`
- *
- * @param string $value The date to escape
- * @return string The escaped date
- */
- private function escapeDate($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
-
- try {
- $value = new fDate($value);
- return "'" . $value->format('Y-m-d') . "'";
-
- } catch (fValidationException $e) {
- return 'NULL';
- }
- }
-
-
- /**
- * Escapes a float for use in SQL
- *
- * A `NULL` value will be returned as `'NULL'`
- *
- * @param float $value The float to escape
- * @return string The escaped float
- */
- private function escapeFloat($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
- if (!strlen($value)) {
- return 'NULL';
- }
- if (!preg_match('#^[+\-]?([0-9]+(\.([0-9]+)?)?|(\.[0-9]+))$#D', $value)) {
- return 'NULL';
- }
-
- $value = rtrim($value, '.');
- $value = preg_replace('#(?<![0-9])\.#', '0.', $value);
-
- return (string) $value;
- }
-
-
- /**
- * Escapes an identifier for use in SQL, necessary for reserved words
- *
- * @param string $value The identifier to escape
- * @return string The escaped identifier
- */
- private function escapeIdentifier($value)
- {
- $value = '"' . str_replace(
- array('"', '.'),
- array('', '"."'),
- $value
- ) . '"';
- if (in_array($this->type, array('oracle', 'db2'))) {
- $value = strtoupper($value);
- }
- return $value;
- }
-
-
- /**
- * Escapes an integer for use in SQL
- *
- * A `NULL` or invalid value will be returned as `'NULL'`
- *
- * @param integer $value The integer to escape
- * @return string The escaped integer
- */
- private function escapeInteger($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
- if (!strlen($value)) {
- return 'NULL';
- }
- if (!preg_match('#^([+\-]?[0-9]+)(\.[0-9]*)?$#D', $value, $matches)) {
- return 'NULL';
- }
- return str_replace('+', '', $matches[1]);
- }
-
-
- /**
- * Escapes a string for use in SQL, includes surrounding quotes
- *
- * A `NULL` value will be returned as `'NULL'`.
- *
- * @param string $value The string to escape
- * @return string The escaped string
- */
- private function escapeString($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
-
- $this->connectToDatabase();
-
- if ($this->type == 'db2') {
- return "'" . str_replace("'", "''", $value) . "'";
- } elseif ($this->extension == 'mysql') {
- return "'" . mysql_real_escape_string($value, $this->connection) . "'";
- } elseif ($this->extension == 'mysqli') {
- return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
- } elseif ($this->extension == 'pgsql') {
- return "'" . pg_escape_string($value) . "'";
- } elseif ($this->extension == 'sqlite') {
- return "'" . sqlite_escape_string($value) . "'";
- } elseif ($this->type == 'oracle') {
- return "'" . str_replace("'", "''", $value) . "'";
-
- } elseif ($this->type == 'mssql') {
-
- // If there are any non-ASCII characters, we need to escape
- if (preg_match('#[^\x00-\x7F]#', $value)) {
- preg_match_all('#.|^\z#us', $value, $characters);
- $output = "";
- $last_type = NULL;
- foreach ($characters[0] as $character) {
- if (strlen($character) > 1) {
- $b = array_map('ord', str_split($character));
- switch (strlen($character)) {
- case 2:
- $bin = substr(decbin($b[0]), 3) .
- substr(decbin($b[1]), 2);
- break;
-
- case 3:
- $bin = substr(decbin($b[0]), 4) .
- substr(decbin($b[1]), 2) .
- substr(decbin($b[2]), 2);
- break;
-
- // If it is a 4-byte character, MSSQL can't store it
- // so instead store a ?
- default:
- $output .= '?';
- continue;
- }
- if ($last_type == 'nchar') {
- $output .= '+';
- } elseif ($last_type == 'char') {
- $output .= "'+";
- }
- $output .= "NCHAR(" . bindec($bin) . ")";
- $last_type = 'nchar';
- } else {
- if (!$last_type) {
- $output .= "'";
- } elseif ($last_type == 'nchar') {
- $output .= "+'";
- }
- $output .= $character;
- // Escape single quotes
- if ($character == "'") {
- $output .= "'";
- }
- $last_type = 'char';
- }
- }
- if ($last_type == 'char') {
- $output .= "'";
- } elseif (!$last_type) {
- $output .= "''";
- }
-
- // ASCII text is normal
- } else {
- $output = "'" . str_replace("'", "''", $value) . "'";
- }
-
- # a \ before a \r\n has to be escaped with another \
- return preg_replace('#(?<!\\\\)\\\\(?=\r\n)#', '\\\\\\\\', $output);
-
- } elseif ($this->extension == 'pdo') {
- return $this->connection->quote($value);
- }
- }
-
-
- /**
- * Takes a SQL string and an array of values and replaces the placeholders with the value
- *
- * @param string $sql The SQL string containing placeholders
- * @param array $values An array of values to escape into the SQL
- * @return string The SQL with the values escaped into it
- */
- private function escapeSQL($sql, $values)
- {
- $original_sql = $sql;
- $pieces = preg_split('#(%[lbdfristp])\b#', $sql, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
-
- $sql = '';
- $value = array_shift($values);
-
- $missing_values = -1;
-
- foreach ($pieces as $piece) {
- switch ($piece) {
- case '%l':
- $callback = $this->escapeBlob;
- break;
- case '%b':
- $callback = $this->escapeBoolean;
- break;
- case '%d':
- $callback = $this->escapeDate;
- break;
- case '%f':
- $callback = $this->escapeFloat;
- break;
- case '%r':
- $callback = $this->escapeIdentifier;
- break;
- case '%i':
- $callback = $this->escapeInteger;
- break;
- case '%s':
- $callback = $this->escapeString;
- break;
- case '%t':
- $callback = $this->escapeTime;
- break;
- case '%p':
- $callback = $this->escapeTimestamp;
- break;
- default:
- $sql .= $piece;
- continue 2;
- }
-
- if (is_array($value)) {
- $sql .= join(', ', array_map($callback, $value));
- } else {
- $sql .= call_user_func($callback, $value);
- }
-
- if (sizeof($values)) {
- $value = array_shift($values);
- } else {
- $value = NULL;
- $missing_values++;
- }
- }
-
- if ($missing_values > 0) {
- throw new fProgrammerException(
- '%1$s value(s) are missing for the placeholders in: %2$s',
- $missing_values,
- $original_sql
- );
- }
-
- if (sizeof($values)) {
- throw new fProgrammerException(
- '%1$s extra value(s) were passed for the placeholders in: %2$s',
- sizeof($values),
- $original_sql
- );
- }
-
- return $sql;
- }
-
-
- /**
- * Escapes a time for use in SQL, includes surrounding quotes
- *
- * A `NULL` or invalid value will be returned as `'NULL'`
- *
- * @param string $value The time to escape
- * @return string The escaped time
- */
- private function escapeTime($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
-
- try {
- $value = new fTime($value);
-
- if ($this->type == 'mssql' || $this->type == 'oracle') {
- return "'" . $value->format('1970-01-01 H:i:s') . "'";
- }
-
- return "'" . $value->format('H:i:s') . "'";
-
- } catch (fValidationException $e) {
- return 'NULL';
- }
- }
-
-
- /**
- * Escapes a timestamp for use in SQL, includes surrounding quotes
- *
- * A `NULL` or invalid value will be returned as `'NULL'`
- *
- * @param string $value The timestamp to escape
- * @return string The escaped timestamp
- */
- private function escapeTimestamp($value)
- {
- if ($value === NULL) {
- return 'NULL';
- }
-
- try {
- $value = new fTimestamp($value);
- return "'" . $value->format('Y-m-d H:i:s') . "'";
-
- } catch (fValidationException $e) {
- return 'NULL';
- }
- }
-
-
- /**
- * Executes one or more SQL queries without returning any results
- *
- * @param string|fStatement $statement One or more SQL statements in a string or an fStatement prepared statement
- * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
- * @param mixed ...
- * @return void
- */
- public function execute($statement)
- {
- $args = func_get_args();
- $params = array_slice($args, 1);
-
- if (is_object($statement)) {
- return $this->run($statement, NULL, $params);
- }
-
- $queries = $this->prepareSQL($statement, $params, FALSE);
-
- $output = array();
- foreach ($queries as $query) {
- $this->run($query);
- }
- }
-
-
- /**
- * Takes in a string of SQL that contains multiple queries and returns any array of them
- *
- * @param string $sql The string of SQL to parse for queries
- * @return array The individual SQL queries
- */
- private function explodeQueries($sql)
- {
- $sql_queries = array();
-
- // Separate the SQL from quoted values
- preg_match_all("#(?:'([^']*(?:'')*)*?')|(?:[^']+)#", $sql, $matches);
-
- $cur_sql = '';
- foreach ($matches[0] as $match) {
-
- // This is a quoted string value, don't do anything to it
- if ($match[0] == "'") {
- $cur_sql .= $match;
-
- // Handle the SQL, exploding on any ; that isn't escaped with a \
- } else {
- $sql_strings = preg_split('#(?<!\\\\);#', $match);
- $cur_sql .= $sql_strings[0];
- for ($i=1; $i < sizeof($sql_strings); $i++) {
- $cur_sql = trim($cur_sql);
- if ($cur_sql) {
- $sql_queries[] = $cur_sql;
- }
- $cur_sql = $sql_strings[$i];
- }
- }
- }
- if (trim($cur_sql)) {
- $sql_queries[] = $cur_sql;
- }
-
- return $sql_queries;
- }
-
-
- /**
- * Returns the database connection resource or object
- *
- * @return mixed The database connection
- */
- public function getConnection()
- {
- $this->connectToDatabase();
- return $this->connection;
- }
-
-
- /**
- * Gets the name of the database currently connected to
- *
- * @return string The name of the database currently connected to
- */
- public function getDatabase()
- {
- return $this->database;
- }
-
-
- /**
- * Gets the php extension being used
- *
- * @internal
- *
- * @return string The php extension used for database interaction
- */
- public function getExtension()
- {
- return $this->extension;
- }
-
-
- /**
- * Gets the host for this database
- *
- * @return string The host
- */
- public function getHost()
- {
- return $this->host;
- }
-
-
- /**
- * Gets the port for this database
- *
- * @return string The port
- */
- public function getPort()
- {
- return $this->port;
- }
-
-
- /**
- * Gets the fSQLTranslation object used for translated queries
- *
- * @return fSQLTranslation The SQL translation object
- */
- public function getSQLTranslation()
- {
- if (!$this->translation) { new fSQLTranslation($this); }
- return $this->translation;
- }
-
-
- /**
- * Gets the database type
- *
- * @return string The database type: `'mssql'`, `'mysql'`, `'postgresql'` or `'sqlite'`
- */
- public function getType()
- {
- return $this->type;
- }
-
-
- /**
- * Gets the username for this database
- *
- * @return string The username
- */
- public function getUsername()
- {
- return $this->username;
- }
-
-
- /**
- * Will grab the auto incremented value from the last query (if one exists)
- *
- * @param fResult $result The result object for the query
- * @param mixed $resource Only applicable for `pdo`, `oci8` and `sqlsrv` extentions or `mysqli` prepared statements - this is either the `PDOStatement` object, `mysqli_stmt` object or the `oci8` or `sqlsrv` resource
- * @return void
- */
- private function handleAutoIncrementedValue($result, $resource=NULL)
- {
- if (!preg_match('#^\s*INSERT\s+(?:INTO\s+)?(?:`|"|\[)?(["\w.]+)(?:`|"|\])?#i', $result->getSQL(), $table_match)) {
- $result->setAutoIncrementedValue(NULL);
- return;
- }
- $quoted_table = $table_match[1];
- $table = str_replace('"', '', strtolower($table_match[1]));
-
- $insert_id = NULL;
-
- if ($this->type == 'oracle') {
- if (!isset($this->schema_info['sequences'])) {
- $sql = "SELECT
- LOWER(OWNER) AS \"SCHEMA\",
- LOWER(TABLE_NAME) AS \"TABLE\",
- TRIGGER_BODY
- FROM
- ALL_TRIGGERS
- WHERE
- TRIGGERING_EVENT LIKE 'INSERT%' AND
- STATUS = 'ENABLED' AND
- TRIGGER_NAME NOT LIKE 'BIN\$%' AND
- OWNER NOT IN (
- 'SYS',
- 'SYSTEM',
- 'OUTLN',
- 'ANONYMOUS',
- 'AURORA\$ORB\$UNAUTHENTICATED',
- 'AWR_STAGE',
- 'CSMIG',
- 'CTXSYS',
- 'DBSNMP',
- 'DIP',
- 'DMSYS',
- 'DSSYS',
- 'EXFSYS',
- 'FLOWS_020100',
- 'FLOWS_FILES',
- 'LBACSYS',
- 'MDSYS',
- 'ORACLE_OCM',
- 'ORDPLUGINS',
- 'ORDSYS',
- 'PERFSTAT',
- 'TRACESVR',
- 'TSMSYS',
- 'XDB'
- )";
-
- $this->schema_info['sequences'] = array();
-
- foreach ($this->query($sql) as $row) {
- if (preg_match('#SELECT\s+(["\w.]+).nextval\s+INTO\s+:new\.(\w+)\s+FROM\s+dual#i', $row['trigger_body'], $matches)) {
- $table_name = $row['table'];
- if ($row['schema'] != strtolower($this->username)) {
- $table_name = $row['schema'] . '.' . $table_name;
- }
- $this->schema_info['sequences'][$table_name] = array('sequence' => $matches[1], 'column' => str_replace('"', '', $matches[2]));
- }
- }
-
- if ($this->cache) {
- $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
- }
- }
-
- if (!isset($this->schema_info['sequences'][$table]) || preg_match('#INSERT\s+INTO\s+"?' . preg_quote($quoted_table, '#') . '"?\s+\([^\)]*?(\b|")' . preg_quote($this->schema_info['sequences'][$table]['column'], '#') . '(\b|")#i', $result->getSQL())) {
- return;
- }
-
- $insert_id_sql = "SELECT " . $this->schema_info['sequences'][$table]['sequence'] . ".currval AS INSERT_ID FROM dual";
- }
-
- if ($this->type == 'postgresql') {
- if (!isset($this->schema_info['sequences'])) {
- $sql = "SELECT
- pg_namespace.nspname AS \"schema\",
- pg_class.relname AS \"table\",
- pg_attribute.attname AS column
- FROM
- pg_attribute INNER JOIN
- pg_class ON pg_attribute.attrelid = pg_class.oid INNER JOIN
- pg_namespace ON pg_class.relnamespace = pg_namespace.oid INNER JOIN
- pg_attrdef ON pg_class.oid = pg_attrdef.adrelid AND pg_attribute.attnum = pg_attrdef.adnum
- WHERE
- NOT pg_attribute.attisdropped AND
- pg_attrdef.adsrc LIKE 'nextval(%'";
-
- $this->schema_info['sequences'] = array();
-
- foreach ($this->query($sql) as $row) {
- $table_name = strtolower($row['table']);
- if ($row['schema'] != 'public') {
- $table_name = $row['schema'] . '.' . $table_name;
- }
- $this->schema_info['sequences'][$table_name] = $row['column'];
- }
-
- if ($this->cache) {
- $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
- }
- }
-
- if (!isset($this->schema_info['sequences'][$table]) || preg_match('#INSERT\s+INTO\s+"?' . preg_quote($quoted_table, '#') . '"?\s+\([^\)]*?(\b|")' . preg_quote($this->schema_i…
Large files files are truncated, but you can click here to view the full file