~drizzle-trunk/drizzle/development

660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1
/* Copyright (C) 2000-2006 MySQL AB
1 by brian
clean slate
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
1802.10.2 by Monty Taylor
Update all of the copyright headers to include the correct address.
14
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
1 by brian
clean slate
15
16
17
/**
18
  @file
19
20
  @brief
21
  Sorts a database
22
*/
23
1241.9.36 by Monty Taylor
ZOMG. I deleted drizzled/server_includes.h.
24
#include "config.h"
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
25
26
#include <float.h>
1241.9.59 by Monty Taylor
Removed the first mystrings header.
27
#include <limits.h>
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
28
29
#include <queue>
30
#include <algorithm>
31
1237.9.2 by Padraig O'Sullivan
Moved opt_range.[cc,h] into the optimizer directory and namespace and renamed the files to
32
#include "drizzled/sql_sort.h"
33
#include "drizzled/error.h"
34
#include "drizzled/probes.h"
35
#include "drizzled/session.h"
36
#include "drizzled/table.h"
37
#include "drizzled/table_list.h"
38
#include "drizzled/optimizer/range.h"
1237.9.4 by Padraig O'Sullivan
Removed the inclusion of drizzled/field.h in the server_includes header file.
39
#include "drizzled/records.h"
1241.9.64 by Monty Taylor
Moved remaining non-public portions of mysys and mystrings to drizzled/internal.
40
#include "drizzled/internal/iocache.h"
41
#include "drizzled/internal/my_sys.h"
1241.9.62 by Monty Taylor
Removed plugin/myisam/myisam.h from session.h
42
#include "plugin/myisam/myisam.h"
1273.1.15 by Jay Pipes
This patch completes the first step in the splitting of
43
#include "drizzled/plugin/transactional_storage_engine.h"
1 by brian
clean slate
44
897.1.6 by Padraig
Cleaning up merge_buffers() function a little bit.
45
using namespace std;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
46
47
namespace drizzled
48
{
897.1.6 by Padraig
Cleaning up merge_buffers() function a little bit.
49
520.7.1 by Monty Taylor
Moved hash.c to drizzled.
50
/* functions defined in this file */
1 by brian
clean slate
51
438.1.13 by Brian Aker
uint cleanup.
52
static char **make_char_array(char **old_pos, register uint32_t fields,
641.3.7 by Monty Taylor
More my_malloc removal.
53
                              uint32_t length);
1237.9.2 by Padraig O'Sullivan
Moved opt_range.[cc,h] into the optimizer directory and namespace and renamed the files to
54
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
55
static unsigned char *read_buffpek_from_file(internal::IO_CACHE *buffer_file,
56
                                             uint32_t count,
57
                                             unsigned char *buf);
1237.9.2 by Padraig O'Sullivan
Moved opt_range.[cc,h] into the optimizer directory and namespace and renamed the files to
58
1578.4.11 by Brian Aker
PAss through the code removing current_session
59
static ha_rows find_all_keys(Session *session,
60
                             SORTPARAM *param,
1237.13.3 by Padraig O'Sullivan
Performed numerous style cleanups in range.[cc,h].
61
                             optimizer::SqlSelect *select,
1237.9.2 by Padraig O'Sullivan
Moved opt_range.[cc,h] into the optimizer directory and namespace and renamed the files to
62
			     unsigned char * *sort_keys, 
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
63
                             internal::IO_CACHE *buffer_file,
64
			     internal::IO_CACHE *tempfile,
65
                             internal::IO_CACHE *indexfile);
66
67
static int write_keys(SORTPARAM *param,
68
                      unsigned char * *sort_keys,
69
		      uint32_t count,
70
                      internal::IO_CACHE *buffer_file,
71
                      internal::IO_CACHE *tempfile);
72
73
static void make_sortkey(SORTPARAM *param,
74
                         unsigned char *to,
75
                         unsigned char *ref_pos);
1 by brian
clean slate
76
static void register_used_fields(SORTPARAM *param);
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
77
static int merge_index(SORTPARAM *param,
78
                       unsigned char *sort_buffer,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
79
		       buffpek *buffpek,
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
80
		       uint32_t maxbuffer,
81
                       internal::IO_CACHE *tempfile,
82
		       internal::IO_CACHE *outfile);
83
static bool save_index(SORTPARAM *param,
84
                       unsigned char **sort_keys,
85
                       uint32_t count,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
86
                       filesort_info *table_sort);
438.1.13 by Brian Aker
uint cleanup.
87
static uint32_t suffix_length(uint32_t string_length);
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
88
static uint32_t sortlength(Session *session,
1711.6.1 by Brian Aker
Style on structure cleanup
89
                           SortField *sortorder,
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
90
                           uint32_t s_length,
91
                           bool *multi_byte_charset);
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
92
static sort_addon_field *get_addon_fields(Session *session,
1711.6.1 by Brian Aker
Style on structure cleanup
93
                                             Field **ptabfield,
94
                                             uint32_t sortlength,
95
                                             uint32_t *plength);
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
96
static void unpack_addon_fields(sort_addon_field *addon_field,
481 by Brian Aker
Remove all of uchar.
97
                                unsigned char *buff);
1 by brian
clean slate
98
/**
99
  Sort a table.
100
  Creates a set of pointers that can be used to read the rows
101
  in sorted order. This should be done with the functions
102
  in records.cc.
103
104
  Before calling filesort, one must have done
105
  table->file->info(HA_STATUS_VARIABLE)
106
107
  The result set is stored in table->io_cache or
108
  table->record_pointers.
109
520.1.22 by Brian Aker
Second pass of thd cleanup
110
  @param session           Current thread
1 by brian
clean slate
111
  @param table		Table to sort
112
  @param sortorder	How to sort the table
113
  @param s_length	Number of elements in sortorder
114
  @param select		condition to apply to the rows
115
  @param max_rows	Return only this many rows
116
  @param sort_positions	Set to 1 if we want to force sorting by position
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
117
			(Needed by UPDATE/INSERT or ALTER Table)
1 by brian
clean slate
118
  @param examined_rows	Store number of examined rows here
119
120
  @todo
121
    check why we do this (param.keys--)
122
  @note
123
    If we sort by position (like if sort_positions is 1) filesort() will
124
    call table->prepare_for_position().
125
126
  @retval
127
    HA_POS_ERROR	Error
128
  @retval
129
    \#			Number of rows
130
  @retval
131
    examined_rows	will be set to number of examined rows
132
*/
133
1711.6.1 by Brian Aker
Style on structure cleanup
134
ha_rows filesort(Session *session, Table *table, SortField *sortorder, uint32_t s_length,
1237.13.3 by Padraig O'Sullivan
Performed numerous style cleanups in range.[cc,h].
135
		 optimizer::SqlSelect *select, ha_rows max_rows,
1 by brian
clean slate
136
                 bool sort_positions, ha_rows *examined_rows)
137
{
138
  int error;
308 by Brian Aker
ulong conversion
139
  uint32_t memavl, min_sort_memory;
438.1.13 by Brian Aker
uint cleanup.
140
  uint32_t maxbuffer;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
141
  buffpek *buffpek_inst;
1 by brian
clean slate
142
  ha_rows records= HA_POS_ERROR;
481 by Brian Aker
Remove all of uchar.
143
  unsigned char **sort_keys= 0;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
144
  internal::IO_CACHE tempfile, buffpek_pointers, *selected_records_file, *outfile;
1 by brian
clean slate
145
  SORTPARAM param;
146
  bool multi_byte_charset;
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
147
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
148
  filesort_info table_sort;
327.2.4 by Brian Aker
Refactoring table.h
149
  TableList *tab= table->pos_in_table_list;
1 by brian
clean slate
150
  Item_subselect *subselect= tab ? tab->containing_subselect() : 0;
151
1532.1.15 by Brian Aker
Partial encapsulation of TableShare from Table.
152
  DRIZZLE_FILESORT_START(table->getShare()->getSchemaName(), table->getShare()->getTableName());
1 by brian
clean slate
153
154
  /*
155
   Release InnoDB's adaptive hash index latch (if holding) before
156
   running a sort.
157
  */
1273.1.15 by Jay Pipes
This patch completes the first step in the splitting of
158
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
1 by brian
clean slate
159
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
160
  /*
161
    Don't use table->sort in filesort as it is also used by
1237.13.5 by Padraig O'Sullivan
Split some classes from the range optimizer out in to their own header and implementation files.
162
    QuickIndexMergeSelect. Work with a copy and put it back at the end
1 by brian
clean slate
163
    when index_merge select has finished with it.
164
  */
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
165
  memcpy(&table_sort, &table->sort, sizeof(filesort_info));
1 by brian
clean slate
166
  table->sort.io_cache= NULL;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
167
1 by brian
clean slate
168
  outfile= table_sort.io_cache;
169
  my_b_clear(&tempfile);
170
  my_b_clear(&buffpek_pointers);
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
171
  buffpek_inst=0;
1 by brian
clean slate
172
  error= 1;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
173
  memset(&param, 0, sizeof(param));
520.1.22 by Brian Aker
Second pass of thd cleanup
174
  param.sort_length= sortlength(session, sortorder, s_length, &multi_byte_charset);
1208.3.2 by brian
Update for Cursor renaming.
175
  param.ref_length= table->cursor->ref_length;
1 by brian
clean slate
176
  param.addon_field= 0;
177
  param.addon_length= 0;
1233.1.5 by Brian Aker
More table_flags converted.
178
  if (!(table->cursor->getEngine()->check_flag(HTON_BIT_FAST_KEY_READ)) && !sort_positions)
1 by brian
clean slate
179
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
180
    /*
181
      Get the descriptors of all fields whose values are appended
1 by brian
clean slate
182
      to sorted fields and get its total length in param.spack_length.
183
    */
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
184
    param.addon_field= get_addon_fields(session, table->getFields(),
1 by brian
clean slate
185
                                        param.sort_length,
186
                                        &param.addon_length);
187
  }
188
189
  table_sort.addon_buf= 0;
190
  table_sort.addon_length= param.addon_length;
191
  table_sort.addon_field= param.addon_field;
192
  table_sort.unpack= unpack_addon_fields;
193
  if (param.addon_field)
194
  {
195
    param.res_length= param.addon_length;
641.3.7 by Monty Taylor
More my_malloc removal.
196
    if (!(table_sort.addon_buf= (unsigned char *) malloc(param.addon_length)))
1 by brian
clean slate
197
      goto err;
198
  }
199
  else
200
  {
201
    param.res_length= param.ref_length;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
202
    /*
203
      The reference to the record is considered
1 by brian
clean slate
204
      as an additional sorted field
205
    */
206
    param.sort_length+= param.ref_length;
207
  }
208
  param.rec_length= param.sort_length+param.addon_length;
209
  param.max_rows= max_rows;
210
211
  if (select && select->quick)
212
  {
1689.5.1 by Joseph Daly
remove increment calls
213
    session->status_var.filesort_range_count++;
1 by brian
clean slate
214
  }
215
  else
216
  {
1689.5.1 by Joseph Daly
remove increment calls
217
    session->status_var.filesort_scan_count++;
1 by brian
clean slate
218
  }
219
#ifdef CAN_TRUST_RANGE
220
  if (select && select->quick && select->quick->records > 0L)
221
  {
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
222
    records= min((ha_rows) (select->quick->records*2+EXTRA_RECORDS*2),
1208.3.2 by brian
Update for Cursor renaming.
223
                 table->cursor->stats.records)+EXTRA_RECORDS;
1 by brian
clean slate
224
    selected_records_file=0;
225
  }
226
  else
227
#endif
228
  {
1208.3.2 by brian
Update for Cursor renaming.
229
    records= table->cursor->estimate_rows_upper_bound();
1 by brian
clean slate
230
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
231
      If number of records is not known, use as much of sort buffer
232
      as possible.
1 by brian
clean slate
233
    */
234
    if (records == HA_POS_ERROR)
235
      records--;  // we use 'records+1' below.
236
    selected_records_file= 0;
237
  }
238
239
  if (multi_byte_charset &&
641.3.7 by Monty Taylor
More my_malloc removal.
240
      !(param.tmp_buffer= (char*) malloc(param.sort_length)))
1 by brian
clean slate
241
    goto err;
242
520.1.22 by Brian Aker
Second pass of thd cleanup
243
  memavl= session->variables.sortbuff_size;
1067.4.7 by Nathan Williams
The remaining files using cmax have been converted to std::max.
244
  min_sort_memory= max((uint32_t)MIN_SORT_MEMORY, param.sort_length*MERGEBUFF2);
1 by brian
clean slate
245
  while (memavl >= min_sort_memory)
246
  {
308 by Brian Aker
ulong conversion
247
    uint32_t old_memavl;
248
    uint32_t keys= memavl/(param.rec_length+sizeof(char*));
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
249
    param.keys= (uint32_t) min(records+1, (ha_rows)keys);
1 by brian
clean slate
250
    if ((table_sort.sort_keys=
481 by Brian Aker
Remove all of uchar.
251
	 (unsigned char **) make_char_array((char **) table_sort.sort_keys,
641.3.7 by Monty Taylor
More my_malloc removal.
252
                                            param.keys, param.rec_length)))
1 by brian
clean slate
253
      break;
1034.1.6 by Brian Aker
Increase the default sort buffer size.
254
    old_memavl= memavl;
255
    if ((memavl= memavl/4*3) < min_sort_memory && old_memavl > min_sort_memory)
1 by brian
clean slate
256
      memavl= min_sort_memory;
257
  }
258
  sort_keys= table_sort.sort_keys;
259
  if (memavl < min_sort_memory)
260
  {
261
    my_error(ER_OUT_OF_SORTMEMORY,MYF(ME_ERROR+ME_WAITTANG));
262
    goto err;
263
  }
1556.1.1 by Brian Aker
Updates for moving temporary directory.
264
  if (open_cached_file(&buffpek_pointers,drizzle_tmpdir.c_str(),TEMP_PREFIX,
1 by brian
clean slate
265
		       DISK_BUFFER_SIZE, MYF(MY_WME)))
266
    goto err;
267
268
  param.keys--;  			/* TODO: check why we do this */
269
  param.sort_form= table;
270
  param.end=(param.local_sortorder=sortorder)+s_length;
1578.4.11 by Brian Aker
PAss through the code removing current_session
271
  if ((records=find_all_keys(session, &param,select,sort_keys, &buffpek_pointers,
1 by brian
clean slate
272
			     &tempfile, selected_records_file)) ==
273
      HA_POS_ERROR)
274
    goto err;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
275
  maxbuffer= (uint32_t) (my_b_tell(&buffpek_pointers)/sizeof(*buffpek_inst));
1 by brian
clean slate
276
277
  if (maxbuffer == 0)			// The whole set is in memory
278
  {
438.1.13 by Brian Aker
uint cleanup.
279
    if (save_index(&param,sort_keys,(uint32_t) records, &table_sort))
1 by brian
clean slate
280
      goto err;
281
  }
282
  else
283
  {
284
    if (table_sort.buffpek && table_sort.buffpek_len < maxbuffer)
285
    {
460 by Monty Taylor
Removed x_free calls.
286
      if (table_sort.buffpek)
287
        free(table_sort.buffpek);
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
288
      table_sort.buffpek = 0;
1 by brian
clean slate
289
    }
290
    if (!(table_sort.buffpek=
481 by Brian Aker
Remove all of uchar.
291
          (unsigned char *) read_buffpek_from_file(&buffpek_pointers, maxbuffer,
1 by brian
clean slate
292
                                 table_sort.buffpek)))
293
      goto err;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
294
    buffpek_inst= (buffpek *) table_sort.buffpek;
1 by brian
clean slate
295
    table_sort.buffpek_len= maxbuffer;
296
    close_cached_file(&buffpek_pointers);
297
	/* Open cached file if it isn't open */
298
    if (! my_b_inited(outfile) &&
1556.1.1 by Brian Aker
Updates for moving temporary directory.
299
	open_cached_file(outfile,drizzle_tmpdir.c_str(),TEMP_PREFIX,READ_RECORD_BUFFER,
1 by brian
clean slate
300
			  MYF(MY_WME)))
301
      goto err;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
302
    if (reinit_io_cache(outfile,internal::WRITE_CACHE,0L,0,0))
1 by brian
clean slate
303
      goto err;
304
305
    /*
306
      Use also the space previously used by string pointers in sort_buffer
307
      for temporary key storage.
308
    */
309
    param.keys=((param.keys*(param.rec_length+sizeof(char*))) /
310
		param.rec_length-1);
311
    maxbuffer--;				// Offset from 0
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
312
    if (merge_many_buff(&param,(unsigned char*) sort_keys,buffpek_inst,&maxbuffer, &tempfile))
1 by brian
clean slate
313
      goto err;
314
    if (flush_io_cache(&tempfile) ||
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
315
	reinit_io_cache(&tempfile,internal::READ_CACHE,0L,0,0))
1 by brian
clean slate
316
      goto err;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
317
    if (merge_index(&param,(unsigned char*) sort_keys,buffpek_inst,maxbuffer,&tempfile, outfile))
1 by brian
clean slate
318
      goto err;
319
  }
320
  if (records > param.max_rows)
321
    records=param.max_rows;
322
  error =0;
323
324
 err:
325
  if (param.tmp_buffer)
460 by Monty Taylor
Removed x_free calls.
326
    if (param.tmp_buffer)
327
      free(param.tmp_buffer);
1 by brian
clean slate
328
  if (!subselect || !subselect->is_uncacheable())
329
  {
1510.3.3 by mordred
Fixed note from cppcheck - passing NULL to free is valid, so the check for non-null here is redundant. Also, casting to unsigned char * is pretty pointless.
330
    free(sort_keys);
1 by brian
clean slate
331
    table_sort.sort_keys= 0;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
332
    free(buffpek_inst);
1 by brian
clean slate
333
    table_sort.buffpek= 0;
334
    table_sort.buffpek_len= 0;
335
  }
336
  close_cached_file(&tempfile);
337
  close_cached_file(&buffpek_pointers);
338
  if (my_b_inited(outfile))
339
  {
340
    if (flush_io_cache(outfile))
341
      error=1;
342
    {
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
343
      internal::my_off_t save_pos=outfile->pos_in_file;
1 by brian
clean slate
344
      /* For following reads */
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
345
      if (reinit_io_cache(outfile,internal::READ_CACHE,0L,0,0))
1 by brian
clean slate
346
	error=1;
347
      outfile->end_of_file=save_pos;
348
    }
349
  }
350
  if (error)
1689.5.1 by Joseph Daly
remove increment calls
351
  {
1 by brian
clean slate
352
    my_message(ER_FILSORT_ABORT, ER(ER_FILSORT_ABORT),
353
               MYF(ME_ERROR+ME_WAITTANG));
1689.5.1 by Joseph Daly
remove increment calls
354
  }
1 by brian
clean slate
355
  else
1689.5.1 by Joseph Daly
remove increment calls
356
  {
357
    session->status_var.filesort_rows+= (uint32_t) records;
358
  }
1 by brian
clean slate
359
  *examined_rows= param.examined_rows;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
360
  memcpy(&table->sort, &table_sort, sizeof(filesort_info));
1126.10.9 by Padraig O'Sullivan
Added calls to the filesort dtrace probes.
361
  DRIZZLE_FILESORT_DONE(error, records);
362
  return (error ? HA_POS_ERROR : records);
1 by brian
clean slate
363
} /* filesort */
364
365
1109.1.4 by Brian Aker
More Table refactor
366
void Table::filesort_free_buffers(bool full)
1 by brian
clean slate
367
{
1109.1.4 by Brian Aker
More Table refactor
368
  if (sort.record_pointers)
1 by brian
clean slate
369
  {
1109.1.4 by Brian Aker
More Table refactor
370
    free((unsigned char*) sort.record_pointers);
371
    sort.record_pointers=0;
1 by brian
clean slate
372
  }
373
  if (full)
374
  {
1109.1.4 by Brian Aker
More Table refactor
375
    if (sort.sort_keys )
1 by brian
clean slate
376
    {
1109.1.4 by Brian Aker
More Table refactor
377
      if ((unsigned char*) sort.sort_keys)
378
        free((unsigned char*) sort.sort_keys);
379
      sort.sort_keys= 0;
1 by brian
clean slate
380
    }
1109.1.4 by Brian Aker
More Table refactor
381
    if (sort.buffpek)
1 by brian
clean slate
382
    {
1109.1.4 by Brian Aker
More Table refactor
383
      if ((unsigned char*) sort.buffpek)
384
        free((unsigned char*) sort.buffpek);
385
      sort.buffpek= 0;
386
      sort.buffpek_len= 0;
1 by brian
clean slate
387
    }
388
  }
1109.1.4 by Brian Aker
More Table refactor
389
  if (sort.addon_buf)
1 by brian
clean slate
390
  {
1109.1.4 by Brian Aker
More Table refactor
391
    free((char *) sort.addon_buf);
392
    free((char *) sort.addon_field);
393
    sort.addon_buf=0;
394
    sort.addon_field=0;
1 by brian
clean slate
395
  }
396
}
397
398
/** Make a array of string pointers. */
399
438.1.13 by Brian Aker
uint cleanup.
400
static char **make_char_array(char **old_pos, register uint32_t fields,
641.3.7 by Monty Taylor
More my_malloc removal.
401
                              uint32_t length)
1 by brian
clean slate
402
{
403
  register char **pos;
404
  char *char_pos;
405
406
  if (old_pos ||
641.3.9 by Monty Taylor
More removal of my_malloc.
407
      (old_pos= (char**) malloc((uint32_t) fields*(length+sizeof(char*)))))
1 by brian
clean slate
408
  {
409
    pos=old_pos; char_pos=((char*) (pos+fields)) -length;
410
    while (fields--) *(pos++) = (char_pos+= length);
411
  }
412
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
413
  return(old_pos);
1 by brian
clean slate
414
} /* make_char_array */
415
416
417
/** Read 'count' number of buffer pointers into memory. */
418
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
419
static unsigned char *read_buffpek_from_file(internal::IO_CACHE *buffpek_pointers, uint32_t count,
481 by Brian Aker
Remove all of uchar.
420
                                     unsigned char *buf)
1 by brian
clean slate
421
{
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
422
  uint32_t length= sizeof(buffpek)*count;
481 by Brian Aker
Remove all of uchar.
423
  unsigned char *tmp= buf;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
424
  if (count > UINT_MAX/sizeof(buffpek))
425
    return 0; /* sizeof(buffpek)*count will overflow */
1 by brian
clean slate
426
  if (!tmp)
641.3.7 by Monty Taylor
More my_malloc removal.
427
    tmp= (unsigned char *)malloc(length);
1 by brian
clean slate
428
  if (tmp)
429
  {
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
430
    if (reinit_io_cache(buffpek_pointers,internal::READ_CACHE,0L,0,0) ||
481 by Brian Aker
Remove all of uchar.
431
	my_b_read(buffpek_pointers, (unsigned char*) tmp, length))
1 by brian
clean slate
432
    {
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
433
      free((char*) tmp);
1 by brian
clean slate
434
      tmp=0;
435
    }
436
  }
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
437
  return(tmp);
1 by brian
clean slate
438
}
439
440
441
/**
442
  Search after sort_keys and write them into tempfile.
443
  All produced sequences are guaranteed to be non-empty.
444
445
  @param param             Sorting parameter
446
  @param select            Use this to get source data
447
  @param sort_keys         Array of pointers to sort key + addon buffers.
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
448
  @param buffpek_pointers  File to write buffpeks describing sorted segments
1 by brian
clean slate
449
                           in tempfile.
450
  @param tempfile          File to write sorted sequences of sortkeys to.
451
  @param indexfile         If !NULL, use it for source data (contains rowids)
452
453
  @note
454
    Basic idea:
455
    @verbatim
456
     while (get_next_sortkey())
457
     {
458
       if (no free space in sort_keys buffers)
459
       {
460
         sort sort_keys buffer;
461
         dump sorted sequence to 'tempfile';
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
462
         dump buffpek describing sequence location into 'buffpek_pointers';
1 by brian
clean slate
463
       }
464
       put sort key into 'sort_keys';
465
     }
466
     if (sort_keys has some elements && dumped at least once)
467
       sort-dump-dump as above;
468
     else
469
       don't sort, leave sort_keys array to be sorted by caller.
470
  @endverbatim
471
472
  @retval
473
    Number of records written on success.
474
  @retval
475
    HA_POS_ERROR on error.
476
*/
477
1578.4.11 by Brian Aker
PAss through the code removing current_session
478
static ha_rows find_all_keys(Session *session,
479
                             SORTPARAM *param, 
1237.13.3 by Padraig O'Sullivan
Performed numerous style cleanups in range.[cc,h].
480
                             optimizer::SqlSelect *select,
481 by Brian Aker
Remove all of uchar.
481
			     unsigned char **sort_keys,
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
482
			     internal::IO_CACHE *buffpek_pointers,
483
			     internal::IO_CACHE *tempfile, internal::IO_CACHE *indexfile)
1 by brian
clean slate
484
{
485
  int error,flag,quick_select;
438.1.13 by Brian Aker
uint cleanup.
486
  uint32_t idx,indexpos,ref_length;
481 by Brian Aker
Remove all of uchar.
487
  unsigned char *ref_pos,*next_pos,ref_buff[MAX_REFLENGTH];
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
488
  internal::my_off_t record;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
489
  Table *sort_form;
520.1.22 by Brian Aker
Second pass of thd cleanup
490
  volatile Session::killed_state *killed= &session->killed;
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
491
  Cursor *file;
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
492
  boost::dynamic_bitset<> *save_read_set= NULL;
493
  boost::dynamic_bitset<> *save_write_set= NULL;
1 by brian
clean slate
494
495
  idx=indexpos=0;
496
  error=quick_select=0;
497
  sort_form=param->sort_form;
1208.3.2 by brian
Update for Cursor renaming.
498
  file= sort_form->cursor;
1 by brian
clean slate
499
  ref_length=param->ref_length;
500
  ref_pos= ref_buff;
501
  quick_select=select && select->quick;
502
  record=0;
1220.2.1 by Brian Aker
Move cursor flags up to storage engine flags. These need to be merged.
503
  flag= ((!indexfile && ! file->isOrdered())
1 by brian
clean slate
504
	 || quick_select);
505
  if (indexfile || flag)
506
    ref_pos= &file->ref[0];
507
  next_pos=ref_pos;
508
  if (! indexfile && ! quick_select)
509
  {
481 by Brian Aker
Remove all of uchar.
510
    next_pos=(unsigned char*) 0;			/* Find records in sequence */
1491.1.10 by Jay Pipes
ha_rnd_init -> startTableScan, rnd_init -> doStartTableScan, ha_rnd_end -> endTableScan, rnd_end -> doEndTableScan
511
    file->startTableScan(1);
1 by brian
clean slate
512
    file->extra_opt(HA_EXTRA_CACHE,
1578.4.11 by Brian Aker
PAss through the code removing current_session
513
		    session->variables.read_buff_size);
1 by brian
clean slate
514
  }
515
1538 by Brian Aker
Code shuffle on ReadRecord
516
  ReadRecord read_record_info;
1 by brian
clean slate
517
  if (quick_select)
518
  {
519
    if (select->quick->reset())
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
520
      return(HA_POS_ERROR);
1538 by Brian Aker
Code shuffle on ReadRecord
521
1578.4.11 by Brian Aker
PAss through the code removing current_session
522
    read_record_info.init_read_record(session, select->quick->head, select, 1, 1);
1 by brian
clean slate
523
  }
524
525
  /* Remember original bitmaps */
526
  save_read_set=  sort_form->read_set;
527
  save_write_set= sort_form->write_set;
528
  /* Set up temporary column read map for columns used by sort */
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
529
  sort_form->tmp_set.reset();
1 by brian
clean slate
530
  /* Temporary set for register_used_fields and register_field_in_read_map */
531
  sort_form->read_set= &sort_form->tmp_set;
532
  register_used_fields(param);
533
  if (select && select->cond)
534
    select->cond->walk(&Item::register_field_in_read_map, 1,
481 by Brian Aker
Remove all of uchar.
535
                       (unsigned char*) sort_form);
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
536
  sort_form->column_bitmaps_set(sort_form->tmp_set, sort_form->tmp_set);
1 by brian
clean slate
537
538
  for (;;)
539
  {
540
    if (quick_select)
541
    {
542
      if ((error= read_record_info.read_record(&read_record_info)))
543
      {
544
        error= HA_ERR_END_OF_FILE;
545
        break;
546
      }
1672.3.6 by Brian Aker
First pass in encapsulating row
547
      file->position(sort_form->getInsertRecord());
1 by brian
clean slate
548
    }
549
    else					/* Not quick-select */
550
    {
551
      if (indexfile)
552
      {
971.6.11 by Eric Day
Removed purecov messages.
553
	if (my_b_read(indexfile,(unsigned char*) ref_pos,ref_length))
1 by brian
clean slate
554
	{
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
555
	  error= errno ? errno : -1;		/* Abort */
1 by brian
clean slate
556
	  break;
557
	}
1672.3.6 by Brian Aker
First pass in encapsulating row
558
	error=file->rnd_pos(sort_form->getInsertRecord(),next_pos);
1 by brian
clean slate
559
      }
560
      else
561
      {
1672.3.6 by Brian Aker
First pass in encapsulating row
562
	error=file->rnd_next(sort_form->getInsertRecord());
383.7.1 by Andrey Zhakov
Initial submit of code and tests
563
1 by brian
clean slate
564
	if (!flag)
565
	{
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
566
	  internal::my_store_ptr(ref_pos,ref_length,record); // Position to row
1532.1.15 by Brian Aker
Partial encapsulation of TableShare from Table.
567
	  record+= sort_form->getShare()->db_record_offset;
1 by brian
clean slate
568
	}
569
	else if (!error)
1672.3.6 by Brian Aker
First pass in encapsulating row
570
	  file->position(sort_form->getInsertRecord());
1 by brian
clean slate
571
      }
572
      if (error && error != HA_ERR_RECORD_DELETED)
573
	break;
574
    }
575
576
    if (*killed)
577
    {
578
      if (!indexfile && !quick_select)
579
      {
580
        (void) file->extra(HA_EXTRA_NO_CACHE);
1491.1.10 by Jay Pipes
ha_rnd_init -> startTableScan, rnd_init -> doStartTableScan, ha_rnd_end -> endTableScan, rnd_end -> doEndTableScan
581
        file->endTableScan();
1 by brian
clean slate
582
      }
971.6.11 by Eric Day
Removed purecov messages.
583
      return(HA_POS_ERROR);
1 by brian
clean slate
584
    }
585
    if (error == 0)
586
      param->examined_rows++;
587
    if (error == 0 && (!select || select->skip_record() == 0))
588
    {
589
      if (idx == param->keys)
590
      {
591
	if (write_keys(param,sort_keys,idx,buffpek_pointers,tempfile))
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
592
	  return(HA_POS_ERROR);
1 by brian
clean slate
593
	idx=0;
594
	indexpos++;
595
      }
596
      make_sortkey(param,sort_keys[idx++],ref_pos);
597
    }
598
    else
599
      file->unlock_row();
600
    /* It does not make sense to read more keys in case of a fatal error */
520.1.22 by Brian Aker
Second pass of thd cleanup
601
    if (session->is_error())
1 by brian
clean slate
602
      break;
603
  }
604
  if (quick_select)
605
  {
606
    /*
607
      index_merge quick select uses table->sort when retrieving rows, so free
608
      resoures it has allocated.
609
    */
1538 by Brian Aker
Code shuffle on ReadRecord
610
    read_record_info.end_read_record();
1 by brian
clean slate
611
  }
612
  else
613
  {
614
    (void) file->extra(HA_EXTRA_NO_CACHE);	/* End cacheing of records */
615
    if (!next_pos)
1491.1.10 by Jay Pipes
ha_rnd_init -> startTableScan, rnd_init -> doStartTableScan, ha_rnd_end -> endTableScan, rnd_end -> doEndTableScan
616
      file->endTableScan();
1 by brian
clean slate
617
  }
618
520.1.22 by Brian Aker
Second pass of thd cleanup
619
  if (session->is_error())
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
620
    return(HA_POS_ERROR);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
621
1 by brian
clean slate
622
  /* Signal we should use orignal column read and write maps */
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
623
  sort_form->column_bitmaps_set(*save_read_set, *save_write_set);
1 by brian
clean slate
624
625
  if (error != HA_ERR_END_OF_FILE)
626
  {
1216.1.1 by Brian Aker
Move print_error up to Engine.
627
    sort_form->print_error(error,MYF(ME_ERROR | ME_WAITTANG));
971.6.11 by Eric Day
Removed purecov messages.
628
    return(HA_POS_ERROR);
1 by brian
clean slate
629
  }
630
  if (indexpos && idx &&
631
      write_keys(param,sort_keys,idx,buffpek_pointers,tempfile))
971.6.11 by Eric Day
Removed purecov messages.
632
    return(HA_POS_ERROR);
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
633
  return(my_b_inited(tempfile) ?
1 by brian
clean slate
634
	      (ha_rows) (my_b_tell(tempfile)/param->rec_length) :
635
	      idx);
636
} /* find_all_keys */
637
638
639
/**
640
  @details
641
  Sort the buffer and write:
642
  -# the sorted sequence to tempfile
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
643
  -# a buffpek describing the sorted sequence position to buffpek_pointers
1 by brian
clean slate
644
645
    (was: Skriver en buffert med nycklar till filen)
646
647
  @param param             Sort parameters
648
  @param sort_keys         Array of pointers to keys to sort
649
  @param count             Number of elements in sort_keys array
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
650
  @param buffpek_pointers  One 'buffpek' struct will be written into this file.
651
                           The buffpek::{file_pos, count} will indicate where
1 by brian
clean slate
652
                           the sorted data was stored.
653
  @param tempfile          The sorted sequence will be written into this file.
654
655
  @retval
656
    0 OK
657
  @retval
658
    1 Error
659
*/
660
661
static int
481 by Brian Aker
Remove all of uchar.
662
write_keys(SORTPARAM *param, register unsigned char **sort_keys, uint32_t count,
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
663
           internal::IO_CACHE *buffpek_pointers, internal::IO_CACHE *tempfile)
1 by brian
clean slate
664
{
665
  size_t sort_length, rec_length;
481 by Brian Aker
Remove all of uchar.
666
  unsigned char **end;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
667
  buffpek buffpek;
1 by brian
clean slate
668
669
  sort_length= param->sort_length;
670
  rec_length= param->rec_length;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
671
  internal::my_string_ptr_sort((unsigned char*) sort_keys, (uint32_t) count, sort_length);
1 by brian
clean slate
672
  if (!my_b_inited(tempfile) &&
1556.1.1 by Brian Aker
Updates for moving temporary directory.
673
      open_cached_file(tempfile, drizzle_tmpdir.c_str(), TEMP_PREFIX, DISK_BUFFER_SIZE,
1 by brian
clean slate
674
                       MYF(MY_WME)))
971.6.11 by Eric Day
Removed purecov messages.
675
    goto err;
1 by brian
clean slate
676
  /* check we won't have more buffpeks than we can possibly keep in memory */
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
677
  if (my_b_tell(buffpek_pointers) + sizeof(buffpek) > (uint64_t)UINT_MAX)
1 by brian
clean slate
678
    goto err;
679
  buffpek.file_pos= my_b_tell(tempfile);
680
  if ((ha_rows) count > param->max_rows)
971.6.11 by Eric Day
Removed purecov messages.
681
    count=(uint32_t) param->max_rows;
1 by brian
clean slate
682
  buffpek.count=(ha_rows) count;
683
  for (end=sort_keys+count ; sort_keys != end ; sort_keys++)
481 by Brian Aker
Remove all of uchar.
684
    if (my_b_write(tempfile, (unsigned char*) *sort_keys, (uint32_t) rec_length))
1 by brian
clean slate
685
      goto err;
481 by Brian Aker
Remove all of uchar.
686
  if (my_b_write(buffpek_pointers, (unsigned char*) &buffpek, sizeof(buffpek)))
1 by brian
clean slate
687
    goto err;
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
688
  return(0);
1 by brian
clean slate
689
690
err:
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
691
  return(1);
1 by brian
clean slate
692
} /* write_keys */
693
694
695
/**
696
  Store length as suffix in high-byte-first order.
697
*/
698
481 by Brian Aker
Remove all of uchar.
699
static inline void store_length(unsigned char *to, uint32_t length, uint32_t pack_length)
1 by brian
clean slate
700
{
701
  switch (pack_length) {
702
  case 1:
481 by Brian Aker
Remove all of uchar.
703
    *to= (unsigned char) length;
1 by brian
clean slate
704
    break;
705
  case 2:
706
    mi_int2store(to, length);
707
    break;
708
  case 3:
709
    mi_int3store(to, length);
710
    break;
711
  default:
712
    mi_int4store(to, length);
713
    break;
714
  }
715
}
716
717
718
/** Make a sort-key from record. */
719
720
static void make_sortkey(register SORTPARAM *param,
481 by Brian Aker
Remove all of uchar.
721
			 register unsigned char *to, unsigned char *ref_pos)
1 by brian
clean slate
722
{
1711.6.1 by Brian Aker
Style on structure cleanup
723
  Field *field;
724
  SortField *sort_field;
937.2.7 by Stewart Smith
typesafe set_if_smaller/set_if_greater fixes from Solaris
725
  size_t length;
1 by brian
clean slate
726
727
  for (sort_field=param->local_sortorder ;
728
       sort_field != param->end ;
729
       sort_field++)
730
  {
731
    bool maybe_null=0;
732
    if ((field=sort_field->field))
733
    {						// Field
734
      if (field->maybe_null())
735
      {
736
	if (field->is_null())
737
	{
738
	  if (sort_field->reverse)
212.6.3 by Mats Kindahl
Removing deprecated functions from code and replacing them with C99 equivalents:
739
	    memset(to, 255, sort_field->length+1);
1 by brian
clean slate
740
	  else
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
741
	    memset(to, 0, sort_field->length+1);
1 by brian
clean slate
742
	  to+= sort_field->length+1;
743
	  continue;
744
	}
745
	else
746
	  *to++=1;
747
      }
748
      field->sort_string(to, sort_field->length);
749
    }
750
    else
751
    {						// Item
752
      Item *item=sort_field->item;
753
      maybe_null= item->maybe_null;
754
      switch (sort_field->result_type) {
755
      case STRING_RESULT:
756
      {
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
757
        const CHARSET_INFO * const cs=item->collation.collation;
1 by brian
clean slate
758
        char fill_char= ((cs->state & MY_CS_BINSORT) ? (char) 0 : ' ');
759
        int diff;
438.1.13 by Brian Aker
uint cleanup.
760
        uint32_t sort_field_length;
1 by brian
clean slate
761
762
        if (maybe_null)
763
          *to++=1;
764
        /* All item->str() to use some extra byte for end null.. */
765
        String tmp((char*) to,sort_field->length+4,cs);
766
        String *res= item->str_result(&tmp);
767
        if (!res)
768
        {
769
          if (maybe_null)
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
770
            memset(to-1, 0, sort_field->length+1);
1 by brian
clean slate
771
          else
772
          {
773
            /*
774
              This should only happen during extreme conditions if we run out
775
              of memory or have an item marked not null when it can be null.
776
              This code is here mainly to avoid a hard crash in this case.
777
            */
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
778
            assert(0);
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
779
            memset(to, 0, sort_field->length);	// Avoid crash
1 by brian
clean slate
780
          }
781
          break;
782
        }
783
        length= res->length();
784
        sort_field_length= sort_field->length - sort_field->suffix_length;
785
        diff=(int) (sort_field_length - length);
786
        if (diff < 0)
787
        {
788
          diff=0;
789
          length= sort_field_length;
790
        }
791
        if (sort_field->suffix_length)
792
        {
793
          /* Store length last in result_string */
794
          store_length(to + sort_field_length, length,
795
                       sort_field->suffix_length);
796
        }
797
        if (sort_field->need_strxnfrm)
798
        {
799
          char *from=(char*) res->ptr();
438.1.13 by Brian Aker
uint cleanup.
800
          uint32_t tmp_length;
481 by Brian Aker
Remove all of uchar.
801
          if ((unsigned char*) from == to)
1 by brian
clean slate
802
          {
803
            set_if_smaller(length,sort_field->length);
804
            memcpy(param->tmp_buffer,from,length);
805
            from=param->tmp_buffer;
806
          }
807
          tmp_length= my_strnxfrm(cs,to,sort_field->length,
481 by Brian Aker
Remove all of uchar.
808
                                  (unsigned char*) from, length);
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
809
          assert(tmp_length == sort_field->length);
1 by brian
clean slate
810
        }
811
        else
812
        {
481 by Brian Aker
Remove all of uchar.
813
          my_strnxfrm(cs,(unsigned char*)to,length,(const unsigned char*)res->ptr(),length);
1 by brian
clean slate
814
          cs->cset->fill(cs, (char *)to+length,diff,fill_char);
815
        }
816
        break;
817
      }
818
      case INT_RESULT:
819
	{
152 by Brian Aker
longlong replacement
820
          int64_t value= item->val_int_result();
1 by brian
clean slate
821
          if (maybe_null)
822
          {
971.6.11 by Eric Day
Removed purecov messages.
823
	    *to++=1;
1 by brian
clean slate
824
            if (item->null_value)
825
            {
826
              if (maybe_null)
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
827
                memset(to-1, 0, sort_field->length+1);
1 by brian
clean slate
828
              else
829
              {
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
830
                memset(to, 0, sort_field->length);
1 by brian
clean slate
831
              }
832
              break;
833
            }
834
          }
481 by Brian Aker
Remove all of uchar.
835
	  to[7]= (unsigned char) value;
836
	  to[6]= (unsigned char) (value >> 8);
837
	  to[5]= (unsigned char) (value >> 16);
838
	  to[4]= (unsigned char) (value >> 24);
839
	  to[3]= (unsigned char) (value >> 32);
840
	  to[2]= (unsigned char) (value >> 40);
841
	  to[1]= (unsigned char) (value >> 48);
1 by brian
clean slate
842
          if (item->unsigned_flag)                    /* Fix sign */
481 by Brian Aker
Remove all of uchar.
843
            to[0]= (unsigned char) (value >> 56);
1 by brian
clean slate
844
          else
481 by Brian Aker
Remove all of uchar.
845
            to[0]= (unsigned char) (value >> 56) ^ 128;	/* Reverse signbit */
1 by brian
clean slate
846
	  break;
847
	}
848
      case DECIMAL_RESULT:
849
        {
850
          my_decimal dec_buf, *dec_val= item->val_decimal_result(&dec_buf);
851
          if (maybe_null)
852
          {
853
            if (item->null_value)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
854
            {
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
855
              memset(to, 0, sort_field->length+1);
1 by brian
clean slate
856
              to++;
857
              break;
858
            }
859
            *to++=1;
860
          }
861
          my_decimal2binary(E_DEC_FATAL_ERROR, dec_val, to,
862
                            item->max_length - (item->decimals ? 1:0),
863
                            item->decimals);
864
         break;
865
        }
866
      case REAL_RESULT:
867
	{
868
          double value= item->val_result();
869
	  if (maybe_null)
870
          {
871
            if (item->null_value)
872
            {
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
873
              memset(to, 0, sort_field->length+1);
1 by brian
clean slate
874
              to++;
875
              break;
876
            }
877
	    *to++=1;
878
          }
481 by Brian Aker
Remove all of uchar.
879
	  change_double_for_sort(value,(unsigned char*) to);
1 by brian
clean slate
880
	  break;
881
	}
882
      case ROW_RESULT:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
883
      default:
1 by brian
clean slate
884
	// This case should never be choosen
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
885
	assert(0);
1 by brian
clean slate
886
	break;
887
      }
888
    }
889
    if (sort_field->reverse)
890
    {							/* Revers key */
891
      if (maybe_null)
892
        to[-1]= ~to[-1];
893
      length=sort_field->length;
894
      while (length--)
895
      {
481 by Brian Aker
Remove all of uchar.
896
	*to = (unsigned char) (~ *to);
1 by brian
clean slate
897
	to++;
898
      }
899
    }
900
    else
901
      to+= sort_field->length;
902
  }
903
904
  if (param->addon_field)
905
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
906
    /*
1 by brian
clean slate
907
      Save field values appended to sorted fields.
908
      First null bit indicators are appended then field values follow.
909
      In this implementation we use fixed layout for field values -
910
      the same for all records.
911
    */
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
912
    sort_addon_field *addonf= param->addon_field;
481 by Brian Aker
Remove all of uchar.
913
    unsigned char *nulls= to;
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
914
    assert(addonf != 0);
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
915
    memset(nulls, 0, addonf->offset);
1 by brian
clean slate
916
    to+= addonf->offset;
917
    for ( ; (field= addonf->field) ; addonf++)
918
    {
919
      if (addonf->null_bit && field->is_null())
920
      {
921
        nulls[addonf->null_offset]|= addonf->null_bit;
922
#ifdef HAVE_purify
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
923
	memset(to, 0, addonf->length);
1 by brian
clean slate
924
#endif
925
      }
926
      else
927
      {
928
#ifdef HAVE_purify
481 by Brian Aker
Remove all of uchar.
929
        unsigned char *end= field->pack(to, field->ptr);
438.1.13 by Brian Aker
uint cleanup.
930
	uint32_t length= (uint32_t) ((to + addonf->length) - end);
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
931
	assert((int) length >= 0);
1 by brian
clean slate
932
	if (length)
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
933
	  memset(end, 0, length);
1 by brian
clean slate
934
#else
935
        (void) field->pack(to, field->ptr);
936
#endif
937
      }
938
      to+= addonf->length;
939
    }
940
  }
941
  else
942
  {
943
    /* Save filepos last */
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
944
    memcpy(to, ref_pos, (size_t) param->ref_length);
1 by brian
clean slate
945
  }
946
  return;
947
}
948
949
950
/*
951
  Register fields used by sorting in the sorted table's read set
952
*/
953
954
static void register_used_fields(SORTPARAM *param)
955
{
1711.6.1 by Brian Aker
Style on structure cleanup
956
  SortField *sort_field;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
957
  Table *table=param->sort_form;
1 by brian
clean slate
958
959
  for (sort_field= param->local_sortorder ;
960
       sort_field != param->end ;
961
       sort_field++)
962
  {
963
    Field *field;
964
    if ((field= sort_field->field))
965
    {
1660.1.3 by Brian Aker
Encapsulate Table in field
966
      if (field->getTable() == table)
1005.2.12 by Monty Taylor
Moved some things to the API.
967
        table->setReadSet(field->field_index);
1 by brian
clean slate
968
    }
969
    else
970
    {						// Item
971
      sort_field->item->walk(&Item::register_field_in_read_map, 1,
481 by Brian Aker
Remove all of uchar.
972
                             (unsigned char *) table);
1 by brian
clean slate
973
    }
974
  }
975
976
  if (param->addon_field)
977
  {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
978
    sort_addon_field *addonf= param->addon_field;
1 by brian
clean slate
979
    Field *field;
980
    for ( ; (field= addonf->field) ; addonf++)
1005.2.12 by Monty Taylor
Moved some things to the API.
981
      table->setReadSet(field->field_index);
1 by brian
clean slate
982
  }
983
  else
984
  {
985
    /* Save filepos last */
986
    table->prepare_for_position();
987
  }
988
}
989
990
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
991
static bool save_index(SORTPARAM *param, unsigned char **sort_keys, uint32_t count,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
992
                       filesort_info *table_sort)
1 by brian
clean slate
993
{
438.1.13 by Brian Aker
uint cleanup.
994
  uint32_t offset,res_length;
481 by Brian Aker
Remove all of uchar.
995
  unsigned char *to;
1 by brian
clean slate
996
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
997
  internal::my_string_ptr_sort((unsigned char*) sort_keys, (uint32_t) count, param->sort_length);
1 by brian
clean slate
998
  res_length= param->res_length;
999
  offset= param->rec_length-res_length;
1000
  if ((ha_rows) count > param->max_rows)
438.1.13 by Brian Aker
uint cleanup.
1001
    count=(uint32_t) param->max_rows;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1002
  if (!(to= table_sort->record_pointers=
641.3.7 by Monty Taylor
More my_malloc removal.
1003
        (unsigned char*) malloc(res_length*count)))
971.6.11 by Eric Day
Removed purecov messages.
1004
    return(1);
481 by Brian Aker
Remove all of uchar.
1005
  for (unsigned char **end= sort_keys+count ; sort_keys != end ; sort_keys++)
1 by brian
clean slate
1006
  {
1007
    memcpy(to, *sort_keys+offset, res_length);
1008
    to+= res_length;
1009
  }
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
1010
  return(0);
1 by brian
clean slate
1011
}
1012
1013
1014
/** Merge buffers to make < MERGEBUFF2 buffers. */
1015
481 by Brian Aker
Remove all of uchar.
1016
int merge_many_buff(SORTPARAM *param, unsigned char *sort_buffer,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1017
		    buffpek *buffpek_inst, uint32_t *maxbuffer, internal::IO_CACHE *t_file)
1 by brian
clean slate
1018
{
438.1.13 by Brian Aker
uint cleanup.
1019
  register uint32_t i;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1020
  internal::IO_CACHE t_file2,*from_file,*to_file,*temp;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1021
  buffpek *lastbuff;
1 by brian
clean slate
1022
1023
  if (*maxbuffer < MERGEBUFF2)
971.6.11 by Eric Day
Removed purecov messages.
1024
    return(0);
1 by brian
clean slate
1025
  if (flush_io_cache(t_file) ||
1556.1.1 by Brian Aker
Updates for moving temporary directory.
1026
      open_cached_file(&t_file2,drizzle_tmpdir.c_str(),TEMP_PREFIX,DISK_BUFFER_SIZE,
1 by brian
clean slate
1027
			MYF(MY_WME)))
971.6.11 by Eric Day
Removed purecov messages.
1028
    return(1);
1 by brian
clean slate
1029
1030
  from_file= t_file ; to_file= &t_file2;
1031
  while (*maxbuffer >= MERGEBUFF2)
1032
  {
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1033
    if (reinit_io_cache(from_file,internal::READ_CACHE,0L,0,0))
1 by brian
clean slate
1034
      goto cleanup;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1035
    if (reinit_io_cache(to_file,internal::WRITE_CACHE,0L,0,0))
1 by brian
clean slate
1036
      goto cleanup;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1037
    lastbuff=buffpek_inst;
1 by brian
clean slate
1038
    for (i=0 ; i <= *maxbuffer-MERGEBUFF*3/2 ; i+=MERGEBUFF)
1039
    {
1040
      if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1041
			buffpek_inst+i,buffpek_inst+i+MERGEBUFF-1,0))
1 by brian
clean slate
1042
      goto cleanup;
1043
    }
1044
    if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1045
		      buffpek_inst+i,buffpek_inst+ *maxbuffer,0))
971.6.11 by Eric Day
Removed purecov messages.
1046
      break;
1 by brian
clean slate
1047
    if (flush_io_cache(to_file))
971.6.11 by Eric Day
Removed purecov messages.
1048
      break;
1 by brian
clean slate
1049
    temp=from_file; from_file=to_file; to_file=temp;
1050
    setup_io_cache(from_file);
1051
    setup_io_cache(to_file);
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1052
    *maxbuffer= (uint32_t) (lastbuff-buffpek_inst)-1;
1 by brian
clean slate
1053
  }
1054
cleanup:
1055
  close_cached_file(to_file);			// This holds old result
1056
  if (to_file == t_file)
1057
  {
1058
    *t_file=t_file2;				// Copy result file
1059
    setup_io_cache(t_file);
1060
  }
1061
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
1062
  return(*maxbuffer >= MERGEBUFF2);	/* Return 1 if interrupted */
1 by brian
clean slate
1063
} /* merge_many_buff */
1064
1065
1066
/**
1067
  Read data to buffer.
1068
1069
  @retval
438.1.13 by Brian Aker
uint cleanup.
1070
    (uint32_t)-1 if something goes wrong
1 by brian
clean slate
1071
*/
1072
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1073
uint32_t read_to_buffer(internal::IO_CACHE *fromfile, buffpek *buffpek_inst,
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
1074
                        uint32_t rec_length)
1 by brian
clean slate
1075
{
438.1.13 by Brian Aker
uint cleanup.
1076
  register uint32_t count;
1077
  uint32_t length;
1 by brian
clean slate
1078
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1079
  if ((count= (uint32_t) min((ha_rows) buffpek_inst->max_keys,buffpek_inst->count)))
1 by brian
clean slate
1080
  {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1081
    if (pread(fromfile->file,(unsigned char*) buffpek_inst->base, (length= rec_length*count),buffpek_inst->file_pos) == 0)
971.6.11 by Eric Day
Removed purecov messages.
1082
      return((uint32_t) -1);
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
1083
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1084
    buffpek_inst->key= buffpek_inst->base;
1085
    buffpek_inst->file_pos+= length;			/* New filepos */
1086
    buffpek_inst->count-= count;
1087
    buffpek_inst->mem_count= count;
1 by brian
clean slate
1088
  }
1089
  return (count*rec_length);
1090
} /* read_to_buffer */
1091
1092
897.1.11 by Padraig
Giving function object a better name for this scenario.
1093
class compare_functor
897.1.5 by Padraig
Replacing the instance of QUEUE in the merge_buffers() function in
1094
{
897.1.6 by Padraig
Cleaning up merge_buffers() function a little bit.
1095
  qsort2_cmp key_compare;
897.1.5 by Padraig
Replacing the instance of QUEUE in the merge_buffers() function in
1096
  void *key_compare_arg;
1097
  public:
897.1.11 by Padraig
Giving function object a better name for this scenario.
1098
  compare_functor(qsort2_cmp in_key_compare, void *in_compare_arg)
897.1.6 by Padraig
Cleaning up merge_buffers() function a little bit.
1099
    : key_compare(in_key_compare), key_compare_arg(in_compare_arg) { }
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1100
  inline bool operator()(const buffpek *i, const buffpek *j) const
897.1.5 by Padraig
Replacing the instance of QUEUE in the merge_buffers() function in
1101
  {
897.1.16 by Padraig O'Sullivan
Cleaning up my function object. Making it const correct and putting
1102
    int val= key_compare(key_compare_arg,
1103
                      &i->key, &j->key);
897.1.18 by Padraig O'Sullivan
Cleaning up my function object a little bit.
1104
    return (val >= 0);
897.1.5 by Padraig
Replacing the instance of QUEUE in the merge_buffers() function in
1105
  }
1106
};
1107
1 by brian
clean slate
1108
1109
/**
1110
  Merge buffers to one buffer.
1111
1112
  @param param        Sort parameter
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1113
  @param from_file    File with source data (buffpeks point to this file)
1 by brian
clean slate
1114
  @param to_file      File to write the sorted result data.
1115
  @param sort_buffer  Buffer for data to store up to MERGEBUFF2 sort keys.
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1116
  @param lastbuff     OUT Store here buffpek describing data written to to_file
1117
  @param Fb           First element in source buffpeks array
1118
  @param Tb           Last element in source buffpeks array
1 by brian
clean slate
1119
  @param flag
1120
1121
  @retval
1122
    0      OK
1123
  @retval
1124
    other  error
1125
*/
1126
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1127
int merge_buffers(SORTPARAM *param, internal::IO_CACHE *from_file,
1128
                  internal::IO_CACHE *to_file, unsigned char *sort_buffer,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1129
                  buffpek *lastbuff, buffpek *Fb, buffpek *Tb,
1 by brian
clean slate
1130
                  int flag)
1131
{
1132
  int error;
438.1.13 by Brian Aker
uint cleanup.
1133
  uint32_t rec_length,res_length,offset;
1 by brian
clean slate
1134
  size_t sort_length;
308 by Brian Aker
ulong conversion
1135
  uint32_t maxcount;
1 by brian
clean slate
1136
  ha_rows max_rows,org_max_rows;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1137
  internal::my_off_t to_start_filepos;
481 by Brian Aker
Remove all of uchar.
1138
  unsigned char *strpos;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1139
  buffpek *buffpek_inst;
1 by brian
clean slate
1140
  qsort2_cmp cmp;
1141
  void *first_cmp_arg;
520.1.22 by Brian Aker
Second pass of thd cleanup
1142
  volatile Session::killed_state *killed= &current_session->killed;
520.1.21 by Brian Aker
THD -> Session rename
1143
  Session::killed_state not_killable;
1 by brian
clean slate
1144
1689.5.1 by Joseph Daly
remove increment calls
1145
  current_session->status_var.filesort_merge_passes++;
1 by brian
clean slate
1146
  if (param->not_killable)
1147
  {
1148
    killed= &not_killable;
520.1.21 by Brian Aker
THD -> Session rename
1149
    not_killable= Session::NOT_KILLED;
1 by brian
clean slate
1150
  }
1151
1152
  error=0;
1153
  rec_length= param->rec_length;
1154
  res_length= param->res_length;
1155
  sort_length= param->sort_length;
1156
  offset= rec_length-res_length;
438.1.13 by Brian Aker
uint cleanup.
1157
  maxcount= (uint32_t) (param->keys/((uint32_t) (Tb-Fb) +1));
1 by brian
clean slate
1158
  to_start_filepos= my_b_tell(to_file);
481 by Brian Aker
Remove all of uchar.
1159
  strpos= (unsigned char*) sort_buffer;
1 by brian
clean slate
1160
  org_max_rows=max_rows= param->max_rows;
1161
1162
  /* The following will fire if there is not enough space in sort_buffer */
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
1163
  assert(maxcount!=0);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1164
1 by brian
clean slate
1165
  if (param->unique_buff)
1166
  {
1167
    cmp= param->compare;
1168
    first_cmp_arg= (void *) &param->cmp_context;
1169
  }
1170
  else
1171
  {
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1172
    cmp= internal::get_ptr_compare(sort_length);
1 by brian
clean slate
1173
    first_cmp_arg= (void*) &sort_length;
1174
  }
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1175
  priority_queue<buffpek *, vector<buffpek *>, compare_functor >
897.1.11 by Padraig
Giving function object a better name for this scenario.
1176
    queue(compare_functor(cmp, first_cmp_arg));
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1177
  for (buffpek_inst= Fb ; buffpek_inst <= Tb ; buffpek_inst++)
1 by brian
clean slate
1178
  {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1179
    buffpek_inst->base= strpos;
1180
    buffpek_inst->max_keys= maxcount;
1181
    strpos+= (uint32_t) (error= (int) read_to_buffer(from_file, buffpek_inst,
1 by brian
clean slate
1182
                                                                         rec_length));
1183
    if (error == -1)
971.6.11 by Eric Day
Removed purecov messages.
1184
      goto err;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1185
    buffpek_inst->max_keys= buffpek_inst->mem_count;	// If less data in buffers than expected
1186
    queue.push(buffpek_inst);
1 by brian
clean slate
1187
  }
1188
1189
  if (param->unique_buff)
1190
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1191
    /*
1 by brian
clean slate
1192
       Called by Unique::get()
1193
       Copy the first argument to param->unique_buff for unique removal.
1194
       Store it also in 'to_file'.
1195
1196
       This is safe as we know that there is always more than one element
1197
       in each block to merge (This is guaranteed by the Unique:: algorithm
1198
    */
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1199
    buffpek_inst= queue.top();
1200
    memcpy(param->unique_buff, buffpek_inst->key, rec_length);
1201
    if (my_b_write(to_file, (unsigned char*) buffpek_inst->key, rec_length))
1 by brian
clean slate
1202
    {
971.6.11 by Eric Day
Removed purecov messages.
1203
      error=1; goto err;
1 by brian
clean slate
1204
    }
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1205
    buffpek_inst->key+= rec_length;
1206
    buffpek_inst->mem_count--;
1 by brian
clean slate
1207
    if (!--max_rows)
1208
    {
971.6.11 by Eric Day
Removed purecov messages.
1209
      error= 0;
1210
      goto end;
1 by brian
clean slate
1211
    }
897.1.5 by Padraig
Replacing the instance of QUEUE in the merge_buffers() function in
1212
    /* Top element has been used */
1213
    queue.pop();
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1214
    queue.push(buffpek_inst);
1 by brian
clean slate
1215
  }
1216
  else
1217
    cmp= 0;                                        // Not unique
1218
897.1.6 by Padraig
Cleaning up merge_buffers() function a little bit.
1219
  while (queue.size() > 1)
1 by brian
clean slate
1220
  {
1221
    if (*killed)
1222
    {
971.6.11 by Eric Day
Removed purecov messages.
1223
      error= 1; goto err;
1 by brian
clean slate
1224
    }
1225
    for (;;)
1226
    {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1227
      buffpek_inst= queue.top();
1 by brian
clean slate
1228
      if (cmp)                                        // Remove duplicates
1229
      {
1230
        if (!(*cmp)(first_cmp_arg, &(param->unique_buff),
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1231
                    (unsigned char**) &buffpek_inst->key))
1 by brian
clean slate
1232
              goto skip_duplicate;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1233
            memcpy(param->unique_buff, buffpek_inst->key, rec_length);
1 by brian
clean slate
1234
      }
1235
      if (flag == 0)
1236
      {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1237
        if (my_b_write(to_file,(unsigned char*) buffpek_inst->key, rec_length))
1 by brian
clean slate
1238
        {
971.6.11 by Eric Day
Removed purecov messages.
1239
          error=1; goto err;
1 by brian
clean slate
1240
        }
1241
      }
1242
      else
1243
      {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1244
        if (my_b_write(to_file, (unsigned char*) buffpek_inst->key+offset, res_length))
1 by brian
clean slate
1245
        {
971.6.11 by Eric Day
Removed purecov messages.
1246
          error=1; goto err;
1 by brian
clean slate
1247
        }
1248
      }
1249
      if (!--max_rows)
1250
      {
971.6.11 by Eric Day
Removed purecov messages.
1251
        error= 0;
1252
        goto end;
1 by brian
clean slate
1253
      }
1254
1255
    skip_duplicate:
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1256
      buffpek_inst->key+= rec_length;
1257
      if (! --buffpek_inst->mem_count)
1 by brian
clean slate
1258
      {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1259
        if (!(error= (int) read_to_buffer(from_file,buffpek_inst,
1 by brian
clean slate
1260
                                          rec_length)))
1261
        {
897.1.5 by Padraig
Replacing the instance of QUEUE in the merge_buffers() function in
1262
          queue.pop();
1 by brian
clean slate
1263
          break;                        /* One buffer have been removed */
1264
        }
1265
        else if (error == -1)
971.6.11 by Eric Day
Removed purecov messages.
1266
          goto err;
1 by brian
clean slate
1267
      }
897.1.5 by Padraig
Replacing the instance of QUEUE in the merge_buffers() function in
1268
      /* Top element has been replaced */
1269
      queue.pop();
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1270
      queue.push(buffpek_inst);
1 by brian
clean slate
1271
    }
1272
  }
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1273
  buffpek_inst= queue.top();
1274
  buffpek_inst->base= sort_buffer;
1275
  buffpek_inst->max_keys= param->keys;
1 by brian
clean slate
1276
1277
  /*
1278
    As we know all entries in the buffer are unique, we only have to
1279
    check if the first one is the same as the last one we wrote
1280
  */
1281
  if (cmp)
1282
  {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1283
    if (!(*cmp)(first_cmp_arg, &(param->unique_buff), (unsigned char**) &buffpek_inst->key))
1 by brian
clean slate
1284
    {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1285
      buffpek_inst->key+= rec_length;         // Remove duplicate
1286
      --buffpek_inst->mem_count;
1 by brian
clean slate
1287
    }
1288
  }
1289
1290
  do
1291
  {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1292
    if ((ha_rows) buffpek_inst->mem_count > max_rows)
1 by brian
clean slate
1293
    {                                        /* Don't write too many records */
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1294
      buffpek_inst->mem_count= (uint32_t) max_rows;
1295
      buffpek_inst->count= 0;                        /* Don't read more */
1 by brian
clean slate
1296
    }
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1297
    max_rows-= buffpek_inst->mem_count;
1 by brian
clean slate
1298
    if (flag == 0)
1299
    {
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1300
      if (my_b_write(to_file,(unsigned char*) buffpek_inst->key,
1301
                     (rec_length*buffpek_inst->mem_count)))
1 by brian
clean slate
1302
      {
971.6.11 by Eric Day
Removed purecov messages.
1303
        error= 1; goto err;
1 by brian
clean slate
1304
      }
1305
    }
1306
    else
1307
    {
481 by Brian Aker
Remove all of uchar.
1308
      register unsigned char *end;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1309
      strpos= buffpek_inst->key+offset;
1310
      for (end= strpos+buffpek_inst->mem_count*rec_length ;
1 by brian
clean slate
1311
           strpos != end ;
1312
           strpos+= rec_length)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1313
      {
481 by Brian Aker
Remove all of uchar.
1314
        if (my_b_write(to_file, (unsigned char *) strpos, res_length))
1 by brian
clean slate
1315
        {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1316
          error=1; goto err;
1 by brian
clean slate
1317
        }
1318
      }
1319
    }
1320
  }
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1321
  while ((error=(int) read_to_buffer(from_file,buffpek_inst, rec_length))
1 by brian
clean slate
1322
         != -1 && error != 0);
1323
1324
end:
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
1325
  lastbuff->count= min(org_max_rows-max_rows, param->max_rows);
1 by brian
clean slate
1326
  lastbuff->file_pos= to_start_filepos;
1327
err:
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
1328
  return(error);
1 by brian
clean slate
1329
} /* merge_buffers */
1330
1331
1332
	/* Do a merge to output-file (save only positions) */
1333
481 by Brian Aker
Remove all of uchar.
1334
static int merge_index(SORTPARAM *param, unsigned char *sort_buffer,
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1335
		       buffpek *buffpek_inst, uint32_t maxbuffer,
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1336
		       internal::IO_CACHE *tempfile, internal::IO_CACHE *outfile)
1 by brian
clean slate
1337
{
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1338
  if (merge_buffers(param,tempfile,outfile,sort_buffer,buffpek_inst,buffpek_inst,
1339
		    buffpek_inst+maxbuffer,1))
971.6.11 by Eric Day
Removed purecov messages.
1340
    return(1);
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
1341
  return(0);
1 by brian
clean slate
1342
} /* merge_index */
1343
1344
438.1.13 by Brian Aker
uint cleanup.
1345
static uint32_t suffix_length(uint32_t string_length)
1 by brian
clean slate
1346
{
1347
  if (string_length < 256)
1348
    return 1;
1349
  if (string_length < 256L*256L)
1350
    return 2;
1351
  if (string_length < 256L*256L*256L)
1352
    return 3;
1353
  return 4;                                     // Can't sort longer than 4G
1354
}
1355
1356
1357
1358
/**
1359
  Calculate length of sort key.
1360
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1361
  @param session			  Thread Cursor
1 by brian
clean slate
1362
  @param sortorder		  Order of items to sort
1363
  @param s_length	          Number of items to sort
1364
  @param[out] multi_byte_charset Set to 1 if we are using multi-byte charset
1365
                                 (In which case we have to use strxnfrm())
1366
1367
  @note
1368
    sortorder->length is updated for each sort item.
1369
  @n
1370
    sortorder->need_strxnfrm is set 1 if we have to use strxnfrm
1371
1372
  @return
1373
    Total length of sort buffer in bytes
1374
*/
1375
438.1.13 by Brian Aker
uint cleanup.
1376
static uint32_t
1711.6.1 by Brian Aker
Style on structure cleanup
1377
sortlength(Session *session, SortField *sortorder, uint32_t s_length,
1 by brian
clean slate
1378
           bool *multi_byte_charset)
1379
{
438.1.13 by Brian Aker
uint cleanup.
1380
  register uint32_t length;
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1381
  const CHARSET_INFO *cs;
1 by brian
clean slate
1382
  *multi_byte_charset= 0;
1383
1384
  length=0;
1385
  for (; s_length-- ; sortorder++)
1386
  {
1387
    sortorder->need_strxnfrm= 0;
1388
    sortorder->suffix_length= 0;
1389
    if (sortorder->field)
1390
    {
1391
      cs= sortorder->field->sort_charset();
1392
      sortorder->length= sortorder->field->sort_length();
1393
1394
      if (use_strnxfrm((cs=sortorder->field->sort_charset())))
1395
      {
1396
        sortorder->need_strxnfrm= 1;
1397
        *multi_byte_charset= 1;
1398
        sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length);
1399
      }
1400
      if (sortorder->field->maybe_null())
1401
	length++;				// Place for NULL marker
1402
    }
1403
    else
1404
    {
1405
      sortorder->result_type= sortorder->item->result_type();
152 by Brian Aker
longlong replacement
1406
      if (sortorder->item->result_as_int64_t())
1 by brian
clean slate
1407
        sortorder->result_type= INT_RESULT;
1408
      switch (sortorder->result_type) {
1409
      case STRING_RESULT:
1410
	sortorder->length=sortorder->item->max_length;
892.2.2 by Monty Taylor
More solaris warnings.
1411
        set_if_smaller(sortorder->length,
910.4.4 by Stewart Smith
max_sort_length should be size_t everywhere. Causing numerous failures on SPARC and PowerPC due to strang value being retrieved in filesort. Basically, anything with filesort fails without this patch.
1412
                       session->variables.max_sort_length);
1 by brian
clean slate
1413
	if (use_strnxfrm((cs=sortorder->item->collation.collation)))
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1414
	{
1 by brian
clean slate
1415
          sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length);
1416
	  sortorder->need_strxnfrm= 1;
1417
	  *multi_byte_charset= 1;
1418
	}
1419
        else if (cs == &my_charset_bin)
1420
        {
1421
          /* Store length last to be able to sort blob/varbinary */
1422
          sortorder->suffix_length= suffix_length(sortorder->length);
1423
          sortorder->length+= sortorder->suffix_length;
1424
        }
1425
	break;
1426
      case INT_RESULT:
152 by Brian Aker
longlong replacement
1427
	sortorder->length=8;			// Size of intern int64_t
1 by brian
clean slate
1428
	break;
1429
      case DECIMAL_RESULT:
1430
        sortorder->length=
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1431
          my_decimal_get_binary_size(sortorder->item->max_length -
1 by brian
clean slate
1432
                                     (sortorder->item->decimals ? 1 : 0),
1433
                                     sortorder->item->decimals);
1434
        break;
1435
      case REAL_RESULT:
1436
	sortorder->length=sizeof(double);
1437
	break;
1438
      case ROW_RESULT:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1439
      default:
1 by brian
clean slate
1440
	// This case should never be choosen
51.1.12 by Jay Pipes
Removed/replaced DBUG symbols
1441
	assert(0);
1 by brian
clean slate
1442
	break;
1443
      }
1444
      if (sortorder->item->maybe_null)
1445
	length++;				// Place for NULL marker
1446
    }
892.2.2 by Monty Taylor
More solaris warnings.
1447
    set_if_smaller(sortorder->length,
1448
                   (size_t)session->variables.max_sort_length);
1 by brian
clean slate
1449
    length+=sortorder->length;
1450
  }
1451
  sortorder->field= (Field*) 0;			// end marker
1452
  return length;
1453
}
1454
1455
1456
/**
1457
  Get descriptors of fields appended to sorted fields and
1458
  calculate its total length.
1459
1460
  The function first finds out what fields are used in the result set.
1461
  Then it calculates the length of the buffer to store the values of
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1462
  these fields together with the value of sort values.
1 by brian
clean slate
1463
  If the calculated length is not greater than max_length_for_sort_data
1464
  the function allocates memory for an array of descriptors containing
1465
  layouts for the values of the non-sorted fields in the buffer and
1466
  fills them.
1467
520.1.22 by Brian Aker
Second pass of thd cleanup
1468
  @param session                 Current thread
1 by brian
clean slate
1469
  @param ptabfield           Array of references to the table fields
1470
  @param sortlength          Total length of sorted fields
1471
  @param[out] plength        Total length of appended fields
1472
1473
  @note
1474
    The null bits for the appended values are supposed to be put together
1475
    and stored the buffer just ahead of the value of the first field.
1476
1477
  @return
1478
    Pointer to the layout descriptors for the appended fields, if any
1479
  @retval
1480
    NULL   if we do not store field values with sort data.
1481
*/
1482
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1483
static sort_addon_field *
520.1.22 by Brian Aker
Second pass of thd cleanup
1484
get_addon_fields(Session *session, Field **ptabfield, uint32_t sortlength, uint32_t *plength)
1 by brian
clean slate
1485
{
1486
  Field **pfield;
1487
  Field *field;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1488
  sort_addon_field *addonf;
438.1.13 by Brian Aker
uint cleanup.
1489
  uint32_t length= 0;
1490
  uint32_t fields= 0;
1491
  uint32_t null_fields= 0;
1 by brian
clean slate
1492
1493
  /*
1494
    If there is a reference to a field in the query add it
1495
    to the the set of appended fields.
1496
    Note for future refinement:
1497
    This this a too strong condition.
1498
    Actually we need only the fields referred in the
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1499
    result set. And for some of them it makes sense to use
1 by brian
clean slate
1500
    the values directly from sorted fields.
1501
  */
1502
  *plength= 0;
1503
1504
  for (pfield= ptabfield; (field= *pfield) ; pfield++)
1505
  {
1003.1.12 by Brian Aker
Begin of abstract out the bitmap from direct reference.
1506
    if (!(field->isReadSet()))
1 by brian
clean slate
1507
      continue;
1508
    if (field->flags & BLOB_FLAG)
1509
      return 0;
1510
    length+= field->max_packed_col_length(field->pack_length());
1511
    if (field->maybe_null())
1512
      null_fields++;
1513
    fields++;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1514
  }
1 by brian
clean slate
1515
  if (!fields)
1516
    return 0;
1517
  length+= (null_fields+7)/8;
1518
520.1.22 by Brian Aker
Second pass of thd cleanup
1519
  if (length+sortlength > session->variables.max_length_for_sort_data ||
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1520
      !(addonf= (sort_addon_field *) malloc(sizeof(sort_addon_field)*
641.3.7 by Monty Taylor
More my_malloc removal.
1521
                                            (fields+1))))
1 by brian
clean slate
1522
    return 0;
1523
1524
  *plength= length;
1525
  length= (null_fields+7)/8;
1526
  null_fields= 0;
1527
  for (pfield= ptabfield; (field= *pfield) ; pfield++)
1528
  {
1003.1.12 by Brian Aker
Begin of abstract out the bitmap from direct reference.
1529
    if (!(field->isReadSet()))
1 by brian
clean slate
1530
      continue;
1531
    addonf->field= field;
1532
    addonf->offset= length;
1533
    if (field->maybe_null())
1534
    {
1535
      addonf->null_offset= null_fields/8;
1536
      addonf->null_bit= 1<<(null_fields & 7);
1537
      null_fields++;
1538
    }
1539
    else
1540
    {
1541
      addonf->null_offset= 0;
1542
      addonf->null_bit= 0;
1543
    }
1544
    addonf->length= field->max_packed_col_length(field->pack_length());
1545
    length+= addonf->length;
1546
    addonf++;
1547
  }
1548
  addonf->field= 0;     // Put end marker
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1549
1 by brian
clean slate
1550
  return (addonf-fields);
1551
}
1552
1553
1554
/**
1555
  Copy (unpack) values appended to sorted fields from a buffer back to
1556
  their regular positions specified by the Field::ptr pointers.
1557
1558
  @param addon_field     Array of descriptors for appended fields
1559
  @param buff            Buffer which to unpack the value from
1560
1561
  @note
1562
    The function is supposed to be used only as a callback function
1563
    when getting field values for the sorted result set.
1564
1565
  @return
1566
    void.
1567
*/
1568
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1569
static void
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1570
unpack_addon_fields(struct sort_addon_field *addon_field, unsigned char *buff)
1 by brian
clean slate
1571
{
1572
  Field *field;
1826.1.1 by tdavies
Bug:621861 Changed C structs to C++ class in the following files: filesort.cc, filesort_info.h, sql_sort.h, table.h. removed the '_st' from the name of some of the classes. For more detail of changes made read the merge proposal notes.
1573
  sort_addon_field *addonf= addon_field;
1 by brian
clean slate
1574
1575
  for ( ; (field= addonf->field) ; addonf++)
1576
  {
1577
    if (addonf->null_bit && (addonf->null_bit & buff[addonf->null_offset]))
1578
    {
1579
      field->set_null();
1580
      continue;
1581
    }
1582
    field->set_notnull();
1583
    field->unpack(field->ptr, buff + addonf->offset);
1584
  }
1585
}
1586
1587
/*
1588
** functions to change a double or float to a sortable string
1589
** The following should work for IEEE
1590
*/
1591
1592
#define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)
1593
481 by Brian Aker
Remove all of uchar.
1594
void change_double_for_sort(double nr,unsigned char *to)
1 by brian
clean slate
1595
{
481 by Brian Aker
Remove all of uchar.
1596
  unsigned char *tmp=(unsigned char*) to;
1 by brian
clean slate
1597
  if (nr == 0.0)
1598
  {						/* Change to zero string */
481 by Brian Aker
Remove all of uchar.
1599
    tmp[0]=(unsigned char) 128;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1600
    memset(tmp+1, 0, sizeof(nr)-1);
1 by brian
clean slate
1601
  }
1602
  else
1603
  {
1604
#ifdef WORDS_BIGENDIAN
212.6.3 by Mats Kindahl
Removing deprecated functions from code and replacing them with C99 equivalents:
1605
    memcpy(tmp,&nr,sizeof(nr));
1 by brian
clean slate
1606
#else
1607
    {
481 by Brian Aker
Remove all of uchar.
1608
      unsigned char *ptr= (unsigned char*) &nr;
1 by brian
clean slate
1609
#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN)
1610
      tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
1611
      tmp[4]= ptr[7]; tmp[5]=ptr[6]; tmp[6]= ptr[5]; tmp[7]=ptr[4];
1612
#else
1613
      tmp[0]= ptr[7]; tmp[1]=ptr[6]; tmp[2]= ptr[5]; tmp[3]=ptr[4];
1614
      tmp[4]= ptr[3]; tmp[5]=ptr[2]; tmp[6]= ptr[1]; tmp[7]=ptr[0];
1615
#endif
1616
    }
1617
#endif
1618
    if (tmp[0] & 128)				/* Negative */
1619
    {						/* make complement */
438.1.13 by Brian Aker
uint cleanup.
1620
      uint32_t i;
1 by brian
clean slate
1621
      for (i=0 ; i < sizeof(nr); i++)
481 by Brian Aker
Remove all of uchar.
1622
	tmp[i]=tmp[i] ^ (unsigned char) 255;
1 by brian
clean slate
1623
    }
1624
    else
1625
    {					/* Set high and move exponent one up */
438.1.13 by Brian Aker
uint cleanup.
1626
      uint16_t exp_part=(((uint16_t) tmp[0] << 8) | (uint16_t) tmp[1] |
1627
		       (uint16_t) 32768);
1628
      exp_part+= (uint16_t) 1 << (16-1-DBL_EXP_DIG);
481 by Brian Aker
Remove all of uchar.
1629
      tmp[0]= (unsigned char) (exp_part >> 8);
1630
      tmp[1]= (unsigned char) exp_part;
1 by brian
clean slate
1631
    }
1632
  }
1633
}
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1634
1635
} /* namespace drizzled */