Mysql.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. <?php
  2. /**
  3. * MySQL layer for DBO
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Model.Datasource.Database
  15. * @since CakePHP(tm) v 0.10.5.1790
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('DboSource', 'Model/Datasource');
  19. /**
  20. * MySQL DBO driver object
  21. *
  22. * Provides connection and SQL generation for MySQL RDMS
  23. *
  24. * @package Cake.Model.Datasource.Database
  25. */
  26. class Mysql 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. 'flags' => array()
  46. );
  47. /**
  48. * Reference to the PDO object connection
  49. *
  50. * @var PDO
  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 bool
  69. */
  70. protected $_useAlias = true;
  71. /**
  72. * List of engine specific additional field parameters used on table creating
  73. *
  74. * @var array
  75. */
  76. public $fieldParameters = array(
  77. 'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'),
  78. 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'),
  79. 'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault'),
  80. 'unsigned' => array(
  81. 'value' => 'UNSIGNED', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault',
  82. 'noVal' => true,
  83. 'options' => array(true),
  84. 'types' => array('integer', 'float', 'decimal', 'biginteger')
  85. )
  86. );
  87. /**
  88. * List of table engine specific parameters used on table creating
  89. *
  90. * @var array
  91. */
  92. public $tableParameters = array(
  93. 'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'),
  94. 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'),
  95. 'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine')
  96. );
  97. /**
  98. * MySQL column definition
  99. *
  100. * @var array
  101. */
  102. public $columns = array(
  103. 'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
  104. 'string' => array('name' => 'varchar', 'limit' => '255'),
  105. 'text' => array('name' => 'text'),
  106. 'biginteger' => array('name' => 'bigint', 'limit' => '20'),
  107. 'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
  108. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  109. 'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
  110. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  111. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  112. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  113. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  114. 'binary' => array('name' => 'blob'),
  115. 'boolean' => array('name' => 'tinyint', 'limit' => '1')
  116. );
  117. /**
  118. * Mapping of collation names to character set names
  119. *
  120. * @var array
  121. */
  122. protected $_charsets = array();
  123. /**
  124. * Connects to the database using options in the given configuration array.
  125. *
  126. * MySQL supports a few additional options that other drivers do not:
  127. *
  128. * - `unix_socket` Set to the path of the MySQL sock file. Can be used in place
  129. * of host + port.
  130. * - `ssl_key` SSL key file for connecting via SSL. Must be combined with `ssl_cert`.
  131. * - `ssl_cert` The SSL certificate to use when connecting via SSL. Must be
  132. * combined with `ssl_key`.
  133. * - `ssl_ca` The certificate authority for SSL connections.
  134. *
  135. * @return bool True if the database could be connected, else false
  136. * @throws MissingConnectionException
  137. */
  138. public function connect() {
  139. $config = $this->config;
  140. $this->connected = false;
  141. $flags = $config['flags'] + array(
  142. PDO::ATTR_PERSISTENT => $config['persistent'],
  143. PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
  144. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  145. );
  146. if (!empty($config['encoding'])) {
  147. $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
  148. }
  149. if (!empty($config['ssl_key']) && !empty($config['ssl_cert'])) {
  150. $flags[PDO::MYSQL_ATTR_SSL_KEY] = $config['ssl_key'];
  151. $flags[PDO::MYSQL_ATTR_SSL_CERT] = $config['ssl_cert'];
  152. }
  153. if (!empty($config['ssl_ca'])) {
  154. $flags[PDO::MYSQL_ATTR_SSL_CA] = $config['ssl_ca'];
  155. }
  156. if (empty($config['unix_socket'])) {
  157. $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
  158. } else {
  159. $dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
  160. }
  161. try {
  162. $this->_connection = new PDO(
  163. $dsn,
  164. $config['login'],
  165. $config['password'],
  166. $flags
  167. );
  168. $this->connected = true;
  169. if (!empty($config['settings'])) {
  170. foreach ($config['settings'] as $key => $value) {
  171. $this->_execute("SET $key=$value");
  172. }
  173. }
  174. } catch (PDOException $e) {
  175. throw new MissingConnectionException(array(
  176. 'class' => get_class($this),
  177. 'message' => $e->getMessage()
  178. ));
  179. }
  180. $this->_charsets = array();
  181. $this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");
  182. return $this->connected;
  183. }
  184. /**
  185. * Check whether the MySQL extension is installed/loaded
  186. *
  187. * @return bool
  188. */
  189. public function enabled() {
  190. return in_array('mysql', PDO::getAvailableDrivers());
  191. }
  192. /**
  193. * Returns an array of sources (tables) in the database.
  194. *
  195. * @param mixed $data List of tables.
  196. * @return array Array of table names in the database
  197. */
  198. public function listSources($data = null) {
  199. $cache = parent::listSources();
  200. if ($cache) {
  201. return $cache;
  202. }
  203. $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']));
  204. if (!$result) {
  205. $result->closeCursor();
  206. return array();
  207. }
  208. $tables = array();
  209. while ($line = $result->fetch(PDO::FETCH_NUM)) {
  210. $tables[] = $line[0];
  211. }
  212. $result->closeCursor();
  213. parent::listSources($tables);
  214. return $tables;
  215. }
  216. /**
  217. * Builds a map of the columns contained in a result
  218. *
  219. * @param PDOStatement $results The results to format.
  220. * @return void
  221. */
  222. public function resultSet($results) {
  223. $this->map = array();
  224. $numFields = $results->columnCount();
  225. $index = 0;
  226. while ($numFields-- > 0) {
  227. $column = $results->getColumnMeta($index);
  228. if ($column['len'] === 1 && (empty($column['native_type']) || $column['native_type'] === 'TINY')) {
  229. $type = 'boolean';
  230. } else {
  231. $type = empty($column['native_type']) ? 'string' : $column['native_type'];
  232. }
  233. if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
  234. $this->map[$index++] = array($column['table'], $column['name'], $type);
  235. } else {
  236. $this->map[$index++] = array(0, $column['name'], $type);
  237. }
  238. }
  239. }
  240. /**
  241. * Fetches the next row from the current result set
  242. *
  243. * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
  244. */
  245. public function fetchResult() {
  246. if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
  247. $resultRow = array();
  248. foreach ($this->map as $col => $meta) {
  249. list($table, $column, $type) = $meta;
  250. $resultRow[$table][$column] = $row[$col];
  251. if ($type === 'boolean' && $row[$col] !== null) {
  252. $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
  253. }
  254. }
  255. return $resultRow;
  256. }
  257. $this->_result->closeCursor();
  258. return false;
  259. }
  260. /**
  261. * Gets the database encoding
  262. *
  263. * @return string The database encoding
  264. */
  265. public function getEncoding() {
  266. return $this->_execute('SHOW VARIABLES LIKE ?', array('character_set_client'))->fetchObject()->Value;
  267. }
  268. /**
  269. * Query charset by collation
  270. *
  271. * @param string $name Collation name
  272. * @return string Character set name
  273. */
  274. public function getCharsetName($name) {
  275. if ((bool)version_compare($this->getVersion(), "5", "<")) {
  276. return false;
  277. }
  278. if (isset($this->_charsets[$name])) {
  279. return $this->_charsets[$name];
  280. }
  281. $r = $this->_execute(
  282. 'SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?',
  283. array($name)
  284. );
  285. $cols = $r->fetch(PDO::FETCH_ASSOC);
  286. if (isset($cols['CHARACTER_SET_NAME'])) {
  287. $this->_charsets[$name] = $cols['CHARACTER_SET_NAME'];
  288. } else {
  289. $this->_charsets[$name] = false;
  290. }
  291. return $this->_charsets[$name];
  292. }
  293. /**
  294. * Returns an array of the fields in given table name.
  295. *
  296. * @param Model|string $model Name of database table to inspect or model instance
  297. * @return array Fields in table. Keys are name and type
  298. * @throws CakeException
  299. */
  300. public function describe($model) {
  301. $key = $this->fullTableName($model, false);
  302. $cache = parent::describe($key);
  303. if ($cache) {
  304. return $cache;
  305. }
  306. $table = $this->fullTableName($model);
  307. $fields = false;
  308. $cols = $this->_execute('SHOW FULL COLUMNS FROM ' . $table);
  309. if (!$cols) {
  310. throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table));
  311. }
  312. while ($column = $cols->fetch(PDO::FETCH_OBJ)) {
  313. $fields[$column->Field] = array(
  314. 'type' => $this->column($column->Type),
  315. 'null' => ($column->Null === 'YES' ? true : false),
  316. 'default' => $column->Default,
  317. 'length' => $this->length($column->Type)
  318. );
  319. if (in_array($fields[$column->Field]['type'], $this->fieldParameters['unsigned']['types'], true)) {
  320. $fields[$column->Field]['unsigned'] = $this->_unsigned($column->Type);
  321. }
  322. if (!empty($column->Key) && isset($this->index[$column->Key])) {
  323. $fields[$column->Field]['key'] = $this->index[$column->Key];
  324. }
  325. foreach ($this->fieldParameters as $name => $value) {
  326. if (!empty($column->{$value['column']})) {
  327. $fields[$column->Field][$name] = $column->{$value['column']};
  328. }
  329. }
  330. if (isset($fields[$column->Field]['collate'])) {
  331. $charset = $this->getCharsetName($fields[$column->Field]['collate']);
  332. if ($charset) {
  333. $fields[$column->Field]['charset'] = $charset;
  334. }
  335. }
  336. }
  337. $this->_cacheDescription($key, $fields);
  338. $cols->closeCursor();
  339. return $fields;
  340. }
  341. /**
  342. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  343. *
  344. * @param Model $model The model to update.
  345. * @param array $fields The fields to update.
  346. * @param array $values The values to set.
  347. * @param mixed $conditions The conditions to use.
  348. * @return array
  349. */
  350. public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
  351. if (!$this->_useAlias) {
  352. return parent::update($model, $fields, $values, $conditions);
  353. }
  354. if (!$values) {
  355. $combined = $fields;
  356. } else {
  357. $combined = array_combine($fields, $values);
  358. }
  359. $alias = $joins = false;
  360. $fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
  361. $fields = implode(', ', $fields);
  362. $table = $this->fullTableName($model);
  363. if (!empty($conditions)) {
  364. $alias = $this->name($model->alias);
  365. if ($model->name === $model->alias) {
  366. $joins = implode(' ', $this->_getJoins($model));
  367. }
  368. }
  369. $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
  370. if ($conditions === false) {
  371. return false;
  372. }
  373. if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) {
  374. $model->onError();
  375. return false;
  376. }
  377. return true;
  378. }
  379. /**
  380. * Generates and executes an SQL DELETE statement for given id/conditions on given model.
  381. *
  382. * @param Model $model The model to delete from.
  383. * @param mixed $conditions The conditions to use.
  384. * @return bool Success
  385. */
  386. public function delete(Model $model, $conditions = null) {
  387. if (!$this->_useAlias) {
  388. return parent::delete($model, $conditions);
  389. }
  390. $alias = $this->name($model->alias);
  391. $table = $this->fullTableName($model);
  392. $joins = implode(' ', $this->_getJoins($model));
  393. if (empty($conditions)) {
  394. $alias = $joins = false;
  395. }
  396. $complexConditions = false;
  397. foreach ((array)$conditions as $key => $value) {
  398. if (strpos($key, $model->alias) === false) {
  399. $complexConditions = true;
  400. break;
  401. }
  402. }
  403. if (!$complexConditions) {
  404. $joins = false;
  405. }
  406. $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
  407. if ($conditions === false) {
  408. return false;
  409. }
  410. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  411. $model->onError();
  412. return false;
  413. }
  414. return true;
  415. }
  416. /**
  417. * Sets the database encoding
  418. *
  419. * @param string $enc Database encoding
  420. * @return bool
  421. */
  422. public function setEncoding($enc) {
  423. return $this->_execute('SET NAMES ' . $enc) !== false;
  424. }
  425. /**
  426. * Returns an array of the indexes in given datasource name.
  427. *
  428. * @param string $model Name of model to inspect
  429. * @return array Fields in table. Keys are column and unique
  430. */
  431. public function index($model) {
  432. $index = array();
  433. $table = $this->fullTableName($model);
  434. $old = version_compare($this->getVersion(), '4.1', '<=');
  435. if ($table) {
  436. $indexes = $this->_execute('SHOW INDEX FROM ' . $table);
  437. // @codingStandardsIgnoreStart
  438. // MySQL columns don't match the cakephp conventions.
  439. while ($idx = $indexes->fetch(PDO::FETCH_OBJ)) {
  440. if ($old) {
  441. $idx = (object)current((array)$idx);
  442. }
  443. if (!isset($index[$idx->Key_name]['column'])) {
  444. $col = array();
  445. $index[$idx->Key_name]['column'] = $idx->Column_name;
  446. if ($idx->Index_type === 'FULLTEXT') {
  447. $index[$idx->Key_name]['type'] = strtolower($idx->Index_type);
  448. } else {
  449. $index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0);
  450. }
  451. } else {
  452. if (!empty($index[$idx->Key_name]['column']) && !is_array($index[$idx->Key_name]['column'])) {
  453. $col[] = $index[$idx->Key_name]['column'];
  454. }
  455. $col[] = $idx->Column_name;
  456. $index[$idx->Key_name]['column'] = $col;
  457. }
  458. if (!empty($idx->Sub_part)) {
  459. if (!isset($index[$idx->Key_name]['length'])) {
  460. $index[$idx->Key_name]['length'] = array();
  461. }
  462. $index[$idx->Key_name]['length'][$idx->Column_name] = $idx->Sub_part;
  463. }
  464. }
  465. // @codingStandardsIgnoreEnd
  466. $indexes->closeCursor();
  467. }
  468. return $index;
  469. }
  470. /**
  471. * Generate a MySQL Alter Table syntax for the given Schema comparison
  472. *
  473. * @param array $compare Result of a CakeSchema::compare()
  474. * @param string $table The table name.
  475. * @return array Array of alter statements to make.
  476. */
  477. public function alterSchema($compare, $table = null) {
  478. if (!is_array($compare)) {
  479. return false;
  480. }
  481. $out = '';
  482. $colList = array();
  483. foreach ($compare as $curTable => $types) {
  484. $indexes = $tableParameters = $colList = array();
  485. if (!$table || $table === $curTable) {
  486. $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
  487. foreach ($types as $type => $column) {
  488. if (isset($column['indexes'])) {
  489. $indexes[$type] = $column['indexes'];
  490. unset($column['indexes']);
  491. }
  492. if (isset($column['tableParameters'])) {
  493. $tableParameters[$type] = $column['tableParameters'];
  494. unset($column['tableParameters']);
  495. }
  496. switch ($type) {
  497. case 'add':
  498. foreach ($column as $field => $col) {
  499. $col['name'] = $field;
  500. $alter = 'ADD ' . $this->buildColumn($col);
  501. if (isset($col['after'])) {
  502. $alter .= ' AFTER ' . $this->name($col['after']);
  503. }
  504. $colList[] = $alter;
  505. }
  506. break;
  507. case 'drop':
  508. foreach ($column as $field => $col) {
  509. $col['name'] = $field;
  510. $colList[] = 'DROP ' . $this->name($field);
  511. }
  512. break;
  513. case 'change':
  514. foreach ($column as $field => $col) {
  515. if (!isset($col['name'])) {
  516. $col['name'] = $field;
  517. }
  518. $colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
  519. }
  520. break;
  521. }
  522. }
  523. $colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
  524. $colList = array_merge($colList, $this->_alterTableParameters($curTable, $tableParameters));
  525. $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
  526. }
  527. }
  528. return $out;
  529. }
  530. /**
  531. * Generate a "drop table" statement for the given table
  532. *
  533. * @param type $table Name of the table to drop
  534. * @return string Drop table SQL statement
  535. */
  536. protected function _dropTable($table) {
  537. return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
  538. }
  539. /**
  540. * Generate MySQL table parameter alteration statements for a table.
  541. *
  542. * @param string $table Table to alter parameters for.
  543. * @param array $parameters Parameters to add & drop.
  544. * @return array Array of table property alteration statements.
  545. */
  546. protected function _alterTableParameters($table, $parameters) {
  547. if (isset($parameters['change'])) {
  548. return $this->buildTableParameters($parameters['change']);
  549. }
  550. return array();
  551. }
  552. /**
  553. * Format indexes for create table
  554. *
  555. * @param array $indexes An array of indexes to generate SQL from
  556. * @param string $table Optional table name, not used
  557. * @return array An array of SQL statements for indexes
  558. * @see DboSource::buildIndex()
  559. */
  560. public function buildIndex($indexes, $table = null) {
  561. $join = array();
  562. foreach ($indexes as $name => $value) {
  563. $out = '';
  564. if ($name === 'PRIMARY') {
  565. $out .= 'PRIMARY ';
  566. $name = null;
  567. } else {
  568. if (!empty($value['unique'])) {
  569. $out .= 'UNIQUE ';
  570. }
  571. $name = $this->startQuote . $name . $this->endQuote;
  572. }
  573. if (isset($value['type']) && strtolower($value['type']) === 'fulltext') {
  574. $out .= 'FULLTEXT ';
  575. }
  576. $out .= 'KEY ' . $name . ' (';
  577. if (is_array($value['column'])) {
  578. if (isset($value['length'])) {
  579. $vals = array();
  580. foreach ($value['column'] as $column) {
  581. $name = $this->name($column);
  582. if (isset($value['length'])) {
  583. $name .= $this->_buildIndexSubPart($value['length'], $column);
  584. }
  585. $vals[] = $name;
  586. }
  587. $out .= implode(', ', $vals);
  588. } else {
  589. $out .= implode(', ', array_map(array(&$this, 'name'), $value['column']));
  590. }
  591. } else {
  592. $out .= $this->name($value['column']);
  593. if (isset($value['length'])) {
  594. $out .= $this->_buildIndexSubPart($value['length'], $value['column']);
  595. }
  596. }
  597. $out .= ')';
  598. $join[] = $out;
  599. }
  600. return $join;
  601. }
  602. /**
  603. * Generate MySQL index alteration statements for a table.
  604. *
  605. * @param string $table Table to alter indexes for
  606. * @param array $indexes Indexes to add and drop
  607. * @return array Index alteration statements
  608. */
  609. protected function _alterIndexes($table, $indexes) {
  610. $alter = array();
  611. if (isset($indexes['drop'])) {
  612. foreach ($indexes['drop'] as $name => $value) {
  613. $out = 'DROP ';
  614. if ($name === 'PRIMARY') {
  615. $out .= 'PRIMARY KEY';
  616. } else {
  617. $out .= 'KEY ' . $this->startQuote . $name . $this->endQuote;
  618. }
  619. $alter[] = $out;
  620. }
  621. }
  622. if (isset($indexes['add'])) {
  623. $add = $this->buildIndex($indexes['add']);
  624. foreach ($add as $index) {
  625. $alter[] = 'ADD ' . $index;
  626. }
  627. }
  628. return $alter;
  629. }
  630. /**
  631. * Format length for text indexes
  632. *
  633. * @param array $lengths An array of lengths for a single index
  634. * @param string $column The column for which to generate the index length
  635. * @return string Formatted length part of an index field
  636. */
  637. protected function _buildIndexSubPart($lengths, $column) {
  638. if ($lengths === null) {
  639. return '';
  640. }
  641. if (!isset($lengths[$column])) {
  642. return '';
  643. }
  644. return '(' . $lengths[$column] . ')';
  645. }
  646. /**
  647. * Returns an detailed array of sources (tables) in the database.
  648. *
  649. * @param string $name Table name to get parameters
  650. * @return array Array of table names in the database
  651. */
  652. public function listDetailedSources($name = null) {
  653. $condition = '';
  654. if (is_string($name)) {
  655. $condition = ' WHERE name = ' . $this->value($name);
  656. }
  657. $result = $this->_connection->query('SHOW TABLE STATUS ' . $condition, PDO::FETCH_ASSOC);
  658. if (!$result) {
  659. $result->closeCursor();
  660. return array();
  661. }
  662. $tables = array();
  663. foreach ($result as $row) {
  664. $tables[$row['Name']] = (array)$row;
  665. unset($tables[$row['Name']]['queryString']);
  666. if (!empty($row['Collation'])) {
  667. $charset = $this->getCharsetName($row['Collation']);
  668. if ($charset) {
  669. $tables[$row['Name']]['charset'] = $charset;
  670. }
  671. }
  672. }
  673. $result->closeCursor();
  674. if (is_string($name) && isset($tables[$name])) {
  675. return $tables[$name];
  676. }
  677. return $tables;
  678. }
  679. /**
  680. * Converts database-layer column types to basic types
  681. *
  682. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  683. * @return string Abstract column type (i.e. "string")
  684. */
  685. public function column($real) {
  686. if (is_array($real)) {
  687. $col = $real['name'];
  688. if (isset($real['limit'])) {
  689. $col .= '(' . $real['limit'] . ')';
  690. }
  691. return $col;
  692. }
  693. $col = str_replace(')', '', $real);
  694. $limit = $this->length($real);
  695. if (strpos($col, '(') !== false) {
  696. list($col, $vals) = explode('(', $col);
  697. }
  698. if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
  699. return $col;
  700. }
  701. if (($col === 'tinyint' && $limit === 1) || $col === 'boolean') {
  702. return 'boolean';
  703. }
  704. if (strpos($col, 'bigint') !== false || $col === 'bigint') {
  705. return 'biginteger';
  706. }
  707. if (strpos($col, 'int') !== false) {
  708. return 'integer';
  709. }
  710. if (strpos($col, 'char') !== false || $col === 'tinytext') {
  711. return 'string';
  712. }
  713. if (strpos($col, 'text') !== false) {
  714. return 'text';
  715. }
  716. if (strpos($col, 'blob') !== false || $col === 'binary') {
  717. return 'binary';
  718. }
  719. if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) {
  720. return 'float';
  721. }
  722. if (strpos($col, 'decimal') !== false || strpos($col, 'numeric') !== false) {
  723. return 'decimal';
  724. }
  725. if (strpos($col, 'enum') !== false) {
  726. return "enum($vals)";
  727. }
  728. return 'text';
  729. }
  730. /**
  731. * Gets the schema name
  732. *
  733. * @return string The schema name
  734. */
  735. public function getSchemaName() {
  736. return $this->config['database'];
  737. }
  738. /**
  739. * Check if the server support nested transactions
  740. *
  741. * @return bool
  742. */
  743. public function nestedTransactionSupported() {
  744. return $this->useNestedTransactions && version_compare($this->getVersion(), '4.1', '>=');
  745. }
  746. /**
  747. * Check if column type is unsigned
  748. *
  749. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  750. * @return bool True if column is unsigned, false otherwise
  751. */
  752. protected function _unsigned($real) {
  753. return strpos(strtolower($real), 'unsigned') !== false;
  754. }
  755. }