Mysql.php 22 KB

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