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