odbc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2004 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/2_02.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Author: Stig Bakken <ssb@php.net> |
  17. // | Maintainer: Daniel Convissor <danielc@php.net> |
  18. // +----------------------------------------------------------------------+
  19. //
  20. // $Id: odbc.php,v 1.42 2004/02/18 23:07:10 danielc Exp $
  21. // XXX legend:
  22. // More info on ODBC errors could be found here:
  23. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/trblsql/tr_err_odbc_5stz.asp
  24. //
  25. // XXX ERRORMSG: The error message from the odbc function should
  26. // be registered here.
  27. require_once 'DB/common.php';
  28. /**
  29. * Database independent query interface definition for PHP's ODBC
  30. * extension.
  31. *
  32. * @package DB
  33. * @version $Id: odbc.php,v 1.42 2004/02/18 23:07:10 danielc Exp $
  34. * @category Database
  35. * @author Stig Bakken <ssb@php.net>
  36. */
  37. class DB_odbc extends DB_common
  38. {
  39. // {{{ properties
  40. var $connection;
  41. var $phptype, $dbsyntax;
  42. var $row = array();
  43. // }}}
  44. // {{{ constructor
  45. function DB_odbc()
  46. {
  47. $this->DB_common();
  48. $this->phptype = 'odbc';
  49. $this->dbsyntax = 'sql92';
  50. $this->features = array(
  51. 'prepare' => true,
  52. 'pconnect' => true,
  53. 'transactions' => false,
  54. 'limit' => 'emulate'
  55. );
  56. $this->errorcode_map = array(
  57. '01004' => DB_ERROR_TRUNCATED,
  58. '07001' => DB_ERROR_MISMATCH,
  59. '21S01' => DB_ERROR_MISMATCH,
  60. '21S02' => DB_ERROR_MISMATCH,
  61. '22003' => DB_ERROR_INVALID_NUMBER,
  62. '22005' => DB_ERROR_INVALID_NUMBER,
  63. '22008' => DB_ERROR_INVALID_DATE,
  64. '22012' => DB_ERROR_DIVZERO,
  65. '23000' => DB_ERROR_CONSTRAINT,
  66. '23502' => DB_ERROR_CONSTRAINT_NOT_NULL,
  67. '23503' => DB_ERROR_CONSTRAINT,
  68. '23505' => DB_ERROR_CONSTRAINT,
  69. '24000' => DB_ERROR_INVALID,
  70. '34000' => DB_ERROR_INVALID,
  71. '37000' => DB_ERROR_SYNTAX,
  72. '42000' => DB_ERROR_SYNTAX,
  73. '42601' => DB_ERROR_SYNTAX,
  74. 'IM001' => DB_ERROR_UNSUPPORTED,
  75. 'S0000' => DB_ERROR_NOSUCHTABLE,
  76. 'S0001' => DB_ERROR_ALREADY_EXISTS,
  77. 'S0002' => DB_ERROR_NOSUCHTABLE,
  78. 'S0011' => DB_ERROR_ALREADY_EXISTS,
  79. 'S0012' => DB_ERROR_NOT_FOUND,
  80. 'S0021' => DB_ERROR_ALREADY_EXISTS,
  81. 'S0022' => DB_ERROR_NOSUCHFIELD,
  82. 'S1000' => DB_ERROR_CONSTRAINT_NOT_NULL,
  83. 'S1009' => DB_ERROR_INVALID,
  84. 'S1090' => DB_ERROR_INVALID,
  85. 'S1C00' => DB_ERROR_NOT_CAPABLE
  86. );
  87. }
  88. // }}}
  89. // {{{ connect()
  90. /**
  91. * Connect to a database and log in as the specified user.
  92. *
  93. * @param $dsn the data source name (see DB::parseDSN for syntax)
  94. * @param $persistent (optional) whether the connection should
  95. * be persistent
  96. *
  97. * @return int DB_OK on success, a DB error code on failure
  98. */
  99. function connect($dsninfo, $persistent = false)
  100. {
  101. if (!DB::assertExtension('odbc')) {
  102. return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
  103. }
  104. $this->dsn = $dsninfo;
  105. if ($dsninfo['dbsyntax']) {
  106. $this->dbsyntax = $dsninfo['dbsyntax'];
  107. }
  108. switch ($this->dbsyntax) {
  109. case 'solid':
  110. $this->features = array(
  111. 'prepare' => true,
  112. 'pconnect' => true,
  113. 'transactions' => true
  114. );
  115. break;
  116. case 'navision':
  117. // the Navision driver doesn't support fetch row by number
  118. $this->features['limit'] = false;
  119. break;
  120. case 'access':
  121. if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
  122. $this->errorcode_map['07001'] = DB_ERROR_NOSUCHFIELD;
  123. }
  124. break;
  125. default:
  126. break;
  127. }
  128. /*
  129. * This is hear for backwards compatibility.
  130. * Should have been using 'database' all along, but used hostspec.
  131. */
  132. if ($dsninfo['database']) {
  133. $odbcdsn = $dsninfo['database'];
  134. } elseif ($dsninfo['hostspec']) {
  135. $odbcdsn = $dsninfo['hostspec'];
  136. } else {
  137. $odbcdsn = 'localhost';
  138. }
  139. if ($this->provides('pconnect')) {
  140. $connect_function = $persistent ? 'odbc_pconnect' : 'odbc_connect';
  141. } else {
  142. $connect_function = 'odbc_connect';
  143. }
  144. $conn = @$connect_function($odbcdsn, $dsninfo['username'],
  145. $dsninfo['password']);
  146. if (!is_resource($conn)) {
  147. return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
  148. null, $this->errorNative());
  149. }
  150. $this->connection = $conn;
  151. return DB_OK;
  152. }
  153. // }}}
  154. // {{{ disconnect()
  155. function disconnect()
  156. {
  157. $err = @odbc_close($this->connection);
  158. $this->connection = null;
  159. return $err;
  160. }
  161. // }}}
  162. // {{{ simpleQuery()
  163. /**
  164. * Send a query to ODBC and return the results as a ODBC resource
  165. * identifier.
  166. *
  167. * @param $query the SQL query
  168. *
  169. * @return int returns a valid ODBC result for successful SELECT
  170. * queries, DB_OK for other successful queries. A DB error code
  171. * is returned on failure.
  172. */
  173. function simpleQuery($query)
  174. {
  175. $this->last_query = $query;
  176. $query = $this->modifyQuery($query);
  177. $result = @odbc_exec($this->connection, $query);
  178. if (!$result) {
  179. return $this->odbcRaiseError(); // XXX ERRORMSG
  180. }
  181. // Determine which queries that should return data, and which
  182. // should return an error code only.
  183. if (DB::isManip($query)) {
  184. $this->manip_result = $result; // For affectedRows()
  185. return DB_OK;
  186. }
  187. $this->row[(int)$result] = 0;
  188. $this->manip_result = 0;
  189. return $result;
  190. }
  191. // }}}
  192. // {{{ nextResult()
  193. /**
  194. * Move the internal odbc result pointer to the next available result
  195. *
  196. * @param a valid fbsql result resource
  197. *
  198. * @access public
  199. *
  200. * @return true if a result is available otherwise return false
  201. */
  202. function nextResult($result)
  203. {
  204. return odbc_next_result($result);
  205. }
  206. // }}}
  207. // {{{ fetchInto()
  208. /**
  209. * Fetch a row and insert the data into an existing array.
  210. *
  211. * Formating of the array and the data therein are configurable.
  212. * See DB_result::fetchInto() for more information.
  213. *
  214. * @param resource $result query result identifier
  215. * @param array $arr (reference) array where data from the row
  216. * should be placed
  217. * @param int $fetchmode how the resulting array should be indexed
  218. * @param int $rownum the row number to fetch
  219. *
  220. * @return mixed DB_OK on success, NULL when end of result set is
  221. * reached or on failure
  222. *
  223. * @see DB_result::fetchInto()
  224. * @access private
  225. */
  226. function fetchInto($result, &$arr, $fetchmode, $rownum=null)
  227. {
  228. $arr = array();
  229. if ($rownum !== null) {
  230. $rownum++; // ODBC first row is 1
  231. if (version_compare(phpversion(), '4.2.0', 'ge')) {
  232. $cols = odbc_fetch_into($result, $arr, $rownum);
  233. } else {
  234. $cols = odbc_fetch_into($result, $rownum, $arr);
  235. }
  236. } else {
  237. $cols = odbc_fetch_into($result, $arr);
  238. }
  239. if (!$cols) {
  240. /* XXX FIXME: doesn't work with unixODBC and easysoft
  241. (get corrupted $errno values)
  242. if ($errno = odbc_error($this->connection)) {
  243. return $this->RaiseError($errno);
  244. }*/
  245. return null;
  246. }
  247. if ($fetchmode !== DB_FETCHMODE_ORDERED) {
  248. for ($i = 0; $i < count($arr); $i++) {
  249. $colName = odbc_field_name($result, $i+1);
  250. $a[$colName] = $arr[$i];
  251. }
  252. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  253. $a = array_change_key_case($a, CASE_LOWER);
  254. }
  255. $arr = $a;
  256. }
  257. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  258. $this->_rtrimArrayValues($arr);
  259. }
  260. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  261. $this->_convertNullArrayValuesToEmpty($arr);
  262. }
  263. return DB_OK;
  264. }
  265. // }}}
  266. // {{{ freeResult()
  267. function freeResult($result)
  268. {
  269. unset($this->row[(int)$result]);
  270. return @odbc_free_result($result);
  271. }
  272. // }}}
  273. // {{{ numCols()
  274. function numCols($result)
  275. {
  276. $cols = @odbc_num_fields($result);
  277. if (!$cols) {
  278. return $this->odbcRaiseError();
  279. }
  280. return $cols;
  281. }
  282. // }}}
  283. // {{{ affectedRows()
  284. /**
  285. * Returns the number of rows affected by a manipulative query
  286. * (INSERT, DELETE, UPDATE)
  287. * @return mixed int affected rows, 0 when non manip queries or
  288. * DB error on error
  289. */
  290. function affectedRows()
  291. {
  292. if (empty($this->manip_result)) { // In case of SELECT stms
  293. return 0;
  294. }
  295. $nrows = odbc_num_rows($this->manip_result);
  296. if ($nrows == -1) {
  297. return $this->odbcRaiseError();
  298. }
  299. return $nrows;
  300. }
  301. // }}}
  302. // {{{ numRows()
  303. /**
  304. * ODBC may or may not support counting rows in the result set of
  305. * SELECTs.
  306. *
  307. * @param $result the odbc result resource
  308. * @return the number of rows, or 0
  309. */
  310. function numRows($result)
  311. {
  312. $nrows = odbc_num_rows($result);
  313. if ($nrows == -1) {
  314. return $this->odbcRaiseError(DB_ERROR_UNSUPPORTED);
  315. }
  316. return $nrows;
  317. }
  318. // }}}
  319. // {{{ quoteIdentifier()
  320. /**
  321. * Quote a string so it can be safely used as a table / column name
  322. *
  323. * Quoting style depends on which dbsyntax was passed in the DSN.
  324. *
  325. * Use 'mssql' as the dbsyntax in the DB DSN only if you've unchecked
  326. * "Use ANSI quoted identifiers" when setting up the ODBC data source.
  327. *
  328. * @param string $str identifier name to be quoted
  329. *
  330. * @return string quoted identifier string
  331. *
  332. * @since 1.6.0
  333. * @access public
  334. */
  335. function quoteIdentifier($str)
  336. {
  337. switch ($this->dsn['dbsyntax']) {
  338. case 'access':
  339. return '[' . $str . ']';
  340. case 'mssql':
  341. case 'sybase':
  342. return '[' . str_replace(']', ']]', $str) . ']';
  343. case 'mysql':
  344. case 'mysqli':
  345. return '`' . $str . '`';
  346. default:
  347. return '"' . str_replace('"', '""', $str) . '"';
  348. }
  349. }
  350. // }}}
  351. // {{{ quote()
  352. /**
  353. * @deprecated Deprecated in release 1.6.0
  354. * @internal
  355. */
  356. function quote($str) {
  357. return $this->quoteSmart($str);
  358. }
  359. // }}}
  360. // {{{ errorNative()
  361. /**
  362. * Get the native error code of the last error (if any) that
  363. * occured on the current connection.
  364. *
  365. * @access public
  366. *
  367. * @return int ODBC error code
  368. */
  369. function errorNative()
  370. {
  371. if (!isset($this->connection) || !is_resource($this->connection)) {
  372. return odbc_error() . ' ' . odbc_errormsg();
  373. }
  374. return odbc_error($this->connection) . ' ' . odbc_errormsg($this->connection);
  375. }
  376. // }}}
  377. // {{{ nextId()
  378. /**
  379. * Returns the next free id in a sequence
  380. *
  381. * @param string $seq_name name of the sequence
  382. * @param boolean $ondemand when true, the seqence is automatically
  383. * created if it does not exist
  384. *
  385. * @return int the next id number in the sequence. DB_Error if problem.
  386. *
  387. * @internal
  388. * @see DB_common::nextID()
  389. * @access public
  390. */
  391. function nextId($seq_name, $ondemand = true)
  392. {
  393. $seqname = $this->getSequenceName($seq_name);
  394. $repeat = 0;
  395. do {
  396. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  397. $result = $this->query("update ${seqname} set id = id + 1");
  398. $this->popErrorHandling();
  399. if ($ondemand && DB::isError($result) &&
  400. $result->getCode() == DB_ERROR_NOSUCHTABLE) {
  401. $repeat = 1;
  402. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  403. $result = $this->createSequence($seq_name);
  404. $this->popErrorHandling();
  405. if (DB::isError($result)) {
  406. return $this->raiseError($result);
  407. }
  408. $result = $this->query("insert into ${seqname} (id) values(0)");
  409. } else {
  410. $repeat = 0;
  411. }
  412. } while ($repeat);
  413. if (DB::isError($result)) {
  414. return $this->raiseError($result);
  415. }
  416. $result = $this->query("select id from ${seqname}");
  417. if (DB::isError($result)) {
  418. return $result;
  419. }
  420. $row = $result->fetchRow(DB_FETCHMODE_ORDERED);
  421. if (DB::isError($row || !$row)) {
  422. return $row;
  423. }
  424. return $row[0];
  425. }
  426. /**
  427. * Creates a new sequence
  428. *
  429. * @param string $seq_name name of the new sequence
  430. *
  431. * @return int DB_OK on success. A DB_Error object is returned if
  432. * problems arise.
  433. *
  434. * @internal
  435. * @see DB_common::createSequence()
  436. * @access public
  437. */
  438. function createSequence($seq_name)
  439. {
  440. $seqname = $this->getSequenceName($seq_name);
  441. return $this->query("CREATE TABLE ${seqname} ".
  442. '(id integer NOT NULL,'.
  443. ' PRIMARY KEY(id))');
  444. }
  445. // }}}
  446. // {{{ dropSequence()
  447. /**
  448. * Deletes a sequence
  449. *
  450. * @param string $seq_name name of the sequence to be deleted
  451. *
  452. * @return int DB_OK on success. DB_Error if problems.
  453. *
  454. * @internal
  455. * @see DB_common::dropSequence()
  456. * @access public
  457. */
  458. function dropSequence($seq_name)
  459. {
  460. $seqname = $this->getSequenceName($seq_name);
  461. return $this->query("DROP TABLE ${seqname}");
  462. }
  463. // }}}
  464. // {{{ autoCommit()
  465. function autoCommit($onoff = false)
  466. {
  467. if (!@odbc_autocommit($this->connection, $onoff)) {
  468. return $this->odbcRaiseError();
  469. }
  470. return DB_OK;
  471. }
  472. // }}}
  473. // {{{ commit()
  474. function commit()
  475. {
  476. if (!@odbc_commit($this->connection)) {
  477. return $this->odbcRaiseError();
  478. }
  479. return DB_OK;
  480. }
  481. // }}}
  482. // {{{ rollback()
  483. function rollback()
  484. {
  485. if (!@odbc_rollback($this->connection)) {
  486. return $this->odbcRaiseError();
  487. }
  488. return DB_OK;
  489. }
  490. // }}}
  491. // {{{ odbcRaiseError()
  492. /**
  493. * Gather information about an error, then use that info to create a
  494. * DB error object and finally return that object.
  495. *
  496. * @param integer $errno PEAR error number (usually a DB constant) if
  497. * manually raising an error
  498. * @return object DB error object
  499. * @see errorNative()
  500. * @see DB_common::errorCode()
  501. * @see DB_common::raiseError()
  502. */
  503. function odbcRaiseError($errno = null)
  504. {
  505. if ($errno === null) {
  506. $errno = $this->errorCode(odbc_error($this->connection));
  507. }
  508. return $this->raiseError($errno, null, null, null,
  509. $this->errorNative());
  510. }
  511. // }}}
  512. }
  513. /*
  514. * Local variables:
  515. * tab-width: 4
  516. * c-basic-offset: 4
  517. * End:
  518. */
  519. ?>