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

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

https://github.com/adivik2000/nigraha
PHP | 543 lines | 323 code | 24 blank | 196 comment | 83 complexity | 55405b6079c9a9366be51c7d54fe7e5a MD5 | raw file
  1. <?php
  2. /* SVN FILE: $Id: dbo_mysqli.php 5318 2007-06-20 09:01:21Z phpnut $ */
  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-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.datasources.dbo
  23. * @since CakePHP(tm) v 1.1.4.2974
  24. * @version $Revision: 5318 $
  25. * @modifiedby $LastChangedBy: phpnut $
  26. * @lastmodified $Date: 2007-06-20 04:01:21 -0500 (Wed, 20 Jun 2007) $
  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.datasources.dbo
  36. */
  37. class DboMysqli extends DboSource {
  38. /**
  39. * Enter description here...
  40. *
  41. * @var unknown_type
  42. */
  43. var $description = "Mysqli DBO Driver";
  44. /**
  45. * Enter description here...
  46. *
  47. * @var unknown_type
  48. */
  49. var $startQuote = "`";
  50. /**
  51. * Enter description here...
  52. *
  53. * @var unknown_type
  54. */
  55. var $endQuote = "`";
  56. /**
  57. * Base configuration settings for Mysqli driver
  58. *
  59. * @var array
  60. */
  61. var $_baseConfig = array('persistent' => true,
  62. 'host' => 'localhost',
  63. 'login' => 'root',
  64. 'password' => '',
  65. 'database' => 'cake',
  66. 'port' => '3306',
  67. 'connect' => 'mysqli_connect');
  68. /**
  69. * Mysqli column definition
  70. *
  71. * @var array
  72. */
  73. var $columns = array('primary_key' => array('name' => 'int(11) DEFAULT NULL auto_increment'),
  74. 'string' => array('name' => 'varchar', 'limit' => '255'),
  75. 'text' => array('name' => 'text'),
  76. 'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
  77. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  78. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  79. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  80. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  81. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  82. 'binary' => array('name' => 'blob'),
  83. 'boolean' => array('name' => 'tinyint', 'limit' => '1'));
  84. /**
  85. * Connects to the database using options in the given configuration array.
  86. *
  87. * @return boolean True if the database could be connected, else false
  88. */
  89. function connect() {
  90. $config = $this->config;
  91. $this->connected = false;
  92. $this->connection = mysqli_connect($config['host'], $config['login'], $config['password'], $config['database'], $config['port']);
  93. if ($this->connection !== false) {
  94. $this->connected = true;
  95. }
  96. if (!empty($config['encoding'])) {
  97. $this->setEncoding($config['encoding']);
  98. }
  99. return $this->connected;
  100. }
  101. /**
  102. * Disconnects from database.
  103. *
  104. * @return boolean True if the database could be disconnected, else false
  105. */
  106. function disconnect() {
  107. @mysqli_free_result($this->results);
  108. $this->connected = !@mysqli_close($this->connection);
  109. return !$this->connected;
  110. }
  111. /**
  112. * Executes given SQL statement.
  113. *
  114. * @param string $sql SQL statement
  115. * @return resource Result resource identifier
  116. * @access protected
  117. */
  118. function _execute($sql) {
  119. return mysqli_query($this->connection, $sql);
  120. }
  121. /**
  122. * Returns an array of sources (tables) in the database.
  123. *
  124. * @return array Array of tablenames in the database
  125. */
  126. function listSources() {
  127. $cache = parent::listSources();
  128. if ($cache != null) {
  129. return $cache;
  130. }
  131. $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
  132. if (!$result) {
  133. return array();
  134. } else {
  135. $tables = array();
  136. while ($line = mysqli_fetch_array($result)) {
  137. $tables[] = $line[0];
  138. }
  139. parent::listSources($tables);
  140. return $tables;
  141. }
  142. }
  143. /**
  144. * Returns an array of the fields in given table name.
  145. *
  146. * @param string $tableName Name of database table to inspect
  147. * @return array Fields in table. Keys are name and type
  148. */
  149. function describe(&$model) {
  150. $cache = parent::describe($model);
  151. if ($cache != null) {
  152. return $cache;
  153. }
  154. $fields = false;
  155. $cols = $this->query('DESCRIBE ' . $this->fullTableName($model));
  156. foreach ($cols as $column) {
  157. $colKey = array_keys($column);
  158. if (isset($column[$colKey[0]]) && !isset($column[0])) {
  159. $column[0] = $column[$colKey[0]];
  160. }
  161. if (isset($column[0])) {
  162. $fields[] = array(
  163. 'name' => $column[0]['Field'],
  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. }
  170. }
  171. $this->__cacheDescription($this->fullTableName($model, false), $fields);
  172. return $fields;
  173. }
  174. /**
  175. * Returns a quoted and escaped string of $data for use in an SQL statement.
  176. *
  177. * @param string $data String to be prepared for use in an SQL statement
  178. * @param string $column The column into which this data will be inserted
  179. * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
  180. * @return string Quoted and escaped data
  181. */
  182. function value($data, $column = null, $safe = false) {
  183. $parent = parent::value($data, $column, $safe);
  184. if ($parent != null) {
  185. return $parent;
  186. }
  187. if ($data === null) {
  188. return 'NULL';
  189. }
  190. if ($data === '') {
  191. return "''";
  192. }
  193. switch ($column) {
  194. case 'boolean':
  195. $data = $this->boolean((bool)$data);
  196. break;
  197. case 'integer' :
  198. case 'float' :
  199. case null :
  200. if (is_numeric($data)) {
  201. break;
  202. }
  203. default:
  204. $data = "'" . mysqli_real_escape_string($this->connection, $data) . "'";
  205. break;
  206. }
  207. return $data;
  208. }
  209. /**
  210. * Begin a transaction
  211. *
  212. * @param unknown_type $model
  213. * @return boolean True on success, false on fail
  214. * (i.e. if the database/model does not support transactions).
  215. */
  216. function begin(&$model) {
  217. if (parent::begin($model)) {
  218. if ($this->execute('START TRANSACTION')) {
  219. $this->_transactionStarted = true;
  220. return true;
  221. }
  222. }
  223. return false;
  224. }
  225. /**
  226. * Commit a transaction
  227. *
  228. * @param unknown_type $model
  229. * @return boolean True on success, false on fail
  230. * (i.e. if the database/model does not support transactions,
  231. * or a transaction has not started).
  232. */
  233. function commit(&$model) {
  234. if (parent::commit($model)) {
  235. $this->_transactionStarted = false;
  236. return $this->execute('COMMIT');
  237. }
  238. return false;
  239. }
  240. /**
  241. * Rollback a transaction
  242. *
  243. * @param unknown_type $model
  244. * @return boolean True on success, false on fail
  245. * (i.e. if the database/model does not support transactions,
  246. * or a transaction has not started).
  247. */
  248. function rollback(&$model) {
  249. if (parent::rollback($model)) {
  250. return $this->execute('ROLLBACK');
  251. }
  252. return false;
  253. }
  254. /**
  255. * Returns a formatted error message from previous database operation.
  256. *
  257. * @return string Error message with error number
  258. */
  259. function lastError() {
  260. if (mysqli_errno($this->connection)) {
  261. return mysqli_errno($this->connection).': '.mysqli_error($this->connection);
  262. }
  263. return null;
  264. }
  265. /**
  266. * Returns number of affected rows in previous database operation. If no previous operation exists,
  267. * this returns false.
  268. *
  269. * @return int Number of affected rows
  270. */
  271. function lastAffected() {
  272. if ($this->_result) {
  273. return mysqli_affected_rows($this->connection);
  274. }
  275. return null;
  276. }
  277. /**
  278. * Returns number of rows in previous resultset. If no previous resultset exists,
  279. * this returns false.
  280. *
  281. * @return int Number of rows in resultset
  282. */
  283. function lastNumRows() {
  284. if ($this->_result and is_object($this->_result)) {
  285. return @mysqli_num_rows($this->_result);
  286. }
  287. return null;
  288. }
  289. /**
  290. * Returns the ID generated from the previous INSERT operation.
  291. *
  292. * @param unknown_type $source
  293. * @return in
  294. */
  295. function lastInsertId($source = null) {
  296. $id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
  297. if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
  298. return $id[0]['insertID'];
  299. }
  300. return null;
  301. }
  302. /**
  303. * Converts database-layer column types to basic types
  304. *
  305. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  306. * @return string Abstract column type (i.e. "string")
  307. */
  308. function column($real) {
  309. if (is_array($real)) {
  310. $col = $real['name'];
  311. if (isset($real['limit'])) {
  312. $col .= '('.$real['limit'].')';
  313. }
  314. return $col;
  315. }
  316. $col = r(')', '', $real);
  317. $limit = $this->length($real);
  318. @list($col,$vals) = explode('(', $col);
  319. if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
  320. return $col;
  321. }
  322. if ($col == 'tinyint' && $limit == 1) {
  323. return 'boolean';
  324. }
  325. if (strpos($col, 'int') !== false) {
  326. return 'integer';
  327. }
  328. if (strpos($col, 'char') !== false || $col == 'tinytext') {
  329. return 'string';
  330. }
  331. if (strpos($col, 'text') !== false) {
  332. return 'text';
  333. }
  334. if (strpos($col, 'blob') !== false) {
  335. return 'binary';
  336. }
  337. if (in_array($col, array('float', 'double', 'decimal'))) {
  338. return 'float';
  339. }
  340. if (strpos($col, 'enum') !== false) {
  341. return "enum($vals)";
  342. }
  343. if ($col == 'boolean') {
  344. return $col;
  345. }
  346. return 'text';
  347. }
  348. /**
  349. * Gets the length of a database-native column description, or null if no length
  350. *
  351. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  352. * @return int An integer representing the length of the column
  353. */
  354. function length($real) {
  355. $col = r(array(')', 'unsigned'), '', $real);
  356. $limit = null;
  357. if (strpos($col, '(') !== false) {
  358. list($col, $limit) = explode('(', $col);
  359. }
  360. if ($limit != null) {
  361. return intval($limit);
  362. }
  363. return null;
  364. }
  365. /**
  366. * Enter description here...
  367. *
  368. * @param unknown_type $results
  369. */
  370. function resultSet(&$results) {
  371. $this->results =& $results;
  372. $this->map = array();
  373. $num_fields = mysqli_num_fields($results);
  374. $index = 0;
  375. $j = 0;
  376. while ($j < $num_fields) {
  377. $column = mysqli_fetch_field_direct($results, $j);
  378. if (!empty($column->table)) {
  379. $this->map[$index++] = array($column->table, $column->name);
  380. } else {
  381. $this->map[$index++] = array(0, $column->name);
  382. }
  383. $j++;
  384. }
  385. }
  386. /**
  387. * Fetches the next row from the current result set
  388. *
  389. * @return unknown
  390. */
  391. function fetchResult() {
  392. if ($row = mysqli_fetch_row($this->results)) {
  393. $resultRow = array();
  394. $i = 0;
  395. foreach ($row as $index => $field) {
  396. @list($table, $column) = $this->map[$index];
  397. $resultRow[$table][$column] = $row[$index];
  398. $i++;
  399. }
  400. return $resultRow;
  401. } else {
  402. return false;
  403. }
  404. }
  405. /**
  406. * Sets the database encoding
  407. *
  408. * @param string $enc Database encoding
  409. * @return void
  410. */
  411. function setEncoding($enc) {
  412. return $this->_execute('SET NAMES ' . $enc) != false;
  413. }
  414. /**
  415. * Gets the database encoding
  416. *
  417. * @return string The database encoding
  418. */
  419. function getEncoding() {
  420. return mysqli_client_encoding($this->connection);
  421. }
  422. /**
  423. * Generate a MySQL schema for the given Schema object
  424. *
  425. * @param object $schema An instance of a subclass of CakeSchema
  426. * @param string $table Optional. If specified only the table name given will be generated.
  427. * Otherwise, all tables defined in the schema are generated.
  428. * @return string
  429. */
  430. function generateSchema($schema, $table = null) {
  431. if (!is_a($schema, 'CakeSchema')) {
  432. trigger_error(__('Invalid schema object', true), E_USER_WARNING);
  433. return null;
  434. }
  435. $out = '';
  436. foreach ($schema->tables as $curTable => $columns) {
  437. if (empty($table) || $table == $curTable) {
  438. $out .= 'CREATE TABLE ' . $this->fullTableName($curTable) . " (\n";
  439. $colList = array();
  440. $primary = null;
  441. foreach ($columns as $col) {
  442. if (isset($col['key']) && $col['key'] == 'primary') {
  443. $primary = $col;
  444. }
  445. $colList[] = $this->generateColumnSchema($col);
  446. }
  447. if (empty($primary)) {
  448. $primary = array('id', 'integer', 'key' => 'primary');
  449. array_unshift($colList, $this->generateColumnSchema($primary));
  450. }
  451. $colList[] = 'PRIMARY KEY (' . $this->name($primary[0]) . ')';
  452. $out .= "\t" . join(",\n\t", $colList) . "\n);\n\n";
  453. }
  454. }
  455. return $out;
  456. }
  457. /**
  458. * Generate a MySQL-native column schema string
  459. *
  460. * @param array $column An array structured like the following: array('name', 'type'[, options]),
  461. * where options can be 'default', 'length', or 'key'.
  462. * @return string
  463. */
  464. function generateColumnSchema($column) {
  465. $name = $type = null;
  466. $column = am(array('null' => true), $column);
  467. list($name, $type) = $column;
  468. if (empty($name) || empty($type)) {
  469. trigger_error('Column name or type not defined in schema', E_USER_WARNING);
  470. return null;
  471. }
  472. if (!isset($this->columns[$type])) {
  473. trigger_error("Column type {$type} does not exist", E_USER_WARNING);
  474. return null;
  475. }
  476. $real = $this->columns[$type];
  477. $out = $this->name($name) . ' ' . $real['name'];
  478. if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
  479. if (isset($column['length'])) {
  480. $length = $column['length'];
  481. } elseif (isset($column['limit'])) {
  482. $length = $column['limit'];
  483. } elseif (isset($real['length'])) {
  484. $length = $real['length'];
  485. } else {
  486. $length = $real['limit'];
  487. }
  488. $out .= '(' . $length . ')';
  489. }
  490. if (isset($column['key']) && $column['key'] == 'primary') {
  491. $out .= ' NOT NULL AUTO_INCREMENT';
  492. } elseif (isset($column['default'])) {
  493. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  494. } elseif (isset($column['null']) && $column['null'] == true) {
  495. $out .= ' DEFAULT NULL';
  496. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
  497. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  498. } elseif (isset($column['null']) && $column['null'] == false) {
  499. $out .= ' NOT NULL';
  500. }
  501. return $out;
  502. }
  503. /**
  504. * Enter description here...
  505. *
  506. * @param unknown_type $schema
  507. * @return unknown
  508. */
  509. function buildSchemaQuery($schema) {
  510. $search = array('{AUTOINCREMENT}', '{PRIMARY}', '{UNSIGNED}', '{FULLTEXT}',
  511. '{FULLTEXT_MYSQL}', '{BOOLEAN}', '{UTF_8}');
  512. $replace = array('int(11) not null auto_increment', 'primary key', 'unsigned',
  513. 'FULLTEXT', 'FULLTEXT', 'enum (\'true\', \'false\') NOT NULL default \'true\'',
  514. '/*!40100 CHARACTER SET utf8 COLLATE utf8_unicode_ci */');
  515. $query = trim(r($search, $replace, $schema));
  516. return $query;
  517. }
  518. }
  519. ?>