-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Sql.php
1918 lines (1746 loc) · 67 KB
/
Sql.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
declare(strict_types=1);
namespace PhpMyAdmin;
use PhpMyAdmin\Display\Results as DisplayResults;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Html\MySQLDocumentation;
use PhpMyAdmin\Query\Generator as QueryGenerator;
use PhpMyAdmin\Query\Utilities;
use PhpMyAdmin\SqlParser\Statements\AlterStatement;
use PhpMyAdmin\SqlParser\Statements\DropStatement;
use PhpMyAdmin\SqlParser\Statements\SelectStatement;
use PhpMyAdmin\SqlParser\Utils\Query;
use function array_map;
use function array_sum;
use function bin2hex;
use function ceil;
use function count;
use function explode;
use function htmlspecialchars;
use function in_array;
use function is_array;
use function is_bool;
use function microtime;
use function session_start;
use function session_write_close;
use function sprintf;
use function str_replace;
use function stripos;
use function strlen;
use function strpos;
use function ucwords;
use function defined;
/**
* Set of functions for the SQL executor
*/
class Sql
{
/** @var DatabaseInterface */
private $dbi;
/** @var Relation */
private $relation;
/** @var RelationCleanup */
private $relationCleanup;
/** @var Transformations */
private $transformations;
/** @var Operations */
private $operations;
/** @var Template */
private $template;
public function __construct(
DatabaseInterface $dbi,
Relation $relation,
RelationCleanup $relationCleanup,
Operations $operations,
Transformations $transformations,
Template $template
) {
$this->dbi = $dbi;
$this->relation = $relation;
$this->relationCleanup = $relationCleanup;
$this->operations = $operations;
$this->transformations = $transformations;
$this->template = $template;
}
/**
* Handle remembered sorting order, only for single table query
*
* @param string $db database name
* @param string $table table name
* @param array $analyzed_sql_results the analyzed query results
* @param string $full_sql_query SQL query
*
* @return void
*/
private function handleSortOrder(
$db,
$table,
array &$analyzed_sql_results,
&$full_sql_query
) {
$pmatable = new Table($table, $db);
if (empty($analyzed_sql_results['order'])) {
// Retrieving the name of the column we should sort after.
$sortCol = $pmatable->getUiProp(Table::PROP_SORTED_COLUMN);
if (empty($sortCol)) {
return;
}
// Remove the name of the table from the retrieved field name.
$sortCol = str_replace(
Util::backquote($table) . '.',
'',
$sortCol
);
// Create the new query.
$full_sql_query = Query::replaceClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'ORDER BY ' . $sortCol
);
// TODO: Avoid reparsing the query.
$analyzed_sql_results = Query::getAll($full_sql_query);
} else {
// Store the remembered table into session.
$pmatable->setUiProp(
Table::PROP_SORTED_COLUMN,
Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'ORDER BY'
)
);
}
}
/**
* Append limit clause to SQL query
*
* @param array $analyzed_sql_results the analyzed query results
*
* @return string limit clause appended SQL query
*/
private function getSqlWithLimitClause(array &$analyzed_sql_results)
{
return Query::replaceClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'LIMIT ' . $_SESSION['tmpval']['pos'] . ', '
. $_SESSION['tmpval']['max_rows']
);
}
/**
* Verify whether the result set has columns from just one table
*
* @param array $fields_meta meta fields
*
* @return bool whether the result set has columns from just one table
*/
private function resultSetHasJustOneTable(array $fields_meta)
{
$just_one_table = true;
$prev_table = '';
foreach ($fields_meta as $one_field_meta) {
if ($one_field_meta->table != ''
&& $prev_table != ''
&& $one_field_meta->table != $prev_table
) {
$just_one_table = false;
}
if ($one_field_meta->table == '') {
continue;
}
$prev_table = $one_field_meta->table;
}
return $just_one_table && $prev_table != '';
}
/**
* Verify whether the result set contains all the columns
* of at least one unique key
*
* @param string $db database name
* @param string $table table name
* @param array $fields_meta meta fields
*
* @return bool whether the result set contains a unique key
*/
private function resultSetContainsUniqueKey(string $db, string $table, array $fields_meta)
{
$columns = $this->dbi->getColumns($db, $table);
$resultSetColumnNames = [];
foreach ($fields_meta as $oneMeta) {
$resultSetColumnNames[] = $oneMeta->name;
}
foreach (Index::getFromTable($table, $db) as $index) {
if (! $index->isUnique()) {
continue;
}
$indexColumns = $index->getColumns();
$numberFound = 0;
foreach ($indexColumns as $indexColumnName => $dummy) {
if (in_array($indexColumnName, $resultSetColumnNames)) {
$numberFound++;
} elseif (! in_array($indexColumnName, $columns)) {
$numberFound++;
} elseif (strpos($columns[$indexColumnName]['Extra'], 'INVISIBLE') !== false) {
$numberFound++;
}
}
if ($numberFound == count($indexColumns)) {
return true;
}
}
return false;
}
/**
* Get the HTML for relational column dropdown
* During grid edit, if we have a relational field, returns the html for the
* dropdown
*
* @param string $db current database
* @param string $table current table
* @param string $column current column
* @param string $curr_value current selected value
*
* @return string html for the dropdown
*/
public function getHtmlForRelationalColumnDropdown($db, $table, $column, $curr_value)
{
$foreigners = $this->relation->getForeigners($db, $table, $column);
$foreignData = $this->relation->getForeignData(
$foreigners,
$column,
false,
'',
''
);
if ($foreignData['disp_row'] == null) {
//Handle the case when number of values
//is more than $cfg['ForeignKeyMaxLimit']
$_url_params = [
'db' => $db,
'table' => $table,
'field' => $column,
];
$dropdown = $this->template->render('sql/relational_column_dropdown', [
'current_value' => $_POST['curr_value'],
'params' => $_url_params,
]);
} else {
$dropdown = $this->relation->foreignDropdown(
$foreignData['disp_row'],
$foreignData['foreign_field'],
$foreignData['foreign_display'],
$curr_value,
$GLOBALS['cfg']['ForeignKeyMaxLimit']
);
$dropdown = '<select>' . $dropdown . '</select>';
}
return $dropdown;
}
/** @return array<string, int|array> */
private function getDetailedProfilingStats(array $profilingResults): array
{
$profiling = [
'total_time' => 0,
'states' => [],
'chart' => [],
'profile' => [],
];
foreach ($profilingResults as $oneResult) {
$status = ucwords($oneResult['Status']);
$profiling['total_time'] += $oneResult['Duration'];
$profiling['profile'][] = [
'status' => $status,
'duration' => Util::formatNumber($oneResult['Duration'], 3, 1),
'duration_raw' => $oneResult['Duration'],
];
if (! isset($profiling['states'][$status])) {
$profiling['states'][$status] = [
'total_time' => $oneResult['Duration'],
'calls' => 1,
];
$profiling['chart'][$status] = $oneResult['Duration'];
} else {
$profiling['states'][$status]['calls']++;
$profiling['chart'][$status] += $oneResult['Duration'];
}
}
return $profiling;
}
/**
* Get value of a column for a specific row (marked by $whereClause)
*/
public function getFullValuesForSetColumn(
string $db,
string $table,
string $column,
string $whereClause
): string {
$row = $this->dbi->fetchSingleRow(sprintf(
'SELECT `%s` FROM `%s`.`%s` WHERE %s',
$column,
$db,
$table,
$whereClause
));
if ($row === null) {
return '';
}
return $row[$column];
}
/**
* Get all the values for a enum column or set column in a table
*
* @param string $db current database
* @param string $table current table
* @param string $column current column
*
* @return array|null array containing the value list for the column, null on failure
*/
public function getValuesForColumn(string $db, string $table, string $column): ?array
{
$field_info_query = QueryGenerator::getColumnsSql($db, $table, $this->dbi->escapeString($column));
$field_info_result = $this->dbi->fetchResult(
$field_info_query,
null,
null,
DatabaseInterface::CONNECT_USER,
DatabaseInterface::QUERY_STORE
);
if (! isset($field_info_result[0])) {
return null;
}
return Util::parseEnumSetValues($field_info_result[0]['Type']);
}
/**
* Function to check whether to remember the sorting order or not
*
* @param array $analyzed_sql_results the analyzed query and other variables set
* after analyzing the query
*
* @return bool
*/
private function isRememberSortingOrder(array $analyzed_sql_results)
{
return isset($analyzed_sql_results['select_expr'], $analyzed_sql_results['select_tables'])
&& $GLOBALS['cfg']['RememberSorting']
&& ! ($analyzed_sql_results['is_count']
|| $analyzed_sql_results['is_export']
|| $analyzed_sql_results['is_func']
|| $analyzed_sql_results['is_analyse'])
&& $analyzed_sql_results['select_from']
&& (empty($analyzed_sql_results['select_expr'])
|| ((count($analyzed_sql_results['select_expr']) === 1)
&& ($analyzed_sql_results['select_expr'][0] === '*')))
&& count($analyzed_sql_results['select_tables']) === 1;
}
/**
* Function to check whether the LIMIT clause should be appended or not
*
* @param array $analyzed_sql_results the analyzed query and other variables set
* after analyzing the query
*
* @return bool
*/
private function isAppendLimitClause(array $analyzed_sql_results)
{
// Assigning LIMIT clause to an syntactically-wrong query
// is not needed. Also we would want to show the true query
// and the true error message to the query executor
return (isset($analyzed_sql_results['parser'])
&& count($analyzed_sql_results['parser']->errors) === 0)
&& ($_SESSION['tmpval']['max_rows'] !== 'all')
&& ! ($analyzed_sql_results['is_export']
|| $analyzed_sql_results['is_analyse'])
&& ($analyzed_sql_results['select_from']
|| $analyzed_sql_results['is_subquery'])
&& empty($analyzed_sql_results['limit']);
}
/**
* Function to check whether this query is for just browsing
*
* @param array<string, mixed> $analyzed_sql_results the analyzed query and other variables set
* after analyzing the query
* @param bool|null $find_real_end whether the real end should be found
*/
public static function isJustBrowsing(array $analyzed_sql_results, ?bool $find_real_end): bool
{
return ! $analyzed_sql_results['is_group']
&& ! $analyzed_sql_results['is_func']
&& empty($analyzed_sql_results['union'])
&& empty($analyzed_sql_results['distinct'])
&& $analyzed_sql_results['select_from']
&& (count($analyzed_sql_results['select_tables']) === 1)
&& (empty($analyzed_sql_results['statement']->where)
|| (count($analyzed_sql_results['statement']->where) === 1
&& $analyzed_sql_results['statement']->where[0]->expr === '1'))
&& empty($analyzed_sql_results['group'])
&& ! isset($find_real_end)
&& ! $analyzed_sql_results['is_subquery']
&& ! $analyzed_sql_results['join']
&& empty($analyzed_sql_results['having']);
}
/**
* Function to check whether the related transformation information should be deleted
*
* @param array $analyzed_sql_results the analyzed query and other variables set
* after analyzing the query
*
* @return bool
*/
private function isDeleteTransformationInfo(array $analyzed_sql_results)
{
return ! empty($analyzed_sql_results['querytype'])
&& (($analyzed_sql_results['querytype'] === 'ALTER')
|| ($analyzed_sql_results['querytype'] === 'DROP'));
}
/**
* Function to check whether the user has rights to drop the database
*
* @param array $analyzed_sql_results the analyzed query and other variables set
* after analyzing the query
* @param bool $allowUserDropDatabase whether the user is allowed to drop db
* @param bool $is_superuser whether this user is a superuser
*
* @return bool
*/
public function hasNoRightsToDropDatabase(
array $analyzed_sql_results,
$allowUserDropDatabase,
$is_superuser
) {
return ! $allowUserDropDatabase
&& isset($analyzed_sql_results['drop_database'])
&& $analyzed_sql_results['drop_database']
&& ! $is_superuser;
}
/**
* Function to set a column property
*
* @param Table $pmatable Table instance
* @param string $request_index col_order|col_visib
*
* @return bool|Message
*/
public function setColumnProperty($pmatable, $request_index)
{
$property_value = array_map('intval', explode(',', $_POST[$request_index]));
switch ($request_index) {
case 'col_order':
$property_to_set = Table::PROP_COLUMN_ORDER;
break;
case 'col_visib':
$property_to_set = Table::PROP_COLUMN_VISIB;
break;
default:
$property_to_set = '';
}
return $pmatable->setUiProp(
$property_to_set,
$property_value,
$_POST['table_create_time'] ?? null
);
}
/**
* Function to find the real end of rows
*
* @param string $db the current database
* @param string $table the current table
*
* @return mixed the number of rows if "retain" param is true, otherwise true
*/
public function findRealEndOfRows($db, $table)
{
$unlim_num_rows = $this->dbi->getTable($db, $table)->countRecords(true);
$_SESSION['tmpval']['pos'] = $this->getStartPosToDisplayRow($unlim_num_rows);
return $unlim_num_rows;
}
/**
* Function to get the default sql query for browsing page
*
* @param string $db the current database
* @param string $table the current table
*
* @return string the default $sql_query for browse page
*/
public function getDefaultSqlQueryForBrowse($db, $table)
{
$bookmark = Bookmark::get(
$this->dbi,
$GLOBALS['cfg']['Server']['user'],
$db,
$table,
'label',
false,
true
);
if (! empty($bookmark) && ! empty($bookmark->getQuery())) {
$GLOBALS['using_bookmark_message'] = Message::notice(
__('Using bookmark "%s" as default browse query.')
);
$GLOBALS['using_bookmark_message']->addParam($table);
$GLOBALS['using_bookmark_message']->addHtml(
MySQLDocumentation::showDocumentation('faq', 'faq6-22')
);
$sql_query = $bookmark->getQuery();
} else {
$defaultOrderByClause = '';
if (isset($GLOBALS['cfg']['TablePrimaryKeyOrder'])
&& ($GLOBALS['cfg']['TablePrimaryKeyOrder'] !== 'NONE')
) {
$primaryKey = null;
$primary = Index::getPrimary($table, $db);
if ($primary !== false) {
$primarycols = $primary->getColumns();
foreach ($primarycols as $col) {
$primaryKey = $col->getName();
break;
}
if ($primaryKey != null) {
$defaultOrderByClause = ' ORDER BY '
. Util::backquote($table) . '.'
. Util::backquote($primaryKey) . ' '
. $GLOBALS['cfg']['TablePrimaryKeyOrder'];
}
}
}
$sql_query = 'SELECT * FROM ' . Util::backquote($table)
. $defaultOrderByClause;
}
return $sql_query;
}
/**
* Responds an error when an error happens when executing the query
*
* @param bool $is_gotofile whether goto file or not
* @param string $error error after executing the query
* @param string $full_sql_query full sql query
*
* @return void
*/
private function handleQueryExecuteError($is_gotofile, $error, $full_sql_query)
{
if ($is_gotofile) {
$message = Message::rawError($error);
$response = Response::getInstance();
$response->setRequestStatus(false);
$response->addJSON('message', $message);
} else {
Generator::mysqlDie($error, $full_sql_query, '', '');
}
exit;
}
/**
* Function to store the query as a bookmark
*
* @param string $db the current database
* @param string $bkm_user the bookmarking user
* @param string $sql_query_for_bookmark the query to be stored in bookmark
* @param string $bkm_label bookmark label
* @param bool $bkm_replace whether to replace existing bookmarks
*
* @return void
*/
public function storeTheQueryAsBookmark(
$db,
$bkm_user,
$sql_query_for_bookmark,
$bkm_label,
bool $bkm_replace
) {
$bfields = [
'bkm_database' => $db,
'bkm_user' => $bkm_user,
'bkm_sql_query' => $sql_query_for_bookmark,
'bkm_label' => $bkm_label,
];
// Should we replace bookmark?
if ($bkm_replace) {
$bookmarks = Bookmark::getList(
$this->dbi,
$GLOBALS['cfg']['Server']['user'],
$db
);
foreach ($bookmarks as $bookmark) {
if ($bookmark->getLabel() != $bkm_label) {
continue;
}
$bookmark->delete();
}
}
$bookmark = Bookmark::createBookmark(
$this->dbi,
$GLOBALS['cfg']['Server']['user'],
$bfields,
isset($_POST['bkm_all_users'])
);
$bookmark->save();
}
/**
* Executes the SQL query and measures its execution time
*
* @param string $full_sql_query the full sql query
*
* @return array ($result, $querytime)
*/
private function executeQueryAndMeasureTime($full_sql_query)
{
if (! defined('TESTSUITE')) {
// close session in case the query takes too long
session_write_close();
}
// Measure query time.
$querytime_before = array_sum(explode(' ', microtime()));
$result = @$this->dbi->tryQuery(
$full_sql_query,
DatabaseInterface::CONNECT_USER,
DatabaseInterface::QUERY_STORE
);
$querytime_after = array_sum(explode(' ', microtime()));
if (! defined('TESTSUITE')) {
// reopen session
session_start();
}
return [
$result,
$querytime_after - $querytime_before,
];
}
/**
* Function to get the affected or changed number of rows after executing a query
*
* @param bool $is_affected whether the query affected a table
* @param mixed $result results of executing the query
*
* @return int number of rows affected or changed
*/
private function getNumberOfRowsAffectedOrChanged($is_affected, $result)
{
if (! $is_affected) {
$num_rows = $result ? @$this->dbi->numRows($result) : 0;
} else {
$num_rows = @$this->dbi->affectedRows();
}
return $num_rows;
}
/**
* Checks if the current database has changed
* This could happen if the user sends a query like "USE `database`;"
*
* @param string $db the database in the query
*
* @return bool whether to reload the navigation(1) or not(0)
*/
private function hasCurrentDbChanged($db): bool
{
if (strlen($db) > 0) {
$current_db = $this->dbi->fetchValue('SELECT DATABASE()');
// $current_db is false, except when a USE statement was sent
return ($current_db != false) && ($db !== $current_db);
}
return false;
}
/**
* If a table, database or column gets dropped, clean comments.
*
* @param string $db current database
* @param string $table current table
* @param string|null $column current column
* @param bool $purge whether purge set or not
*
* @return void
*/
private function cleanupRelations($db, $table, ?string $column, $purge)
{
if (empty($purge) || strlen($db) <= 0) {
return;
}
if (strlen($table) > 0) {
if (isset($column) && strlen($column) > 0) {
$this->relationCleanup->column($db, $table, $column);
} else {
$this->relationCleanup->table($db, $table);
}
} else {
$this->relationCleanup->database($db);
}
}
/**
* Function to count the total number of rows for the same 'SELECT' query without
* the 'LIMIT' clause that may have been programatically added
*
* @param int $num_rows number of rows affected/changed by the query
* @param bool $justBrowsing whether just browsing or not
* @param string $db the current database
* @param string $table the current table
* @param array $analyzed_sql_results the analyzed query and other variables set
* after analyzing the query
*
* @return int unlimited number of rows
*/
private function countQueryResults(
$num_rows,
$justBrowsing,
$db,
$table,
array $analyzed_sql_results
) {
/* Shortcut for not analyzed/empty query */
if (empty($analyzed_sql_results)) {
return 0;
}
if (! $this->isAppendLimitClause($analyzed_sql_results)) {
// if we did not append a limit, set this to get a correct
// "Showing rows..." message
// $_SESSION['tmpval']['max_rows'] = 'all';
$unlim_num_rows = $num_rows;
} elseif ($this->isAppendLimitClause($analyzed_sql_results) && $_SESSION['tmpval']['max_rows'] > $num_rows) {
// When user has not defined a limit in query and total rows in
// result are less than max_rows to display, there is no need
// to count total rows for that query again
$unlim_num_rows = $_SESSION['tmpval']['pos'] + $num_rows;
} elseif ($analyzed_sql_results['querytype'] === 'SELECT'
|| $analyzed_sql_results['is_subquery']
) {
// c o u n t q u e r y
// If we are "just browsing", there is only one table (and no join),
// and no WHERE clause (or just 'WHERE 1 '),
// we do a quick count (which uses MaxExactCount) because
// SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
// However, do not count again if we did it previously
// due to $find_real_end == true
if ($justBrowsing) {
// Get row count (is approximate for InnoDB)
$unlim_num_rows = $this->dbi->getTable($db, $table)->countRecords();
/**
* @todo Can we know at this point that this is InnoDB,
* (in this case there would be no need for getting
* an exact count)?
*/
if ($unlim_num_rows < $GLOBALS['cfg']['MaxExactCount']) {
// Get the exact count if approximate count
// is less than MaxExactCount
/**
* @todo In countRecords(), MaxExactCount is also verified,
* so can we avoid checking it twice?
*/
$unlim_num_rows = $this->dbi->getTable($db, $table)
->countRecords(true);
}
} else {
$statement = $analyzed_sql_results['statement'];
$token_list = $analyzed_sql_results['parser']->list;
$replaces = [
// Remove ORDER BY to decrease unnecessary sorting time
[
'ORDER BY',
'',
],
// Removes LIMIT clause that might have been added
[
'LIMIT',
'',
],
];
$count_query = 'SELECT COUNT(*) FROM (' . Query::replaceClauses(
$statement,
$token_list,
$replaces
) . ') as cnt';
$unlim_num_rows = $this->dbi->fetchValue($count_query);
if ($unlim_num_rows === false) {
$unlim_num_rows = 0;
}
}
} else {// not $is_select
$unlim_num_rows = 0;
}
return $unlim_num_rows;
}
/**
* Function to handle all aspects relating to executing the query
*
* @param array $analyzed_sql_results analyzed sql results
* @param string $full_sql_query full sql query
* @param bool $is_gotofile whether to go to a file
* @param string|null $db current database
* @param string|null $table current table
* @param bool|null $find_real_end whether to find the real end
* @param string $sql_query_for_bookmark sql query to be stored as bookmark
* @param array $extra_data extra data
*
* @return mixed
*/
private function executeTheQuery(
array $analyzed_sql_results,
$full_sql_query,
$is_gotofile,
$db,
$table,
?bool $find_real_end,
$sql_query_for_bookmark,
$extra_data
) {
$response = Response::getInstance();
$response->getHeader()->getMenu()->setTable($table);
// Only if we ask to see the php code
if (isset($GLOBALS['show_as_php'])) {
$result = null;
$num_rows = 0;
$unlim_num_rows = 0;
} else { // If we don't ask to see the php code
Profiling::enable($this->dbi);
[
$result,
$GLOBALS['querytime'],
] = $this->executeQueryAndMeasureTime($full_sql_query);
// Displays an error message if required and stop parsing the script
$error = $this->dbi->getError();
if ($error && $GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
$extra_data['error'] = $error;
} elseif ($error) {
$this->handleQueryExecuteError($is_gotofile, $error, $full_sql_query);
}
// If there are no errors and bookmarklabel was given,
// store the query as a bookmark
if (! empty($_POST['bkm_label']) && ! empty($sql_query_for_bookmark)) {
$cfgBookmark = Bookmark::getParams($GLOBALS['cfg']['Server']['user']);
$this->storeTheQueryAsBookmark(
$db,
is_array($cfgBookmark) ? $cfgBookmark['user'] : '',
$sql_query_for_bookmark,
$_POST['bkm_label'],
isset($_POST['bkm_replace'])
);
}
// Gets the number of rows affected/returned
// (This must be done immediately after the query because
// mysql_affected_rows() reports about the last query done)
$num_rows = $this->getNumberOfRowsAffectedOrChanged(
$analyzed_sql_results['is_affected'],
$result
);
$profiling_results = Profiling::getInformation($this->dbi);
$justBrowsing = self::isJustBrowsing(
$analyzed_sql_results,
$find_real_end ?? null
);
$unlim_num_rows = $this->countQueryResults(
$num_rows,
$justBrowsing,
$db,
$table,
$analyzed_sql_results
);
$this->cleanupRelations(
$db ?? '',
$table ?? '',
$_POST['dropped_column'] ?? null,
$_POST['purge'] ?? null
);
if (isset($_POST['dropped_column'])
&& isset($db) && strlen($db) > 0
&& isset($table) && strlen($table) > 0
) {
// to refresh the list of indexes (Ajax mode)
$indexes = Index::getFromTable($table, $db);
$indexesDuplicates = Index::findDuplicates($table, $db);
$template = new Template();
$extra_data['indexes_list'] = $template->render('indexes', [
'url_params' => $GLOBALS['url_params'],
'indexes' => $indexes,
'indexes_duplicates' => $indexesDuplicates,
]);
}
}
return [
$result,
$num_rows,
$unlim_num_rows,
$profiling_results ?? null,
$extra_data,
];
}
/**
* Delete related transformation information
*
* @param string $db current database
* @param string $table current table
* @param array $analyzed_sql_results analyzed sql results
*
* @return void
*/
private function deleteTransformationInfo($db, $table, array $analyzed_sql_results)
{
if (! isset($analyzed_sql_results['statement'])) {
return;
}
$statement = $analyzed_sql_results['statement'];
if ($statement instanceof AlterStatement) {
if (! empty($statement->altered[0])
&& $statement->altered[0]->options->has('DROP')
) {
if (! empty($statement->altered[0]->field->column)) {
$this->transformations->clear(
$db,
$table,
$statement->altered[0]->field->column
);
}
}
} elseif ($statement instanceof DropStatement) {
$this->transformations->clear($db, $table);
}
}
/**
* Function to get the message for the no rows returned case
*
* @param string $message_to_show message to show
* @param array $analyzed_sql_results analyzed sql results
* @param int $num_rows number of rows
*
* @return Message
*/
private function getMessageForNoRowsReturned(
$message_to_show,
array $analyzed_sql_results,
$num_rows