PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

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

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