Mysql.php 22 KB

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