CreateAddField.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin;
  4. use PhpMyAdmin\Html\Generator;
  5. use function count;
  6. use function implode;
  7. use function in_array;
  8. use function intval;
  9. use function json_decode;
  10. use function min;
  11. use function preg_replace;
  12. use function rtrim;
  13. use function strlen;
  14. use function trim;
  15. /**
  16. * Set of functions for /table/create and /table/add-field
  17. */
  18. class CreateAddField
  19. {
  20. /** @var DatabaseInterface */
  21. private $dbi;
  22. /**
  23. * @param DatabaseInterface $dbi DatabaseInterface interface
  24. */
  25. public function __construct(DatabaseInterface $dbi)
  26. {
  27. $this->dbi = $dbi;
  28. }
  29. /**
  30. * Transforms the radio button field_key into 4 arrays
  31. *
  32. * @return array An array of arrays which represents column keys for each index type
  33. * @psalm-return array{int, array, array, array, array, array}
  34. */
  35. private function getIndexedColumns(): array
  36. {
  37. $fieldCount = count($_POST['field_name']);
  38. $fieldPrimary = json_decode($_POST['primary_indexes'], true);
  39. $fieldIndex = json_decode($_POST['indexes'], true);
  40. $fieldUnique = json_decode($_POST['unique_indexes'], true);
  41. $fieldFullText = json_decode($_POST['fulltext_indexes'], true);
  42. $fieldSpatial = json_decode($_POST['spatial_indexes'], true);
  43. return [
  44. $fieldCount,
  45. $fieldPrimary,
  46. $fieldIndex,
  47. $fieldUnique,
  48. $fieldFullText,
  49. $fieldSpatial,
  50. ];
  51. }
  52. /**
  53. * Initiate the column creation statement according to the table creation or
  54. * add columns to a existing table
  55. *
  56. * @param int $fieldCount number of columns
  57. * @param bool $isCreateTable true if requirement is to get the statement
  58. * for table creation
  59. *
  60. * @return array An array of initial sql statements
  61. * according to the request
  62. */
  63. private function buildColumnCreationStatement(
  64. int $fieldCount,
  65. bool $isCreateTable = true
  66. ): array {
  67. $definitions = [];
  68. $previousField = -1;
  69. for ($i = 0; $i < $fieldCount; ++$i) {
  70. // '0' is also empty for php :-(
  71. if (strlen($_POST['field_name'][$i]) === 0) {
  72. continue;
  73. }
  74. $definition = $this->getStatementPrefix($isCreateTable) . Table::generateFieldSpec(
  75. rtrim($_POST['field_name'][$i]),
  76. $_POST['field_type'][$i],
  77. $_POST['field_length'][$i],
  78. $_POST['field_attribute'][$i],
  79. $_POST['field_collation'][$i] ?? '',
  80. $_POST['field_null'][$i] ?? 'NO',
  81. $_POST['field_default_type'][$i],
  82. $_POST['field_default_value'][$i],
  83. $_POST['field_extra'][$i] ?? false,
  84. $_POST['field_comments'][$i] ?? '',
  85. $_POST['field_virtuality'][$i] ?? '',
  86. $_POST['field_expression'][$i] ?? ''
  87. );
  88. $definition .= $this->setColumnCreationStatementSuffix($previousField, $isCreateTable);
  89. $previousField = $i;
  90. $definitions[] = $definition;
  91. }
  92. return $definitions;
  93. }
  94. /**
  95. * Set column creation suffix according to requested position of the new column
  96. *
  97. * @param int $previousField previous field for ALTER statement
  98. * @param bool $isCreateTable true if requirement is to get the statement
  99. * for table creation
  100. *
  101. * @return string suffix
  102. */
  103. private function setColumnCreationStatementSuffix(
  104. int $previousField,
  105. bool $isCreateTable = true
  106. ): string {
  107. // no suffix is needed if request is a table creation
  108. if ($isCreateTable) {
  109. return ' ';
  110. }
  111. if ((string) $_POST['field_where'] === 'last') {
  112. return ' ';
  113. }
  114. // Only the first field can be added somewhere other than at the end
  115. if ($previousField === -1) {
  116. if ((string) $_POST['field_where'] === 'first') {
  117. return ' FIRST';
  118. }
  119. if (! empty($_POST['after_field'])) {
  120. return ' AFTER '
  121. . Util::backquote($_POST['after_field']);
  122. }
  123. return ' ';
  124. }
  125. return ' AFTER ' . Util::backquote($_POST['field_name'][$previousField]);
  126. }
  127. /**
  128. * Create relevant index statements
  129. *
  130. * @param array $index an array of index columns
  131. * @param string $indexChoice index choice that which represents
  132. * the index type of $indexed_fields
  133. * @param bool $isCreateTable true if requirement is to get the statement
  134. * for table creation
  135. *
  136. * @return string sql statement for indexes
  137. */
  138. private function buildIndexStatement(
  139. array $index,
  140. string $indexChoice,
  141. bool $isCreateTable = true
  142. ): string {
  143. if ($index === []) {
  144. return '';
  145. }
  146. $sqlQuery = $this->getStatementPrefix($isCreateTable) . $indexChoice;
  147. if (! empty($index['Key_name']) && $index['Key_name'] !== 'PRIMARY') {
  148. $sqlQuery .= ' ' . Util::backquote($index['Key_name']);
  149. }
  150. $indexFields = [];
  151. foreach ($index['columns'] as $key => $column) {
  152. $indexFields[$key] = Util::backquote(rtrim($_POST['field_name'][$column['col_index']]));
  153. if (! $column['size']) {
  154. continue;
  155. }
  156. $indexFields[$key] .= '(' . $column['size'] . ')';
  157. }
  158. $sqlQuery .= ' (' . implode(', ', $indexFields) . ')';
  159. if ($index['Key_block_size']) {
  160. $sqlQuery .= ' KEY_BLOCK_SIZE = '
  161. . $this->dbi->escapeString($index['Key_block_size']);
  162. }
  163. // specifying index type is allowed only for primary, unique and index only
  164. if (
  165. $index['Index_choice'] !== 'SPATIAL'
  166. && $index['Index_choice'] !== 'FULLTEXT'
  167. && in_array($index['Index_type'], Index::getIndexTypes())
  168. ) {
  169. $sqlQuery .= ' USING ' . $index['Index_type'];
  170. }
  171. if ($index['Index_choice'] === 'FULLTEXT' && $index['Parser']) {
  172. $sqlQuery .= ' WITH PARSER ' . $this->dbi->escapeString($index['Parser']);
  173. }
  174. if ($index['Index_comment']) {
  175. $sqlQuery .= " COMMENT '" . $this->dbi->escapeString($index['Index_comment']) . "'";
  176. }
  177. return $sqlQuery;
  178. }
  179. /**
  180. * Statement prefix for the buildColumnCreationStatement()
  181. *
  182. * @param bool $isCreateTable true if requirement is to get the statement
  183. * for table creation
  184. *
  185. * @return string prefix
  186. */
  187. private function getStatementPrefix(bool $isCreateTable = true): string
  188. {
  189. return $isCreateTable ? '' : 'ADD ';
  190. }
  191. /**
  192. * Returns sql statement according to the column and index specifications as
  193. * requested
  194. *
  195. * @param bool $isCreateTable true if requirement is to get the statement
  196. * for table creation
  197. *
  198. * @return string sql statement
  199. */
  200. private function getColumnCreationStatements(bool $isCreateTable = true): string
  201. {
  202. $sqlStatement = '';
  203. [
  204. $fieldCount,
  205. $fieldPrimary,
  206. $fieldIndex,
  207. $fieldUnique,
  208. $fieldFullText,
  209. $fieldSpatial,
  210. ] = $this->getIndexedColumns();
  211. $definitions = $this->buildColumnCreationStatement($fieldCount, $isCreateTable);
  212. // Builds the PRIMARY KEY statements
  213. if (isset($fieldPrimary[0])) {
  214. $definitions[] = $this->buildIndexStatement($fieldPrimary[0], 'PRIMARY KEY', $isCreateTable);
  215. }
  216. // Builds the INDEX statements
  217. foreach ($fieldIndex as $index) {
  218. $definitions[] = $this->buildIndexStatement($index, 'INDEX', $isCreateTable);
  219. }
  220. // Builds the UNIQUE statements
  221. foreach ($fieldUnique as $index) {
  222. $definitions[] = $this->buildIndexStatement($index, 'UNIQUE', $isCreateTable);
  223. }
  224. // Builds the FULLTEXT statements
  225. foreach ($fieldFullText as $index) {
  226. $definitions[] = $this->buildIndexStatement($index, 'FULLTEXT', $isCreateTable);
  227. }
  228. // Builds the SPATIAL statements
  229. foreach ($fieldSpatial as $index) {
  230. $definitions[] = $this->buildIndexStatement($index, 'SPATIAL', $isCreateTable);
  231. }
  232. if ($definitions !== []) {
  233. $sqlStatement = implode(', ', $definitions);
  234. }
  235. return preg_replace('@, $@', '', $sqlStatement) ?? '';
  236. }
  237. /**
  238. * Returns the partitioning clause
  239. *
  240. * @return string partitioning clause
  241. */
  242. public function getPartitionsDefinition(): string
  243. {
  244. $sqlQuery = '';
  245. if (
  246. ! empty($_POST['partition_by'])
  247. && ! empty($_POST['partition_expr'])
  248. && ! empty($_POST['partition_count'])
  249. && $_POST['partition_count'] > 1
  250. ) {
  251. $sqlQuery .= ' PARTITION BY ' . $_POST['partition_by']
  252. . ' (' . $_POST['partition_expr'] . ')'
  253. . ' PARTITIONS ' . $_POST['partition_count'];
  254. }
  255. if (
  256. ! empty($_POST['subpartition_by'])
  257. && ! empty($_POST['subpartition_expr'])
  258. && ! empty($_POST['subpartition_count'])
  259. && $_POST['subpartition_count'] > 1
  260. ) {
  261. $sqlQuery .= ' SUBPARTITION BY ' . $_POST['subpartition_by']
  262. . ' (' . $_POST['subpartition_expr'] . ')'
  263. . ' SUBPARTITIONS ' . $_POST['subpartition_count'];
  264. }
  265. if (! empty($_POST['partitions'])) {
  266. $partitions = [];
  267. foreach ($_POST['partitions'] as $partition) {
  268. $partitions[] = $this->getPartitionDefinition($partition);
  269. }
  270. $sqlQuery .= ' (' . implode(', ', $partitions) . ')';
  271. }
  272. return $sqlQuery;
  273. }
  274. /**
  275. * Returns the definition of a partition/subpartition
  276. *
  277. * @param array $partition array of partition/subpartition details
  278. * @param bool $isSubPartition whether a subpartition
  279. *
  280. * @return string partition/subpartition definition
  281. */
  282. private function getPartitionDefinition(
  283. array $partition,
  284. bool $isSubPartition = false
  285. ): string {
  286. $sqlQuery = ' ' . ($isSubPartition ? 'SUB' : '') . 'PARTITION ';
  287. $sqlQuery .= $partition['name'];
  288. if (! empty($partition['value_type'])) {
  289. $sqlQuery .= ' VALUES ' . $partition['value_type'];
  290. if ($partition['value_type'] !== 'LESS THAN MAXVALUE') {
  291. $sqlQuery .= ' (' . $partition['value'] . ')';
  292. }
  293. }
  294. if (! empty($partition['engine'])) {
  295. $sqlQuery .= ' ENGINE = ' . $partition['engine'];
  296. }
  297. if (! empty($partition['comment'])) {
  298. $sqlQuery .= " COMMENT = '" . $partition['comment'] . "'";
  299. }
  300. if (! empty($partition['data_directory'])) {
  301. $sqlQuery .= " DATA DIRECTORY = '" . $partition['data_directory'] . "'";
  302. }
  303. if (! empty($partition['index_directory'])) {
  304. $sqlQuery .= " INDEX_DIRECTORY = '" . $partition['index_directory'] . "'";
  305. }
  306. if (! empty($partition['max_rows'])) {
  307. $sqlQuery .= ' MAX_ROWS = ' . $partition['max_rows'];
  308. }
  309. if (! empty($partition['min_rows'])) {
  310. $sqlQuery .= ' MIN_ROWS = ' . $partition['min_rows'];
  311. }
  312. if (! empty($partition['tablespace'])) {
  313. $sqlQuery .= ' TABLESPACE = ' . $partition['tablespace'];
  314. }
  315. if (! empty($partition['node_group'])) {
  316. $sqlQuery .= ' NODEGROUP = ' . $partition['node_group'];
  317. }
  318. if (! empty($partition['subpartitions'])) {
  319. $subpartitions = [];
  320. foreach ($partition['subpartitions'] as $subpartition) {
  321. $subpartitions[] = $this->getPartitionDefinition($subpartition, true);
  322. }
  323. $sqlQuery .= ' (' . implode(', ', $subpartitions) . ')';
  324. }
  325. return $sqlQuery;
  326. }
  327. /**
  328. * Function to get table creation sql query
  329. *
  330. * @param string $db database name
  331. * @param string $table table name
  332. */
  333. public function getTableCreationQuery(string $db, string $table): string
  334. {
  335. // get column addition statements
  336. $sqlStatement = $this->getColumnCreationStatements(true);
  337. // Builds the 'create table' statement
  338. $sqlQuery = 'CREATE TABLE ' . Util::backquote($db) . '.'
  339. . Util::backquote(trim($table)) . ' (' . $sqlStatement . ')';
  340. // Adds table type, character set, comments and partition definition
  341. if (
  342. ! empty($_POST['tbl_storage_engine'])
  343. && ($_POST['tbl_storage_engine'] !== 'Default')
  344. && StorageEngine::isValid($_POST['tbl_storage_engine'])
  345. ) {
  346. $sqlQuery .= ' ENGINE = ' . $_POST['tbl_storage_engine'];
  347. }
  348. if (! empty($_POST['tbl_collation'])) {
  349. $sqlQuery .= Util::getCharsetQueryPart($_POST['tbl_collation'] ?? '');
  350. }
  351. if (
  352. ! empty($_POST['connection'])
  353. && ! empty($_POST['tbl_storage_engine'])
  354. && $_POST['tbl_storage_engine'] === 'FEDERATED'
  355. ) {
  356. $sqlQuery .= " CONNECTION = '"
  357. . $this->dbi->escapeString($_POST['connection']) . "'";
  358. }
  359. if (! empty($_POST['comment'])) {
  360. $sqlQuery .= ' COMMENT = \''
  361. . $this->dbi->escapeString($_POST['comment']) . '\'';
  362. }
  363. $sqlQuery .= $this->getPartitionsDefinition();
  364. $sqlQuery .= ';';
  365. return $sqlQuery;
  366. }
  367. /**
  368. * Function to get the number of fields for the table creation form
  369. */
  370. public function getNumberOfFieldsFromRequest(): int
  371. {
  372. // Limit to 4096 fields (MySQL maximal value)
  373. $mysqlLimit = 4096;
  374. if (isset($_POST['submit_num_fields'])) { // adding new fields
  375. $numberOfFields = intval($_POST['orig_num_fields']) + intval($_POST['added_fields']);
  376. } elseif (isset($_POST['orig_num_fields'])) { // retaining existing fields
  377. $numberOfFields = intval($_POST['orig_num_fields']);
  378. } elseif (
  379. isset($_POST['num_fields'])
  380. && intval($_POST['num_fields']) > 0
  381. ) { // new table with specified number of fields
  382. $numberOfFields = intval($_POST['num_fields']);
  383. } else { // new table with unspecified number of fields
  384. $numberOfFields = 4;
  385. }
  386. return min($numberOfFields, $mysqlLimit);
  387. }
  388. /**
  389. * Function to get the column creation statement
  390. *
  391. * @param string $table current table
  392. */
  393. public function getColumnCreationQuery(
  394. string $table
  395. ): string {
  396. // get column addition statements
  397. $sqlStatement = $this->getColumnCreationStatements(false);
  398. $sqlQuery = 'ALTER TABLE ' .
  399. Util::backquote($table) . ' ' . $sqlStatement;
  400. if (isset($_POST['online_transaction'])) {
  401. $sqlQuery .= ', ALGORITHM=INPLACE, LOCK=NONE';
  402. }
  403. return $sqlQuery . ';';
  404. }
  405. /**
  406. * Function to execute the column creation statement
  407. *
  408. * @param string $db current database
  409. * @param string $sqlQuery the query to run
  410. * @param string $errorUrl error page url
  411. */
  412. public function tryColumnCreationQuery(
  413. string $db,
  414. string $sqlQuery,
  415. string $errorUrl
  416. ): bool {
  417. // To allow replication, we first select the db to use and then run queries
  418. // on this db.
  419. if (! $this->dbi->selectDb($db)) {
  420. Generator::mysqlDie(
  421. $this->dbi->getError(),
  422. 'USE ' . Util::backquote($db),
  423. false,
  424. $errorUrl
  425. );
  426. }
  427. return (bool) $this->dbi->tryQuery($sqlQuery);
  428. }
  429. }