PageRenderTime 180ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/public/sspdir/app/cake/libs/model/datasources/dbo/dbo_mysql.php

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