PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

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

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