forked from mysql/mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilesort.cc
2630 lines (2334 loc) · 80.3 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, 2016, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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 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
@brief
Sorts a database
*/
#include "filesort.h"
#include <m_ctype.h>
#include "sql_sort.h"
#include "probes_mysql.h"
#include "opt_range.h" // QUICK
#include "bounded_queue.h"
#include "filesort_utils.h"
#include "sql_select.h"
#include "debug_sync.h"
#include "opt_trace.h"
#include "sql_optimizer.h" // JOIN
#include "sql_base.h"
#include "opt_costmodel.h"
#include "priority_queue.h"
#include "log.h"
#include "item_sum.h" // Item_sum
#include "json_dom.h" // Json_wrapper
#include "template_utils.h"
#include "pfs_file_provider.h"
#include "mysql/psi/mysql_file.h"
#include <algorithm>
#include <utility>
using std::max;
using std::min;
namespace {
struct Mem_compare
{
Mem_compare() : m_compare_length(0) {}
Mem_compare(const Mem_compare &that)
: m_compare_length(that.m_compare_length)
{
}
bool operator()(const uchar *s1, const uchar *s2) const
{
// memcmp(s1, s2, 0) is guaranteed to return zero.
return memcmp(s1, s2, m_compare_length) < 0;
}
size_t m_compare_length;
};
}
/* functions defined in this file */
static ha_rows find_all_keys(Sort_param *param, QEP_TAB *qep_tab,
Filesort_info *fs_info,
IO_CACHE *buffer_file,
IO_CACHE *chunk_file,
Bounded_queue<uchar *, uchar *, Sort_param,
Mem_compare> *pq,
ha_rows *found_rows);
static int write_keys(Sort_param *param, Filesort_info *fs_info,
uint count, IO_CACHE *buffer_file, IO_CACHE *tempfile);
static void register_used_fields(Sort_param *param);
static int merge_index(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);
static uint suffix_length(ulong string_length);
static bool check_if_pq_applicable(Opt_trace_context *trace,
Sort_param *param, Filesort_info *info,
TABLE *table,
ha_rows records, ulong memory_available,
bool keep_addon_fields);
void Sort_param::init_for_filesort(Filesort *file_sort,
uint sortlen, TABLE *table,
ulong max_length_for_sort_data,
ha_rows maxrows, bool sort_positions)
{
DBUG_ASSERT(max_rows == 0); // function should not be called twice
sort_length= sortlen;
ref_length= table->file->ref_length;
if (!(table->file->ha_table_flags() & HA_FAST_KEY_READ) &&
!table->fulltext_searched && !sort_positions)
{
/*
Get the descriptors of all fields whose values are appended
to sorted fields and get its total length in addon_length.
*/
addon_fields=
file_sort->get_addon_fields(max_length_for_sort_data,
table->field, sort_length, &addon_length,
&m_packable_length);
}
if (using_addon_fields())
{
res_length= addon_length;
}
else
{
res_length= ref_length;
/*
The reference to the record is considered
as an additional sorted field
*/
sort_length+= ref_length;
}
/*
Add hash at the end of sort key to order cut values correctly.
Needed for GROUPing, rather than for ORDERing.
*/
if (use_hash)
sort_length+= sizeof(ulonglong);
rec_length= sort_length + addon_length;
max_rows= maxrows;
}
void Sort_param::try_to_pack_addons(ulong max_length_for_sort_data)
{
if (!using_addon_fields() || // no addons, or
using_packed_addons()) // already packed
return;
if (!Addon_fields::can_pack_addon_fields(res_length))
return;
const uint sz= Addon_fields::size_of_length_field;
if (rec_length + sz > max_length_for_sort_data)
return;
// Heuristic: skip packing if potential savings are less than 10 bytes.
if (m_packable_length < (10 + sz))
return;
Addon_fields_array::iterator addonf= addon_fields->begin();
for ( ; addonf != addon_fields->end(); ++addonf)
{
addonf->offset+= sz;
addonf->null_offset+= sz;
}
addon_fields->set_using_packed_addons(true);
m_using_packed_addons= true;
addon_length+= sz;
res_length+= sz;
rec_length+= sz;
}
static void trace_filesort_information(Opt_trace_context *trace,
const st_sort_field *sortorder,
uint s_length)
{
if (!trace->is_started())
return;
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");
if (sortorder->field)
{
if (strlen(sortorder->field->table->alias) != 0)
oto.add_utf8_table(sortorder->field->table->pos_in_table_list);
else
oto.add_alnum("table", "intermediate_tmp_table");
oto.add_alnum("field", sortorder->field->field_name ?
sortorder->field->field_name : "tmp_table_column");
}
else
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.
Before calling filesort, one must have done
table->file->info(HA_STATUS_VARIABLE)
The result set is stored in table->sort.io_cache or
table->sort.sorted_result, or left in the main filesort buffer.
@param thd Current thread
@param filesort Table and how to sort it
@param sort_positions Set to TRUE if we want to force sorting by position
(Needed by UPDATE/INSERT or ALTER TABLE or
when rowids are required by executor)
@param[out] examined_rows Store number of examined rows here
This is the number of found rows before
applying WHERE condition.
@param[out] found_rows Store the number of found rows here.
This is the number of found rows after
applying WHERE condition.
@param[out] returned_rows Number of rows in the result, could be less than
found_rows if LIMIT is provided.
@note
If we sort by position (like if sort_positions is 1) filesort() will
call table->prepare_for_position().
@returns False if success, true if error
*/
bool filesort(THD *thd, Filesort *filesort, bool sort_positions,
ha_rows *examined_rows, ha_rows *found_rows,
ha_rows *returned_rows)
{
int error;
ulong memory_available= thd->variables.sortbuff_size;
size_t num_chunks;
ha_rows num_rows= 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;
bool multi_byte_charset;
Bounded_queue<uchar *, uchar *, Sort_param, Mem_compare>
pq((Malloc_allocator<uchar*>
(key_memory_Filesort_info_record_pointers)));
Opt_trace_context * const trace= &thd->opt_trace;
QEP_TAB *const tab= filesort->tab;
TABLE *const table= tab->table();
ha_rows max_rows= filesort->limit;
uint s_length= 0;
DBUG_ENTER("filesort");
if (!(s_length= filesort->make_sortorder()))
DBUG_RETURN(true); /* purecov: inspected */
/*
We need a nameless wrapper, since we may be inside the "steps" of
"join_execution".
*/
Opt_trace_object trace_wrapper(trace);
trace_filesort_information(trace, filesort->sortorder, s_length);
DBUG_ASSERT(!table->reginfo.join_tab);
DBUG_ASSERT(tab == table->reginfo.qep_tab);
Item_subselect *const subselect= tab && tab->join() ?
tab->join()->select_lex->master_unit()->item : NULL;
MYSQL_FILESORT_START(const_cast<char*>(table->s->db.str),
const_cast<char*>(table->s->table_name.str));
DEBUG_SYNC(thd, "filesort_start");
/*
Release InnoDB's adaptive hash index latch (if holding) before
running a sort.
*/
ha_release_temporary_latches(thd);
/*
Don't use table->sort in filesort as it is also used by
QUICK_INDEX_MERGE_SELECT. Work with a copy and put it back at the end
when index_merge select has finished with it.
*/
Filesort_info table_sort= table->sort;
table->sort.io_cache= NULL;
DBUG_ASSERT(table_sort.sorted_result == NULL);
table_sort.sorted_result_in_fsbuf= false;
outfile= table_sort.io_cache;
my_b_clear(&tempfile);
my_b_clear(&chunk_file);
error= 1;
param.init_for_filesort(filesort,
sortlength(thd, filesort->sortorder, s_length,
&multi_byte_charset,
¶m.use_hash),
table,
thd->variables.max_length_for_sort_data,
max_rows, sort_positions);
table_sort.addon_fields= param.addon_fields;
if (tab->quick())
thd->inc_status_sort_range();
else
thd->inc_status_sort_scan();
// If number of rows is not known, use as much of sort buffer as possible.
num_rows= table->file->estimate_rows_upper_bound();
if (multi_byte_charset &&
!(param.tmp_buffer= (char*) my_malloc(key_memory_Sort_param_tmp_buffer,
param.sort_length,MYF(MY_WME))))
goto err;
if (check_if_pq_applicable(trace, ¶m, &table_sort,
table, num_rows, memory_available,
subselect != NULL))
{
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 lazy initialization).
*/
table_sort.init_record_pointers();
if (pq.init(param.max_rows,
¶m, table_sort.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"));
table_sort.free_sort_buffer();
DBUG_ASSERT(thd->is_error());
goto err;
}
filesort->using_pq= true;
param.using_pq= true;
}
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(thd->variables.max_length_for_sort_data);
/*
We need space for at least one record from each merge chunk, i.e.
param->max_keys_per_buffer >= MERGEBUFF2
See merge_buffers()),
memory_available must be large enough for
param->max_keys_per_buffer * (record + record pointer) bytes
(the main sort buffer, see alloc_sort_buffer()).
Hence this minimum:
*/
const ulong min_sort_memory=
max<ulong>(MIN_SORT_MEMORY,
ALIGN_SIZE(MERGEBUFF2 * (param.rec_length + sizeof(uchar*))));
/*
Cannot depend on num_rows. For external sort, space for upto MERGEBUFF2
rows is required.
*/
if (num_rows < MERGEBUFF2)
num_rows= MERGEBUFF2;
while (memory_available >= min_sort_memory)
{
ha_rows keys= memory_available / (param.rec_length + sizeof(char*));
// If the table is empty, allocate space for one row.
param.max_keys_per_buffer= (uint) min(num_rows > 0 ? num_rows : 1, keys);
table_sort.alloc_sort_buffer(param.max_keys_per_buffer, param.rec_length);
if (table_sort.sort_buffer_size() > 0)
break;
ulong old_memory_available= memory_available;
memory_available= memory_available/4*3;
if (memory_available < min_sort_memory &&
old_memory_available > min_sort_memory)
memory_available= min_sort_memory;
}
if (memory_available < min_sort_memory)
{
my_error(ER_OUT_OF_SORTMEMORY,MYF(ME_ERRORLOG + ME_FATALERROR));
goto err;
}
}
if (open_cached_file(&chunk_file,mysql_tmpdir,TEMP_PREFIX,
DISK_BUFFER_SIZE, MYF(MY_WME)))
goto err;
param.sort_form= table;
param.local_sortorder=
Bounds_checked_array<st_sort_field>(filesort->sortorder, s_length);
// New scope, because subquery execution must be traced within an array.
{
Opt_trace_array ota(trace, "filesort_execution");
num_rows= find_all_keys(¶m, tab,
&table_sort,
&chunk_file,
&tempfile,
param.using_pq ? &pq : NULL,
found_rows);
if (num_rows == HA_POS_ERROR)
goto err;
}
num_chunks= static_cast<size_t>(my_b_tell(&chunk_file)) /
sizeof(Merge_chunk);
Opt_trace_object(trace, "filesort_summary")
.add("rows", num_rows)
.add("examined_rows", param.examined_rows)
.add("number_of_tmp_files", num_chunks)
.add("sort_buffer_size", table_sort.sort_buffer_size())
.add_alnum("sort_mode",
param.using_packed_addons() ?
"<sort_key, packed_additional_fields>" :
param.using_addon_fields() ?
"<sort_key, additional_fields>" : "<sort_key, rowid>");
if (num_chunks == 0) // The whole set is in memory
{
if (save_index(¶m, (uint) num_rows, &table_sort))
goto err;
}
else
{
// We will need an extra buffer in rr_unpack_from_tempfile()
if (table_sort.using_addon_fields() &&
!(table_sort.addon_fields->allocate_addon_buf(param.addon_length)))
goto err; /* purecov: inspected */
table_sort.read_chunk_descriptors(&chunk_file, num_chunks);
if (table_sort.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,0,0))
goto err;
/*
Use also the space previously used by string pointers in sort_buffer
for temporary key storage.
*/
param.max_keys_per_buffer=
table_sort.sort_buffer_size() / param.rec_length;
if (merge_many_buff(¶m,
table_sort.get_raw_buf(),
table_sort.merge_chunks,
&num_chunks,
&tempfile))
goto err;
if (flush_io_cache(&tempfile) ||
reinit_io_cache(&tempfile,READ_CACHE,0L,0,0))
goto err;
if (merge_index(¶m,
table_sort.get_raw_buf(),
Merge_chunk_array(table_sort.merge_chunks.begin(),
num_chunks),
&tempfile,
outfile))
goto err;
}
if (num_rows > param.max_rows)
{
// If find_all_keys() produced more results than the query LIMIT.
num_rows= param.max_rows;
}
error= 0;
err:
my_free(param.tmp_buffer);
if (!subselect || !subselect->is_uncacheable())
{
if (!table_sort.sorted_result_in_fsbuf)
table_sort.free_sort_buffer();
my_free(table_sort.merge_chunks.array());
table_sort.merge_chunks= Merge_chunk_array(NULL, 0);
}
close_cached_file(&tempfile);
close_cached_file(&chunk_file);
if (my_b_inited(outfile))
{
if (flush_io_cache(outfile))
error=1;
{
my_off_t save_pos=outfile->pos_in_file;
/* For following reads */
if (reinit_io_cache(outfile,READ_CACHE,0L,0,0))
error=1;
outfile->end_of_file=save_pos;
}
}
if (error)
{
int kill_errno= thd->killed_errno();
DBUG_ASSERT(thd->is_error() || kill_errno);
/*
We replace the table->sort at the end.
Hence calling free_io_cache to make sure table->sort.io_cache
used for QUICK_INDEX_MERGE_SELECT is free.
*/
free_io_cache(table);
/*
Guard against Bug#11745656 -- KILL QUERY should not send "server shutdown"
to client!
*/
const char *cause= kill_errno
? ((kill_errno == THD::KILL_CONNECTION && !abort_loop)
? ER(THD::KILL_QUERY)
: ER(kill_errno))
: thd->get_stmt_da()->message_text();
const char *msg= ER_THD(thd, ER_FILSORT_ABORT);
my_printf_error(ER_FILSORT_ABORT,
"%s: %s",
MYF(0),
msg,
cause);
if (thd->is_fatal_error)
sql_print_information("%s, host: %s, user: %s, "
"thread: %u, error: %s, query: %-.4096s",
msg,
thd->security_context()->host_or_ip().str,
thd->security_context()->priv_user().str,
thd->thread_id(),
cause,
thd->query().str);
}
else
thd->inc_status_sort_rows(num_rows);
*examined_rows= param.examined_rows;
*returned_rows= num_rows;
/* table->sort.io_cache should be free by this time */
DBUG_ASSERT(NULL == table->sort.io_cache);
// Assign the copy back!
table->sort= table_sort;
DBUG_PRINT("exit",
("num_rows: %ld examined_rows: %ld found_rows: %ld",
(long) num_rows, (long) *examined_rows, (long) *found_rows));
MYSQL_FILESORT_DONE(error, num_rows);
DBUG_RETURN(error);
} /* filesort */
void filesort_free_buffers(TABLE *table, bool full)
{
DBUG_ENTER("filesort_free_buffers");
my_free(table->sort.sorted_result);
table->sort.sorted_result= NULL;
table->sort.sorted_result_in_fsbuf= false;
if (full)
{
table->sort.free_sort_buffer();
my_free(table->sort.merge_chunks.array());
table->sort.merge_chunks= Merge_chunk_array(NULL, 0);
}
table->sort.addon_fields= NULL;
DBUG_VOID_RETURN;
}
uint Filesort::make_sortorder()
{
uint count;
st_sort_field *sort,*pos;
ORDER *ord;
DBUG_ENTER("make_sortorder");
count=0;
for (ord = order; ord; ord= ord->next)
count++;
if (!sortorder)
sortorder= (st_sort_field*) sql_alloc(sizeof(st_sort_field) * (count + 1));
pos= sort= sortorder;
if (!pos)
DBUG_RETURN(0);
for (ord= order; ord; ord= ord->next, pos++)
{
Item *const item= ord->item[0], *const real_item= item->real_item();
pos->field= 0; pos->item= 0;
if (real_item->type() == Item::FIELD_ITEM)
{
/*
Could be a field, or Item_direct_view_ref/Item_ref wrapping a field
If it is an Item_outer_ref, only_full_group_by has been switched off.
*/
DBUG_ASSERT
(item->type() == Item::FIELD_ITEM ||
(item->type() == Item::REF_ITEM &&
(down_cast<Item_ref*>(item)->ref_type() == Item_ref::VIEW_REF
|| down_cast<Item_ref*>(item)->ref_type() == Item_ref::OUTER_REF
|| down_cast<Item_ref*>(item)->ref_type() == Item_ref::REF)
));
pos->field= down_cast<Item_field*>(real_item)->field;
}
else if (real_item->type() == Item::SUM_FUNC_ITEM &&
!real_item->const_item())
{
// Aggregate, or Item_aggregate_ref
DBUG_ASSERT(item->type() == Item::SUM_FUNC_ITEM ||
(item->type() == Item::REF_ITEM &&
static_cast<Item_ref*>(item)->ref_type() ==
Item_ref::AGGREGATE_REF));
pos->field= item->get_tmp_table_field();
}
else if (real_item->type() == Item::COPY_STR_ITEM)
{ // Blob patch
pos->item= static_cast<Item_copy*>(real_item)->get_item();
}
else
pos->item= item;
pos->reverse= (ord->direction == ORDER::ORDER_DESC);
DBUG_ASSERT(pos->field != NULL || pos->item != NULL);
}
DBUG_RETURN(count);
}
void Filesort_info::read_chunk_descriptors(IO_CACHE *chunk_file, uint count)
{
DBUG_ENTER("Filesort_info::read_chunk_descriptors");
// 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(NULL, 0); /* purecov: inspected */
}
void *rawmem= merge_chunks.array();
const size_t length= sizeof(Merge_chunk) * count;
if (NULL == rawmem)
{
rawmem= my_malloc(key_memory_Filesort_info_merge, length, MYF(MY_WME));
if (rawmem == NULL)
DBUG_VOID_RETURN; /* purecov: inspected */
}
if (reinit_io_cache(chunk_file, READ_CACHE, 0L, 0, 0) ||
my_b_read(chunk_file, static_cast<uchar*>(rawmem), length))
{
my_free(rawmem); /* purecov: inspected */
rawmem= NULL; /* purecov: inspected */
count= 0; /* purecov: inspected */
}
merge_chunks= Merge_chunk_array(static_cast<Merge_chunk*>(rawmem), count);
DBUG_VOID_RETURN;
}
#ifndef DBUG_OFF
/*
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, 1);
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()
{
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.
*/
virtual bool handle_condition(THD *thd,
uint sql_errno,
const char* sqlstate,
Sql_condition::enum_severity_level *level,
const char* msg)
{
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 const Item::enum_walk walk_subquery=
Item::enum_walk(Item::WALK_POSTFIX | Item::WALK_SUBQUERY);
/**
Search after sort_keys, and write them into tempfile
(if we run out of space in the sort buffer).
All produced sequences are guaranteed to be non-empty.
@param param Sorting parameter
@param select Use this to get source data
@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 [out] found_rows The number of FOUND_ROWS().
For a query with LIMIT, this value will typically
be larger than the function return value.
@note
Basic idea:
@verbatim
while (get_next_sortkey())
{
if (using priority queue)
push sort key into queue
else
{
if (no free space in sort buffer)
{
sort buffer;
dump sorted sequence to 'tempfile';
dump Merge_chunk describing sequence location into 'chunk_file';
}
put sort key into buffer;
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 find_all_keys(Sort_param *param, QEP_TAB *qep_tab,
Filesort_info *fs_info,
IO_CACHE *chunk_file,
IO_CACHE *tempfile,
Bounded_queue<uchar *, uchar *, Sort_param,
Mem_compare> *pq,
ha_rows *found_rows)
{
int error,flag;
uint idx,indexpos,ref_length;
uchar *ref_pos,*next_pos,ref_buff[MAX_REFLENGTH];
my_off_t record;
TABLE *sort_form;
THD *thd= current_thd;
volatile THD::killed_state *killed= &thd->killed;
handler *file;
MY_BITMAP *save_read_set, *save_write_set;
bool skip_record;
ha_rows num_records= 0;
const bool packed_addon_fields= param->using_packed_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.
*/
Filesort_error_handler error_handler(thd);
DBUG_ENTER("find_all_keys");
DBUG_PRINT("info",("using: %s",
(qep_tab->condition() ? qep_tab->quick() ? "ranges" : "where":
"every row")));
idx=indexpos=0;
error= 0;
sort_form=param->sort_form;
file=sort_form->file;
ref_length=param->ref_length;
ref_pos= ref_buff;
const bool quick_select= qep_tab->quick() != NULL;
record=0;
*found_rows= 0;
flag= ((file->ha_table_flags() & HA_REC_NOT_IN_SEQ) || quick_select);
if (flag)
ref_pos= &file->ref[0];
next_pos=ref_pos;
if (!quick_select)
{
next_pos=(uchar*) 0; /* Find records in sequence */
DBUG_EXECUTE_IF("bug14365043_1",
DBUG_SET("+d,ha_rnd_init_fail"););
if ((error= file->ha_rnd_init(1)))
{
file->print_error(error, MYF(0));
DBUG_RETURN(HA_POS_ERROR);
}
file->extra_opt(HA_EXTRA_CACHE,
current_thd->variables.read_buff_size);
}
if (quick_select)
{
if ((error= qep_tab->quick()->reset()))
{
file->print_error(error, MYF(0));
DBUG_RETURN(HA_POS_ERROR);
}
}
/* Remember original bitmaps */
save_read_set= sort_form->read_set;
save_write_set= sort_form->write_set;
/*
Set up temporary column read map for columns used by sort and verify
it's not used
*/
DBUG_ASSERT(sort_form->tmp_set.n_bits == 0 ||
bitmap_is_clear_all(&sort_form->tmp_set));
// Temporary set for register_used_fields and mark_field_in_map()
sort_form->read_set= &sort_form->tmp_set;
// Include fields used for sorting in the read_set.
register_used_fields(param);
// Include fields used by conditions in the read_set.
if (qep_tab->condition())
{
Mark_field mf(sort_form, MARK_COLUMNS_TEMP);
qep_tab->condition()->walk(&Item::mark_field_in_map,
walk_subquery, (uchar*) &mf);
}
// Include fields used by pushed conditions in the read_set.
if (qep_tab->table()->file->pushed_idx_cond)
{
Mark_field mf(sort_form, MARK_COLUMNS_TEMP);
qep_tab->table()->file->pushed_idx_cond->walk(&Item::mark_field_in_map,
walk_subquery,
(uchar*) &mf);
}
sort_form->column_bitmaps_set(&sort_form->tmp_set, &sort_form->tmp_set);
DEBUG_SYNC(thd, "after_index_merge_phase1");
for (;;)
{
if (quick_select)
{
if ((error= qep_tab->quick()->get_next()))
break;
file->position(sort_form->record[0]);
DBUG_EXECUTE_IF("debug_filesort", dbug_print_record(sort_form, TRUE););
}
else /* Not quick-select */
{
DBUG_EXECUTE_IF("bug19656296", DBUG_SET("+d,ha_rnd_next_deadlock"););
{
error= file->ha_rnd_next(sort_form->record[0]);
if (!flag)
{
my_store_ptr(ref_pos,ref_length,record); // Position to row
record+= sort_form->s->db_record_offset;
}
else if (!error)
file->position(sort_form->record[0]);
}
if (error && error != HA_ERR_RECORD_DELETED)
break;
}
if (*killed)
{
DBUG_PRINT("info",("Sort killed by user"));
if (!quick_select)
{
(void) file->extra(HA_EXTRA_NO_CACHE);
file->ha_rnd_end();
}
num_records= HA_POS_ERROR;