PageRenderTime 54ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/Zend/Db/Adapter/Oracle.php

https://github.com/quarkness/piwik
PHP | 643 lines | 318 code | 40 blank | 285 comment | 37 complexity | 2b190daba528c06706d7a44651e85b32 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Db
  17. * @subpackage Adapter
  18. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Oracle.php 23775 2011-03-01 17:25:24Z ralph $
  21. */
  22. /**
  23. * @see Zend_Db_Adapter_Abstract
  24. */
  25. // require_once 'Zend/Db/Adapter/Abstract.php';
  26. /**
  27. * @see Zend_Db_Statement_Oracle
  28. */
  29. // require_once 'Zend/Db/Statement/Oracle.php';
  30. /**
  31. * @category Zend
  32. * @package Zend_Db
  33. * @subpackage Adapter
  34. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  35. * @license http://framework.zend.com/license/new-bsd New BSD License
  36. */
  37. class Zend_Db_Adapter_Oracle extends Zend_Db_Adapter_Abstract
  38. {
  39. /**
  40. * User-provided configuration.
  41. *
  42. * Basic keys are:
  43. *
  44. * username => (string) Connect to the database as this username.
  45. * password => (string) Password associated with the username.
  46. * dbname => Either the name of the local Oracle instance, or the
  47. * name of the entry in tnsnames.ora to which you want to connect.
  48. * persistent => (boolean) Set TRUE to use a persistent connection
  49. * @var array
  50. */
  51. protected $_config = array(
  52. 'dbname' => null,
  53. 'username' => null,
  54. 'password' => null,
  55. 'persistent' => false
  56. );
  57. /**
  58. * Keys are UPPERCASE SQL datatypes or the constants
  59. * Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
  60. *
  61. * Values are:
  62. * 0 = 32-bit integer
  63. * 1 = 64-bit integer
  64. * 2 = float or decimal
  65. *
  66. * @var array Associative array of datatypes to values 0, 1, or 2.
  67. */
  68. protected $_numericDataTypes = array(
  69. Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
  70. Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
  71. Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
  72. 'BINARY_DOUBLE' => Zend_Db::FLOAT_TYPE,
  73. 'BINARY_FLOAT' => Zend_Db::FLOAT_TYPE,
  74. 'NUMBER' => Zend_Db::FLOAT_TYPE,
  75. );
  76. /**
  77. * @var integer
  78. */
  79. protected $_execute_mode = null;
  80. /**
  81. * Default class name for a DB statement.
  82. *
  83. * @var string
  84. */
  85. protected $_defaultStmtClass = 'Zend_Db_Statement_Oracle';
  86. /**
  87. * Check if LOB field are returned as string
  88. * instead of OCI-Lob object
  89. *
  90. * @var boolean
  91. */
  92. protected $_lobAsString = null;
  93. /**
  94. * Creates a connection resource.
  95. *
  96. * @return void
  97. * @throws Zend_Db_Adapter_Oracle_Exception
  98. */
  99. protected function _connect()
  100. {
  101. if (is_resource($this->_connection)) {
  102. // connection already exists
  103. return;
  104. }
  105. if (!extension_loaded('oci8')) {
  106. /**
  107. * @see Zend_Db_Adapter_Oracle_Exception
  108. */
  109. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  110. throw new Zend_Db_Adapter_Oracle_Exception('The OCI8 extension is required for this adapter but the extension is not loaded');
  111. }
  112. $this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);
  113. $connectionFuncName = ($this->_config['persistent'] == true) ? 'oci_pconnect' : 'oci_connect';
  114. $this->_connection = @$connectionFuncName(
  115. $this->_config['username'],
  116. $this->_config['password'],
  117. $this->_config['dbname'],
  118. $this->_config['charset']);
  119. // check the connection
  120. if (!$this->_connection) {
  121. /**
  122. * @see Zend_Db_Adapter_Oracle_Exception
  123. */
  124. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  125. throw new Zend_Db_Adapter_Oracle_Exception(oci_error());
  126. }
  127. }
  128. /**
  129. * Test if a connection is active
  130. *
  131. * @return boolean
  132. */
  133. public function isConnected()
  134. {
  135. return ((bool) (is_resource($this->_connection)
  136. && (get_resource_type($this->_connection) == 'oci8 connection'
  137. || get_resource_type($this->_connection) == 'oci8 persistent connection')));
  138. }
  139. /**
  140. * Force the connection to close.
  141. *
  142. * @return void
  143. */
  144. public function closeConnection()
  145. {
  146. if ($this->isConnected()) {
  147. oci_close($this->_connection);
  148. }
  149. $this->_connection = null;
  150. }
  151. /**
  152. * Activate/deactivate return of LOB as string
  153. *
  154. * @param string $lob_as_string
  155. * @return Zend_Db_Adapter_Oracle
  156. */
  157. public function setLobAsString($lobAsString)
  158. {
  159. $this->_lobAsString = (bool) $lobAsString;
  160. return $this;
  161. }
  162. /**
  163. * Return whether or not LOB are returned as string
  164. *
  165. * @return boolean
  166. */
  167. public function getLobAsString()
  168. {
  169. if ($this->_lobAsString === null) {
  170. // if never set by user, we use driver option if it exists otherwise false
  171. if (isset($this->_config['driver_options']) &&
  172. isset($this->_config['driver_options']['lob_as_string'])) {
  173. $this->_lobAsString = (bool) $this->_config['driver_options']['lob_as_string'];
  174. } else {
  175. $this->_lobAsString = false;
  176. }
  177. }
  178. return $this->_lobAsString;
  179. }
  180. /**
  181. * Returns an SQL statement for preparation.
  182. *
  183. * @param string $sql The SQL statement with placeholders.
  184. * @return Zend_Db_Statement_Oracle
  185. */
  186. public function prepare($sql)
  187. {
  188. $this->_connect();
  189. $stmtClass = $this->_defaultStmtClass;
  190. if (!class_exists($stmtClass)) {
  191. // require_once 'Zend/Loader.php';
  192. Zend_Loader::loadClass($stmtClass);
  193. }
  194. $stmt = new $stmtClass($this, $sql);
  195. if ($stmt instanceof Zend_Db_Statement_Oracle) {
  196. $stmt->setLobAsString($this->getLobAsString());
  197. }
  198. $stmt->setFetchMode($this->_fetchMode);
  199. return $stmt;
  200. }
  201. /**
  202. * Quote a raw string.
  203. *
  204. * @param string $value Raw string
  205. * @return string Quoted string
  206. */
  207. protected function _quote($value)
  208. {
  209. if (is_int($value) || is_float($value)) {
  210. return $value;
  211. }
  212. $value = str_replace("'", "''", $value);
  213. return "'" . addcslashes($value, "\000\n\r\\\032") . "'";
  214. }
  215. /**
  216. * Quote a table identifier and alias.
  217. *
  218. * @param string|array|Zend_Db_Expr $ident The identifier or expression.
  219. * @param string $alias An alias for the table.
  220. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  221. * @return string The quoted identifier and alias.
  222. */
  223. public function quoteTableAs($ident, $alias = null, $auto = false)
  224. {
  225. // Oracle doesn't allow the 'AS' keyword between the table identifier/expression and alias.
  226. return $this->_quoteIdentifierAs($ident, $alias, $auto, ' ');
  227. }
  228. /**
  229. * Return the most recent value from the specified sequence in the database.
  230. * This is supported only on RDBMS brands that support sequences
  231. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  232. *
  233. * @param string $sequenceName
  234. * @return string
  235. */
  236. public function lastSequenceId($sequenceName)
  237. {
  238. $this->_connect();
  239. $sql = 'SELECT '.$this->quoteIdentifier($sequenceName, true).'.CURRVAL FROM dual';
  240. $value = $this->fetchOne($sql);
  241. return $value;
  242. }
  243. /**
  244. * Generate a new value from the specified sequence in the database, and return it.
  245. * This is supported only on RDBMS brands that support sequences
  246. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  247. *
  248. * @param string $sequenceName
  249. * @return string
  250. */
  251. public function nextSequenceId($sequenceName)
  252. {
  253. $this->_connect();
  254. $sql = 'SELECT '.$this->quoteIdentifier($sequenceName, true).'.NEXTVAL FROM dual';
  255. $value = $this->fetchOne($sql);
  256. return $value;
  257. }
  258. /**
  259. * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
  260. *
  261. * As a convention, on RDBMS brands that support sequences
  262. * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
  263. * from the arguments and returns the last id generated by that sequence.
  264. * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
  265. * returns the last value generated for such a column, and the table name
  266. * argument is disregarded.
  267. *
  268. * Oracle does not support IDENTITY columns, so if the sequence is not
  269. * specified, this method returns null.
  270. *
  271. * @param string $tableName OPTIONAL Name of table.
  272. * @param string $primaryKey OPTIONAL Name of primary key column.
  273. * @return string
  274. */
  275. public function lastInsertId($tableName = null, $primaryKey = null)
  276. {
  277. if ($tableName !== null) {
  278. $sequenceName = $tableName;
  279. if ($primaryKey) {
  280. $sequenceName .= "_$primaryKey";
  281. }
  282. $sequenceName .= '_seq';
  283. return $this->lastSequenceId($sequenceName);
  284. }
  285. // No support for IDENTITY columns; return null
  286. return null;
  287. }
  288. /**
  289. * Returns a list of the tables in the database.
  290. *
  291. * @return array
  292. */
  293. public function listTables()
  294. {
  295. $this->_connect();
  296. $data = $this->fetchCol('SELECT table_name FROM all_tables');
  297. return $data;
  298. }
  299. /**
  300. * Returns the column descriptions for a table.
  301. *
  302. * The return value is an associative array keyed by the column name,
  303. * as returned by the RDBMS.
  304. *
  305. * The value of each array element is an associative array
  306. * with the following keys:
  307. *
  308. * SCHEMA_NAME => string; name of schema
  309. * TABLE_NAME => string;
  310. * COLUMN_NAME => string; column name
  311. * COLUMN_POSITION => number; ordinal position of column in table
  312. * DATA_TYPE => string; SQL datatype name of column
  313. * DEFAULT => string; default expression of column, null if none
  314. * NULLABLE => boolean; true if column can have nulls
  315. * LENGTH => number; length of CHAR/VARCHAR
  316. * SCALE => number; scale of NUMERIC/DECIMAL
  317. * PRECISION => number; precision of NUMERIC/DECIMAL
  318. * UNSIGNED => boolean; unsigned property of an integer type
  319. * PRIMARY => boolean; true if column is part of the primary key
  320. * PRIMARY_POSITION => integer; position of column in primary key
  321. * IDENTITY => integer; true if column is auto-generated with unique values
  322. *
  323. * @todo Discover integer unsigned property.
  324. *
  325. * @param string $tableName
  326. * @param string $schemaName OPTIONAL
  327. * @return array
  328. */
  329. public function describeTable($tableName, $schemaName = null)
  330. {
  331. $version = $this->getServerVersion();
  332. if (($version === null) || version_compare($version, '9.0.0', '>=')) {
  333. $sql = "SELECT TC.TABLE_NAME, TC.OWNER, TC.COLUMN_NAME, TC.DATA_TYPE,
  334. TC.DATA_DEFAULT, TC.NULLABLE, TC.COLUMN_ID, TC.DATA_LENGTH,
  335. TC.DATA_SCALE, TC.DATA_PRECISION, C.CONSTRAINT_TYPE, CC.POSITION
  336. FROM ALL_TAB_COLUMNS TC
  337. LEFT JOIN (ALL_CONS_COLUMNS CC JOIN ALL_CONSTRAINTS C
  338. ON (CC.CONSTRAINT_NAME = C.CONSTRAINT_NAME AND CC.TABLE_NAME = C.TABLE_NAME AND CC.OWNER = C.OWNER AND C.CONSTRAINT_TYPE = 'P'))
  339. ON TC.TABLE_NAME = CC.TABLE_NAME AND TC.COLUMN_NAME = CC.COLUMN_NAME
  340. WHERE UPPER(TC.TABLE_NAME) = UPPER(:TBNAME)";
  341. $bind[':TBNAME'] = $tableName;
  342. if ($schemaName) {
  343. $sql .= ' AND UPPER(TC.OWNER) = UPPER(:SCNAME)';
  344. $bind[':SCNAME'] = $schemaName;
  345. }
  346. $sql .= ' ORDER BY TC.COLUMN_ID';
  347. } else {
  348. $subSql="SELECT AC.OWNER, AC.TABLE_NAME, ACC.COLUMN_NAME, AC.CONSTRAINT_TYPE, ACC.POSITION
  349. from ALL_CONSTRAINTS AC, ALL_CONS_COLUMNS ACC
  350. WHERE ACC.CONSTRAINT_NAME = AC.CONSTRAINT_NAME
  351. AND ACC.TABLE_NAME = AC.TABLE_NAME
  352. AND ACC.OWNER = AC.OWNER
  353. AND AC.CONSTRAINT_TYPE = 'P'
  354. AND UPPER(AC.TABLE_NAME) = UPPER(:TBNAME)";
  355. $bind[':TBNAME'] = $tableName;
  356. if ($schemaName) {
  357. $subSql .= ' AND UPPER(ACC.OWNER) = UPPER(:SCNAME)';
  358. $bind[':SCNAME'] = $schemaName;
  359. }
  360. $sql="SELECT TC.TABLE_NAME, TC.OWNER, TC.COLUMN_NAME, TC.DATA_TYPE,
  361. TC.DATA_DEFAULT, TC.NULLABLE, TC.COLUMN_ID, TC.DATA_LENGTH,
  362. TC.DATA_SCALE, TC.DATA_PRECISION, CC.CONSTRAINT_TYPE, CC.POSITION
  363. FROM ALL_TAB_COLUMNS TC, ($subSql) CC
  364. WHERE UPPER(TC.TABLE_NAME) = UPPER(:TBNAME)
  365. AND TC.OWNER = CC.OWNER(+) AND TC.TABLE_NAME = CC.TABLE_NAME(+) AND TC.COLUMN_NAME = CC.COLUMN_NAME(+)";
  366. if ($schemaName) {
  367. $sql .= ' AND UPPER(TC.OWNER) = UPPER(:SCNAME)';
  368. }
  369. $sql .= ' ORDER BY TC.COLUMN_ID';
  370. }
  371. $stmt = $this->query($sql, $bind);
  372. /**
  373. * Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
  374. */
  375. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  376. $table_name = 0;
  377. $owner = 1;
  378. $column_name = 2;
  379. $data_type = 3;
  380. $data_default = 4;
  381. $nullable = 5;
  382. $column_id = 6;
  383. $data_length = 7;
  384. $data_scale = 8;
  385. $data_precision = 9;
  386. $constraint_type = 10;
  387. $position = 11;
  388. $desc = array();
  389. foreach ($result as $key => $row) {
  390. list ($primary, $primaryPosition, $identity) = array(false, null, false);
  391. if ($row[$constraint_type] == 'P') {
  392. $primary = true;
  393. $primaryPosition = $row[$position];
  394. /**
  395. * Oracle does not support auto-increment keys.
  396. */
  397. $identity = false;
  398. }
  399. $desc[$this->foldCase($row[$column_name])] = array(
  400. 'SCHEMA_NAME' => $this->foldCase($row[$owner]),
  401. 'TABLE_NAME' => $this->foldCase($row[$table_name]),
  402. 'COLUMN_NAME' => $this->foldCase($row[$column_name]),
  403. 'COLUMN_POSITION' => $row[$column_id],
  404. 'DATA_TYPE' => $row[$data_type],
  405. 'DEFAULT' => $row[$data_default],
  406. 'NULLABLE' => (bool) ($row[$nullable] == 'Y'),
  407. 'LENGTH' => $row[$data_length],
  408. 'SCALE' => $row[$data_scale],
  409. 'PRECISION' => $row[$data_precision],
  410. 'UNSIGNED' => null, // @todo
  411. 'PRIMARY' => $primary,
  412. 'PRIMARY_POSITION' => $primaryPosition,
  413. 'IDENTITY' => $identity
  414. );
  415. }
  416. return $desc;
  417. }
  418. /**
  419. * Leave autocommit mode and begin a transaction.
  420. *
  421. * @return void
  422. */
  423. protected function _beginTransaction()
  424. {
  425. $this->_setExecuteMode(OCI_DEFAULT);
  426. }
  427. /**
  428. * Commit a transaction and return to autocommit mode.
  429. *
  430. * @return void
  431. * @throws Zend_Db_Adapter_Oracle_Exception
  432. */
  433. protected function _commit()
  434. {
  435. if (!oci_commit($this->_connection)) {
  436. /**
  437. * @see Zend_Db_Adapter_Oracle_Exception
  438. */
  439. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  440. throw new Zend_Db_Adapter_Oracle_Exception(oci_error($this->_connection));
  441. }
  442. $this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);
  443. }
  444. /**
  445. * Roll back a transaction and return to autocommit mode.
  446. *
  447. * @return void
  448. * @throws Zend_Db_Adapter_Oracle_Exception
  449. */
  450. protected function _rollBack()
  451. {
  452. if (!oci_rollback($this->_connection)) {
  453. /**
  454. * @see Zend_Db_Adapter_Oracle_Exception
  455. */
  456. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  457. throw new Zend_Db_Adapter_Oracle_Exception(oci_error($this->_connection));
  458. }
  459. $this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);
  460. }
  461. /**
  462. * Set the fetch mode.
  463. *
  464. * @todo Support FETCH_CLASS and FETCH_INTO.
  465. *
  466. * @param integer $mode A fetch mode.
  467. * @return void
  468. * @throws Zend_Db_Adapter_Oracle_Exception
  469. */
  470. public function setFetchMode($mode)
  471. {
  472. switch ($mode) {
  473. case Zend_Db::FETCH_NUM: // seq array
  474. case Zend_Db::FETCH_ASSOC: // assoc array
  475. case Zend_Db::FETCH_BOTH: // seq+assoc array
  476. case Zend_Db::FETCH_OBJ: // object
  477. $this->_fetchMode = $mode;
  478. break;
  479. case Zend_Db::FETCH_BOUND: // bound to PHP variable
  480. /**
  481. * @see Zend_Db_Adapter_Oracle_Exception
  482. */
  483. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  484. throw new Zend_Db_Adapter_Oracle_Exception('FETCH_BOUND is not supported yet');
  485. break;
  486. default:
  487. /**
  488. * @see Zend_Db_Adapter_Oracle_Exception
  489. */
  490. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  491. throw new Zend_Db_Adapter_Oracle_Exception("Invalid fetch mode '$mode' specified");
  492. break;
  493. }
  494. }
  495. /**
  496. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  497. *
  498. * @param string $sql
  499. * @param integer $count
  500. * @param integer $offset OPTIONAL
  501. * @return string
  502. * @throws Zend_Db_Adapter_Oracle_Exception
  503. */
  504. public function limit($sql, $count, $offset = 0)
  505. {
  506. $count = intval($count);
  507. if ($count <= 0) {
  508. /**
  509. * @see Zend_Db_Adapter_Oracle_Exception
  510. */
  511. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  512. throw new Zend_Db_Adapter_Oracle_Exception("LIMIT argument count=$count is not valid");
  513. }
  514. $offset = intval($offset);
  515. if ($offset < 0) {
  516. /**
  517. * @see Zend_Db_Adapter_Oracle_Exception
  518. */
  519. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  520. throw new Zend_Db_Adapter_Oracle_Exception("LIMIT argument offset=$offset is not valid");
  521. }
  522. /**
  523. * Oracle does not implement the LIMIT clause as some RDBMS do.
  524. * We have to simulate it with subqueries and ROWNUM.
  525. * Unfortunately because we use the column wildcard "*",
  526. * this puts an extra column into the query result set.
  527. */
  528. $limit_sql = "SELECT z2.*
  529. FROM (
  530. SELECT z1.*, ROWNUM AS \"zend_db_rownum\"
  531. FROM (
  532. " . $sql . "
  533. ) z1
  534. ) z2
  535. WHERE z2.\"zend_db_rownum\" BETWEEN " . ($offset+1) . " AND " . ($offset+$count);
  536. return $limit_sql;
  537. }
  538. /**
  539. * @param integer $mode
  540. * @throws Zend_Db_Adapter_Oracle_Exception
  541. */
  542. private function _setExecuteMode($mode)
  543. {
  544. switch($mode) {
  545. case OCI_COMMIT_ON_SUCCESS:
  546. case OCI_DEFAULT:
  547. case OCI_DESCRIBE_ONLY:
  548. $this->_execute_mode = $mode;
  549. break;
  550. default:
  551. /**
  552. * @see Zend_Db_Adapter_Oracle_Exception
  553. */
  554. // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
  555. throw new Zend_Db_Adapter_Oracle_Exception("Invalid execution mode '$mode' specified");
  556. break;
  557. }
  558. }
  559. /**
  560. * @return int
  561. */
  562. public function _getExecuteMode()
  563. {
  564. return $this->_execute_mode;
  565. }
  566. /**
  567. * Check if the adapter supports real SQL parameters.
  568. *
  569. * @param string $type 'positional' or 'named'
  570. * @return bool
  571. */
  572. public function supportsParameters($type)
  573. {
  574. switch ($type) {
  575. case 'named':
  576. return true;
  577. case 'positional':
  578. default:
  579. return false;
  580. }
  581. }
  582. /**
  583. * Retrieve server version in PHP style
  584. *
  585. * @return string
  586. */
  587. public function getServerVersion()
  588. {
  589. $this->_connect();
  590. $version = oci_server_version($this->_connection);
  591. if ($version !== false) {
  592. $matches = null;
  593. if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $version, $matches)) {
  594. return $matches[1];
  595. } else {
  596. return null;
  597. }
  598. } else {
  599. return null;
  600. }
  601. }
  602. }