6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
19 include_once($phpbb_root_path . 'includes/db/dbal.' . $phpEx);
22 * Oracle Database Abstraction Layer
25 class dbal_oracle extends dbal
27 var $last_query_text = '';
32 function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
34 $this->persistency = $persistency;
35 $this->user = $sqluser;
36 $this->server = $sqlserver . (($port) ? ':' . $port : '');
37 $this->dbname = $database;
41 // support for "easy connect naming"
42 if ($sqlserver !== '' && $sqlserver !== '/')
44 if (substr($sqlserver, -1, 1) == '/')
46 $sqlserver == substr($sqlserver, 0, -1);
48 $connect = $sqlserver . (($port) ? ':' . $port : '') . '/' . $database;
51 $this->db_connect_id = ($new_link) ? @ocinlogon($this->user, $sqlpassword, $connect, 'UTF8') : (($this->persistency) ? @ociplogon($this->user, $sqlpassword, $connect, 'UTF8') : @ocilogon($this->user, $sqlpassword, $connect, 'UTF8'));
53 return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
57 * Version information about used database
58 * @param bool $raw if true, only return the fetched sql_server_version
59 * @param bool $use_cache forced to false for Oracle
60 * @return string sql server version
62 function sql_server_info($raw = false, $use_cache = true)
65 * force $use_cache false. I didn't research why the caching code below is commented out
66 * but I assume its because the Oracle extension provides a direct method to access it
74 if (empty($cache) || ($this->sql_server_version = $cache->get('oracle_version')) === false)
76 $result = @ociparse($this->db_connect_id, 'SELECT * FROM v$version WHERE banner LIKE \'Oracle%\'');
77 @ociexecute($result, OCI_DEFAULT);
78 @ocicommit($this->db_connect_id);
81 @ocifetchinto($result, $row, OCI_ASSOC + OCI_RETURN_NULLS);
82 @ocifreestatement($result);
83 $this->sql_server_version = trim($row['BANNER']);
85 $cache->put('oracle_version', $this->sql_server_version);
88 $this->sql_server_version = @ociserverversion($this->db_connect_id);
90 return $this->sql_server_version;
97 function _sql_transaction($status = 'begin')
106 return @ocicommit($this->db_connect_id);
110 return @ocirollback($this->db_connect_id);
118 * Oracle specific code to handle the fact that it does not compare columns properly
121 function _rewrite_col_compare($args)
123 if (sizeof($args) == 4)
127 return '(' . $args[0] . ' OR (' . $args[1] . ' is NULL AND ' . $args[3] . ' is NULL))';
129 else if ($args[2] == '<>')
131 // really just a fancy way of saying foo <> bar or (foo is NULL XOR bar is NULL) but SQL has no XOR :P
132 return '(' . $args[0] . ' OR ((' . $args[1] . ' is NULL AND ' . $args[3] . ' is NOT NULL) OR (' . $args[1] . ' is NOT NULL AND ' . $args[3] . ' is NULL)))';
137 return $this->_rewrite_where($args[0]);
142 * Oracle specific code to handle it's lack of sanity
145 function _rewrite_where($where_clause)
147 preg_match_all('/\s*(AND|OR)?\s*([\w_.()]++)\s*(?:(=|<[=>]?|>=?|LIKE)\s*((?>\'(?>[^\']++|\'\')*+\'|[\d-.()]+))|((NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]+,? ?)*+\)))/', $where_clause, $result, PREG_SET_ORDER);
149 foreach ($result as $val)
153 if ($val[4] !== "''")
159 $out .= ' ' . $val[1] . ' ' . $val[2];
164 else if ($val[3] == '<>')
166 $out .= ' is NOT NULL';
172 $in_clause = array();
173 $sub_exp = substr($val[5], strpos($val[5], '(') + 1, -1);
175 preg_match_all('/\'(?>[^\']++|\'\')*+\'|[\d-.]++/', $sub_exp, $sub_vals, PREG_PATTERN_ORDER);
177 foreach ($sub_vals[0] as $sub_val)
180 // 1) This determines if an empty string was in the IN clausing, making us turn it into a NULL comparison
181 // 2) This fixes the 1000 list limit that Oracle has (ORA-01795)
182 if ($sub_val !== "''")
184 $in_clause[(int) $i++/1000][] = $sub_val;
191 if (!$extra && $i < 1000)
197 $out .= ' ' . $val[1] . '(';
200 // constuct each IN() clause
201 foreach ($in_clause as $in_values)
203 $in_array[] = $val[2] . ' ' . (isset($val[6]) ? $val[6] : '') . 'IN(' . implode(', ', $in_values) . ')';
206 // Join the IN() clauses against a few ORs (IN is just a nicer OR anyway)
207 $out .= implode(' OR ', $in_array);
209 // handle the empty string case
212 $out .= ' OR ' . $val[2] . ' is ' . (isset($val[6]) ? $val[6] : '') . 'NULL';
216 unset($in_array, $in_clause);
227 * @param string $query Contains the SQL query which shall be executed
228 * @param int $cache_ttl Either 0 to avoid caching or the time in seconds which the result shall be kept in cache
229 * @return mixed When casted to bool the returned value returns true on success and false on failure
233 function sql_query($query = '', $cache_ttl = 0)
239 // EXPLAIN only in extra debug mode
240 if (defined('DEBUG_EXTRA'))
242 $this->sql_report('start', $query);
245 $this->last_query_text = $query;
246 $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
247 $this->sql_add_num_queries($this->query_result);
249 if ($this->query_result === false)
251 $in_transaction = false;
252 if (!$this->transaction)
254 $this->sql_transaction('begin');
258 $in_transaction = true;
263 // We overcome Oracle's 4000 char limit by binding vars
264 if (strlen($query) > 4000)
266 if (preg_match('/^(INSERT INTO[^(]++)\\(([^()]+)\\) VALUES[^(]++\\((.*?)\\)$/sU', $query, $regs))
268 if (strlen($regs[3]) > 4000)
270 $cols = explode(', ', $regs[2]);
272 preg_match_all('/\'(?:[^\']++|\'\')*+\'|[\d-.]+/', $regs[3], $vals, PREG_PATTERN_ORDER);
274 /* The code inside this comment block breaks clob handling, but does allow the
275 database restore script to work. If you want to allow no posts longer than 4KB
276 and/or need the db restore script, uncomment this.
279 if (sizeof($cols) !== sizeof($vals))
281 // Try to replace some common data we know is from our restore script or from other sources
282 $regs[3] = str_replace("'||chr(47)||'", '/', $regs[3]);
283 $_vals = explode(', ', $regs[3]);
290 foreach ($_vals as $value)
292 if (strpos($value, "'") === false && !$is_in_val)
294 $vals[$i++] = $value;
298 if (substr($value, -1) === "'")
300 $vals[$i] = $string . (($is_in_val) ? ', ' : '') . $value;
304 if ($vals[$i][0] !== "'")
306 $vals[$i] = "''" . $vals[$i];
313 $string .= (($is_in_val) ? ', ' : '') . $value;
320 // New value if cols != value
321 $vals[(sizeof($cols) !== sizeof($vals)) ? $i : $i - 1] .= $string;
324 $vals = array(0 => $vals);
331 foreach ($inserts as $key => $value)
333 if (!empty($value) && $value[0] === "'" && strlen($value) > 4002) // check to see if this thing is greater than the max + 'x2
335 $inserts[$key] = ':' . strtoupper($cols[$key]);
336 $array[$inserts[$key]] = str_replace("''", "'", substr($value, 1, -1));
340 $query = $regs[1] . '(' . $regs[2] . ') VALUES (' . implode(', ', $inserts) . ')';
343 else if (preg_match_all('/^(UPDATE [\\w_]++\\s+SET )([\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+)(?:,\\s*[\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+)\\s+(WHERE.*)$/s', $query, $data, PREG_SET_ORDER))
345 if (strlen($data[0][2]) > 4000)
347 $update = $data[0][1];
348 $where = $data[0][3];
349 preg_match_all('/([\\w_]++)\\s*=\\s*(\'(?:[^\']++|\'\')*+\'|[\d-.]++)/', $data[0][2], $temp, PREG_SET_ORDER);
353 foreach ($temp as $value)
355 if (!empty($value[2]) && $value[2][0] === "'" && strlen($value[2]) > 4002) // check to see if this thing is greater than the max + 'x2
357 $cols[] = $value[1] . '=:' . strtoupper($value[1]);
358 $array[$value[1]] = str_replace("''", "'", substr($value[2], 1, -1));
362 $cols[] = $value[1] . '=' . $value[2];
366 $query = $update . implode(', ', $cols) . ' ' . $where;
372 switch (substr($query, 0, 6))
375 if (preg_match('/^(DELETE FROM [\w_]++ WHERE)((?:\s*(?:AND|OR)?\s*[\w_]+\s*(?:(?:=|<>)\s*(?>\'(?>[^\']++|\'\')*+\'|[\d-.]+)|(?:NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]+,? ?)*+\)))*+)$/', $query, $regs))
377 $query = $regs[1] . $this->_rewrite_where($regs[2]);
383 if (preg_match('/^(UPDATE [\\w_]++\\s+SET [\\w_]+\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]++|:\w++)(?:, [\\w_]+\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]++|:\w++))*+\\s+WHERE)(.*)$/s', $query, $regs))
385 $query = $regs[1] . $this->_rewrite_where($regs[2]);
391 $query = preg_replace_callback('/([\w_.]++)\s*(?:(=|<>)\s*(?>\'(?>[^\']++|\'\')*+\'|[\d-.]++|([\w_.]++))|(?:NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]++,? ?)*+\))/', array($this, '_rewrite_col_compare'), $query);
395 $this->query_result = @ociparse($this->db_connect_id, $query);
397 foreach ($array as $key => $value)
399 @ocibindbyname($this->query_result, $key, $array[$key], -1);
402 $success = @ociexecute($this->query_result, OCI_DEFAULT);
406 $this->sql_error($query);
407 $this->query_result = false;
411 if (!$in_transaction)
413 $this->sql_transaction('commit');
417 if (defined('DEBUG_EXTRA'))
419 $this->sql_report('stop', $query);
422 if ($cache_ttl && method_exists($cache, 'sql_save'))
424 $this->open_queries[(int) $this->query_result] = $this->query_result;
425 $cache->sql_save($query, $this->query_result, $cache_ttl);
427 else if (strpos($query, 'SELECT') === 0 && $this->query_result)
429 $this->open_queries[(int) $this->query_result] = $this->query_result;
432 else if (defined('DEBUG_EXTRA'))
434 $this->sql_report('fromcache', $query);
442 return $this->query_result;
448 function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
450 $this->query_result = false;
452 $query = 'SELECT * FROM (SELECT /*+ FIRST_ROWS */ rownum AS xrownum, a.* FROM (' . $query . ') a WHERE rownum <= ' . ($offset + $total) . ') WHERE xrownum >= ' . $offset;
454 return $this->sql_query($query, $cache_ttl);
458 * Return number of affected rows
460 function sql_affectedrows()
462 return ($this->query_result) ? @ocirowcount($this->query_result) : false;
468 function sql_fetchrow($query_id = false)
472 if ($query_id === false)
474 $query_id = $this->query_result;
477 if (isset($cache->sql_rowset[$query_id]))
479 return $cache->sql_fetchrow($query_id);
482 if ($query_id !== false)
485 $result = @ocifetchinto($query_id, $row, OCI_ASSOC + OCI_RETURN_NULLS);
487 if (!$result || !$row)
492 $result_row = array();
493 foreach ($row as $key => $value)
495 // Oracle treats empty strings as null
502 if (is_object($value))
504 $value = $value->load();
507 $result_row[strtolower($key)] = $value;
517 * Seek to given row number
518 * rownum is zero-based
520 function sql_rowseek($rownum, &$query_id)
524 if ($query_id === false)
526 $query_id = $this->query_result;
529 if (isset($cache->sql_rowset[$query_id]))
531 return $cache->sql_rowseek($rownum, $query_id);
534 if ($query_id === false)
539 // Reset internal pointer
540 @ociexecute($query_id, OCI_DEFAULT);
542 // We do not fetch the row for rownum == 0 because then the next resultset would be the second row
543 for ($i = 0; $i < $rownum; $i++)
545 if (!$this->sql_fetchrow($query_id))
555 * Get last inserted id after insert statement
557 function sql_nextid()
559 $query_id = $this->query_result;
561 if ($query_id !== false && $this->last_query_text != '')
563 if (preg_match('#^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)#is', $this->last_query_text, $tablename))
565 $query = 'SELECT ' . $tablename[1] . '_seq.currval FROM DUAL';
566 $stmt = @ociparse($this->db_connect_id, $query);
567 @ociexecute($stmt, OCI_DEFAULT);
569 $temp_result = @ocifetchinto($stmt, $temp_array, OCI_ASSOC + OCI_RETURN_NULLS);
570 @ocifreestatement($stmt);
574 return $temp_array['CURRVAL'];
589 function sql_freeresult($query_id = false)
593 if ($query_id === false)
595 $query_id = $this->query_result;
598 if (isset($cache->sql_rowset[$query_id]))
600 return $cache->sql_freeresult($query_id);
603 if (isset($this->open_queries[(int) $query_id]))
605 unset($this->open_queries[(int) $query_id]);
606 return @ocifreestatement($query_id);
613 * Escape string used in sql query
615 function sql_escape($msg)
617 return str_replace(array("'", "\0"), array("''", ''), $msg);
621 * Build LIKE expression
624 function _sql_like_expression($expression)
626 return $expression . " ESCAPE '\\'";
629 function _sql_custom_build($stage, $data)
634 function _sql_bit_and($column_name, $bit, $compare = '')
636 return 'BITAND(' . $column_name . ', ' . (1 << $bit) . ')' . (($compare) ? ' ' . $compare : '');
639 function _sql_bit_or($column_name, $bit, $compare = '')
641 return 'BITOR(' . $column_name . ', ' . (1 << $bit) . ')' . (($compare) ? ' ' . $compare : '');
645 * return sql error array
648 function _sql_error()
650 $error = @ocierror();
651 $error = (!$error) ? @ocierror($this->query_result) : $error;
652 $error = (!$error) ? @ocierror($this->db_connect_id) : $error;
656 $this->last_error_result = $error;
660 $error = (isset($this->last_error_result) && $this->last_error_result) ? $this->last_error_result : array();
667 * Close sql connection
670 function _sql_close()
672 return @ocilogoff($this->db_connect_id);
676 * Build db-specific report
679 function _sql_report($mode, $query = '')
687 // Grab a plan table, any will do
688 $sql = "SELECT table_name
690 WHERE table_name LIKE '%PLAN_TABLE%'";
691 $stmt = ociparse($this->db_connect_id, $sql);
695 if (ocifetchinto($stmt, $result, OCI_ASSOC + OCI_RETURN_NULLS))
697 $table = $result['TABLE_NAME'];
699 // This is the statement_id that will allow us to track the plan
700 $statement_id = substr(md5($query), 0, 30);
702 // Remove any stale plans
703 $stmt2 = ociparse($this->db_connect_id, "DELETE FROM $table WHERE statement_id='$statement_id'");
705 ocifreestatement($stmt2);
709 SET STATEMENT_ID = '$statement_id'
711 $stmt2 = ociparse($this->db_connect_id, $sql);
713 ocifreestatement($stmt2);
715 // Get the data from the plan
716 $sql = "SELECT operation, options, object_name, object_type, cardinality, cost
718 START WITH id = 0 AND statement_id = '$statement_id'
719 CONNECT BY PRIOR id = parent_id
720 AND statement_id = '$statement_id'";
721 $stmt2 = ociparse($this->db_connect_id, $sql);
725 while (ocifetchinto($stmt2, $row, OCI_ASSOC + OCI_RETURN_NULLS))
727 $html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
730 ocifreestatement($stmt2);
732 // Remove the plan we just made, we delete them on request anyway
733 $stmt2 = ociparse($this->db_connect_id, "DELETE FROM $table WHERE statement_id='$statement_id'");
735 ocifreestatement($stmt2);
738 ocifreestatement($stmt);
742 $this->html_hold .= '</table>';
748 $endtime = explode(' ', microtime());
749 $endtime = $endtime[0] + $endtime[1];
751 $result = @ociparse($this->db_connect_id, $query);
752 $success = @ociexecute($result, OCI_DEFAULT);
755 while (@ocifetchinto($result, $row, OCI_ASSOC + OCI_RETURN_NULLS))
757 // Take the time spent on parsing rows into account
759 @ocifreestatement($result);
761 $splittime = explode(' ', microtime());
762 $splittime = $splittime[0] + $splittime[1];
764 $this->sql_report('record_fromcache', $query, $endtime, $splittime);