MySqlSchemaManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. namespace Doctrine\DBAL\Schema;
  3. use Doctrine\DBAL\Platforms\MariaDb1027Platform;
  4. use Doctrine\DBAL\Platforms\MySqlPlatform;
  5. use Doctrine\DBAL\Types\Type;
  6. use function array_change_key_case;
  7. use function array_shift;
  8. use function array_values;
  9. use function assert;
  10. use function explode;
  11. use function is_string;
  12. use function preg_match;
  13. use function strpos;
  14. use function strtok;
  15. use function strtolower;
  16. use function strtr;
  17. use const CASE_LOWER;
  18. /**
  19. * Schema manager for the MySql RDBMS.
  20. */
  21. class MySqlSchemaManager extends AbstractSchemaManager
  22. {
  23. /**
  24. * @see https://mariadb.com/kb/en/library/string-literals/#escape-sequences
  25. */
  26. private const MARIADB_ESCAPE_SEQUENCES = [
  27. '\\0' => "\0",
  28. "\\'" => "'",
  29. '\\"' => '"',
  30. '\\b' => "\b",
  31. '\\n' => "\n",
  32. '\\r' => "\r",
  33. '\\t' => "\t",
  34. '\\Z' => "\x1a",
  35. '\\\\' => '\\',
  36. '\\%' => '%',
  37. '\\_' => '_',
  38. // Internally, MariaDB escapes single quotes using the standard syntax
  39. "''" => "'",
  40. ];
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected function _getPortableViewDefinition($view)
  45. {
  46. return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. protected function _getPortableTableDefinition($table)
  52. {
  53. return array_shift($table);
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. protected function _getPortableUserDefinition($user)
  59. {
  60. return [
  61. 'user' => $user['User'],
  62. 'password' => $user['Password'],
  63. ];
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
  69. {
  70. foreach ($tableIndexes as $k => $v) {
  71. $v = array_change_key_case($v, CASE_LOWER);
  72. if ($v['key_name'] === 'PRIMARY') {
  73. $v['primary'] = true;
  74. } else {
  75. $v['primary'] = false;
  76. }
  77. if (strpos($v['index_type'], 'FULLTEXT') !== false) {
  78. $v['flags'] = ['FULLTEXT'];
  79. } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
  80. $v['flags'] = ['SPATIAL'];
  81. }
  82. // Ignore prohibited prefix `length` for spatial index
  83. if (strpos($v['index_type'], 'SPATIAL') === false) {
  84. $v['length'] = isset($v['sub_part']) ? (int) $v['sub_part'] : null;
  85. }
  86. $tableIndexes[$k] = $v;
  87. }
  88. return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. protected function _getPortableDatabaseDefinition($database)
  94. {
  95. return $database['Database'];
  96. }
  97. /**
  98. * {@inheritdoc}
  99. */
  100. protected function _getPortableTableColumnDefinition($tableColumn)
  101. {
  102. $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
  103. $dbType = strtolower($tableColumn['type']);
  104. $dbType = strtok($dbType, '(), ');
  105. assert(is_string($dbType));
  106. $length = $tableColumn['length'] ?? strtok('(), ');
  107. $fixed = null;
  108. if (! isset($tableColumn['name'])) {
  109. $tableColumn['name'] = '';
  110. }
  111. $scale = null;
  112. $precision = null;
  113. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  114. // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
  115. if (isset($tableColumn['comment'])) {
  116. $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
  117. $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
  118. }
  119. switch ($dbType) {
  120. case 'char':
  121. case 'binary':
  122. $fixed = true;
  123. break;
  124. case 'float':
  125. case 'double':
  126. case 'real':
  127. case 'numeric':
  128. case 'decimal':
  129. if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
  130. $precision = $match[1];
  131. $scale = $match[2];
  132. $length = null;
  133. }
  134. break;
  135. case 'tinytext':
  136. $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
  137. break;
  138. case 'text':
  139. $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
  140. break;
  141. case 'mediumtext':
  142. $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
  143. break;
  144. case 'tinyblob':
  145. $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
  146. break;
  147. case 'blob':
  148. $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
  149. break;
  150. case 'mediumblob':
  151. $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
  152. break;
  153. case 'tinyint':
  154. case 'smallint':
  155. case 'mediumint':
  156. case 'int':
  157. case 'integer':
  158. case 'bigint':
  159. case 'year':
  160. $length = null;
  161. break;
  162. }
  163. if ($this->_platform instanceof MariaDb1027Platform) {
  164. $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
  165. } else {
  166. $columnDefault = $tableColumn['default'];
  167. }
  168. $options = [
  169. 'length' => $length !== null ? (int) $length : null,
  170. 'unsigned' => strpos($tableColumn['type'], 'unsigned') !== false,
  171. 'fixed' => (bool) $fixed,
  172. 'default' => $columnDefault,
  173. 'notnull' => $tableColumn['null'] !== 'YES',
  174. 'scale' => null,
  175. 'precision' => null,
  176. 'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
  177. 'comment' => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
  178. ? $tableColumn['comment']
  179. : null,
  180. ];
  181. if ($scale !== null && $precision !== null) {
  182. $options['scale'] = (int) $scale;
  183. $options['precision'] = (int) $precision;
  184. }
  185. $column = new Column($tableColumn['field'], Type::getType($type), $options);
  186. if (isset($tableColumn['characterset'])) {
  187. $column->setPlatformOption('charset', $tableColumn['characterset']);
  188. }
  189. if (isset($tableColumn['collation'])) {
  190. $column->setPlatformOption('collation', $tableColumn['collation']);
  191. }
  192. return $column;
  193. }
  194. /**
  195. * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
  196. *
  197. * - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
  198. * to distinguish them from expressions (see MDEV-10134).
  199. * - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
  200. * as current_timestamp(), currdate(), currtime()
  201. * - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
  202. * null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
  203. * - \' is always stored as '' in information_schema (normalized)
  204. *
  205. * @link https://mariadb.com/kb/en/library/information-schema-columns-table/
  206. * @link https://jira.mariadb.org/browse/MDEV-13132
  207. *
  208. * @param string|null $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
  209. */
  210. private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault): ?string
  211. {
  212. if ($columnDefault === 'NULL' || $columnDefault === null) {
  213. return null;
  214. }
  215. if (preg_match('/^\'(.*)\'$/', $columnDefault, $matches)) {
  216. return strtr($matches[1], self::MARIADB_ESCAPE_SEQUENCES);
  217. }
  218. switch ($columnDefault) {
  219. case 'current_timestamp()':
  220. return $platform->getCurrentTimestampSQL();
  221. case 'curdate()':
  222. return $platform->getCurrentDateSQL();
  223. case 'curtime()':
  224. return $platform->getCurrentTimeSQL();
  225. }
  226. return $columnDefault;
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. protected function _getPortableTableForeignKeysList($tableForeignKeys)
  232. {
  233. $list = [];
  234. foreach ($tableForeignKeys as $value) {
  235. $value = array_change_key_case($value, CASE_LOWER);
  236. if (! isset($list[$value['constraint_name']])) {
  237. if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') {
  238. $value['delete_rule'] = null;
  239. }
  240. if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') {
  241. $value['update_rule'] = null;
  242. }
  243. $list[$value['constraint_name']] = [
  244. 'name' => $value['constraint_name'],
  245. 'local' => [],
  246. 'foreign' => [],
  247. 'foreignTable' => $value['referenced_table_name'],
  248. 'onDelete' => $value['delete_rule'],
  249. 'onUpdate' => $value['update_rule'],
  250. ];
  251. }
  252. $list[$value['constraint_name']]['local'][] = $value['column_name'];
  253. $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
  254. }
  255. $result = [];
  256. foreach ($list as $constraint) {
  257. $result[] = new ForeignKeyConstraint(
  258. array_values($constraint['local']),
  259. $constraint['foreignTable'],
  260. array_values($constraint['foreign']),
  261. $constraint['name'],
  262. [
  263. 'onDelete' => $constraint['onDelete'],
  264. 'onUpdate' => $constraint['onUpdate'],
  265. ]
  266. );
  267. }
  268. return $result;
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function listTableDetails($name)
  274. {
  275. $table = parent::listTableDetails($name);
  276. $platform = $this->_platform;
  277. assert($platform instanceof MySqlPlatform);
  278. $sql = $platform->getListTableMetadataSQL($name);
  279. $tableOptions = $this->_conn->fetchAssociative($sql);
  280. if ($tableOptions === false) {
  281. return $table;
  282. }
  283. $table->addOption('engine', $tableOptions['ENGINE']);
  284. if ($tableOptions['TABLE_COLLATION'] !== null) {
  285. $table->addOption('collation', $tableOptions['TABLE_COLLATION']);
  286. }
  287. if ($tableOptions['AUTO_INCREMENT'] !== null) {
  288. $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
  289. }
  290. $table->addOption('comment', $tableOptions['TABLE_COMMENT']);
  291. $table->addOption('create_options', $this->parseCreateOptions($tableOptions['CREATE_OPTIONS']));
  292. return $table;
  293. }
  294. /**
  295. * @return string[]|true[]
  296. */
  297. private function parseCreateOptions(?string $string): array
  298. {
  299. $options = [];
  300. if ($string === null || $string === '') {
  301. return $options;
  302. }
  303. foreach (explode(' ', $string) as $pair) {
  304. $parts = explode('=', $pair, 2);
  305. $options[$parts[0]] = $parts[1] ?? true;
  306. }
  307. return $options;
  308. }
  309. }