~drizzle-trunk/drizzle/development

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Copyright (C) 2008-2009 Sun Microsystems
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"

#include "drizzled/sql_base.h"
#include "drizzled/sql_select.h"
#include "drizzled/memory/sql_alloc.h"
#include "drizzled/optimizer/range.h"
#include "drizzled/optimizer/range_param.h"
#include "drizzled/optimizer/sel_arg.h"
#include "drizzled/optimizer/sel_tree.h"
#include "drizzled/optimizer/sel_imerge.h"

using namespace std;
using namespace drizzled;

static optimizer::SEL_ARG *key_or(optimizer::RangeParameter *param, optimizer::SEL_ARG *key1, optimizer::SEL_ARG *key2);
static bool eq_tree(optimizer::SEL_ARG* a, optimizer::SEL_ARG *b);

bool optimizer::sel_trees_can_be_ored(optimizer::SEL_TREE *tree1, 
                                      optimizer::SEL_TREE *tree2,
                                      optimizer::RangeParameter* param)
{
  key_map common_keys= tree1->keys_map;
  common_keys&= tree2->keys_map;

  if (common_keys.none())
  {
    return false;
  }

  /* trees have a common key, check if they refer to same key part */
  optimizer::SEL_ARG **key1,**key2;
  for (uint32_t key_no=0; key_no < param->keys; key_no++)
  {
    if (common_keys.test(key_no))
    {
      key1= tree1->keys + key_no;
      key2= tree2->keys + key_no;
      if ((*key1)->part == (*key2)->part)
      {
        return true;
      }
    }
  }
  return false;
}


/*
  Perform OR operation on 2 index_merge lists, storing result in first list.

  NOTES
    The following conversion is implemented:
     (a_1 &&...&& a_N)||(b_1 &&...&& b_K) = AND_i,j(a_i || b_j) =>
      => (a_1||b_1).

    i.e. all conjuncts except the first one are currently dropped.
    This is done to avoid producing N*K ways to do index_merge.

    If (a_1||b_1) produce a condition that is always true, NULL is returned
    and index_merge is discarded (while it is actually possible to try
    harder).

    As a consequence of this, choice of keys to do index_merge read may depend
    on the order of conditions in WHERE part of the query.

  RETURN
    0     OK, result is stored in *im1
    other Error, both passed lists are unusable
*/

static int imerge_list_or_list(optimizer::RangeParameter *param,
                               List<optimizer::SEL_IMERGE> *im1,
                               List<optimizer::SEL_IMERGE> *im2)
{
  optimizer::SEL_IMERGE *imerge= im1->head();
  im1->empty();
  im1->push_back(imerge);

  return imerge->or_sel_imerge_with_checks(param, im2->head());
}


/*
  Perform OR operation on index_merge list and key tree.

  RETURN
     0     OK, result is stored in *im1.
     other Error
 */

static int imerge_list_or_tree(optimizer::RangeParameter *param,
                               List<optimizer::SEL_IMERGE> *im1,
                               optimizer::SEL_TREE *tree)
{
  optimizer::SEL_IMERGE *imerge= NULL;
  List_iterator<optimizer::SEL_IMERGE> it(*im1);
  while ((imerge= it++))
  {
    if (imerge->or_sel_tree_with_checks(param, tree))
      it.remove();
  }
  return im1->is_empty();
}


optimizer::SEL_TREE *
optimizer::tree_or(optimizer::RangeParameter *param,
                   optimizer::SEL_TREE *tree1,
                   optimizer::SEL_TREE *tree2)
{
  if (! tree1 || ! tree2)
  {
    return 0;
  }

  if (tree1->type == optimizer::SEL_TREE::IMPOSSIBLE || tree2->type == optimizer::SEL_TREE::ALWAYS)
  {
    return tree2;
  }

  if (tree2->type == optimizer::SEL_TREE::IMPOSSIBLE || tree1->type == optimizer::SEL_TREE::ALWAYS)
  {
    return tree1;
  }

  if (tree1->type == optimizer::SEL_TREE::MAYBE)
  {
    return tree1; // Can't use this
  }

  if (tree2->type == optimizer::SEL_TREE::MAYBE)
  {
    return tree2;
  }

  optimizer::SEL_TREE *result= NULL;
  key_map  result_keys;
  result_keys.reset();
  if (sel_trees_can_be_ored(tree1, tree2, param))
  {
    /* Join the trees key per key */
    optimizer::SEL_ARG **key1= NULL;
    optimizer::SEL_ARG **key2= NULL;
    optimizer::SEL_ARG **end= NULL;
    for (key1= tree1->keys,key2= tree2->keys,end= key1+param->keys;
         key1 != end; 
         key1++, key2++)
    {
      *key1= key_or(param, *key1, *key2);
      if (*key1)
      {
        result= tree1; // Added to tree1
        result_keys.set(key1 - tree1->keys);
      }
    }
    if (result)
      result->keys_map= result_keys;
  }
  else
  {
    /* ok, two trees have KEY type but cannot be used without index merge */
    if (tree1->merges.is_empty() && tree2->merges.is_empty())
    {
      if (param->remove_jump_scans)
      {
        bool no_trees= optimizer::remove_nonrange_trees(param, tree1);
        no_trees= no_trees || optimizer::remove_nonrange_trees(param, tree2);
        if (no_trees)
        {
          return (new optimizer::SEL_TREE(optimizer::SEL_TREE::ALWAYS));
        }
      }
      optimizer::SEL_IMERGE *merge= NULL;
      /* both trees are "range" trees, produce new index merge structure */
      if (! (result= new optimizer::SEL_TREE()) || 
          ! (merge= new optimizer::SEL_IMERGE()) ||
          (result->merges.push_back(merge)) ||
          (merge->or_sel_tree(param, tree1)) ||
          (merge->or_sel_tree(param, tree2)))
      {
        result= NULL;
      }
      else
      {
        result->type= tree1->type;
      }
    }
    else if (!tree1->merges.is_empty() && !tree2->merges.is_empty())
    {
      if (imerge_list_or_list(param, &tree1->merges, &tree2->merges))
        result= new optimizer::SEL_TREE(optimizer::SEL_TREE::ALWAYS);
      else
        result= tree1;
    }
    else
    {
      /* one tree is index merge tree and another is range tree */
      if (tree1->merges.is_empty())
        std::swap(tree1, tree2);

      if (param->remove_jump_scans && optimizer::remove_nonrange_trees(param, tree2))
         return(new optimizer::SEL_TREE(optimizer::SEL_TREE::ALWAYS));
      /* add tree2 to tree1->merges, checking if it collapses to ALWAYS */
      if (imerge_list_or_tree(param, &tree1->merges, tree2))
        result= new optimizer::SEL_TREE(optimizer::SEL_TREE::ALWAYS);
      else
        result= tree1;
    }
  }
  return result;
}


static optimizer::SEL_ARG *
key_or(optimizer::RangeParameter *param, optimizer::SEL_ARG *key1, optimizer::SEL_ARG *key2)
{
  if (! key1)
  {
    if (key2)
    {
      key2->use_count--;
      key2->free_tree();
    }
    return 0;
  }
  if (! key2)
  {
    key1->use_count--;
    key1->free_tree();
    return 0;
  }
  key1->use_count--;
  key2->use_count--;

  if (key1->part != key2->part)
  {
    key1->free_tree();
    key2->free_tree();
    return 0;					// Can't optimize this
  }

  // If one of the key is MAYBE_KEY then the found region may be bigger
  if (key1->type == optimizer::SEL_ARG::MAYBE_KEY)
  {
    key2->free_tree();
    key1->use_count++;
    return key1;
  }
  if (key2->type == optimizer::SEL_ARG::MAYBE_KEY)
  {
    key1->free_tree();
    key2->use_count++;
    return key2;
  }

  if (key1->use_count > 0)
  {
    if (key2->use_count == 0 || key1->elements > key2->elements)
    {
      std::swap(key1,key2);
    }
    if (key1->use_count > 0 || !(key1=key1->clone_tree(param)))
      return 0;					// OOM
  }

  // Add tree at key2 to tree at key1
  bool key2_shared= key2->use_count != 0;
  key1->maybe_flag|= key2->maybe_flag;

  for (key2=key2->first(); key2; )
  {
    optimizer::SEL_ARG *tmp= key1->find_range(key2); // Find key1.min <= key2.min
    int cmp;

    if (! tmp)
    {
      tmp=key1->first(); // tmp.min > key2.min
      cmp= -1;
    }
    else if ((cmp=tmp->cmp_max_to_min(key2)) < 0)
    {						// Found tmp.max < key2.min
      optimizer::SEL_ARG *next= tmp->next;
      if (cmp == -2 && eq_tree(tmp->next_key_part,key2->next_key_part))
      {
        // Join near ranges like tmp.max < 0 and key2.min >= 0
        optimizer::SEL_ARG *key2_next=key2->next;
        if (key2_shared)
        {
          if (! (key2=new optimizer::SEL_ARG(*key2)))
            return 0;		// out of memory
          key2->increment_use_count(key1->use_count+1);
          key2->next= key2_next; // New copy of key2
        }
        key2->copy_min(tmp);
        if (! (key1=key1->tree_delete(tmp)))
        {					// Only one key in tree
          key1= key2;
          key1->make_root();
          key2= key2_next;
          break;
        }
      }
      if (! (tmp= next)) // tmp.min > key2.min
        break; // Copy rest of key2
    }
    if (cmp < 0)
    {						// tmp.min > key2.min
      int tmp_cmp;
      if ((tmp_cmp= tmp->cmp_min_to_max(key2)) > 0) // if tmp.min > key2.max
      {
        if (tmp_cmp == 2 && eq_tree(tmp->next_key_part,key2->next_key_part))
        {					// ranges are connected
          tmp->copy_min_to_min(key2);
          key1->merge_flags(key2);
          if (tmp->min_flag & NO_MIN_RANGE &&
              tmp->max_flag & NO_MAX_RANGE)
          {
            if (key1->maybe_flag)
              return new optimizer::SEL_ARG(optimizer::SEL_ARG::MAYBE_KEY);
            return 0;
          }
          key2->increment_use_count(-1);	// Free not used tree
          key2= key2->next;
          continue;
        }
        else
        {
          optimizer::SEL_ARG *next= key2->next; // Keys are not overlapping
          if (key2_shared)
          {
            optimizer::SEL_ARG *cpy= new optimizer::SEL_ARG(*key2); // Must make copy
            if (! cpy)
              return 0; // OOM
            key1= key1->insert(cpy);
            key2->increment_use_count(key1->use_count+1);
          }
          else
            key1= key1->insert(key2);		// Will destroy key2_root
          key2= next;
          continue;
        }
      }
    }

    // tmp.max >= key2.min && tmp.min <= key.cmax(overlapping ranges)
    if (eq_tree(tmp->next_key_part,key2->next_key_part))
    {
      if (tmp->is_same(key2))
      {
        tmp->merge_flags(key2);			// Copy maybe flags
        key2->increment_use_count(-1);		// Free not used tree
      }
      else
      {
        optimizer::SEL_ARG *last= tmp;
        while (last->next && last->next->cmp_min_to_max(key2) <= 0 &&
               eq_tree(last->next->next_key_part,key2->next_key_part))
        {
          optimizer::SEL_ARG *save= last;
          last= last->next;
          key1= key1->tree_delete(save);
        }
        last->copy_min(tmp);
        if (last->copy_min(key2) || last->copy_max(key2))
        {					// Full range
          key1->free_tree();
          for (; key2; key2= key2->next)
            key2->increment_use_count(-1);	// Free not used tree
          if (key1->maybe_flag)
            return new optimizer::SEL_ARG(optimizer::SEL_ARG::MAYBE_KEY);
          return 0;
        }
      }
      key2= key2->next;
      continue;
    }

    if (cmp >= 0 && tmp->cmp_min_to_min(key2) < 0)
    {						// tmp.min <= x < key2.min
      optimizer::SEL_ARG *new_arg= tmp->clone_first(key2);
      if (! new_arg)
        return 0;				// OOM
      if ((new_arg->next_key_part= key1->next_key_part))
        new_arg->increment_use_count(key1->use_count+1);
      tmp->copy_min_to_min(key2);
      key1= key1->insert(new_arg);
    }

    // tmp.min >= key2.min && tmp.min <= key2.max
    optimizer::SEL_ARG key(*key2); // Get copy we can modify
    for (;;)
    {
      if (tmp->cmp_min_to_min(&key) > 0)
      {						// key.min <= x < tmp.min
        optimizer::SEL_ARG *new_arg= key.clone_first(tmp);
        if (! new_arg)
          return 0;				// OOM
        if ((new_arg->next_key_part=key.next_key_part))
          new_arg->increment_use_count(key1->use_count+1);
        key1= key1->insert(new_arg);
      }
      if ((cmp=tmp->cmp_max_to_max(&key)) <= 0)
      {						// tmp.min. <= x <= tmp.max
        tmp->maybe_flag|= key.maybe_flag;
        key.increment_use_count(key1->use_count+1);
        tmp->next_key_part= key_or(param, tmp->next_key_part, key.next_key_part);
        if (! cmp)				// Key2 is ready
          break;
        key.copy_max_to_min(tmp);
        if (! (tmp= tmp->next))
        {
          optimizer::SEL_ARG *tmp2= new optimizer::SEL_ARG(key);
          if (! tmp2)
            return 0;				// OOM
          key1= key1->insert(tmp2);
          key2= key2->next;
          goto end;
        }
        if (tmp->cmp_min_to_max(&key) > 0)
        {
          optimizer::SEL_ARG *tmp2= new optimizer::SEL_ARG(key);
          if (! tmp2)
            return 0;				// OOM
          key1= key1->insert(tmp2);
          break;
        }
      }
      else
      {
        optimizer::SEL_ARG *new_arg= tmp->clone_last(&key); // tmp.min <= x <= key.max
        if (! new_arg)
          return 0;				// OOM
        tmp->copy_max_to_min(&key);
        tmp->increment_use_count(key1->use_count+1);
        /* Increment key count as it may be used for next loop */
        key.increment_use_count(1);
        new_arg->next_key_part= key_or(param, tmp->next_key_part, key.next_key_part);
        key1= key1->insert(new_arg);
        break;
      }
    }
    key2= key2->next;
  }

end:
  while (key2)
  {
    optimizer::SEL_ARG *next= key2->next;
    if (key2_shared)
    {
      optimizer::SEL_ARG *tmp= new optimizer::SEL_ARG(*key2);		// Must make copy
      if (! tmp)
        return 0;
      key2->increment_use_count(key1->use_count+1);
      key1= key1->insert(tmp);
    }
    else
      key1= key1->insert(key2);			// Will destroy key2_root
    key2= next;
  }
  key1->use_count++;
  return key1;
}


/*
  Remove the trees that are not suitable for record retrieval.
  SYNOPSIS
    param  Range analysis parameter
    tree   Tree to be processed, tree->type is KEY or KEY_SMALLER

  DESCRIPTION
    This function walks through tree->keys[] and removes the SEL_ARG* trees
    that are not "maybe" trees (*) and cannot be used to construct quick range
    selects.
    (*) - have type MAYBE or MAYBE_KEY. Perhaps we should remove trees of
          these types here as well.

    A SEL_ARG* tree cannot be used to construct quick select if it has
    tree->part != 0. (e.g. it could represent "keypart2 < const").

    WHY THIS FUNCTION IS NEEDED

    Normally we allow construction of optimizer::SEL_TREE objects that have SEL_ARG
    trees that do not allow quick range select construction. For example for
    " keypart1=1 AND keypart2=2 " the execution will proceed as follows:
    tree1= optimizer::SEL_TREE { SEL_ARG{keypart1=1} }
    tree2= optimizer::SEL_TREE { SEL_ARG{keypart2=2} } -- can't make quick range select
                                               from this
    call tree_and(tree1, tree2) -- this joins SEL_ARGs into a usable SEL_ARG
                                   tree.

    There is an exception though: when we construct index_merge optimizer::SEL_TREE,
    any SEL_ARG* tree that cannot be used to construct quick range select can
    be removed, because current range analysis code doesn't provide any way
    that tree could be later combined with another tree.
    Consider an example: we should not construct
    st1 = optimizer::SEL_TREE {
      merges = SEL_IMERGE {
                            optimizer::SEL_TREE(t.key1part1 = 1),
                            optimizer::SEL_TREE(t.key2part2 = 2)   -- (*)
                          }
                   };
    because
     - (*) cannot be used to construct quick range select,
     - There is no execution path that would cause (*) to be converted to
       a tree that could be used.

    The latter is easy to verify: first, notice that the only way to convert
    (*) into a usable tree is to call tree_and(something, (*)).

    Second look at what tree_and/tree_or function would do when passed a
    optimizer::SEL_TREE that has the structure like st1 tree has, and conlcude that
    tree_and(something, (*)) will not be called.

  RETURN
    0  Ok, some suitable trees left
    1  No tree->keys[] left.
*/
bool optimizer::remove_nonrange_trees(optimizer::RangeParameter *param, optimizer::SEL_TREE *tree)
{
  bool res= false;
  for (uint32_t i= 0; i < param->keys; i++)
  {
    if (tree->keys[i])
    {
      if (tree->keys[i]->part)
      {
        tree->keys[i]= NULL;
        tree->keys_map.reset(i);
      }
      else
        res= true;
    }
  }
  return ! res;
}


/* Compare if two trees are equal */
static bool eq_tree(optimizer::SEL_ARG *a, optimizer::SEL_ARG *b)
{
  if (a == b)
  {
    return true;
  }

  if (! a || ! b || ! a->is_same(b))
  {
    return false;
  }

  if (a->left != &optimizer::null_element && b->left != &optimizer::null_element)
  {
    if (! eq_tree(a->left,b->left))
      return false;
  }
  else if (a->left != &optimizer::null_element || b->left != &optimizer::null_element)
  {
    return false;
  }

  if (a->right != &optimizer::null_element && b->right != &optimizer::null_element)
  {
    if (! eq_tree(a->right,b->right))
      return false;
  }
  else if (a->right != &optimizer::null_element || b->right != &optimizer::null_element)
  {
    return false;
  }

  if (a->next_key_part != b->next_key_part)
  {						// Sub range
    if (! a->next_key_part != ! b->next_key_part ||
	      ! eq_tree(a->next_key_part, b->next_key_part))
      return false;
  }

  return true;
}