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

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

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