-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
StructureController.php
1621 lines (1499 loc) · 58.9 KB
/
StructureController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Holds the PhpMyAdmin\Controllers\Table\StructureController
*
* @package PhpMyAdmin\Controllers
*/
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Table;
use PhpMyAdmin\CentralColumns;
use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\Core;
use PhpMyAdmin\CreateAddField;
use PhpMyAdmin\Index;
use PhpMyAdmin\Message;
use PhpMyAdmin\ParseAnalyze;
use PhpMyAdmin\Partition;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Sql;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statements\CreateStatement;
use PhpMyAdmin\Table;
use PhpMyAdmin\Tracker;
use PhpMyAdmin\Transformations;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
/**
* Handles table structure logic
*
* @package PhpMyAdmin\Controllers
*/
class StructureController extends AbstractController
{
/**
* @var Table The table object
*/
protected $table_obj;
/**
* @var string The URL query string
*/
protected $_url_query;
/**
* @var bool DB is information_schema
*/
protected $_db_is_system_schema;
/**
* @var bool Table is a view
*/
protected $_tbl_is_view;
/**
* @var string Table storage engine
*/
protected $_tbl_storage_engine;
/**
* @var int Number of rows
*/
protected $_table_info_num_rows;
/**
* @var string Table collation
*/
protected $_tbl_collation;
/**
* @var array Show table info
*/
protected $_showtable;
/**
* @var CreateAddField
*/
private $createAddField;
/**
* @var Relation
*/
private $relation;
/**
* @var Transformations
*/
private $transformations;
/**
* StructureController constructor
*
* @param \PhpMyAdmin\Response $response Response object
* @param \PhpMyAdmin\DatabaseInterface $dbi DatabaseInterface object
* @param string $db Database name
* @param string $table Table name
* @param bool $db_is_system_schema DB is information_schema
* @param bool $tbl_is_view Table is a view
* @param string $tbl_storage_engine Table storage engine
* @param int $table_info_num_rows Number of rows
* @param string $tbl_collation Table collation
* @param array $showtable Show table info
*/
public function __construct(
$response,
$dbi,
$db,
$table,
$db_is_system_schema,
$tbl_is_view,
$tbl_storage_engine,
$table_info_num_rows,
$tbl_collation,
$showtable
) {
parent::__construct($response, $dbi, $db, $table);
$this->_db_is_system_schema = $db_is_system_schema;
$this->_url_query = Url::getCommonRaw(['db' => $db, 'table' => $table]);
$this->_tbl_is_view = $tbl_is_view;
$this->_tbl_storage_engine = $tbl_storage_engine;
$this->_table_info_num_rows = $table_info_num_rows;
$this->_tbl_collation = $tbl_collation;
$this->_showtable = $showtable;
$this->table_obj = $this->dbi->getTable($this->db, $this->table);
$this->createAddField = new CreateAddField($dbi);
$this->relation = new Relation($dbi);
$this->transformations = new Transformations();
}
/**
* Index action
*
* @return void
*/
public function indexAction()
{
PageSettings::showGroup('TableStructure');
$checkUserPrivileges = new CheckUserPrivileges($this->dbi);
$checkUserPrivileges->getPrivileges();
$this->response->getHeader()->getScripts()->addFiles(
[
'tbl_structure.js',
'indexes.js',
]
);
/**
* Handle column moving
*/
if (isset($_POST['move_columns'])
&& is_array($_POST['move_columns'])
&& $this->response->isAjax()
) {
$this->moveColumns();
return;
}
/**
* handle MySQL reserved words columns check
*/
if (isset($_POST['reserved_word_check'])) {
if ($GLOBALS['cfg']['ReservedWordDisableWarning'] === false) {
$columns_names = $_POST['field_name'];
$reserved_keywords_names = [];
foreach ($columns_names as $column) {
if (Context::isKeyword(trim($column), true)) {
$reserved_keywords_names[] = trim($column);
}
}
if (Context::isKeyword(trim($this->table), true)) {
$reserved_keywords_names[] = trim($this->table);
}
if (count($reserved_keywords_names) == 0) {
$this->response->setRequestStatus(false);
}
$this->response->addJSON(
'message',
sprintf(
_ngettext(
'The name \'%s\' is a MySQL reserved keyword.',
'The names \'%s\' are MySQL reserved keywords.',
count($reserved_keywords_names)
),
implode(',', $reserved_keywords_names)
)
);
} else {
$this->response->setRequestStatus(false);
}
return;
}
/**
* A click on Change has been made for one column
*/
if (isset($_GET['change_column'])) {
$this->displayHtmlForColumnChange(null, 'tbl_structure.php');
return;
}
/**
* Adding or editing partitioning of the table
*/
if (isset($_POST['edit_partitioning'])
&& ! isset($_POST['save_partitioning'])
) {
$this->displayHtmlForPartitionChange();
return;
}
/**
* handle multiple field commands if required
*
* submit_mult_*_x comes from IE if <input type="img" ...> is used
*/
$submit_mult = $this->getMultipleFieldCommandType();
if (! empty($submit_mult)) {
if (isset($_POST['selected_fld'])) {
if ($submit_mult == 'browse') {
// browsing the table displaying only selected columns
$this->displayTableBrowseForSelectedColumns(
$GLOBALS['goto'],
$GLOBALS['pmaThemeImage']
);
} else {
// handle multiple field commands
// handle confirmation of deleting multiple columns
$action = 'tbl_structure.php';
$GLOBALS['selected'] = $_POST['selected_fld'];
list(
$what_ret, $query_type_ret, $is_unset_submit_mult,
$mult_btn_ret, $centralColsError
)
= $this->getDataForSubmitMult(
$submit_mult,
$_POST['selected_fld'],
$action
);
//update the existing variables
// todo: refactor mult_submits.inc.php such as
// below globals are not needed anymore
if (isset($what_ret)) {
$GLOBALS['what'] = $what_ret;
global $what;
}
if (isset($query_type_ret)) {
$GLOBALS['query_type'] = $query_type_ret;
global $query_type;
}
if ($is_unset_submit_mult) {
unset($submit_mult);
}
if (isset($mult_btn_ret)) {
$GLOBALS['mult_btn'] = $mult_btn_ret;
global $mult_btn;
}
include ROOT_PATH . 'libraries/mult_submits.inc.php';
/**
* if $submit_mult == 'change', execution will have stopped
* at this point
*/
if (empty($message)) {
$message = Message::success();
}
$this->response->addHTML(
Util::getMessage($message, $sql_query)
);
}
} else {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No column selected.'));
}
}
/**
* Modifications have been submitted -> updates the table
*/
if (isset($_POST['do_save_data'])) {
$regenerate = $this->updateColumns();
if (! $regenerate) {
// continue to show the table's structure
unset($_POST['selected']);
}
}
/**
* Modifications to the partitioning have been submitted -> updates the table
*/
if (isset($_POST['save_partitioning'])) {
$this->updatePartitioning();
}
/**
* Adding indexes
*/
if (isset($_POST['add_key'])
|| isset($_POST['partition_maintenance'])
) {
//todo: set some variables for sql.php include, to be eliminated
//after refactoring sql.php
$db = $this->db;
$table = $this->table;
$sql_query = $GLOBALS['sql_query'];
$cfg = $GLOBALS['cfg'];
$pmaThemeImage = $GLOBALS['pmaThemeImage'];
include ROOT_PATH . 'sql.php';
$GLOBALS['reload'] = true;
}
/**
* Gets the relation settings
*/
$cfgRelation = $this->relation->getRelationsParam();
/**
* Runs common work
*/
// set db, table references, for require_once that follows
// got to be eliminated in long run
$db = &$this->db;
$table = &$this->table;
$url_params = [];
include_once ROOT_PATH . 'libraries/tbl_common.inc.php';
$this->_db_is_system_schema = $db_is_system_schema;
$this->_url_query = Url::getCommonRaw([
'db' => $db,
'table' => $table,
'goto' => 'tbl_structure.php',
'back' => 'tbl_structure.php',
]);
/* The url_params array is initialized in above include */
$url_params['goto'] = 'tbl_structure.php';
$url_params['back'] = 'tbl_structure.php';
// 2. Gets table keys and retains them
// @todo should be: $server->db($db)->table($table)->primary()
$primary = Index::getPrimary($this->table, $this->db);
$columns_with_index = $this->dbi
->getTable($this->db, $this->table)
->getColumnsWithIndex(
Index::UNIQUE | Index::INDEX | Index::SPATIAL
| Index::FULLTEXT
);
$columns_with_unique_index = $this->dbi
->getTable($this->db, $this->table)
->getColumnsWithIndex(Index::UNIQUE);
// 3. Get fields
$fields = (array) $this->dbi->getColumns(
$this->db,
$this->table,
null,
true
);
//display table structure
$this->response->addHTML(
$this->displayStructure(
$cfgRelation,
$columns_with_unique_index,
$url_params,
$primary,
$fields,
$columns_with_index
)
);
}
/**
* Moves columns in the table's structure based on $_REQUEST
*
* @return void
*/
protected function moveColumns()
{
$this->dbi->selectDb($this->db);
/*
* load the definitions for all columns
*/
$columns = $this->dbi->getColumnsFull($this->db, $this->table);
$column_names = array_keys($columns);
$changes = [];
// move columns from first to last
for ($i = 0, $l = count($_POST['move_columns']); $i < $l; $i++) {
$column = $_POST['move_columns'][$i];
// is this column already correctly placed?
if ($column_names[$i] == $column) {
continue;
}
// it is not, let's move it to index $i
$data = $columns[$column];
$extracted_columnspec = Util::extractColumnSpec($data['Type']);
if (isset($data['Extra'])
&& $data['Extra'] == 'on update CURRENT_TIMESTAMP'
) {
$extracted_columnspec['attribute'] = $data['Extra'];
unset($data['Extra']);
}
$current_timestamp = ($data['Type'] == 'timestamp'
|| $data['Type'] == 'datetime')
&& ($data['Default'] == 'CURRENT_TIMESTAMP'
|| $data['Default'] == 'current_timestamp()');
if ($data['Null'] === 'YES' && $data['Default'] === null) {
$default_type = 'NULL';
} elseif ($current_timestamp) {
$default_type = 'CURRENT_TIMESTAMP';
} elseif ($data['Default'] === null) {
$default_type = 'NONE';
} else {
$default_type = 'USER_DEFINED';
}
$virtual = [
'VIRTUAL',
'PERSISTENT',
'VIRTUAL GENERATED',
'STORED GENERATED',
];
$data['Virtuality'] = '';
$data['Expression'] = '';
if (isset($data['Extra']) && in_array($data['Extra'], $virtual)) {
$data['Virtuality'] = str_replace(' GENERATED', '', $data['Extra']);
$expressions = $this->table_obj->getColumnGenerationExpression($column);
$data['Expression'] = $expressions[$column];
}
$changes[] = 'CHANGE ' . Table::generateAlter(
$column,
$column,
mb_strtoupper($extracted_columnspec['type']),
$extracted_columnspec['spec_in_brackets'],
$extracted_columnspec['attribute'],
isset($data['Collation']) ? $data['Collation'] : '',
$data['Null'] === 'YES' ? 'NULL' : 'NOT NULL',
$default_type,
$current_timestamp ? '' : $data['Default'],
isset($data['Extra']) && $data['Extra'] !== '' ? $data['Extra']
: false,
isset($data['COLUMN_COMMENT']) && $data['COLUMN_COMMENT'] !== ''
? $data['COLUMN_COMMENT'] : false,
$data['Virtuality'],
$data['Expression'],
$i === 0 ? '-first' : $column_names[$i - 1]
);
// update current column_names array, first delete old position
for ($j = 0, $ll = count($column_names); $j < $ll; $j++) {
if ($column_names[$j] == $column) {
unset($column_names[$j]);
}
}
// insert moved column
array_splice($column_names, $i, 0, $column);
}
if (empty($changes) && ! isset($_REQUEST['preview_sql'])) { // should never happen
$this->response->setRequestStatus(false);
return;
}
// query for moving the columns
$sql_query = sprintf(
'ALTER TABLE %s %s',
Util::backquote($this->table),
implode(', ', $changes)
);
if (isset($_REQUEST['preview_sql'])) { // preview sql
$this->response->addJSON(
'sql_data',
$this->template->render('preview_sql', [
'query_data' => $sql_query,
])
);
} else { // move column
$this->dbi->tryQuery($sql_query);
$tmp_error = $this->dbi->getError();
if ($tmp_error) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', Message::error($tmp_error));
} else {
$message = Message::success(
__('The columns have been moved successfully.')
);
$this->response->addJSON('message', $message);
$this->response->addJSON('columns', $column_names);
}
}
}
/**
* Displays HTML for changing one or more columns
*
* @param array $selected the selected columns
* @param string $action target script to call
*
* @return void
*
*/
protected function displayHtmlForColumnChange($selected, $action)
{
// $selected comes from mult_submits.inc.php
if (empty($selected)) {
$selected[] = $_REQUEST['field'];
$selected_cnt = 1;
} else { // from a multiple submit
$selected_cnt = count($selected);
}
/**
* @todo optimize in case of multiple fields to modify
*/
$fields_meta = [];
for ($i = 0; $i < $selected_cnt; $i++) {
$value = $this->dbi->getColumns(
$this->db,
$this->table,
$selected[$i],
true
);
if (count($value) == 0) {
$message = Message::error(
__('Failed to get description of column %s!')
);
$message->addParam($selected[$i]);
$this->response->addHTML($message);
} else {
$fields_meta[] = $value;
}
}
$num_fields = count($fields_meta);
// set these globals because tbl_columns_definition_form.inc.php
// verifies them
// @todo: refactor tbl_columns_definition_form.inc.php so that it uses
// protected function params
$GLOBALS['action'] = $action;
$GLOBALS['num_fields'] = $num_fields;
/**
* Form for changing properties.
*/
$checkUserPrivileges = new CheckUserPrivileges($this->dbi);
$checkUserPrivileges->getPrivileges();
include ROOT_PATH . 'libraries/tbl_columns_definition_form.inc.php';
}
/**
* Displays HTML for partition change
*
* @return void
*/
protected function displayHtmlForPartitionChange()
{
$partitionDetails = null;
if (! isset($_POST['partition_by'])) {
$partitionDetails = $this->_extractPartitionDetails();
}
include ROOT_PATH . 'libraries/tbl_partition_definition.inc.php';
$this->response->addHTML(
$this->template->render('table/structure/partition_definition_form', [
'db' => $this->db,
'table' => $this->table,
'partition_details' => $partitionDetails,
])
);
}
/**
* Extracts partition details from CREATE TABLE statement
*
* @return array[] array of partition details
*/
private function _extractPartitionDetails()
{
$createTable = (new Table($this->table, $this->db))->showCreate();
if (! $createTable) {
return null;
}
$parser = new Parser($createTable);
/**
* @var CreateStatement $stmt
*/
$stmt = $parser->statements[0];
$partitionDetails = [];
$partitionDetails['partition_by'] = '';
$partitionDetails['partition_expr'] = '';
$partitionDetails['partition_count'] = '';
if (! empty($stmt->partitionBy)) {
$openPos = strpos($stmt->partitionBy, "(");
$closePos = strrpos($stmt->partitionBy, ")");
$partitionDetails['partition_by']
= trim(substr($stmt->partitionBy, 0, $openPos));
$partitionDetails['partition_expr']
= trim(substr($stmt->partitionBy, $openPos + 1, $closePos - ($openPos + 1)));
if (isset($stmt->partitionsNum)) {
$count = $stmt->partitionsNum;
} else {
$count = count($stmt->partitions);
}
$partitionDetails['partition_count'] = $count;
}
$partitionDetails['subpartition_by'] = '';
$partitionDetails['subpartition_expr'] = '';
$partitionDetails['subpartition_count'] = '';
if (! empty($stmt->subpartitionBy)) {
$openPos = strpos($stmt->subpartitionBy, "(");
$closePos = strrpos($stmt->subpartitionBy, ")");
$partitionDetails['subpartition_by']
= trim(substr($stmt->subpartitionBy, 0, $openPos));
$partitionDetails['subpartition_expr']
= trim(substr($stmt->subpartitionBy, $openPos + 1, $closePos - ($openPos + 1)));
if (isset($stmt->subpartitionsNum)) {
$count = $stmt->subpartitionsNum;
} else {
$count = count($stmt->partitions[0]->subpartitions);
}
$partitionDetails['subpartition_count'] = $count;
}
// Only LIST and RANGE type parameters allow subpartitioning
$partitionDetails['can_have_subpartitions']
= $partitionDetails['partition_count'] > 1
&& ($partitionDetails['partition_by'] == 'RANGE'
|| $partitionDetails['partition_by'] == 'RANGE COLUMNS'
|| $partitionDetails['partition_by'] == 'LIST'
|| $partitionDetails['partition_by'] == 'LIST COLUMNS');
// Values are specified only for LIST and RANGE type partitions
$partitionDetails['value_enabled'] = isset($partitionDetails['partition_by'])
&& ($partitionDetails['partition_by'] == 'RANGE'
|| $partitionDetails['partition_by'] == 'RANGE COLUMNS'
|| $partitionDetails['partition_by'] == 'LIST'
|| $partitionDetails['partition_by'] == 'LIST COLUMNS');
$partitionDetails['partitions'] = [];
for ($i = 0, $iMax = (int) $partitionDetails['partition_count']; $i < $iMax; $i++) {
if (! isset($stmt->partitions[$i])) {
$partitionDetails['partitions'][$i] = [
'name' => 'p' . $i,
'value_type' => '',
'value' => '',
'engine' => '',
'comment' => '',
'data_directory' => '',
'index_directory' => '',
'max_rows' => '',
'min_rows' => '',
'tablespace' => '',
'node_group' => '',
];
} else {
$p = $stmt->partitions[$i];
$type = $p->type;
$expr = trim((string) $p->expr, '()');
if ($expr == 'MAXVALUE') {
$type .= ' MAXVALUE';
$expr = '';
}
$partitionDetails['partitions'][$i] = [
'name' => $p->name,
'value_type' => $type,
'value' => $expr,
'engine' => $p->options->has('ENGINE', true),
'comment' => trim((string) $p->options->has('COMMENT', true), "'"),
'data_directory' => trim((string) $p->options->has('DATA DIRECTORY', true), "'"),
'index_directory' => trim((string) $p->options->has('INDEX_DIRECTORY', true), "'"),
'max_rows' => $p->options->has('MAX_ROWS', true),
'min_rows' => $p->options->has('MIN_ROWS', true),
'tablespace' => $p->options->has('TABLESPACE', true),
'node_group' => $p->options->has('NODEGROUP', true),
];
}
$partition =& $partitionDetails['partitions'][$i];
$partition['prefix'] = 'partitions[' . $i . ']';
if ($partitionDetails['subpartition_count'] > 1) {
$partition['subpartition_count'] = $partitionDetails['subpartition_count'];
$partition['subpartitions'] = [];
for ($j = 0, $jMax = (int) $partitionDetails['subpartition_count']; $j < $jMax; $j++) {
if (! isset($stmt->partitions[$i]->subpartitions[$j])) {
$partition['subpartitions'][$j] = [
'name' => $partition['name'] . '_s' . $j,
'engine' => '',
'comment' => '',
'data_directory' => '',
'index_directory' => '',
'max_rows' => '',
'min_rows' => '',
'tablespace' => '',
'node_group' => '',
];
} else {
$sp = $stmt->partitions[$i]->subpartitions[$j];
$partition['subpartitions'][$j] = [
'name' => $sp->name,
'engine' => $sp->options->has('ENGINE', true),
'comment' => trim($sp->options->has('COMMENT', true), "'"),
'data_directory' => trim($sp->options->has('DATA DIRECTORY', true), "'"),
'index_directory' => trim($sp->options->has('INDEX_DIRECTORY', true), "'"),
'max_rows' => $sp->options->has('MAX_ROWS', true),
'min_rows' => $sp->options->has('MIN_ROWS', true),
'tablespace' => $sp->options->has('TABLESPACE', true),
'node_group' => $sp->options->has('NODEGROUP', true),
];
}
$subpartition =& $partition['subpartitions'][$j];
$subpartition['prefix'] = 'partitions[' . $i . ']'
. '[subpartitions][' . $j . ']';
}
}
}
return $partitionDetails;
}
/**
* Update the table's partitioning based on $_REQUEST
*
* @return void
*/
protected function updatePartitioning()
{
$sql_query = "ALTER TABLE " . Util::backquote($this->table) . " "
. $this->createAddField->getPartitionsDefinition();
// Execute alter query
$result = $this->dbi->tryQuery($sql_query);
if ($result !== false) {
$message = Message::success(
__('Table %1$s has been altered successfully.')
);
$message->addParam($this->table);
$this->response->addHTML(
Util::getMessage($message, $sql_query, 'success')
);
} else {
$this->response->setRequestStatus(false);
$this->response->addJSON(
'message',
Message::rawError(
__('Query error') . ':<br>' . $this->dbi->getError()
)
);
}
}
/**
* Function to get the type of command for multiple field handling
*
* @return string
*/
protected function getMultipleFieldCommandType()
{
$types = [
'change',
'drop',
'primary',
'index',
'unique',
'spatial',
'fulltext',
'browse',
];
foreach ($types as $type) {
if (isset($_POST['submit_mult_' . $type . '_x'])) {
return $type;
}
}
if (isset($_POST['submit_mult'])) {
return $_POST['submit_mult'];
} elseif (isset($_POST['mult_btn'])
&& $_POST['mult_btn'] == __('Yes')
) {
if (isset($_POST['selected'])) {
$_POST['selected_fld'] = $_POST['selected'];
}
return 'row_delete';
}
return null;
}
/**
* Function to display table browse for selected columns
*
* @param string $goto goto page url
* @param string $pmaThemeImage URI of the pma theme image
*
* @return void
*/
protected function displayTableBrowseForSelectedColumns($goto, $pmaThemeImage)
{
$GLOBALS['active_page'] = 'sql.php';
$fields = [];
foreach ($_POST['selected_fld'] as $sval) {
$fields[] = Util::backquote($sval);
}
$sql_query = sprintf(
'SELECT %s FROM %s.%s',
implode(', ', $fields),
Util::backquote($this->db),
Util::backquote($this->table)
);
// Parse and analyze the query
$db = &$this->db;
list(
$analyzed_sql_results,
$db,
) = ParseAnalyze::sqlQuery($sql_query, $db);
// @todo: possibly refactor
extract($analyzed_sql_results);
$sql = new Sql();
$this->response->addHTML(
$sql->executeQueryAndGetQueryResponse(
isset($analyzed_sql_results) ? $analyzed_sql_results : '',
false, // is_gotofile
$this->db, // db
$this->table, // table
null, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
)
);
}
/**
* Update the table's structure based on $_REQUEST
*
* @return boolean true if error occurred
*
*/
protected function updateColumns()
{
$err_url = 'tbl_structure.php' . Url::getCommon(
[
'db' => $this->db,
'table' => $this->table,
]
);
$regenerate = false;
$field_cnt = count($_POST['field_name']);
$changes = [];
$adjust_privileges = [];
$columns_with_index = $this->dbi
->getTable($this->db, $this->table)
->getColumnsWithIndex(
Index::PRIMARY | Index::UNIQUE
);
for ($i = 0; $i < $field_cnt; $i++) {
if (! $this->columnNeedsAlterTable($i)) {
continue;
}
$changes[] = 'CHANGE ' . Table::generateAlter(
Util::getValueByKey($_POST, "field_orig.${i}", ''),
$_POST['field_name'][$i],
$_POST['field_type'][$i],
$_POST['field_length'][$i],
$_POST['field_attribute'][$i],
Util::getValueByKey($_POST, "field_collation.${i}", ''),
Util::getValueByKey($_POST, "field_null.${i}", 'NOT NULL'),
$_POST['field_default_type'][$i],
$_POST['field_default_value'][$i],
Util::getValueByKey($_POST, "field_extra.${i}", false),
Util::getValueByKey($_POST, "field_comments.${i}", ''),
Util::getValueByKey($_POST, "field_virtuality.${i}", ''),
Util::getValueByKey($_POST, "field_expression.${i}", ''),
Util::getValueByKey($_POST, "field_move_to.${i}", ''),
$columns_with_index
);
// find the remembered sort expression
$sorted_col = $this->table_obj->getUiProp(
Table::PROP_SORTED_COLUMN
);
// if the old column name is part of the remembered sort expression
if (mb_strpos(
(string) $sorted_col,
Util::backquote($_POST['field_orig'][$i])
) !== false) {
// delete the whole remembered sort expression
$this->table_obj->removeUiProp(Table::PROP_SORTED_COLUMN);
}
if (isset($_POST['field_adjust_privileges'][$i])
&& ! empty($_POST['field_adjust_privileges'][$i])
&& $_POST['field_orig'][$i] != $_POST['field_name'][$i]
) {
$adjust_privileges[$_POST['field_orig'][$i]]
= $_POST['field_name'][$i];
}
} // end for
if (count($changes) > 0 || isset($_POST['preview_sql'])) {
// Builds the primary keys statements and updates the table
$key_query = '';
/**
* this is a little bit more complex
*
* @todo if someone selects A_I when altering a column we need to check:
* - no other column with A_I
* - the column has an index, if not create one
*
*/
// To allow replication, we first select the db to use
// and then run queries on this db.
if (! $this->dbi->selectDb($this->db)) {
Util::mysqlDie(
$this->dbi->getError(),
'USE ' . Util::backquote($this->db) . ';',
false,
$err_url
);
}
$sql_query = 'ALTER TABLE ' . Util::backquote($this->table) . ' ';
$sql_query .= implode(', ', $changes) . $key_query;
$sql_query .= ';';
// If there is a request for SQL previewing.
if (isset($_POST['preview_sql'])) {
Core::previewSQL(count($changes) > 0 ? $sql_query : '');
}
$columns_with_index = $this->dbi
->getTable($this->db, $this->table)
->getColumnsWithIndex(
Index::PRIMARY | Index::UNIQUE | Index::INDEX
| Index::SPATIAL | Index::FULLTEXT
);
$changedToBlob = [];
// While changing the Column Collation
// First change to BLOB
for ($i = 0; $i < $field_cnt; $i++) {
if (isset($_POST['field_collation'][$i])
&& isset($_POST['field_collation_orig'][$i])
&& $_POST['field_collation'][$i] !== $_POST['field_collation_orig'][$i]
&& ! in_array($_POST['field_orig'][$i], $columns_with_index)
) {
$secondary_query = 'ALTER TABLE ' . Util::backquote(
$this->table
)
. ' CHANGE ' . Util::backquote(
$_POST['field_orig'][$i]
)
. ' ' . Util::backquote($_POST['field_orig'][$i])
. ' BLOB;';
$this->dbi->query($secondary_query);
$changedToBlob[$i] = true;
} else {
$changedToBlob[$i] = false;
}
}
// Then make the requested changes
$result = $this->dbi->tryQuery($sql_query);
if ($result !== false) {
$changed_privileges = $this->adjustColumnPrivileges(
$adjust_privileges
);
if ($changed_privileges) {
$message = Message::success(
__(
'Table %1$s has been altered successfully. Privileges ' .
'have been adjusted.'