-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathfilesort.cc
2421 lines (2131 loc) · 84.4 KB
/
filesort.cc
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
/*
Copyright (c) 2000, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file sql/filesort.cc
Standard external sort. We read rows into a buffer until there's no more room.
At that point, we use it (using the sorting algorithms from STL), and write it
to disk (thus the name “filesort”). When there are no more rows, we merge
chunks recursively, seven and seven (although we can go all the way up to 15
in the final pass if it helps us do one pass less).
If all the rows fit in a single chunk, the data never hits disk, but remains
in RAM.
*/
#include "sql/filesort.h"
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <atomic>
#include <memory>
#include <new>
#include <optional>
#include <vector>
#include "add_with_saturate.h"
#include "decimal.h"
#include "field_types.h" // enum_field_types
#include "map_helpers.h"
#include "my_basename.h"
#include "my_bitmap.h"
#include "my_byteorder.h"
#include "my_compiler.h"
#include "my_config.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_sys.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/my_loglevel.h"
#include "mysql/psi/mysql_file.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql/strings/m_ctype.h"
#include "mysql/udf_registration_types.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "priority_queue.h"
#include "sql-common/json_dom.h" // Json_wrapper
#include "sql-common/my_decimal.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/bounded_queue.h"
#include "sql/cmp_varlen_keys.h"
#include "sql/debug_sync.h"
#include "sql/derror.h"
#include "sql/error_handler.h"
#include "sql/field.h"
#include "sql/filesort_utils.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_subselect.h"
#include "sql/iterators/row_iterator.h"
#include "sql/iterators/sorting_iterator.h"
#include "sql/key_spec.h"
#include "sql/malloc_allocator.h"
#include "sql/merge_many_buff.h"
#include "sql/mysqld.h" // mysql_tmpdir
#include "sql/opt_costmodel.h"
#include "sql/opt_trace.h"
#include "sql/opt_trace_context.h"
#include "sql/pfs_batch_mode.h"
#include "sql/psi_memory_key.h"
#include "sql/sort_param.h"
#include "sql/sql_array.h"
#include "sql/sql_base.h"
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_sort.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thr_malloc.h"
#include "sql/tztime.h"
#include "sql_string.h"
#include "template_utils.h"
using std::max;
using std::min;
namespace {
struct Mem_compare_queue_key {
Mem_compare_queue_key() : m_compare_length(0), m_param(nullptr) {}
Mem_compare_queue_key(const Mem_compare_queue_key &that) = default;
bool operator()(const uchar *s1, const uchar *s2) const {
if (m_param)
return cmp_varlen_keys(m_param->local_sortorder, m_param->use_hash, s1,
s2);
// memcmp(s1, s2, 0) is guaranteed to return zero.
return memcmp(s1, s2, m_compare_length) < 0;
}
size_t m_compare_length;
Sort_param *m_param;
};
} // namespace
/* functions defined in this file */
static ha_rows read_all_rows(
THD *thd, Sort_param *param, const Mem_root_array<TABLE *> &tables,
table_map tables_to_get_rowid_for, Filesort_info *fs_info,
IO_CACHE *chunk_file, IO_CACHE *tempfile,
Bounded_queue<uchar *, uchar *, Sort_param, Mem_compare_queue_key> *pq,
RowIterator *source_iterator, ha_rows *found_rows, size_t *longest_key,
size_t *longest_addon);
static int write_keys(Sort_param *param, Filesort_info *fs_info, uint count,
IO_CACHE *buffer_file, IO_CACHE *tempfile);
static int merge_index(THD *thd, Sort_param *param, Sort_buffer sort_buffer,
Merge_chunk_array chunk_array, IO_CACHE *tempfile,
IO_CACHE *outfile);
static bool save_index(Sort_param *param, uint count, Filesort_info *table_sort,
Sort_result *sort_result);
static bool check_if_pq_applicable(Opt_trace_context *trace, Sort_param *param,
Filesort_info *info, ha_rows records,
ulong memory_available);
void Sort_param::decide_addon_fields(Filesort *file_sort,
const Mem_root_array<TABLE *> &tables,
bool force_sort_rowids) {
if (m_addon_fields_status != Addon_fields_status::unknown_status) {
// Already decided.
return;
}
DBUG_EXECUTE_IF("filesort_force_sort_row_ids", {
m_addon_fields_status = Addon_fields_status::keep_rowid;
return;
});
// Generally, prefer using addon fields (ie., sorting rows instead of just
// row IDs) if we can.
//
// NOTE: If the table is already in memory (e.g. the MEMORY engine; see the
// HA_FAST_KEY_READ flag), it would normally be beneficial to sort row IDs
// over rows to get smaller sort chunks. However, eliding the temporary table
// entirely is even better than using row IDs, and only possible if we sort
// rows. Furthermore, since we set up filesort at optimize time, we don't know
// yet whether the source table would _remain_ in memory, or could be spilled
// to disk using InnoDB. Thus, the only case that reasonably remains where
// we'd want to use row IDs without being forced would be on user (ie.,
// non-temporary) MEMORY tables, which doesn't seem reasonable to add
// complexity for.
for (TABLE *table : tables) {
if (table->pos_in_table_list &&
table->pos_in_table_list->is_fulltext_searched()) {
// See comment in SortWillBeOnRowId().
m_addon_fields_status = Addon_fields_status::fulltext_searched;
return;
}
}
if (force_sort_rowids) {
m_addon_fields_status = Addon_fields_status::keep_rowid;
} else {
/*
Get the descriptors of all fields whose values are appended
to sorted fields and get its total length in m_addon_length.
*/
addon_fields = file_sort->get_addon_fields(
&m_addon_fields_status, &m_addon_length, &m_packable_length);
}
}
void Sort_param::clear_addon_fields() {
m_addon_fields_status = Addon_fields_status::unknown_status;
addon_fields = nullptr;
}
void Sort_param::init_for_filesort(Filesort *file_sort,
Bounds_checked_array<st_sort_field> sf_array,
uint sortlen,
const Mem_root_array<TABLE *> &tables,
ha_rows maxrows, bool remove_duplicates) {
m_fixed_sort_length = sortlen;
m_remove_duplicates = remove_duplicates;
sum_ref_length = 0;
for (TABLE *table : tables) {
if (table->is_nullable()) {
// TODO(sgunders): Allow variable-length ref, so that we don't
// have to store the row ID for NULL rows.
++sum_ref_length;
}
sum_ref_length += table->file->ref_length;
}
local_sortorder = sf_array;
decide_addon_fields(file_sort, tables, file_sort->m_force_sort_rowids);
if (using_addon_fields()) {
fixed_res_length = m_addon_length;
} else {
fixed_res_length = sum_ref_length;
/*
The reference to the record is considered
as an additional sorted field
*/
AddWithSaturate(sum_ref_length, &m_fixed_sort_length);
}
m_num_varlen_keys = count_varlen_keys();
m_num_json_keys = count_json_keys();
if (using_varlen_keys()) {
AddWithSaturate(size_of_varlength_field, &m_fixed_sort_length);
}
/*
Add hash at the end of sort key to order cut values correctly.
Needed for GROUPing, rather than for ORDERing.
*/
if (using_json_keys()) {
use_hash = true;
AddWithSaturate(sizeof(ulonglong), &m_fixed_sort_length);
}
m_fixed_rec_length = AddWithSaturate(m_fixed_sort_length, m_addon_length);
max_rows = maxrows;
}
void Sort_param::try_to_pack_addons() {
if (!using_addon_fields() || // no addons, or
using_packed_addons()) // already packed
return;
// Heuristic: skip packing if potential savings are less than 10 bytes.
const uint sz = Addon_fields::size_of_length_field;
if (m_packable_length < (10 + sz)) {
m_addon_fields_status = Addon_fields_status::skip_heuristic;
return;
}
addon_fields->set_using_packed_addons(true);
m_using_packed_addons = true;
AddWithSaturate(sz, &m_addon_length);
AddWithSaturate(sz, &fixed_res_length);
AddWithSaturate(sz, &m_fixed_rec_length);
}
int Sort_param::count_json_keys() const {
int retval = 0;
for (const auto &sf : local_sortorder) {
if (sf.field_type == MYSQL_TYPE_JSON) {
++retval;
}
}
return retval;
}
size_t Sort_param::get_record_length(uchar *p) const {
uchar *start_of_payload = get_start_of_payload(p);
const uint size_of_payload =
using_packed_addons() ? Addon_fields::read_addon_length(start_of_payload)
: fixed_res_length;
uchar *end_of_payload = start_of_payload + size_of_payload;
return end_of_payload - p;
}
void Sort_param::get_rec_and_res_len(uchar *record_start, uint *recl,
uint *resl) {
if (!using_packed_addons() && !using_varlen_keys()) {
*recl = m_fixed_rec_length;
*resl = fixed_res_length;
return;
}
uchar *plen = get_start_of_payload(record_start);
if (using_packed_addons())
*resl = Addon_fields::read_addon_length(plen);
else
*resl = fixed_res_length;
assert(*resl <= fixed_res_length);
const uchar *record_end = plen + *resl;
*recl = static_cast<uint>(record_end - record_start);
}
static void trace_filesort_information(Opt_trace_context *trace,
const st_sort_field *sortorder,
uint s_length) {
if (!trace->is_started()) return;
const Opt_trace_array trace_filesort(trace, "filesort_information");
for (; s_length--; sortorder++) {
Opt_trace_object oto(trace);
oto.add_alnum("direction", sortorder->reverse ? "desc" : "asc");
oto.add("expression", sortorder->item);
}
}
/**
Sort a table.
Creates a set of pointers that can be used to read the rows
in sorted order. This should be done with the functions
in records.cc.
The result set is stored in fs_info->io_cache or
fs_info->sorted_result, or left in the main filesort buffer.
@param thd Current thread
@param filesort How to sort the table
@param source_iterator Where to read the rows to be sorted from.
@param tables_to_get_rowid_for
Which tables we are responsible for getting row IDs
for. Tables in this set that are not also in
"tables" are ignored.
@param num_rows_estimate How many rows source_iterator is expected
to produce. Only used for whether we intend
to use the priority queue optimization or not;
if we estimate fewer rows than we can fit into
RAM, we never use the priority queue.
@param fs_info Owns the buffers for sort_result.
@param sort_result Where to store the sort result.
@param[out] found_rows Store the number of found rows here.
This is the number of found rows after
applying WHERE condition.
@note
If we sort row IDs (as opposed to addon fields), filesort() will
call table->prepare_for_position().
@returns False if success, true if error
*/
bool filesort(THD *thd, Filesort *filesort, RowIterator *source_iterator,
table_map tables_to_get_rowid_for, ha_rows num_rows_estimate,
Filesort_info *fs_info, Sort_result *sort_result,
ha_rows *found_rows) {
int error;
const ulong memory_available = thd->variables.sortbuff_size;
ha_rows num_rows_found = HA_POS_ERROR;
IO_CACHE tempfile; // Temporary file for storing intermediate results.
IO_CACHE chunk_file; // For saving Merge_chunk structs.
IO_CACHE *outfile; // Contains the final, sorted result.
Sort_param *param = &filesort->m_sort_param;
const ha_rows max_rows = filesort->limit;
uint s_length = 0;
DBUG_TRACE;
if (!(s_length = filesort->sort_order_length()))
return true; /* purecov: inspected */
DEBUG_SYNC(thd, "filesort_start");
assert(sort_result->sorted_result == nullptr);
sort_result->sorted_result_in_fsbuf = false;
outfile = sort_result->io_cache;
my_b_clear(&tempfile);
my_b_clear(&chunk_file);
error = 1;
if (!param->using_addon_fields()) {
for (TABLE *table : filesort->tables) {
if (table->pos_in_table_list == nullptr ||
(tables_to_get_rowid_for & table->pos_in_table_list->map())) {
table->prepare_for_position();
}
}
}
// Make sure the source iterator is initialized before init_for_filesort(),
// since table->file (and in particular, ref_length) may not be initialized
// before that.
DBUG_EXECUTE_IF("bug14365043_1", DBUG_SET("+d,ha_rnd_init_fail"););
if (source_iterator->Init()) {
return true;
}
/*
We need a nameless wrapper, since we may be inside the "steps" of
"join_execution".
*/
Opt_trace_context *const trace = &thd->opt_trace;
Opt_trace_object trace_wrapper(trace);
if (filesort->tables.size() == 1) {
trace_wrapper.add_alnum("sorting_table", filesort->tables[0]->alias);
}
trace_filesort_information(trace, filesort->sortorder, s_length);
param->init_for_filesort(filesort, make_array(filesort->sortorder, s_length),
sortlength(thd, filesort->sortorder, s_length),
filesort->tables, max_rows,
filesort->m_remove_duplicates);
fs_info->addon_fields = param->addon_fields;
thd->inc_status_sort_scan();
Bounded_queue<uchar *, uchar *, Sort_param, Mem_compare_queue_key> pq(
param->max_record_length(),
(Malloc_allocator<uchar *>(key_memory_Filesort_info_record_pointers)));
// We would have liked to do this ahead-of-time so that we can show it
// in EXPLAIN. However, we don't know the table->file->ref_length before
// sorting time, which makes it hard to make the decision if we're row IDs.
// (If we sort rows, we would know, but it's not much use knowing it
// ahead-of-time _sometimes_.)
//
// However, do note this cannot change the addon fields status,
// so that we at least know that when checking whether we can skip
// in-between temporary tables (StreamingIterator).
if (check_if_pq_applicable(trace, param, fs_info, num_rows_estimate,
memory_available)) {
DBUG_PRINT("info", ("filesort PQ is applicable"));
/*
For PQ queries (with limit) we know exactly how many pointers/records
we have in the buffer, so to simplify things, we initialize
all pointers here. (We cannot pack fields anyways, so there is no
point in doing incremental allocation).
*/
if (fs_info->preallocate_records(param->max_rows_per_buffer)) {
my_error(ER_OUT_OF_SORTMEMORY, ME_FATALERROR);
LogErr(ERROR_LEVEL, ER_SERVER_OUT_OF_SORTMEMORY);
goto err;
}
if (pq.init(param->max_rows, param, fs_info->get_sort_keys())) {
/*
If we fail to init pq, we have to give up:
out of memory means my_malloc() will call my_error().
*/
DBUG_PRINT("info", ("failed to allocate PQ"));
fs_info->free_sort_buffer();
assert(thd->is_error());
goto err;
}
filesort->using_pq = true;
param->using_pq = true;
param->m_addon_fields_status = Addon_fields_status::using_priority_queue;
} else {
DBUG_PRINT("info", ("filesort PQ is not applicable"));
filesort->using_pq = false;
param->using_pq = false;
/*
When sorting using priority queue, we cannot use packed addons.
Without PQ, we can try.
*/
param->try_to_pack_addons();
/*
NOTE: param->max_rows_per_buffer is merely informative (for optimizer
trace) in this case, not actually used.
*/
if (num_rows_estimate < MERGEBUFF2) num_rows_estimate = MERGEBUFF2;
const ha_rows keys =
memory_available / (param->max_record_length() + sizeof(char *));
param->max_rows_per_buffer =
min(num_rows_estimate > 0 ? num_rows_estimate : 1, keys);
fs_info->set_max_size(memory_available, param->max_record_length());
}
size_t longest_key, longest_addons;
longest_addons = 0;
// New scope, because subquery execution must be traced within an array.
{
const Opt_trace_array ota(trace, "filesort_execution");
num_rows_found = read_all_rows(
thd, param, filesort->tables, tables_to_get_rowid_for, fs_info,
&chunk_file, &tempfile, param->using_pq ? &pq : nullptr,
source_iterator, found_rows, &longest_key, &longest_addons);
if (num_rows_found == HA_POS_ERROR) goto err;
}
size_t num_chunks, num_initial_chunks;
if (my_b_inited(&chunk_file)) {
num_chunks =
static_cast<size_t>(my_b_tell(&chunk_file)) / sizeof(Merge_chunk);
} else {
num_chunks = 0;
}
num_initial_chunks = num_chunks;
if (num_chunks == 0) // The whole set is in memory
{
ha_rows rows_in_chunk =
param->using_pq ? pq.num_elements() : num_rows_found;
if (save_index(param, rows_in_chunk, fs_info, sort_result)) goto err;
} else {
// If deduplicating, we'll need to remember the previous key somehow.
if (filesort->m_remove_duplicates) {
param->m_last_key_seen =
static_cast<uchar *>(thd->mem_root->Alloc(longest_key));
}
// We will need an extra buffer in SortFileIndirectIterator
if (fs_info->addon_fields != nullptr &&
!(fs_info->addon_fields->allocate_addon_buf(longest_addons)))
goto err; /* purecov: inspected */
fs_info->read_chunk_descriptors(&chunk_file, num_chunks);
if (fs_info->merge_chunks.is_null()) goto err; /* purecov: inspected */
close_cached_file(&chunk_file);
/* Open cached file if it isn't open */
if (!my_b_inited(outfile) &&
open_cached_file(outfile, mysql_tmpdir, TEMP_PREFIX, READ_RECORD_BUFFER,
MYF(MY_WME)))
goto err;
if (reinit_io_cache(outfile, WRITE_CACHE, 0L, false, false)) goto err;
param->max_rows_per_buffer = static_cast<uint>(
fs_info->max_size_in_bytes() / param->max_record_length());
Bounds_checked_array<uchar> merge_buf = fs_info->get_contiguous_buffer();
if (merge_buf.array() == nullptr) {
my_error(ER_OUT_OF_SORTMEMORY, ME_FATALERROR);
LogErr(ERROR_LEVEL, ER_SERVER_OUT_OF_SORTMEMORY);
goto err;
}
if (merge_many_buff(thd, param, merge_buf, fs_info->merge_chunks,
&num_chunks, &tempfile))
goto err;
if (flush_io_cache(&tempfile) ||
reinit_io_cache(&tempfile, READ_CACHE, 0L, false, false))
goto err;
if (merge_index(
thd, param, merge_buf,
Merge_chunk_array(fs_info->merge_chunks.begin(), num_chunks),
&tempfile, outfile))
goto err;
sort_result->found_records = num_rows_found;
}
if (trace->is_started()) {
char buffer[100];
String sort_mode(buffer, sizeof(buffer), &my_charset_bin);
sort_mode.length(0);
sort_mode.append("<");
if (param->using_varlen_keys())
sort_mode.append("varlen_sort_key");
else
sort_mode.append("fixed_sort_key");
sort_mode.append(", ");
sort_mode.append(param->using_packed_addons() ? "packed_additional_fields"
: param->using_addon_fields() ? "additional_fields"
: "rowid");
sort_mode.append(">");
const char *algo_text[] = {"none", "std::sort", "std::stable_sort"};
Opt_trace_object filesort_summary(trace, "filesort_summary");
filesort_summary.add("memory_available", memory_available)
.add("key_size", param->max_compare_length())
.add("row_size", param->max_record_length())
.add("max_rows_per_buffer", param->max_rows_per_buffer)
.add("num_rows_estimate", num_rows_estimate)
.add("num_rows_found", num_rows_found)
.add("num_initial_chunks_spilled_to_disk", num_initial_chunks)
.add("peak_memory_used", fs_info->peak_memory_used())
.add_alnum("sort_algorithm", algo_text[param->m_sort_algorithm]);
if (!param->using_packed_addons())
filesort_summary.add_alnum(
"unpacked_addon_fields",
addon_fields_text(param->m_addon_fields_status));
filesort_summary.add_alnum("sort_mode", sort_mode.c_ptr());
}
if (num_rows_found > param->max_rows) {
// If read_all_rows() produced more results than the query LIMIT.
num_rows_found = param->max_rows;
}
error = 0;
err:
if (!filesort->keep_buffers) {
if (!sort_result->sorted_result_in_fsbuf) fs_info->free_sort_buffer();
my_free(fs_info->merge_chunks.array());
fs_info->merge_chunks = Merge_chunk_array(nullptr, 0);
}
close_cached_file(&tempfile);
close_cached_file(&chunk_file);
if (my_b_inited(outfile)) {
if (flush_io_cache(outfile)) error = 1;
{
const my_off_t save_pos = outfile->pos_in_file;
/* For following reads */
if (reinit_io_cache(outfile, READ_CACHE, 0L, false, false)) error = 1;
outfile->end_of_file = save_pos;
}
}
if (error) {
assert(thd->is_error() || thd->killed);
} else
thd->inc_status_sort_rows(num_rows_found);
return error;
} /* filesort */
void filesort_free_buffers(TABLE *table, bool full) {
DBUG_TRACE;
table->unique_result.sorted_result.reset();
assert(!table->unique_result.sorted_result_in_fsbuf);
table->unique_result.sorted_result_in_fsbuf = false;
if (full) {
if (table->sorting_iterator != nullptr) {
table->sorting_iterator->CleanupAfterQuery();
table->sorting_iterator = nullptr; // The TABLE object can be reused.
}
if (table->duplicate_removal_iterator != nullptr) {
table->duplicate_removal_iterator->CleanupAfterQuery();
table->duplicate_removal_iterator =
nullptr; // The TABLE object can be reused.
}
}
}
Filesort::Filesort(THD *thd, Mem_root_array<TABLE *> tables_arg,
bool keep_buffers_arg, ORDER *order, ha_rows limit_arg,
bool remove_duplicates, bool force_sort_rowids,
bool unwrap_rollup)
: m_thd(thd),
tables(std::move(tables_arg)),
keep_buffers(keep_buffers_arg),
limit(limit_arg),
sortorder(nullptr),
using_pq(false),
m_remove_duplicates(remove_duplicates),
m_force_sort_rowids(force_sort_rowids),
m_sort_order_length(make_sortorder(order, unwrap_rollup)) {}
uint Filesort::make_sortorder(ORDER *order, bool unwrap_rollup) {
uint count;
st_sort_field *sort, *pos;
ORDER *ord;
DBUG_TRACE;
count = 0;
for (ord = order; ord; ord = ord->next) count++;
assert(count > 0);
const size_t sortorder_size = sizeof(*sortorder) * (count + 1);
if (sortorder == nullptr)
sortorder =
static_cast<st_sort_field *>((*THR_MALLOC)->Alloc(sortorder_size));
if (sortorder == nullptr) return 0; /* purecov: inspected */
memset(sortorder, 0, sortorder_size);
pos = sort = sortorder;
for (ord = order; ord; ord = ord->next, pos++) {
Item *const item = ord->item[0], *const real_item = item->real_item();
pos->item = real_item;
// If filesort runs before GROUP BY (potentially to sort rows
// in preparation for grouping), we cannot have any rollup NULLs
// (and they don't have any rollup state to query), so we need to
// remove the wrappers.
if (unwrap_rollup) {
pos->item = unwrap_rollup_group(pos->item);
}
pos->reverse = (ord->direction == ORDER_DESC);
}
return count;
}
void Filesort_info::read_chunk_descriptors(IO_CACHE *chunk_file, uint count) {
DBUG_TRACE;
// If we already have a chunk array, we're doing sort in a subquery.
if (!merge_chunks.is_null() && merge_chunks.size() < count) {
my_free(merge_chunks.array()); /* purecov: inspected */
merge_chunks = Merge_chunk_array(nullptr, 0); /* purecov: inspected */
}
void *rawmem = merge_chunks.array();
const size_t length = sizeof(Merge_chunk) * count;
if (nullptr == rawmem) {
rawmem = my_malloc(key_memory_Filesort_info_merge, length, MYF(MY_WME));
if (rawmem == nullptr) return; /* purecov: inspected */
}
if (reinit_io_cache(chunk_file, READ_CACHE, 0L, false, false) ||
my_b_read(chunk_file, static_cast<uchar *>(rawmem), length)) {
my_free(rawmem); /* purecov: inspected */
rawmem = nullptr; /* purecov: inspected */
count = 0; /* purecov: inspected */
}
merge_chunks = Merge_chunk_array(static_cast<Merge_chunk *>(rawmem), count);
}
#ifndef NDEBUG
/*
Print a text, SQL-like record representation into dbug trace.
Note: this function is a work in progress: at the moment
- column read bitmap is ignored (can print garbage for unused columns)
- there is no quoting
*/
static void dbug_print_record(TABLE *table, bool print_rowid) {
char buff[1024];
Field **pfield;
String tmp(buff, sizeof(buff), &my_charset_bin);
DBUG_LOCK_FILE;
fprintf(DBUG_FILE, "record (");
for (pfield = table->field; *pfield; pfield++)
fprintf(DBUG_FILE, "%s%s", (*pfield)->field_name, (pfield[1]) ? ", " : "");
fprintf(DBUG_FILE, ") = ");
fprintf(DBUG_FILE, "(");
for (pfield = table->field; *pfield; pfield++) {
Field *field = *pfield;
if (field->is_null()) {
if (fwrite("NULL", sizeof(char), 4, DBUG_FILE) != 4) {
goto unlock_file_and_quit;
}
}
if (field->type() == MYSQL_TYPE_BIT)
(void)field->val_int_as_str(&tmp, true);
else
field->val_str(&tmp);
if (fwrite(tmp.ptr(), sizeof(char), tmp.length(), DBUG_FILE) !=
tmp.length()) {
goto unlock_file_and_quit;
}
if (pfield[1]) {
if (fwrite(", ", sizeof(char), 2, DBUG_FILE) != 2) {
goto unlock_file_and_quit;
}
}
}
fprintf(DBUG_FILE, ")");
if (print_rowid) {
fprintf(DBUG_FILE, " rowid ");
for (uint i = 0; i < table->file->ref_length; i++) {
fprintf(DBUG_FILE, "%x", table->file->ref[i]);
}
}
fprintf(DBUG_FILE, "\n");
unlock_file_and_quit:
DBUG_UNLOCK_FILE;
}
#endif
/// Error handler for filesort.
class Filesort_error_handler : public Internal_error_handler {
THD *m_thd; ///< The THD in which filesort is executed.
bool m_seen_not_supported; ///< Has a not supported warning has been seen?
public:
/**
Create an error handler and push it onto the error handler
stack. The handler will be automatically popped from the error
handler stack when it is destroyed.
*/
Filesort_error_handler(THD *thd) : m_thd(thd), m_seen_not_supported(false) {
thd->push_internal_handler(this);
}
/**
Pop the error handler from the error handler stack, and destroy
it.
*/
~Filesort_error_handler() override { m_thd->pop_internal_handler(); }
/**
Handle a condition.
The handler will make sure that no more than a single
ER_NOT_SUPPORTED_YET warning will be seen by the higher
layers. This warning is generated by Json_wrapper::make_sort_key()
for every value that it doesn't know how to create a sort key
for. It is sufficient for the higher layers to report this warning
only once per sort.
*/
bool handle_condition(THD *, uint sql_errno, const char *,
Sql_condition::enum_severity_level *level,
const char *) override {
if (*level == Sql_condition::SL_WARNING &&
sql_errno == ER_NOT_SUPPORTED_YET) {
if (m_seen_not_supported) return true;
m_seen_not_supported = true;
}
return false;
}
};
static bool alloc_and_make_sortkey(Sort_param *param, Filesort_info *fs_info,
const Mem_root_array<TABLE *> &tables,
size_t *key_length, size_t *longest_addons) {
size_t min_bytes = 1;
for (;;) { // Termination condition within loop.
Bounds_checked_array<uchar> sort_key_buf =
fs_info->get_next_record_pointer(min_bytes);
if (sort_key_buf.array() == nullptr) return true;
const uint rec_sz =
param->make_sortkey(sort_key_buf, tables, longest_addons);
if (current_thd->is_error()) return true;
if (rec_sz > sort_key_buf.size()) {
// The record wouldn't fit. Try again, asking for a larger buffer.
min_bytes = sort_key_buf.size() + 1;
} else {
fs_info->commit_used_memory(rec_sz);
*key_length = rec_sz;
return false;
}
}
}
/**
Read all rows, and write them into a temporary file
(if we run out of space in the sort buffer).
All produced sequences are guaranteed to be non-empty.
@param thd Thread handle
@param param Sorting parameter
@param tables List of all tables being sorted.
@param tables_to_get_rowid_for
Which tables we are responsible for getting row IDs
for. Tables in this set that are not also in "tables"
are ignored.
@param fs_info Struct containing sort buffer etc.
@param chunk_file File to write Merge_chunks describing sorted segments
in tempfile.
@param tempfile File to write sorted sequences of sortkeys to.
@param pq If !NULL, use it for keeping top N elements
@param source_iterator Where to read the rows to be sorted from.
@param [out] found_rows The number of FOUND_ROWS().
For a query with LIMIT, this value will typically
be larger than the function return value.
@param [out] longest_key The largest single key found, in bytes.
@param [out] longest_addons
The longest addon field row (sum of all addon fields for any single
given row) found.
@note
Basic idea:
@verbatim
while (get_next_sortkey())
{
if (using priority queue)
push sort key into queue
else
{
try to put sort key into buffer;
if (no free space in sort buffer)
{
do {
allocate new, larger buffer;
retry putting sort key into buffer;
} until (record fits or no space for new buffer)
if (no space for new buffer)
{
sort record pointers (all buffers);
dump sorted sequence to 'tempfile';
dump Merge_chunk describing sequence location into 'chunk_file';
}
}
if (key was packed)
tell sort buffer the actual number of bytes used;
}
}
if (buffer has some elements && dumped at least once)
sort-dump-dump as above;
else
don't sort, leave sort buffer to be sorted by caller.
@endverbatim
@returns
Number of records written on success.
@returns
HA_POS_ERROR on error.
*/
static ha_rows read_all_rows(
THD *thd, Sort_param *param, const Mem_root_array<TABLE *> &tables,
table_map tables_to_get_rowid_for, Filesort_info *fs_info,
IO_CACHE *chunk_file, IO_CACHE *tempfile,
Bounded_queue<uchar *, uchar *, Sort_param, Mem_compare_queue_key> *pq,
RowIterator *source_iterator, ha_rows *found_rows, size_t *longest_key,
size_t *longest_addons) {
/*
Set up an error handler for filesort. It is automatically pushed
onto the internal error handler stack upon creation, and will be
popped off the stack automatically when the handler goes out of
scope.
*/
const Filesort_error_handler error_handler(thd);
DBUG_TRACE;
int error = 0;
*found_rows = 0;
size_t longest_key_so_far = 0;
size_t longest_addon_so_far = 0;
// NOTE(sgunders): When we sort row IDs, our read sets are a bit larger
// than required by read_all_rows(); in particular, columns that we
// don't sort on will still be read. (In particular, this makes us read
// and allocate blobs, where present.) However, with sorting row IDs being
// a rather marginal case, it's not worth it for us to try to compute new
// read sets to have different ones in the first phase of such sorts.
//
// This isn't the only case of too large read sets. For a query such as
// SELECT a FROM t1 WHERE b ORDER BY c, all three fields a,b,c will be in
// the read set; in particular, find_order_in_list() will include any
// columns used in ORDER BY in the read sets, as part of resolving them.
// This is required for correct operation. However, anything that is part
// of the read set will by extension be included as addon fields,
// unless we sort row IDs for some reason -- even c, which is part of
// the key. To remedy this, one would probably need a system
// of pushing read sets through the iterator tree (except it should
// ideally be done before optimization, where we set them up), so that
// each iterator can use the right read set for its time.
DEBUG_SYNC(thd, "after_index_merge_phase1");
ha_rows num_total_records = 0, num_records_this_chunk = 0;
uint num_written_chunks = 0;
if (pq == nullptr) {
fs_info->reset();
fs_info->clear_peak_memory_used();
}
const PFSBatchMode batch_mode(source_iterator);
for (;;) {
DBUG_EXECUTE_IF("bug19656296", DBUG_SET("+d,ha_rnd_next_deadlock"););
if ((error = source_iterator->Read())) {
break;
}
// Note where we are, for the case where we are not using addon fields.
if (!param->using_addon_fields()) {
for (TABLE *table : tables) {
if (!can_call_position(table)) {
continue;
}
if (table->pos_in_table_list == nullptr ||
(table->pos_in_table_list->map() & tables_to_get_rowid_for)) {
table->file->position(table->record[0]);
}
}
}
DBUG_EXECUTE_IF("debug_filesort", {
for (TABLE *table : tables) {
dbug_print_record(table, true);
}
});
if (thd->killed) {
DBUG_PRINT("info", ("Sort killed by user"));
return HA_POS_ERROR;
}