summaryrefslogtreecommitdiff
path: root/lib/SQL/oracle.php
diff options
context:
space:
mode:
Diffstat (limited to 'lib/SQL/oracle.php')
-rw-r--r--lib/SQL/oracle.php467
1 files changed, 467 insertions, 0 deletions
diff --git a/lib/SQL/oracle.php b/lib/SQL/oracle.php
new file mode 100644
index 0000000..4bc072c
--- /dev/null
+++ b/lib/SQL/oracle.php
@@ -0,0 +1,467 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------------+
+ | This file is part of the Kolab Web Admin Panel |
+ | |
+ | Copyright (C) 2011-2014, Kolab Systems AG |
+ | |
+ | This program is free software: you can redistribute it and/or modify |
+ | it under the terms of the GNU Affero General Public License as published |
+ | by the Free Software Foundation, either version 3 of the License, or |
+ | (at your option) any later version. |
+ | |
+ | This program 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 Affero General Public License for more details. |
+ | |
+ | You should have received a copy of the GNU Affero General Public License |
+ | along with this program. If not, see <http://www.gnu.org/licenses/> |
+ +--------------------------------------------------------------------------+
+ | Author: Aleksander Machniak <machniak@kolabsys.com> |
+ +--------------------------------------------------------------------------+
+*/
+
+/**
+ * Database independent query interface
+ */
+class SQL_oracle extends SQL
+{
+ public $db_provider = 'oracle';
+
+ /**
+ * Connects to database
+ */
+ protected function connect()
+ {
+ if (!$this->conn && !$this->conn_tried) {
+ Log::debug("SQL: Connecting to " . $this->sql_uri);
+
+ $this->conn_tried = true;
+
+ $dsn = self::parse_dsn($this->sql_uri);
+
+ // Get database specific connection options
+ $dsn_options = $this->dsn_options($dsn);
+
+ $function = $this->db_pconn ? 'oci_pconnect' : 'oci_connect';
+
+ if (!function_exists($function)) {
+ $this->db_error = true;
+ $this->db_error_msg = 'OCI8 extension not loaded. See http://php.net/manual/en/book.oci8.php';
+
+ Log::error($this->db_error_msg);
+ return;
+ }
+
+ // connect
+ $dbh = @$function($dsn['username'], $dsn['password'], $dsn_options['database'], $dsn_options['charset']);
+
+ if (!$dbh) {
+ $error = oci_error();
+ $this->db_error = true;
+ $this->db_error_msg = $error['message'];
+
+ Log::error($this->db_error_msg);
+ return;
+ }
+
+ // configure session
+ $this->conn_configure($dsn, $dbh);
+
+ $this->conn = $dbh;
+ }
+
+ return $this->conn;
+ }
+
+ /**
+ * Driver-specific configuration of database connection
+ *
+ * @param array $dsn DSN for DB connections
+ * @param PDO $dbh Connection handler
+ */
+ protected function conn_configure($dsn, $dbh)
+ {
+ $init_queries = array(
+ "ALTER SESSION SET nls_date_format = 'YYYY-MM-DD'",
+ "ALTER SESSION SET nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS'",
+ );
+
+ foreach ($init_queries as $query) {
+ $stmt = oci_parse($dbh, $query);
+ oci_execute($stmt);
+ }
+ }
+
+ /**
+ * Execute a SQL query with limits
+ *
+ * @param string $query SQL query to execute
+ * @param array $params Values to be inserted in query
+ * @param int $offset Offset for LIMIT statement
+ * @param int $numrows Number of rows for LIMIT statement
+ *
+ * @return resource|bool Query handle or False on error
+ */
+ public function query($query, $params = array(), $offset = null, $numrows = null)
+ {
+ if (!$this->connect()) {
+ return $this->last_result = false;
+ }
+
+ $query = ltrim($query);
+
+ if ($numrows || $offset) {
+ $query = $this->set_limit($query, $numrows, $offset);
+ }
+
+ // replace self::DEFAULT_QUOTE with driver-specific quoting
+ $query = $this->query_parse($query);
+
+ // Because in Roundcube we mostly use queries that are
+ // executed only once, we will not use prepared queries
+ $pos = 0;
+ $idx = 0;
+ $args = array();
+
+ if (count($params)) {
+ while ($pos = strpos($query, '?', $pos)) {
+ if ($query[$pos+1] == '?') { // skip escaped '?'
+ $pos += 2;
+ }
+ else {
+ $val = $this->quote($params[$idx++]);
+
+ // long strings are not allowed inline, need to be parametrized
+ if (strlen($val) > 4000) {
+ $key = ':param' . (count($args) + 1);
+ $args[$key] = $params[$idx-1];
+ $val = $key;
+ }
+
+ unset($params[$idx-1]);
+ $query = substr_replace($query, $val, $pos, 1);
+ $pos += strlen($val);
+ }
+ }
+ }
+
+ // replace escaped '?' back to normal, see self::quote()
+ $query = str_replace('??', '?', $query);
+ $query = rtrim($query, " \t\n\r\0\x0B;");
+
+ // log query
+ Log::debug('SQL: ' . $query);
+
+ // destroy reference to previous result
+ $this->last_result = null;
+ $this->db_error_msg = null;
+
+ // prepare query
+ $result = @oci_parse($this->conn, $query);
+ $mode = $this->in_transaction ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
+
+ if ($result) {
+ foreach ($args as $param => $arg) {
+ oci_bind_by_name($result, $param, $args[$param], -1, SQLT_LNG);
+ }
+ }
+
+ // execute query
+ if (!$result || !@oci_execute($result, $mode)) {
+ $result = $this->handle_error($query, $result);
+ }
+
+ return $this->last_result = $result;
+ }
+
+ /**
+ * Helper method to handle DB errors.
+ * This by default logs the error but could be overriden by a driver implementation
+ *
+ * @param string Query that triggered the error
+ * @return mixed Result to be stored and returned
+ */
+ protected function handle_error($query, $result = null)
+ {
+ $error = oci_error(is_resource($result) ? $result : $this->conn);
+
+ // @TODO: Find error codes for key errors
+ if (empty($this->options['ignore_key_errors']) || !in_array($error['code'], array('23000', '23505'))) {
+ $this->db_error = true;
+ $this->db_error_msg = sprintf('[%s] %s', $error['code'], $error['message']);
+
+ Log::error($this->db_error_msg . " (SQL Query: $query)");
+ }
+
+ return false;
+ }
+
+ /**
+ * Get last inserted record ID
+ *
+ * @param string $table Table name (to find the incremented sequence)
+ *
+ * @return mixed ID or false on failure
+ */
+ public function insert_id($table = null)
+ {
+ $sequence = $this->quote_identifier($this->sequence_name($table));
+ $result = $this->query("SELECT $sequence.currval FROM dual");
+ $result = $this->fetch_array($result);
+
+ return $result[0] ?: false;
+ }
+
+ /**
+ * Get number of affected rows for the last query
+ *
+ * @param mixed $result Optional query handle
+ *
+ * @return int Number of (matching) rows
+ */
+ public function affected_rows($result = null)
+ {
+ if ($result || ($result === null && ($result = $this->last_result))) {
+ return oci_num_rows($result);
+ }
+
+ return 0;
+ }
+
+ /**
+ * Get an associative array for one row
+ * If no query handle is specified, the last query will be taken as reference
+ *
+ * @param mixed $result Optional query handle
+ *
+ * @return mixed Array with col values or false on failure
+ */
+ public function fetch_assoc($result = null)
+ {
+ return $this->_fetch_row($result, OCI_ASSOC);
+ }
+
+ /**
+ * Get an index array for one row
+ * If no query handle is specified, the last query will be taken as reference
+ *
+ * @param mixed $result Optional query handle
+ *
+ * @return mixed Array with col values or false on failure
+ */
+ public function fetch_array($result = null)
+ {
+ return $this->_fetch_row($result, OCI_NUM);
+ }
+
+ /**
+ * Get col values for a result row
+ *
+ * @param mixed $result Optional query handle
+ * @param int $mode Fetch mode identifier
+ *
+ * @return mixed Array with col values or false on failure
+ */
+ protected function _fetch_row($result, $mode)
+ {
+ if ($result || ($result === null && ($result = $this->last_result))) {
+ return oci_fetch_array($result, $mode + OCI_RETURN_NULLS + OCI_RETURN_LOBS);
+ }
+
+ return false;
+ }
+
+ /**
+ * Formats input so it can be safely used in a query
+ * PDO_OCI does not implement quote() method
+ *
+ * @param mixed $input Value to quote
+ * @param string $type Type of data (integer, bool, ident)
+ *
+ * @return string Quoted/converted string for use in query
+ */
+ public function quote($input, $type = null)
+ {
+ // handle int directly for better performance
+ if ($type == 'integer' || $type == 'int') {
+ return intval($input);
+ }
+
+ if (is_null($input)) {
+ return 'NULL';
+ }
+
+ if ($type == 'ident') {
+ return $this->quote_identifier($input);
+ }
+
+ switch ($type) {
+ case 'bool':
+ case 'integer':
+ return intval($input);
+ default:
+ return "'" . strtr($input, array(
+ '?' => '??',
+ "'" => "''",
+ SQL::DEFAULT_QUOTE => SQL::DEFAULT_QUOTE . SQL::DEFAULT_QUOTE
+ )) . "'";
+ }
+ }
+
+ /**
+ * Return correct name for a specific database sequence
+ *
+ * @param string $table Table name
+ *
+ * @return string Translated sequence name
+ */
+ protected function sequence_name($table)
+ {
+ // Note: we support only one sequence per table
+ // Note: The sequence name must be <table_name>_seq
+ return $table . '_seq';
+ }
+
+ /**
+ * Return SQL statement for case insensitive LIKE
+ *
+ * @param string $column Field name
+ * @param string $value Search value
+ *
+ * @return string SQL statement to use in query
+ */
+ public function ilike($column, $value)
+ {
+ return 'UPPER(' . $this->quote_identifier($column) . ') LIKE UPPER(' . $this->quote($value) . ')';
+ }
+
+ /**
+ * Return SQL function for current time and date
+ *
+ * @param int $interval Optional interval (in seconds) to add/subtract
+ *
+ * @return string SQL function to use in query
+ */
+ public function now($interval = 0)
+ {
+ if ($interval) {
+ $interval = intval($interval);
+ return "current_timestamp + INTERVAL '$interval' SECOND";
+ }
+
+ return "current_timestamp";
+ }
+
+ /**
+ * Adds TOP (LIMIT,OFFSET) clause to the query
+ *
+ * @param string $query SQL query
+ * @param int $limit Number of rows
+ * @param int $offset Offset
+ *
+ * @return string SQL query
+ */
+ protected function set_limit($query, $limit = 0, $offset = 0)
+ {
+ $limit = intval($limit);
+ $offset = intval($offset);
+ $end = $offset + $limit;
+
+ // @TODO: Oracle 12g has better OFFSET support
+
+ if (!$offset) {
+ $query = "SELECT * FROM ($query) a WHERE rownum <= $end";
+ }
+ else {
+ $query = "SELECT * FROM (SELECT a.*, rownum as rn FROM ($query) a WHERE rownum <= $end) b WHERE rn > $offset";
+ }
+
+ return $query;
+ }
+
+ /**
+ * Returns connection options from DSN array
+ */
+ protected function dsn_options($dsn)
+ {
+ $params = array();
+
+ if ($dsn['hostspec']) {
+ $host = $dsn['hostspec'];
+ if ($dsn['port']) {
+ $host .= ':' . $dsn['port'];
+ }
+
+ $params['database'] = $host . '/' . $dsn['database'];
+ }
+
+ $params['charset'] = 'UTF8';
+
+ return $params;
+ }
+
+ /**
+ * Start transaction
+ *
+ * @return bool True on success, False on failure
+ */
+ public function startTransaction()
+ {
+ if (!$this->connect()) {
+ return $this->last_result = false;
+ }
+
+ Log::debug('BEGIN TRANSACTION');
+
+ return $this->last_result = $this->in_transaction = true;
+ }
+
+ /**
+ * Commit transaction
+ *
+ * @return bool True on success, False on failure
+ */
+ public function endTransaction()
+ {
+ if (!$this->connect()) {
+ return $this->last_result = false;
+ }
+
+ Log::debug('COMMIT TRANSACTION');
+
+ if ($result = @oci_commit($this->conn)) {
+ $this->in_transaction = true;
+ }
+ else {
+ $this->handle_error('COMMIT');
+ }
+
+ return $this->last_result = $result;
+ }
+
+ /**
+ * Rollback transaction
+ *
+ * @return bool True on success, False on failure
+ */
+ public function rollbackTransaction()
+ {
+ if (!$this->connect()) {
+ return $this->last_result = false;
+ }
+
+ Log::debug('ROLLBACK TRANSACTION');
+
+ if ($result = @oci_rollback($this->conn)) {
+ $this->in_transaction = false;
+ }
+ else {
+ $this->handle_error('ROLLBACK');
+ }
+
+ return $this->last_result = $this->conn->rollBack();
+ }
+}