PageRenderTime 39ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/hardsshah/bookmarks
PHP | 427 lines | 256 code | 23 blank | 148 comment | 84 complexity | f05f3c4bbac61a860e4cecbe664be8de MD5 | raw file
  1. <?php
  2. /* SVN FILE: $Id$ */
  3. /**
  4. * MySQLi 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-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
  12. *
  13. * Licensed under The MIT License
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @filesource
  17. * @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
  18. * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
  19. * @package cake
  20. * @subpackage cake.cake.libs.model.datasources.dbo
  21. * @since CakePHP(tm) v 1.1.4.2974
  22. * @version $Revision$
  23. * @modifiedby $LastChangedBy$
  24. * @lastmodified $Date$
  25. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  26. */
  27. App::import('Core', 'DboMysql');
  28. /**
  29. * MySQLi DBO driver object
  30. *
  31. * Provides connection and SQL generation for MySQL RDMS using PHP's MySQLi Interface
  32. *
  33. * @package cake
  34. * @subpackage cake.cake.libs.model.datasources.dbo
  35. */
  36. class DboMysqli extends DboMysqlBase {
  37. /**
  38. * Enter description here...
  39. *
  40. * @var unknown_type
  41. */
  42. var $description = "Mysqli DBO Driver";
  43. /**
  44. * Base configuration settings for Mysqli driver
  45. *
  46. * @var array
  47. */
  48. var $_baseConfig = array(
  49. 'persistent' => true,
  50. 'host' => 'localhost',
  51. 'login' => 'root',
  52. 'password' => '',
  53. 'database' => 'cake',
  54. 'port' => '3306',
  55. 'connect' => 'mysqli_connect'
  56. );
  57. /**
  58. * Connects to the database using options in the given configuration array.
  59. *
  60. * @return boolean True if the database could be connected, else false
  61. */
  62. function connect() {
  63. $config = $this->config;
  64. $this->connected = false;
  65. if (is_numeric($config['port'])) {
  66. $config['socket'] = null;
  67. } else {
  68. $config['socket'] = $config['port'];
  69. $config['port'] = null;
  70. }
  71. $this->connection = mysqli_connect($config['host'], $config['login'], $config['password'], $config['database'], $config['port'], $config['socket']);
  72. if ($this->connection !== false) {
  73. $this->connected = true;
  74. }
  75. $this->_useAlias = (bool)version_compare(mysqli_get_server_info($this->connection), "4.1", ">=");
  76. if (!empty($config['encoding'])) {
  77. $this->setEncoding($config['encoding']);
  78. }
  79. return $this->connected;
  80. }
  81. /**
  82. * Disconnects from database.
  83. *
  84. * @return boolean True if the database could be disconnected, else false
  85. */
  86. function disconnect() {
  87. if (isset($this->results) && is_resource($this->results)) {
  88. mysqli_free_result($this->results);
  89. }
  90. $this->connected = !@mysqli_close($this->connection);
  91. return !$this->connected;
  92. }
  93. /**
  94. * Executes given SQL statement.
  95. *
  96. * @param string $sql SQL statement
  97. * @return resource Result resource identifier
  98. * @access protected
  99. */
  100. function _execute($sql) {
  101. if (preg_match('/^\s*call/i', $sql)) {
  102. return $this->_executeProcedure($sql);
  103. } else {
  104. return mysqli_query($this->connection, $sql);
  105. }
  106. }
  107. /**
  108. * Executes given SQL statement (procedure call).
  109. *
  110. * @param string $sql SQL statement (procedure call)
  111. * @return resource Result resource identifier for first recordset
  112. * @access protected
  113. */
  114. function _executeProcedure($sql) {
  115. $answer = mysqli_multi_query($this->connection, $sql);
  116. $firstResult = mysqli_store_result($this->connection);
  117. if (mysqli_more_results($this->connection)) {
  118. while ($lastResult = mysqli_next_result($this->connection));
  119. }
  120. return $firstResult;
  121. }
  122. /**
  123. * Returns an array of sources (tables) in the database.
  124. *
  125. * @return array Array of tablenames in the database
  126. */
  127. function listSources() {
  128. $cache = parent::listSources();
  129. if ($cache != null) {
  130. return $cache;
  131. }
  132. $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
  133. if (!$result) {
  134. return array();
  135. } else {
  136. $tables = array();
  137. while ($line = mysqli_fetch_array($result)) {
  138. $tables[] = $line[0];
  139. }
  140. parent::listSources($tables);
  141. return $tables;
  142. }
  143. }
  144. /**
  145. * Returns an array of the fields in given table name.
  146. *
  147. * @param string $tableName Name of database table to inspect
  148. * @return array Fields in table. Keys are name and type
  149. */
  150. function describe(&$model) {
  151. $cache = parent::describe($model);
  152. if ($cache != null) {
  153. return $cache;
  154. }
  155. $fields = false;
  156. $cols = $this->query('DESCRIBE ' . $this->fullTableName($model));
  157. foreach ($cols as $column) {
  158. $colKey = array_keys($column);
  159. if (isset($column[$colKey[0]]) && !isset($column[0])) {
  160. $column[0] = $column[$colKey[0]];
  161. }
  162. if (isset($column[0])) {
  163. $fields[$column[0]['Field']] = array(
  164. 'type' => $this->column($column[0]['Type']),
  165. 'null' => ($column[0]['Null'] == 'YES' ? true : false),
  166. 'default' => $column[0]['Default'],
  167. 'length' => $this->length($column[0]['Type'])
  168. );
  169. if (!empty($column[0]['Key']) && isset($this->index[$column[0]['Key']])) {
  170. $fields[$column[0]['Field']]['key'] = $this->index[$column[0]['Key']];
  171. }
  172. }
  173. }
  174. $this->__cacheDescription($this->fullTableName($model, false), $fields);
  175. return $fields;
  176. }
  177. /**
  178. * Returns a quoted and escaped string of $data for use in an SQL statement.
  179. *
  180. * @param string $data String to be prepared for use in an SQL statement
  181. * @param string $column The column into which this data will be inserted
  182. * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
  183. * @return string Quoted and escaped data
  184. */
  185. function value($data, $column = null, $safe = false) {
  186. $parent = parent::value($data, $column, $safe);
  187. if ($parent != null) {
  188. return $parent;
  189. }
  190. if ($data === null) {
  191. return 'NULL';
  192. }
  193. if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
  194. return "''";
  195. }
  196. switch ($column) {
  197. case 'boolean':
  198. $data = $this->boolean((bool)$data);
  199. break;
  200. case 'integer' :
  201. case 'float' :
  202. case null :
  203. if ($data === '') {
  204. return 'NULL';
  205. }
  206. if ((is_int($data) || is_float($data) || $data === '0') || (
  207. is_numeric($data) && strpos($data, ',') === false &&
  208. $data[0] != '0' && strpos($data, 'e') === false)) {
  209. return $data;
  210. }
  211. default:
  212. $data = "'" . mysqli_real_escape_string($this->connection, $data) . "'";
  213. break;
  214. }
  215. return $data;
  216. }
  217. /**
  218. * Begin a transaction
  219. *
  220. * @param unknown_type $model
  221. * @return boolean True on success, false on fail
  222. * (i.e. if the database/model does not support transactions).
  223. */
  224. function begin(&$model) {
  225. if (parent::begin($model) && $this->execute('START TRANSACTION')) {
  226. $this->_transactionStarted = true;
  227. return true;
  228. }
  229. return false;
  230. }
  231. /**
  232. * Returns a formatted error message from previous database operation.
  233. *
  234. * @return string Error message with error number
  235. */
  236. function lastError() {
  237. if (mysqli_errno($this->connection)) {
  238. return mysqli_errno($this->connection).': '.mysqli_error($this->connection);
  239. }
  240. return null;
  241. }
  242. /**
  243. * Returns number of affected rows in previous database operation. If no previous operation exists,
  244. * this returns false.
  245. *
  246. * @return integer Number of affected rows
  247. */
  248. function lastAffected() {
  249. if ($this->_result) {
  250. return mysqli_affected_rows($this->connection);
  251. }
  252. return null;
  253. }
  254. /**
  255. * Returns number of rows in previous resultset. If no previous resultset exists,
  256. * this returns false.
  257. *
  258. * @return integer Number of rows in resultset
  259. */
  260. function lastNumRows() {
  261. if ($this->hasResult()) {
  262. return mysqli_num_rows($this->_result);
  263. }
  264. return null;
  265. }
  266. /**
  267. * Returns the ID generated from the previous INSERT operation.
  268. *
  269. * @param unknown_type $source
  270. * @return in
  271. */
  272. function lastInsertId($source = null) {
  273. $id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
  274. if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
  275. return $id[0]['insertID'];
  276. }
  277. return null;
  278. }
  279. /**
  280. * Converts database-layer column types to basic types
  281. *
  282. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  283. * @return string Abstract column type (i.e. "string")
  284. */
  285. function column($real) {
  286. if (is_array($real)) {
  287. $col = $real['name'];
  288. if (isset($real['limit'])) {
  289. $col .= '('.$real['limit'].')';
  290. }
  291. return $col;
  292. }
  293. $col = str_replace(')', '', $real);
  294. $limit = $this->length($real);
  295. if (strpos($col, '(') !== false) {
  296. list($col, $vals) = explode('(', $col);
  297. }
  298. if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
  299. return $col;
  300. }
  301. if (($col == 'tinyint' && $limit == 1) || $col == 'boolean') {
  302. return 'boolean';
  303. }
  304. if (strpos($col, 'int') !== false) {
  305. return 'integer';
  306. }
  307. if (strpos($col, 'char') !== false || $col == 'tinytext') {
  308. return 'string';
  309. }
  310. if (strpos($col, 'text') !== false) {
  311. return 'text';
  312. }
  313. if (strpos($col, 'blob') !== false || $col == 'binary') {
  314. return 'binary';
  315. }
  316. if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
  317. return 'float';
  318. }
  319. if (strpos($col, 'enum') !== false) {
  320. return "enum($vals)";
  321. }
  322. return 'text';
  323. }
  324. /**
  325. * Gets the length of a database-native column description, or null if no length
  326. *
  327. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  328. * @return integer An integer representing the length of the column
  329. */
  330. function length($real) {
  331. $col = str_replace(array(')', 'unsigned'), '', $real);
  332. $limit = null;
  333. if (strpos($col, '(') !== false) {
  334. list($col, $limit) = explode('(', $col);
  335. }
  336. if ($limit != null) {
  337. return intval($limit);
  338. }
  339. return null;
  340. }
  341. /**
  342. * Enter description here...
  343. *
  344. * @param unknown_type $results
  345. */
  346. function resultSet(&$results) {
  347. if (isset($this->results) && is_resource($this->results) && $this->results != $results) {
  348. mysqli_free_result($this->results);
  349. }
  350. $this->results =& $results;
  351. $this->map = array();
  352. $numFields = mysqli_num_fields($results);
  353. $index = 0;
  354. $j = 0;
  355. while ($j < $numFields) {
  356. $column = mysqli_fetch_field_direct($results, $j);
  357. if (!empty($column->table)) {
  358. $this->map[$index++] = array($column->table, $column->name);
  359. } else {
  360. $this->map[$index++] = array(0, $column->name);
  361. }
  362. $j++;
  363. }
  364. }
  365. /**
  366. * Fetches the next row from the current result set
  367. *
  368. * @return unknown
  369. */
  370. function fetchResult() {
  371. if ($row = mysqli_fetch_row($this->results)) {
  372. $resultRow = array();
  373. $i = 0;
  374. foreach ($row as $index => $field) {
  375. $table = $column = null;
  376. if (count($this->map[$index]) == 2) {
  377. list($table, $column) = $this->map[$index];
  378. }
  379. $resultRow[$table][$column] = $row[$index];
  380. $i++;
  381. }
  382. return $resultRow;
  383. } else {
  384. return false;
  385. }
  386. }
  387. /**
  388. * Gets the database encoding
  389. *
  390. * @return string The database encoding
  391. */
  392. function getEncoding() {
  393. return mysqli_client_encoding($this->connection);
  394. }
  395. /**
  396. * Checks if the result is valid
  397. *
  398. * @return boolean True if the result is valid, else false
  399. */
  400. function hasResult() {
  401. return is_object($this->_result);
  402. }
  403. }
  404. ?>