PageRenderTime 73ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/webtools/partytool/cake/libs/model/datasources/dbo/dbo_firebird.php

https://github.com/jrmuizel/mozilla-cvs-history
PHP | 517 lines | 298 code | 24 blank | 195 comment | 62 complexity | 08aedf35e8767621d27699632600c7fe MD5 | raw file
  1. <?php
  2. /* SVN FILE: $Id: dbo_firebird.php,v 1.1 2007-11-19 09:05:48 rflint%ryanflint.com Exp $ */
  3. /**
  4. * Firebird/Interbase layer for DBO
  5. *
  6. * Long description for file
  7. *
  8. * PHP versions 4 and 5
  9. *
  10. * CakePHP(tm) : Rapid Development Framework <http://www.cakephp.org/>
  11. * Copyright 2005-2007, Cake Software Foundation, Inc.
  12. * 1785 E. Sahara Avenue, Suite 490-204
  13. * Las Vegas, Nevada 89104
  14. *
  15. * Licensed under The MIT License
  16. * Redistributions of files must retain the above copyright notice.
  17. *
  18. * @filesource
  19. * @copyright Copyright 2005-2007, Cake Software Foundation, Inc.
  20. * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
  21. * @package cake
  22. * @subpackage cake.cake.libs.model.dbo
  23. * @since CakePHP(tm) v 1.2.0.5152
  24. * @version $Revision: 1.1 $
  25. * @modifiedby $LastChangedBy: phpnut $
  26. * @lastmodified $Date: 2007-11-19 09:05:48 $
  27. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  28. */
  29. /**
  30. * Short description for class.
  31. *
  32. * Long description for class
  33. *
  34. * @package cake
  35. * @subpackage cake.cake.libs.model.dbo
  36. */
  37. class DboFirebird extends DboSource {
  38. /**
  39. * Enter description here...
  40. *
  41. * @var unknown_type
  42. */
  43. var $description = "Firebird/Interbase DBO Driver";
  44. /**
  45. * Saves the original table name
  46. *
  47. * @var unknown_type
  48. */
  49. var $modeltmp = array();
  50. /**
  51. * Enter description here...
  52. *
  53. * @var unknown_type
  54. */
  55. var $startQuote = "\'";
  56. /**
  57. * Enter description here...
  58. *
  59. * @var unknown_type
  60. */
  61. var $endQuote = "\'";
  62. /**
  63. * Enter description here...
  64. *
  65. * @var unknown_type
  66. */
  67. var $alias = ' ';
  68. /**
  69. * Enter description here...
  70. *
  71. * @var unknown_type
  72. */
  73. var $goofyLimit = true;
  74. /**
  75. * Creates a map between field aliases and numeric indexes.
  76. *
  77. * @var array
  78. */
  79. var $__fieldMappings = array();
  80. /**
  81. * Base configuration settings for Firebird driver
  82. *
  83. * @var array
  84. */
  85. var $_baseConfig = array(
  86. 'persistent' => true,
  87. 'host' => 'localhost',
  88. 'login' => 'SYSDBA',
  89. 'password' => 'masterkey',
  90. 'database' => 'c:\\CAKE.FDB',
  91. 'port' => '3050',
  92. 'connect' => 'ibase_connect'
  93. );
  94. /**
  95. * Firebird column definition
  96. *
  97. * @var array
  98. */
  99. var $columns = array(
  100. 'primary_key' => array('name' => 'integer IDENTITY (1, 1) NOT NULL'),
  101. 'string' => array('name' => 'varchar', 'limit' => '255'),
  102. 'text' => array('name' => 'BLOB SUB_TYPE 1 SEGMENT SIZE 100 CHARACTER SET NONE'),
  103. 'integer' => array('name' => 'integer'),
  104. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  105. 'datetime' => array('name' => 'timestamp', 'format' => 'd.m.Y H:i:s', 'formatter' => 'date'),
  106. 'timestamp' => array('name' => 'timestamp', 'format' => 'd.m.Y H:i:s', 'formatter' => 'date'),
  107. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  108. 'date' => array('name' => 'date', 'format' => 'd.m.Y', 'formatter' => 'date'),
  109. 'binary' => array('name' => 'blob'),
  110. 'boolean' => array('name' => 'smallint')
  111. );
  112. /**
  113. * Connects to the database using options in the given configuration array.
  114. *
  115. * @return boolean True if the database could be connected, else false
  116. */
  117. function connect() {
  118. $config = $this->config;
  119. $connect = $config['connect'];
  120. $this->connected = false;
  121. $this->connection = $connect($config['host'] . ':' . $config['database'], $config['login'], $config['password']);
  122. $this->connected = true;
  123. }
  124. /**
  125. * Disconnects from database.
  126. *
  127. * @return boolean True if the database could be disconnected, else false
  128. */
  129. function disconnect() {
  130. $this->connected = false;
  131. return @ibase_close($this->connection);
  132. }
  133. /**
  134. * Executes given SQL statement.
  135. *
  136. * @param string $sql SQL statement
  137. * @return resource Result resource identifier
  138. * @access protected
  139. */
  140. function _execute($sql) {
  141. if (strpos(strtolower($sql),"update") > 0) {
  142. break;
  143. }
  144. return @ibase_query($this->connection, $sql);
  145. }
  146. /**
  147. * Returns a row from given resultset as an array .
  148. *
  149. * @param boolean $assoc Associative array only, or both?
  150. * @return array The fetched row as an array
  151. */
  152. function fetchRow($assoc = false) {
  153. if (is_resource($this->_result)) {
  154. $this->resultSet($this->_result);
  155. $resultRow = $this->fetchResult();
  156. return $resultRow;
  157. } else {
  158. return null;
  159. }
  160. }
  161. /**
  162. * Returns an array of sources (tables) in the database.
  163. *
  164. * @return array Array of tablenames in the database
  165. */
  166. function listSources() {
  167. $cache = parent::listSources();
  168. if ($cache != null) {
  169. return $cache;
  170. }
  171. $sql = "select RDB" . "$" . "RELATION_NAME as name
  172. FROM RDB" ."$" . "RELATIONS
  173. Where RDB" . "$" . "SYSTEM_FLAG =0";
  174. $result = @ibase_query($this->connection,$sql);
  175. $tables=array();
  176. while ($row = ibase_fetch_row ($result)) {
  177. $tables[] = strtolower(trim($row[0]));
  178. }
  179. parent::listSources($tables);
  180. return $tables;
  181. }
  182. /**
  183. * Returns an array of the fields in given table name.
  184. *
  185. * @param Model $model Model object to describe
  186. * @return array Fields in table. Keys are name and type
  187. */
  188. function describe(&$model) {
  189. $this->modeltmp[$model->table] = $model->name;
  190. $cache = parent::describe($model);
  191. if ($cache != null) {
  192. return $cache;
  193. }
  194. $fields = false;
  195. $sql = "SELECT * FROM " . $this->fullTableName($model, false);
  196. $rs = ibase_query($sql);
  197. $coln = ibase_num_fields($rs);
  198. $fields = false;
  199. for ($i = 0; $i < $coln; $i++) {
  200. $col_info = ibase_field_info($rs, $i);
  201. $col_info['type'] = $this->column($col_info['type']);
  202. $fields[strtolower($col_info['name'])] = array(
  203. 'type' => $col_info['type'],
  204. 'null' => '',
  205. 'length' => $col_info['length']
  206. );
  207. }
  208. $this->__cacheDescription($this->fullTableName($model, false), $fields);
  209. return $fields;
  210. }
  211. /**
  212. * Returns a quoted name of $data for use in an SQL statement.
  213. *
  214. * @param string $data Name (table.field) to be prepared for use in an SQL statement
  215. * @return string Quoted for Firebird
  216. */
  217. function name($data) {
  218. if ($data == '*') {
  219. return '*';
  220. }
  221. $pos = strpos($data, '"');
  222. if ($pos === false) {
  223. if (!strpos($data, ".")) {
  224. $data = '"' . strtoupper($data) . '"';
  225. } else {
  226. $build = explode('.', $data);
  227. $data = '"' . strtoupper($build[0]) . '"."' . strtoupper($build[1]) . '"';
  228. }
  229. }
  230. return $data;
  231. }
  232. /**
  233. * Returns a quoted and escaped string of $data for use in an SQL statement.
  234. *
  235. * @param string $data String to be prepared for use in an SQL statement
  236. * @param string $column The column into which this data will be inserted
  237. * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
  238. * @return string Quoted and escaped data
  239. */
  240. function value($data, $column = null, $safe = false) {
  241. $parent = parent::value($data, $column, $safe);
  242. if ($parent != null) {
  243. return $parent;
  244. }
  245. if ($data === null) {
  246. return 'NULL';
  247. }
  248. if ($data === '') {
  249. return "''";
  250. }
  251. switch($column) {
  252. case 'boolean':
  253. $data = $this->boolean((bool)$data);
  254. break;
  255. default:
  256. if (get_magic_quotes_gpc()) {
  257. $data = stripslashes(r("'", "''", $data));
  258. } else {
  259. $data = r("'", "''", $data);
  260. }
  261. break;
  262. }
  263. return "'" . $data . "'";
  264. }
  265. /**
  266. * Removes Identity (primary key) column from update data before returning to parent
  267. *
  268. * @param Model $model
  269. * @param array $fields
  270. * @param array $values
  271. * @return array
  272. */
  273. function update(&$model, $fields = array(), $values = array()) {
  274. foreach ($fields as $i => $field) {
  275. if ($field == $model->primaryKey) {
  276. unset ($fields[$i]);
  277. unset ($values[$i]);
  278. break;
  279. }
  280. }
  281. return parent::update($model, $fields, $values);
  282. }
  283. /**
  284. * Returns a formatted error message from previous database operation.
  285. *
  286. * @return string Error message with error number
  287. */
  288. function lastError() {
  289. $error = ibase_errmsg();
  290. if ($error !== false) {
  291. return $error;
  292. }
  293. return null;
  294. }
  295. /**
  296. * Returns number of affected rows in previous database operation. If no previous operation exists,
  297. * this returns false.
  298. *
  299. * @return integer Number of affected rows
  300. */
  301. function lastAffected() {
  302. if ($this->_result) {
  303. return ibase_affected_rows($this->connection);
  304. }
  305. return null;
  306. }
  307. /**
  308. * Returns number of rows in previous resultset. If no previous resultset exists,
  309. * this returns false.
  310. *
  311. * @return integer Number of rows in resultset
  312. */
  313. function lastNumRows() {
  314. return $this->_result? /*ibase_affected_rows($this->_result)*/ 1: false;
  315. }
  316. /**
  317. * Returns the ID generated from the previous INSERT operation.
  318. *
  319. * @param unknown_type $source
  320. * @return in
  321. */
  322. function lastInsertId($source = null, $field = 'id') {
  323. $query = "SELECT RDB\$TRIGGER_SOURCE
  324. FROM RDB\$TRIGGERS WHERE RDB\$RELATION_NAME = '". strtoupper($source) . "' AND
  325. RDB\$SYSTEM_FLAG IS NULL AND RDB\$TRIGGER_TYPE = 1 ";
  326. $result = @ibase_query($this->connection,$query);
  327. $generator = "";
  328. while ($row = ibase_fetch_row($result, IBASE_TEXT)) {
  329. if (strpos($row[0], "NEW." . strtoupper($field))) {
  330. $pos = strpos($row[0], "GEN_ID(");
  331. if ($pos > 0) {
  332. $pos2 = strpos($row[0],",",$pos + 7);
  333. if ($pos2 > 0) {
  334. $generator = substr($row[0], $pos +7, $pos2 - $pos- 7);
  335. }
  336. }
  337. break;
  338. }
  339. }
  340. if (!empty($generator)) {
  341. $sql = "SELECT GEN_ID(". $generator . ",0) AS maxi FROM RDB" . "$" . "DATABASE";
  342. $res = $this->rawQuery($sql);
  343. $data = $this->fetchRow($res);
  344. return $data['maxi'];
  345. } else {
  346. return false;
  347. }
  348. }
  349. /**
  350. * Returns a limit statement in the correct format for the particular database.
  351. *
  352. * @param integer $limit Limit of results returned
  353. * @param integer $offset Offset from which to start results
  354. * @return string SQL limit/offset statement
  355. */
  356. function limit($limit, $offset = null) {
  357. if ($limit) {
  358. $rt = '';
  359. if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
  360. $rt = ' FIRST';
  361. }
  362. $rt .= ' ' . $limit;
  363. if (is_int($offset) && $offset > 0) {
  364. $rt .= ' SKIP ' . $offset;
  365. }
  366. return $rt;
  367. }
  368. return null;
  369. }
  370. /**
  371. * Converts database-layer column types to basic types
  372. *
  373. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  374. * @return string Abstract column type (i.e. "string")
  375. */
  376. function column($real) {
  377. if (is_array($real)) {
  378. $col = $real['name'];
  379. if (isset($real['limit'])) {
  380. $col .= '(' . $real['limit'] . ')';
  381. }
  382. return $col;
  383. }
  384. $col = r(')', '', $real);
  385. $limit = null;
  386. @list($col, $limit)=explode('(', $col);
  387. if (in_array($col, array('DATE', 'TIME'))) {
  388. return strtolower($col);
  389. }
  390. if ($col == 'TIMESTAMP') {
  391. return 'datetime';
  392. }
  393. if ($col == 'SMALLINT') {
  394. return 'boolean';
  395. }
  396. if (strpos($col, 'int') !== false || $col == 'numeric' || $col == 'INTEGER') {
  397. return 'integer';
  398. }
  399. if (strpos($col, 'char') !== false) {
  400. return 'string';
  401. }
  402. if (strpos($col, 'text') !== false) {
  403. return 'text';
  404. }
  405. if (strpos($col, 'VARCHAR') !== false) {
  406. return 'string';
  407. }
  408. if (strpos($col, 'BLOB') !== false) {
  409. return 'text';
  410. }
  411. if (in_array($col, array('FLOAT', 'NUMERIC', 'DECIMAL'))) {
  412. return 'float';
  413. }
  414. return 'text';
  415. }
  416. /**
  417. * Enter description here...
  418. *
  419. * @param unknown_type $results
  420. */
  421. function resultSet(&$results) {
  422. $this->results =& $results;
  423. $this->map = array();
  424. $num_fields = ibase_num_fields($results);
  425. $index = 0;
  426. $j = 0;
  427. while ($j < $num_fields) {
  428. $column = ibase_field_info($results, $j);
  429. if (!empty($column[2])) {
  430. $this->map[$index++] = array(ucfirst(strtolower($this->modeltmp[strtolower($column[2])])), strtolower($column[1]));
  431. } else {
  432. $this->map[$index++] = array(0, strtolower($column[1]));
  433. }
  434. $j++;
  435. }
  436. }
  437. /**
  438. * Builds final SQL statement
  439. *
  440. * @param array $data Query data
  441. * @return string
  442. */
  443. function renderStatement($data) {
  444. extract($data);
  445. if (preg_match('/offset\s+([0-9]+)/i', $limit, $offset)) {
  446. $limit = preg_replace('/\s*offset.*$/i', '', $limit);
  447. preg_match('/top\s+([0-9]+)/i', $limit, $limitVal);
  448. $offset = intval($offset[1]) + intval($limitVal[1]);
  449. $rOrder = $this->__switchSort($order);
  450. list($order2, $rOrder) = array($this->__mapFields($order), $this->__mapFields($rOrder));
  451. return "SELECT * FROM (SELECT {$limit} * FROM (SELECT TOP {$offset} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$order}) AS Set1 {$rOrder}) AS Set2 {$order2}";
  452. } else {
  453. return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$order}";
  454. }
  455. }
  456. /**
  457. * Fetches the next row from the current result set
  458. *
  459. * @return unknown
  460. */
  461. function fetchResult() {
  462. if ($row = ibase_fetch_row($this->results, IBASE_TEXT)) {
  463. $resultRow = array();
  464. $i = 0;
  465. foreach ($row as $index => $field) {
  466. list($table, $column) = $this->map[$index];
  467. if (trim($table) == "") {
  468. $resultRow[0][$column] = $row[$index];
  469. } else {
  470. $resultRow[$table][$column] = $row[$index];
  471. $i++;
  472. }
  473. }
  474. return $resultRow;
  475. } else {
  476. return false;
  477. }
  478. }
  479. /**
  480. * Inserts multiple values into a join table
  481. *
  482. * @param string $table
  483. * @param string $fields
  484. * @param array $values
  485. */
  486. function insertMulti($table, $fields, $values) {
  487. $count = count($values);
  488. for ($x = 0; $x < $count; $x++) {
  489. $this->query("INSERT INTO {$table} ({$fields}) VALUES {$values[$x]}");
  490. }
  491. }
  492. }
  493. ?>