PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/scalr-2/tags/scalr-2.0.0/app/src/Lib/Data/DB/adodb_lite/adodbSQL_drivers/postgres/postgres_driver.inc

http://scalr.googlecode.com/
PHP | 657 lines | 578 code | 27 blank | 52 comment | 30 complexity | 7268f158ea23b8aa2b0923be7ca7e955 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, GPL-3.0
  1. <?php
  2. /**
  3. * ADOdb Lite is a PHP class to encapsulate multiple database APIs and is compatible with
  4. * a subset of the ADODB Command Syntax.
  5. * Currently supports Frontbase, MaxDB, miniSQL, MSSQL, MSSQL Pro, MySQLi, MySQLt, MySQL, PostgresSQL,
  6. * PostgresSQL64, PostgresSQL7, SqLite and Sybase.
  7. *
  8. */
  9. class postgres_driver_ADOConnection extends ADOConnection
  10. {
  11. var $connect_string;
  12. var $sysDate = "CURRENT_DATE";
  13. var $sysTimeStamp = "CURRENT_TIMESTAMP";
  14. function postgres_driver_ADOConnection()
  15. {
  16. $this->dbtype = 'postgres';
  17. $this->dataProvider = 'postgres';
  18. }
  19. /**
  20. * Connection to database server and selected database
  21. *
  22. * @access private
  23. */
  24. function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew)
  25. {
  26. if (!function_exists('pg_connect')) return false;
  27. $this->host = $host;
  28. $this->username = $this->query_addslashes($username);
  29. $this->password = $this->query_addslashes($password);
  30. if (strlen($database) == 0) $database = 'template1';
  31. $this->database = $this->query_addslashes($database);
  32. if ($this->username || $this->password || $this->database) {
  33. $this->connect_string = $this->host;
  34. if ($this->connect_string) {
  35. $host = split(":", $this->connect_string);
  36. if ($host[0]) $this->connect_string = "host=" . $this->query_addslashes($host[0]);
  37. else $this->connect_string = 'host=localhost';
  38. if (isset($host[1])) $this->connect_string .= " port=$host[1]";
  39. else if (!empty($this->port)) $this->connect_string .= " port=" . $this->port;
  40. }
  41. if ($this->username) $this->connect_string .= " user=" . $this->username;
  42. if ($this->password) $this->connect_string .= " password=" . $this->password;
  43. if ($this->database) $this->connect_string .= " dbname=" . $this->database;
  44. }
  45. else
  46. {
  47. $this->connect_string = $this->host;
  48. }
  49. $this->persistent = $persistent;
  50. $this->forcenewconnection = $forcenew;
  51. $this->_makeconnection();
  52. if ($this->connectionId === false)
  53. {
  54. if ($fn = $this->raiseErrorFn)
  55. $fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this);
  56. return $this->SelectDB( $this->database );
  57. }
  58. return true;
  59. }
  60. function _makeconnection()
  61. {
  62. if($this->persistent == 1)
  63. {
  64. $this->connectionId = @pg_pconnect( $this->connect_string );
  65. }
  66. else
  67. {
  68. if(!$this->forcenewconnection)
  69. {
  70. $this->connectionId = @pg_connect( $this->connect_string );
  71. }
  72. else
  73. {
  74. $this->connectionId = @pg_connect( $this->connect_string, PGSQL_CONNECT_FORCE_NEW );
  75. }
  76. }
  77. }
  78. function query_addslashes($query)
  79. {
  80. $len = strlen($query);
  81. if ($len == 0)
  82. return "''";
  83. if (strncmp($query,"'",1) === 0 && substr($query,$len-1) == "'")
  84. return $s;
  85. return "'".addslashes($query)."'";
  86. }
  87. /**
  88. * Choose a database to connect.
  89. *
  90. * @param dbname is the name of the database to select
  91. * @return true or false
  92. * @access public
  93. */
  94. function SelectDB($dbname)
  95. {
  96. $this->database = $dbname;
  97. if ($this->connectionId === false)
  98. {
  99. if($this->createdatabase == true)
  100. {
  101. $this->connectionId = @pg_pconnect( $this->connect_string );
  102. $result = @pg_query($this->connectionId, "CREATE DATABASE " . $this->database );
  103. if ($result === false) { // error handling if query fails
  104. $this->connectionId = false;
  105. return false;
  106. }
  107. $this->_makeconnection();
  108. if($this->connectionId === false)
  109. {
  110. $this->connectionId = false;
  111. return false;
  112. }
  113. else
  114. {
  115. return true;
  116. }
  117. }
  118. $this->connectionId = false;
  119. return false;
  120. }
  121. else
  122. {
  123. return true;
  124. }
  125. }
  126. /**
  127. * Return database error message
  128. * Usage: $errormessage =& $db->ErrorMsg();
  129. *
  130. * @access public
  131. */
  132. function ErrorMsg()
  133. {
  134. return @pg_last_error($this->connectionId);
  135. }
  136. /**
  137. * Return database error number
  138. * Usage: $errorbo =& $db->ErrorNo();
  139. *
  140. * @access public
  141. */
  142. function ErrorNo()
  143. {
  144. $error = @pg_last_error( $this->connectionId );
  145. return strlen($error) ? $error : 0;
  146. }
  147. /**
  148. * Returns # of affected rows from insert/delete/update query
  149. *
  150. * @access public
  151. * @return integer Affected rows
  152. */
  153. function Affected_Rows()
  154. {
  155. return @pg_affected_rows($this->record_set);
  156. }
  157. /**
  158. * Returns the last record id of an inserted item
  159. * Usage: $db->Insert_ID();
  160. *
  161. * @access public
  162. */
  163. function Insert_ID()
  164. {
  165. return @pg_getlastoid($this->record_set);
  166. }
  167. /**
  168. * Correctly quotes a string so that all strings are escape coded.
  169. * An example is $db->qstr("Haven't a clue.");
  170. *
  171. * @param string the string to quote
  172. * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  173. *
  174. * @return single-quoted string IE: 'Haven\'t a clue.'
  175. */
  176. function qstr($string, $magic_quotes=false)
  177. {
  178. if (!$magic_quotes) {
  179. if (strnatcmp(PHP_VERSION, '4.2.0') >= 0) {
  180. return "'" . pg_escape_string($string) . "'";
  181. }
  182. $string = str_replace("'", "\\'", str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
  183. return "'" . $string . "'";
  184. }
  185. return "'" . str_replace('\\"', '"', $string) . "'";
  186. }
  187. function QMagic($string)
  188. {
  189. return $this->qstr($string, get_magic_quotes_gpc());
  190. }
  191. /**
  192. * Returns concatenated string
  193. * Usage: $db->Concat($str1,$str2);
  194. *
  195. * @return concatenated string
  196. */
  197. function Concat()
  198. {
  199. $arr = func_get_args();
  200. return implode("||", $arr);
  201. }
  202. function IfNull( $field, $ifNull )
  203. {
  204. return " coalesce($field, $ifNull) ";
  205. }
  206. /**
  207. * Closes database connection
  208. * Usage: $db->close();
  209. *
  210. * @access public
  211. */
  212. function Close()
  213. {
  214. @pg_close( $this->connectionId );
  215. $this->connectionId = false;
  216. }
  217. /**
  218. * Returns All Records in an array
  219. *
  220. * Usage: $db->GetAll($sql);
  221. * @access public
  222. */
  223. function &GetAll($sql, $inputarr = false)
  224. {
  225. $data =& $this->GetArray($sql, $inputarr);
  226. return $data;
  227. }
  228. /**
  229. * Returns All Records in an array
  230. *
  231. * Usage: $db->GetArray($sql);
  232. * @access public
  233. */
  234. function &GetArray($sql, $inputarr = false)
  235. {
  236. $data = false;
  237. $result =& $this->Execute($sql, $inputarr);
  238. if ($result)
  239. {
  240. $data =& $result->GetArray();
  241. $result->Close();
  242. }
  243. return $data;
  244. }
  245. /**
  246. * Executes SQL query and instantiates resultset methods
  247. *
  248. * @access private
  249. * @return mixed Resultset methods
  250. */
  251. function &do_query( $sql, $offset, $nrows, $inputarr=false )
  252. {
  253. global $ADODB_FETCH_MODE;
  254. $false = false;
  255. // $limit = '';
  256. // if ($offset != -1 || $nrows != -1)
  257. // {
  258. // $offset = ($offset>=0) ? $offset . "," : '';
  259. // $limit = ' LIMIT ' . $offset . ' ' . $nrows;
  260. // }
  261. if ($inputarr && is_array($inputarr)) {
  262. $sqlarr = explode('?', $sql);
  263. if (!is_array(reset($inputarr))) $inputarr = array($inputarr);
  264. foreach($inputarr as $arr) {
  265. $sql = ''; $i = 0;
  266. foreach($arr as $v) {
  267. $sql .= $sqlarr[$i];
  268. switch(gettype($v)){
  269. case 'string':
  270. $sql .= $this->qstr($v);
  271. break;
  272. case 'double':
  273. $sql .= str_replace(',', '.', $v);
  274. break;
  275. case 'boolean':
  276. $sql .= $v ? "'t'" : "'f'";
  277. break;
  278. default:
  279. if ($v === null)
  280. $sql .= 'NULL';
  281. else $sql .= $v;
  282. }
  283. $i += 1;
  284. }
  285. $sql .= $sqlarr[$i];
  286. if ($i+1 != sizeof($sqlarr))
  287. return $false;
  288. $this->sql = $sql;
  289. $time_start = array_sum(explode(' ', microtime()));
  290. $this->query_count++;
  291. $resultId = @pg_query($this->connectionId, $this->sql );
  292. $time_total = (array_sum(explode(' ', microtime())) - $time_start);
  293. $this->query_time_total += $time_total;
  294. if($this->debug_console)
  295. {
  296. $this->query_list[] = $this->sql;
  297. $this->query_list_time[] = $time_total;
  298. $this->query_list_errors[] = $this->ErrorMsg();
  299. }
  300. if($this->debug)
  301. {
  302. $this->outp($sql);
  303. }
  304. if ($resultId === false) { // error handling if query fails
  305. if ($fn = $this->raiseErrorFn)
  306. $fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
  307. return $false;
  308. }
  309. }
  310. }
  311. else
  312. {
  313. $this->sql = $sql;
  314. $time_start = array_sum(explode(' ', microtime()));
  315. $this->query_count++;
  316. $resultId = @pg_query($this->connectionId, $this->sql );
  317. $time_total = (array_sum(explode(' ', microtime())) - $time_start);
  318. $this->query_time_total += $time_total;
  319. if($this->debug_console)
  320. {
  321. $this->query_list[] = $this->sql;
  322. $this->query_list_time[] = $time_total;
  323. $this->query_list_errors[] = $this->ErrorMsg();
  324. }
  325. if($this->debug)
  326. {
  327. $this->outp($sql);
  328. }
  329. }
  330. if ($resultId === false) { // error handling if query fails
  331. if ($fn = $this->raiseErrorFn)
  332. $fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this);
  333. return $false;
  334. }
  335. if (@pg_numfields( $resultId ) <= 0) { // return simplified recordset for inserts/updates/deletes with lower overhead
  336. $recordset = new ADORecordSet_empty();
  337. $this->record_set = $recordset;
  338. return $recordset;
  339. }
  340. $resultset_name = $this->last_module_name . "_ResultSet";
  341. $recordset = new $resultset_name( $resultId, $this->connectionId );
  342. $this->record_set = $recordset;
  343. $recordset->_currentRow = 0;
  344. switch ($ADODB_FETCH_MODE)
  345. {
  346. case ADODB_FETCH_NUM: $recordset->fetchMode = PGSQL_NUM; break;
  347. case ADODB_FETCH_ASSOC:$recordset->fetchMode = PGSQL_ASSOC; break;
  348. default:
  349. case ADODB_FETCH_DEFAULT:
  350. case ADODB_FETCH_BOTH:$recordset->fetchMode = PGSQL_BOTH; break;
  351. }
  352. $recordset->_numOfRows = @pg_numrows( $resultId );
  353. if( $recordset->_numOfRows == 0)
  354. {
  355. $recordset->EOF = true;
  356. }
  357. $recordset->_numOfFields = @pg_numfields( $resultId );
  358. $recordset->_fetch();
  359. return $recordset;
  360. }
  361. }
  362. class postgres_driver_ResultSet
  363. {
  364. var $connectionId;
  365. var $fields;
  366. var $resultId;
  367. var $_currentRow = 0;
  368. var $_numOfRows = -1;
  369. var $_numOfFields = -1;
  370. var $fetchMode;
  371. var $EOF;
  372. /**
  373. * pgsqlResultSet Constructor
  374. *
  375. * @access private
  376. * @param string $record
  377. * @param string $resultId
  378. */
  379. function postgres_driver_ResultSet( $resultId, $connectionId )
  380. {
  381. $this->fields = array();
  382. $this->connectionId = $connectionId;
  383. $this->record = array();
  384. $this->resultId = $resultId;
  385. $this->EOF = false;
  386. }
  387. /**
  388. * Frees resultset
  389. *
  390. * @access public
  391. */
  392. function Close()
  393. {
  394. pg_free_result( $this->resultId );
  395. $this->fields = array();
  396. $this->resultId = false;
  397. }
  398. /**
  399. * Returns field name from select query
  400. *
  401. * @access public
  402. * @param string $field
  403. * @return string Field name
  404. */
  405. function fields( $field )
  406. {
  407. if(empty($field))
  408. {
  409. return $this->fields;
  410. }
  411. else
  412. {
  413. return $this->fields[$field];
  414. }
  415. }
  416. /**
  417. * Returns numrows from select query
  418. *
  419. * @access public
  420. * @return integer Numrows
  421. */
  422. function RecordCount()
  423. {
  424. return $this->_numOfRows;
  425. }
  426. /**
  427. * Returns num of fields from select query
  428. *
  429. * @access public
  430. * @return integer numfields
  431. */
  432. function FieldCount()
  433. {
  434. return $this->_numOfFields;
  435. }
  436. /**
  437. * Returns next record
  438. *
  439. * @access public
  440. */
  441. function MoveNext()
  442. {
  443. if (@$this->fields = pg_fetch_array($this->resultId, NULL, $this->fetchMode)) {
  444. $this->_currentRow += 1;
  445. return true;
  446. }
  447. if (!$this->EOF) {
  448. $this->_currentRow += 1;
  449. $this->EOF = true;
  450. }
  451. return false;
  452. }
  453. /**
  454. * Move to the first row in the recordset. Many databases do NOT support this.
  455. *
  456. * @return true or false
  457. */
  458. function MoveFirst()
  459. {
  460. if ($this->_currentRow == 0) return true;
  461. return $this->Move(0);
  462. }
  463. /**
  464. * Returns the Last Record
  465. *
  466. * @access public
  467. */
  468. function MoveLast()
  469. {
  470. if ($this->EOF) return false;
  471. return $this->Move($this->_numOfRows - 1);
  472. }
  473. /**
  474. * Random access to a specific row in the recordset. Some databases do not support
  475. * access to previous rows in the databases (no scrolling backwards).
  476. *
  477. * @param rowNumber is the row to move to (0-based)
  478. *
  479. * @return true if there still rows available, or false if there are no more rows (EOF).
  480. */
  481. function Move($rowNumber = 0)
  482. {
  483. if ($rowNumber == $this->_currentRow) return true;
  484. $this->EOF = false;
  485. if ($this->_numOfRows > 0){
  486. if ($rowNumber >= $this->_numOfRows - 1){
  487. $rowNumber = $this->_numOfRows - 1;
  488. }
  489. }
  490. if ($this->_seek($rowNumber)) {
  491. $this->_currentRow = $rowNumber;
  492. if ($this->_fetch()) {
  493. return true;
  494. }
  495. $this->fields = false;
  496. }
  497. $this->EOF = true;
  498. return false;
  499. }
  500. /**
  501. * Perform Seek to specific row
  502. *
  503. * @access private
  504. */
  505. function _seek($row)
  506. {
  507. if ($this->_numOfRows == 0) return false;
  508. return @pg_result_seek($this->resultId,$row);
  509. }
  510. /**
  511. * Fills field array with first database element when query initially executed
  512. *
  513. * @access private
  514. */
  515. function _fetch()
  516. {
  517. $this->fields = @pg_fetch_array($this->resultId, NULL, $this->fetchMode);
  518. return is_array($this->fields);
  519. }
  520. /**
  521. * Check to see if last record reached
  522. *
  523. * @access public
  524. */
  525. function EOF()
  526. {
  527. if( $this->_currentRow < $this->_numOfRows)
  528. {
  529. return false;
  530. }
  531. else
  532. {
  533. $this->EOF = true;
  534. return true;
  535. }
  536. }
  537. /**
  538. * Returns All Records in an array
  539. *
  540. * @access public
  541. * @param [nRows] is the number of rows to return. -1 means every row.
  542. */
  543. function &GetArray($nRows = -1)
  544. {
  545. $results = array();
  546. $cnt = 0;
  547. while (!$this->EOF && $nRows != $cnt) {
  548. $results[] = $this->fields;
  549. $this->MoveNext();
  550. $cnt++;
  551. }
  552. return $results;
  553. }
  554. function &GetRows($nRows = -1)
  555. {
  556. $arr =& $this->GetArray($nRows);
  557. return $arr;
  558. }
  559. function &GetAll($nRows = -1)
  560. {
  561. $arr =& $this->GetArray($nRows);
  562. return $arr;
  563. }
  564. /**
  565. * Fetch field information for a table.
  566. *
  567. * @return object containing the name, type and max_length
  568. */
  569. function FetchField($fieldOffset = -1)
  570. {
  571. $fieldObject= new ADOFieldObject();
  572. $fieldObject->name = @pg_fieldname($this->resultId, $fieldOffset);
  573. $fieldObject->type = @pg_fieldtype($this->resultId, $fieldOffset);
  574. $fieldObject->max_length = @pg_fieldsize($this->resultId, $fieldOffset);
  575. return $fieldObject;
  576. }
  577. }
  578. ?>