PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/Datasource/Database/Mysql.php

https://github.com/Bancha/cakephp
PHP | 677 lines | 435 code | 49 blank | 193 comment | 98 complexity | 019931615776e94685d05df31835cd5d MD5 | raw file
  1. <?php
  2. /**
  3. * MySQL layer for DBO
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.libs.model.datasources.dbo
  16. * @since CakePHP(tm) v 0.10.5.1790
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('DboSource', 'Model/Datasource');
  20. /**
  21. * MySQL DBO driver object
  22. *
  23. * Provides connection and SQL generation for MySQL RDMS
  24. *
  25. * @package cake.libs.model.datasources.dbo
  26. */
  27. class Mysql extends DboSource {
  28. /**
  29. * Datasource description
  30. *
  31. * @var string
  32. */
  33. public $description = "MySQL DBO Driver";
  34. /**
  35. * Base configuration settings for MySQL driver
  36. *
  37. * @var array
  38. */
  39. protected $_baseConfig = array(
  40. 'persistent' => true,
  41. 'host' => 'localhost',
  42. 'login' => 'root',
  43. 'password' => '',
  44. 'database' => 'cake',
  45. 'port' => '3306'
  46. );
  47. /**
  48. * Reference to the PDO object connection
  49. *
  50. * @var PDO $_connection
  51. */
  52. protected $_connection = null;
  53. /**
  54. * Start quote
  55. *
  56. * @var string
  57. */
  58. public $startQuote = "`";
  59. /**
  60. * End quote
  61. *
  62. * @var string
  63. */
  64. public $endQuote = "`";
  65. /**
  66. * use alias for update and delete. Set to true if version >= 4.1
  67. *
  68. * @var boolean
  69. * @access protected
  70. */
  71. protected $_useAlias = true;
  72. /**
  73. * Index of basic SQL commands
  74. *
  75. * @var array
  76. * @access protected
  77. */
  78. protected $_commands = array(
  79. 'begin' => 'START TRANSACTION',
  80. 'commit' => 'COMMIT',
  81. 'rollback' => 'ROLLBACK'
  82. );
  83. /**
  84. * List of engine specific additional field parameters used on table creating
  85. *
  86. * @var array
  87. * @access public
  88. */
  89. public $fieldParameters = array(
  90. 'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'),
  91. 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'),
  92. 'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault')
  93. );
  94. /**
  95. * List of table engine specific parameters used on table creating
  96. *
  97. * @var array
  98. * @access public
  99. */
  100. public $tableParameters = array(
  101. 'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'),
  102. 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'),
  103. 'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine')
  104. );
  105. /**
  106. * MySQL column definition
  107. *
  108. * @var array
  109. */
  110. public $columns = array(
  111. 'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
  112. 'string' => array('name' => 'varchar', 'limit' => '255'),
  113. 'text' => array('name' => 'text'),
  114. 'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
  115. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  116. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  117. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  118. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  119. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  120. 'binary' => array('name' => 'blob'),
  121. 'boolean' => array('name' => 'tinyint', 'limit' => '1')
  122. );
  123. /**
  124. * Connects to the database using options in the given configuration array.
  125. *
  126. * @return boolean True if the database could be connected, else false
  127. */
  128. function connect() {
  129. $config = $this->config;
  130. $this->connected = false;
  131. try {
  132. $flags = array(
  133. PDO::ATTR_PERSISTENT => $config['persistent'],
  134. PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
  135. );
  136. if (!empty($config['encoding'])) {
  137. $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
  138. }
  139. $this->_connection = new PDO(
  140. "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
  141. $config['login'],
  142. $config['password'],
  143. $flags
  144. );
  145. $this->connected = true;
  146. } catch (PDOException $e) {
  147. throw new MissingConnectionException(array('class' => $e->getMessage()));
  148. }
  149. $this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");
  150. return $this->connected;
  151. }
  152. /**
  153. * Check whether the MySQL extension is installed/loaded
  154. *
  155. * @return boolean
  156. */
  157. function enabled() {
  158. return in_array('mysql', PDO::getAvailableDrivers());
  159. }
  160. /**
  161. * Returns an array of sources (tables) in the database.
  162. *
  163. * @return array Array of tablenames in the database
  164. */
  165. function listSources($data = null) {
  166. $cache = parent::listSources();
  167. if ($cache != null) {
  168. return $cache;
  169. }
  170. $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']));
  171. if (!$result) {
  172. $result->closeCursor();
  173. return array();
  174. } else {
  175. $tables = array();
  176. while ($line = $result->fetch()) {
  177. $tables[] = $line[0];
  178. }
  179. $result->closeCursor();
  180. parent::listSources($tables);
  181. return $tables;
  182. }
  183. }
  184. /**
  185. * Builds a map of the columns contained in a result
  186. *
  187. * @param PDOStatement $results
  188. */
  189. function resultSet($results) {
  190. $this->map = array();
  191. $numFields = $results->columnCount();
  192. $index = 0;
  193. while ($numFields-- > 0) {
  194. $column = $results->getColumnMeta($index);
  195. if (empty($column['native_type'])) {
  196. $type = ($column['len'] == 1) ? 'boolean' : 'string';
  197. } else {
  198. $type = $column['native_type'];
  199. }
  200. if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
  201. $this->map[$index++] = array($column['table'], $column['name'], $type);
  202. } else {
  203. $this->map[$index++] = array(0, $column['name'], $type);
  204. }
  205. }
  206. }
  207. /**
  208. * Fetches the next row from the current result set
  209. *
  210. * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
  211. */
  212. function fetchResult() {
  213. if ($row = $this->_result->fetch()) {
  214. $resultRow = array();
  215. foreach ($this->map as $col => $meta) {
  216. list($table, $column, $type) = $meta;
  217. $resultRow[$table][$column] = $row[$col];
  218. if ($type === 'boolean' && !is_null($row[$col])) {
  219. $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
  220. }
  221. }
  222. return $resultRow;
  223. }
  224. $this->_result->closeCursor();
  225. return false;
  226. }
  227. /**
  228. * Gets the database encoding
  229. *
  230. * @return string The database encoding
  231. */
  232. public function getEncoding() {
  233. return $this->_execute('SHOW VARIABLES LIKE ?', array('character_set_client'))->fetchObject()->Value;
  234. }
  235. /**
  236. * Gets the version string of the database server
  237. *
  238. * @return string The database encoding
  239. */
  240. public function getVersion() {
  241. return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  242. }
  243. /**
  244. * Query charset by collation
  245. *
  246. * @param string $name Collation name
  247. * @return string Character set name
  248. */
  249. public function getCharsetName($name) {
  250. if ((bool)version_compare($this->getVersion(), "5", ">=")) {
  251. $r = $this->_execute('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?', array($name));
  252. $cols = $r->fetch();
  253. if (isset($cols['CHARACTER_SET_NAME'])) {
  254. return $cols['CHARACTER_SET_NAME'];
  255. }
  256. }
  257. return false;
  258. }
  259. /**
  260. * Returns an array of the fields in given table name.
  261. *
  262. * @param mixed $tableName Name of database table to inspect or model instance
  263. * @return array Fields in table. Keys are name and type
  264. */
  265. function describe($model) {
  266. $cache = parent::describe($model);
  267. if ($cache != null) {
  268. return $cache;
  269. }
  270. $fields = false;
  271. $cols = $this->_execute('SHOW FULL COLUMNS FROM ' . $this->fullTableName($model));
  272. if (!$cols) {
  273. throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $model->name));
  274. }
  275. foreach ($cols as $column) {
  276. $fields[$column->Field] = array(
  277. 'type' => $this->column($column->Type),
  278. 'null' => ($column->Null === 'YES' ? true : false),
  279. 'default' => $column->Default,
  280. 'length' => $this->length($column->Type),
  281. );
  282. if (!empty($column->Key) && isset($this->index[$column->Key])) {
  283. $fields[$column->Field]['key'] = $this->index[$column->Key];
  284. }
  285. foreach ($this->fieldParameters as $name => $value) {
  286. if (!empty($column->{$value['column']})) {
  287. $fields[$column->Field][$name] = $column->{$value['column']};
  288. }
  289. }
  290. if (isset($fields[$column->Field]['collate'])) {
  291. $charset = $this->getCharsetName($fields[$column->Field]['collate']);
  292. if ($charset) {
  293. $fields[$column->Field]['charset'] = $charset;
  294. }
  295. }
  296. }
  297. $this->__cacheDescription($this->fullTableName($model, false), $fields);
  298. $cols->closeCursor();
  299. return $fields;
  300. }
  301. /**
  302. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  303. *
  304. * @param Model $model
  305. * @param array $fields
  306. * @param array $values
  307. * @param mixed $conditions
  308. * @return array
  309. */
  310. function update($model, $fields = array(), $values = null, $conditions = null) {
  311. if (!$this->_useAlias) {
  312. return parent::update($model, $fields, $values, $conditions);
  313. }
  314. if ($values == null) {
  315. $combined = $fields;
  316. } else {
  317. $combined = array_combine($fields, $values);
  318. }
  319. $alias = $joins = false;
  320. $fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
  321. $fields = implode(', ', $fields);
  322. $table = $this->fullTableName($model);
  323. if (!empty($conditions)) {
  324. $alias = $this->name($model->alias);
  325. if ($model->name == $model->alias) {
  326. $joins = implode(' ', $this->_getJoins($model));
  327. }
  328. }
  329. $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
  330. if ($conditions === false) {
  331. return false;
  332. }
  333. if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) {
  334. $model->onError();
  335. return false;
  336. }
  337. return true;
  338. }
  339. /**
  340. * Generates and executes an SQL DELETE statement for given id/conditions on given model.
  341. *
  342. * @param Model $model
  343. * @param mixed $conditions
  344. * @return boolean Success
  345. */
  346. function delete($model, $conditions = null) {
  347. if (!$this->_useAlias) {
  348. return parent::delete($model, $conditions);
  349. }
  350. $alias = $this->name($model->alias);
  351. $table = $this->fullTableName($model);
  352. $joins = implode(' ', $this->_getJoins($model));
  353. if (empty($conditions)) {
  354. $alias = $joins = false;
  355. }
  356. $complexConditions = false;
  357. foreach ((array)$conditions as $key => $value) {
  358. if (strpos($key, $model->alias) === false) {
  359. $complexConditions = true;
  360. break;
  361. }
  362. }
  363. if (!$complexConditions) {
  364. $joins = false;
  365. }
  366. $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
  367. if ($conditions === false) {
  368. return false;
  369. }
  370. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  371. $model->onError();
  372. return false;
  373. }
  374. return true;
  375. }
  376. /**
  377. * Sets the database encoding
  378. *
  379. * @param string $enc Database encoding
  380. */
  381. function setEncoding($enc) {
  382. return $this->_execute('SET NAMES ' . $enc) !== false;
  383. }
  384. /**
  385. * Returns an array of the indexes in given datasource name.
  386. *
  387. * @param string $model Name of model to inspect
  388. * @return array Fields in table. Keys are column and unique
  389. */
  390. function index($model) {
  391. $index = array();
  392. $table = $this->fullTableName($model);
  393. $old = version_compare($this->getVersion(), '4.1', '<=');
  394. if ($table) {
  395. $indices = $this->_execute('SHOW INDEX FROM ' . $table);
  396. while ($idx = $indices->fetch()) {
  397. if ($old) {
  398. $idx = (object) current((array)$idx);
  399. }
  400. if (!isset($index[$idx->Key_name]['column'])) {
  401. $col = array();
  402. $index[$idx->Key_name]['column'] = $idx->Column_name;
  403. $index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0);
  404. } else {
  405. if (!empty($index[$idx->Key_name]['column']) && !is_array($index[$idx->Key_name]['column'])) {
  406. $col[] = $index[$idx->Key_name]['column'];
  407. }
  408. $col[] = $idx->Column_name;
  409. $index[$idx->Key_name]['column'] = $col;
  410. }
  411. }
  412. $indices->closeCursor();
  413. }
  414. return $index;
  415. }
  416. /**
  417. * Generate a MySQL Alter Table syntax for the given Schema comparison
  418. *
  419. * @param array $compare Result of a CakeSchema::compare()
  420. * @return array Array of alter statements to make.
  421. */
  422. function alterSchema($compare, $table = null) {
  423. if (!is_array($compare)) {
  424. return false;
  425. }
  426. $out = '';
  427. $colList = array();
  428. foreach ($compare as $curTable => $types) {
  429. $indexes = $tableParameters = $colList = array();
  430. if (!$table || $table == $curTable) {
  431. $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
  432. foreach ($types as $type => $column) {
  433. if (isset($column['indexes'])) {
  434. $indexes[$type] = $column['indexes'];
  435. unset($column['indexes']);
  436. }
  437. if (isset($column['tableParameters'])) {
  438. $tableParameters[$type] = $column['tableParameters'];
  439. unset($column['tableParameters']);
  440. }
  441. switch ($type) {
  442. case 'add':
  443. foreach ($column as $field => $col) {
  444. $col['name'] = $field;
  445. $alter = 'ADD ' . $this->buildColumn($col);
  446. if (isset($col['after'])) {
  447. $alter .= ' AFTER ' . $this->name($col['after']);
  448. }
  449. $colList[] = $alter;
  450. }
  451. break;
  452. case 'drop':
  453. foreach ($column as $field => $col) {
  454. $col['name'] = $field;
  455. $colList[] = 'DROP ' . $this->name($field);
  456. }
  457. break;
  458. case 'change':
  459. foreach ($column as $field => $col) {
  460. if (!isset($col['name'])) {
  461. $col['name'] = $field;
  462. }
  463. $colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
  464. }
  465. break;
  466. }
  467. }
  468. $colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
  469. $colList = array_merge($colList, $this->_alterTableParameters($curTable, $tableParameters));
  470. $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
  471. }
  472. }
  473. return $out;
  474. }
  475. /**
  476. * Generate a MySQL "drop table" statement for the given Schema object
  477. *
  478. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  479. * @param string $table Optional. If specified only the table name given will be generated.
  480. * Otherwise, all tables defined in the schema are generated.
  481. * @return string
  482. */
  483. function dropSchema(CakeSchema $schema, $table = null) {
  484. $out = '';
  485. foreach ($schema->tables as $curTable => $columns) {
  486. if (!$table || $table === $curTable) {
  487. $out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
  488. }
  489. }
  490. return $out;
  491. }
  492. /**
  493. * Generate MySQL table parameter alteration statementes for a table.
  494. *
  495. * @param string $table Table to alter parameters for.
  496. * @param array $parameters Parameters to add & drop.
  497. * @return array Array of table property alteration statementes.
  498. * @todo Implement this method.
  499. */
  500. function _alterTableParameters($table, $parameters) {
  501. if (isset($parameters['change'])) {
  502. return $this->buildTableParameters($parameters['change']);
  503. }
  504. return array();
  505. }
  506. /**
  507. * Generate MySQL index alteration statements for a table.
  508. *
  509. * @param string $table Table to alter indexes for
  510. * @param array $new Indexes to add and drop
  511. * @return array Index alteration statements
  512. */
  513. function _alterIndexes($table, $indexes) {
  514. $alter = array();
  515. if (isset($indexes['drop'])) {
  516. foreach($indexes['drop'] as $name => $value) {
  517. $out = 'DROP ';
  518. if ($name == 'PRIMARY') {
  519. $out .= 'PRIMARY KEY';
  520. } else {
  521. $out .= 'KEY ' . $name;
  522. }
  523. $alter[] = $out;
  524. }
  525. }
  526. if (isset($indexes['add'])) {
  527. foreach ($indexes['add'] as $name => $value) {
  528. $out = 'ADD ';
  529. if ($name == 'PRIMARY') {
  530. $out .= 'PRIMARY ';
  531. $name = null;
  532. } else {
  533. if (!empty($value['unique'])) {
  534. $out .= 'UNIQUE ';
  535. }
  536. }
  537. if (is_array($value['column'])) {
  538. $out .= 'KEY '. $name .' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  539. } else {
  540. $out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')';
  541. }
  542. $alter[] = $out;
  543. }
  544. }
  545. return $alter;
  546. }
  547. /**
  548. * Returns an detailed array of sources (tables) in the database.
  549. *
  550. * @param string $name Table name to get parameters
  551. * @return array Array of tablenames in the database
  552. */
  553. function listDetailedSources($name = null) {
  554. $condition = '';
  555. $params = array();
  556. if (is_string($name)) {
  557. $condition = ' WHERE name = ?' ;
  558. $params = array($name);
  559. }
  560. $result = $this->_execute('SHOW TABLE STATUS ' . $condition, $params);
  561. if (!$result) {
  562. $result->closeCursor();
  563. return array();
  564. } else {
  565. $tables = array();
  566. while ($row = $result->fetch()) {
  567. $tables[$row->Name] = (array) $row;
  568. unset($tables[$row->Name]['queryString']);
  569. if (!empty($row->Collation)) {
  570. $charset = $this->getCharsetName($row->Collation);
  571. if ($charset) {
  572. $tables[$row->Name]['charset'] = $charset;
  573. }
  574. }
  575. }
  576. $result->closeCursor();
  577. if (is_string($name) && isset($tables[$name])) {
  578. return $tables[$name];
  579. }
  580. return $tables;
  581. }
  582. }
  583. /**
  584. * Converts database-layer column types to basic types
  585. *
  586. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  587. * @return string Abstract column type (i.e. "string")
  588. */
  589. function column($real) {
  590. if (is_array($real)) {
  591. $col = $real['name'];
  592. if (isset($real['limit'])) {
  593. $col .= '(' . $real['limit'] . ')';
  594. }
  595. return $col;
  596. }
  597. $col = str_replace(')', '', $real);
  598. $limit = $this->length($real);
  599. if (strpos($col, '(') !== false) {
  600. list($col, $vals) = explode('(', $col);
  601. }
  602. if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
  603. return $col;
  604. }
  605. if (($col === 'tinyint' && $limit == 1) || $col === 'boolean') {
  606. return 'boolean';
  607. }
  608. if (strpos($col, 'int') !== false) {
  609. return 'integer';
  610. }
  611. if (strpos($col, 'char') !== false || $col === 'tinytext') {
  612. return 'string';
  613. }
  614. if (strpos($col, 'text') !== false) {
  615. return 'text';
  616. }
  617. if (strpos($col, 'blob') !== false || $col === 'binary') {
  618. return 'binary';
  619. }
  620. if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
  621. return 'float';
  622. }
  623. if (strpos($col, 'enum') !== false) {
  624. return "enum($vals)";
  625. }
  626. return 'text';
  627. }
  628. }