~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: Brian Aker
  • Date: 2010-10-28 17:12:01 UTC
  • mfrom: (1887.1.3 merge)
  • Revision ID: brian@tangent.org-20101028171201-baj6l1bnntn1s4ad
Merge in POTFILES changes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
  @file
18
18
 
19
19
  @brief
20
 
  select_query and join optimization
 
20
  mysql_select and join optimization
21
21
 
22
22
  @defgroup Query_Optimizer  Query Optimizer
23
23
  @{
51
51
#include "drizzled/index_hint.h"
52
52
#include "drizzled/records.h"
53
53
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
55
 
#include "drizzled/plugin/storage_engine.h"
56
54
 
57
55
#include "drizzled/sql_union.h"
58
56
#include "drizzled/optimizer/key_field.h"
63
61
#include "drizzled/optimizer/quick_range_select.h"
64
62
#include "drizzled/optimizer/quick_ror_intersect_select.h"
65
63
 
66
 
#include "drizzled/filesort.h"
67
 
 
68
64
using namespace std;
69
65
 
70
66
namespace drizzled
79
75
static Item* part_of_refkey(Table *form,Field *field);
80
76
static bool cmp_buffer_with_ref(JoinTable *tab);
81
77
static void change_cond_ref_to_const(Session *session,
82
 
                                     list<COND_CMP>& save_list,
 
78
                                     vector<COND_CMP>& save_list,
83
79
                                     Item *and_father,
84
80
                                     Item *cond,
85
81
                                     Item *field,
118
114
{
119
115
  bool res;
120
116
  register Select_Lex *select_lex= &lex->select_lex;
121
 
  DRIZZLE_SELECT_START(session->getQueryString()->c_str());
 
117
  DRIZZLE_SELECT_START(session->query.c_str());
122
118
 
123
119
  if (select_lex->master_unit()->is_union() ||
124
120
      select_lex->master_unit()->fake_select_lex)
132
128
    unit->set_limit(unit->global_parameters);
133
129
    session->session_marker= 0;
134
130
    /*
135
 
      'options' of select_query will be set in JOIN, as far as JOIN for
 
131
      'options' of mysql_select will be set in JOIN, as far as JOIN for
136
132
      every PS/SP execution new, we will not need reset this flag if
137
133
      setup_tables_done_option changed for next rexecution
138
134
    */
139
 
    res= select_query(session,
140
 
                      &select_lex->ref_pointer_array,
 
135
    res= mysql_select(session, &select_lex->ref_pointer_array,
141
136
                      (TableList*) select_lex->table_list.first,
142
 
                      select_lex->with_wild,
143
 
                      select_lex->item_list,
 
137
                      select_lex->with_wild, select_lex->item_list,
144
138
                      select_lex->where,
145
139
                      select_lex->order_list.elements +
146
140
                      select_lex->group_list.elements,
147
 
                      (Order*) select_lex->order_list.first,
148
 
                      (Order*) select_lex->group_list.first,
 
141
                      (order_st*) select_lex->order_list.first,
 
142
                      (order_st*) select_lex->group_list.first,
149
143
                      select_lex->having,
150
144
                      select_lex->options | session->options |
151
145
                      setup_tables_done_option,
271
265
 
272
266
/*****************************************************************************
273
267
  Check fields, find best join, do the select and output fields.
274
 
  select_query assumes that all tables are already opened
 
268
  mysql_select assumes that all tables are already opened
275
269
*****************************************************************************/
276
270
 
277
271
/*
351
345
  @retval
352
346
    true   an error
353
347
*/
354
 
bool select_query(Session *session,
 
348
bool mysql_select(Session *session,
355
349
                  Item ***rref_pointer_array,
356
350
                  TableList *tables, 
357
351
                  uint32_t wild_num, 
358
352
                  List<Item> &fields,
359
353
                  COND *conds, 
360
354
                  uint32_t og_num,  
361
 
                  Order *order,
362
 
                  Order *group,
 
355
                  order_st *order, 
 
356
                  order_st *group,
363
357
                  Item *having, 
364
358
                  uint64_t select_options,
365
359
                  select_result *result, 
453
447
  return (cond? (new Item_cond_and(cond, item)) : item);
454
448
}
455
449
 
 
450
static void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
 
451
{
 
452
  List_iterator<TableList> it(*tlist);
 
453
  TableList *table;
 
454
  while ((table= it++))
 
455
  {
 
456
    if (table->on_expr)
 
457
      table->on_expr->fix_after_pullout(new_parent, &table->on_expr);
 
458
    if (table->getNestedJoin())
 
459
      fix_list_after_tbl_changes(new_parent, &table->getNestedJoin()->join_list);
 
460
  }
 
461
}
 
462
 
456
463
/*****************************************************************************
457
464
  Create JoinTableS, make a guess about the table types,
458
465
  Approximate how many records will be used in each table
573
580
  sz= sizeof(optimizer::KeyField) *
574
581
      (((session->lex->current_select->cond_count+1)*2 +
575
582
        session->lex->current_select->between_count)*m+1);
576
 
  if (! (key_fields= (optimizer::KeyField*) session->getMemRoot()->allocate(sz)))
 
583
  if (! (key_fields= (optimizer::KeyField*) session->alloc(sz)))
577
584
    return true;
578
585
  and_level= 0;
579
586
  field= end= key_fields;
749
756
{
750
757
  List<Item_field> indexed_fields;
751
758
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
752
 
  Order      *cur_group;
 
759
  order_st      *cur_group;
753
760
  Item_field *cur_item;
754
761
  key_map possible_keys(0);
755
762
 
932
939
 
933
940
  /*
934
941
    we should restore old value of count_cuted_fields because
935
 
    store_val_in_field can be called from insert_query
 
942
    store_val_in_field can be called from mysql_insert
936
943
    with select_insert, which make count_cuted_fields= 1
937
944
   */
938
945
  enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
1005
1012
  j->ref.key_length=length;
1006
1013
  j->ref.key=(int) key;
1007
1014
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
1008
 
      !(j->ref.key_copy= (StoredKey**) session->getMemRoot()->allocate((sizeof(StoredKey*) *
 
1015
      !(j->ref.key_copy= (StoredKey**) session->alloc((sizeof(StoredKey*) *
1009
1016
               (keyparts+1)))) ||
1010
 
      !(j->ref.items=    (Item**) session->getMemRoot()->allocate(sizeof(Item*)*keyparts)) ||
1011
 
      !(j->ref.cond_guards= (bool**) session->getMemRoot()->allocate(sizeof(uint*)*keyparts)))
 
1017
      !(j->ref.items=    (Item**) session->alloc(sizeof(Item*)*keyparts)) ||
 
1018
      !(j->ref.cond_guards= (bool**) session->alloc(sizeof(uint*)*keyparts)))
1012
1019
  {
1013
1020
    return(true);
1014
1021
  }
1209
1216
  return tmp;
1210
1217
}
1211
1218
 
 
1219
/*
 
1220
  Check if given expression uses only table fields covered by the given index
 
1221
 
 
1222
  SYNOPSIS
 
1223
    uses_index_fields_only()
 
1224
      item           Expression to check
 
1225
      tbl            The table having the index
 
1226
      keyno          The index number
 
1227
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
1228
 
 
1229
  DESCRIPTION
 
1230
    Check if given expression only uses fields covered by index #keyno in the
 
1231
    table tbl. The expression can use any fields in any other tables.
 
1232
 
 
1233
    The expression is guaranteed not to be AND or OR - those constructs are
 
1234
    handled outside of this function.
 
1235
 
 
1236
  RETURN
 
1237
    true   Yes
 
1238
    false  No
 
1239
*/
 
1240
static bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
 
1241
{
 
1242
  if (item->const_item())
 
1243
    return true;
 
1244
 
 
1245
  /*
 
1246
    Don't push down the triggered conditions. Nested outer joins execution
 
1247
    code may need to evaluate a condition several times (both triggered and
 
1248
    untriggered), and there is no way to put thi
 
1249
    TODO: Consider cloning the triggered condition and using the copies for:
 
1250
      1. push the first copy down, to have most restrictive index condition
 
1251
         possible
 
1252
      2. Put the second copy into tab->select_cond.
 
1253
  */
 
1254
  if (item->type() == Item::FUNC_ITEM &&
 
1255
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
 
1256
    return false;
 
1257
 
 
1258
  if (!(item->used_tables() & tbl->map))
 
1259
    return other_tbls_ok;
 
1260
 
 
1261
  Item::Type item_type= item->type();
 
1262
  switch (item_type) {
 
1263
  case Item::FUNC_ITEM:
 
1264
    {
 
1265
      /* This is a function, apply condition recursively to arguments */
 
1266
      Item_func *item_func= (Item_func*)item;
 
1267
      Item **child;
 
1268
      Item **item_end= (item_func->arguments()) + item_func->argument_count();
 
1269
      for (child= item_func->arguments(); child != item_end; child++)
 
1270
      {
 
1271
        if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
 
1272
          return false;
 
1273
      }
 
1274
      return true;
 
1275
    }
 
1276
  case Item::COND_ITEM:
 
1277
    {
 
1278
      /* This is a function, apply condition recursively to arguments */
 
1279
      List_iterator<Item> li(*((Item_cond*)item)->argument_list());
 
1280
      Item *list_item;
 
1281
      while ((list_item=li++))
 
1282
      {
 
1283
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
 
1284
          return false;
 
1285
      }
 
1286
      return true;
 
1287
    }
 
1288
  case Item::FIELD_ITEM:
 
1289
    {
 
1290
      Item_field *item_field= (Item_field*)item;
 
1291
      if (item_field->field->getTable() != tbl)
 
1292
        return true;
 
1293
      return item_field->field->part_of_key.test(keyno);
 
1294
    }
 
1295
  case Item::REF_ITEM:
 
1296
    return uses_index_fields_only(item->real_item(), tbl, keyno,
 
1297
                                  other_tbls_ok);
 
1298
  default:
 
1299
    return false; /* Play it safe, don't push unknown non-const items */
 
1300
  }
 
1301
}
 
1302
 
1212
1303
#define ICP_COND_USES_INDEX_ONLY 10
1213
1304
 
 
1305
/*
 
1306
  Get a part of the condition that can be checked using only index fields
 
1307
 
 
1308
  SYNOPSIS
 
1309
    make_cond_for_index()
 
1310
      cond           The source condition
 
1311
      table          The table that is partially available
 
1312
      keyno          The index in the above table. Only fields covered by the index
 
1313
                     are available
 
1314
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
1315
 
 
1316
  DESCRIPTION
 
1317
    Get a part of the condition that can be checked when for the given table
 
1318
    we have values only of fields covered by some index. The condition may
 
1319
    refer to other tables, it is assumed that we have values of all of their
 
1320
    fields.
 
1321
 
 
1322
    Example:
 
1323
      make_cond_for_index(
 
1324
         "cond(t1.field) AND cond(t2.key1) AND cond(t2.non_key) AND cond(t2.key2)",
 
1325
          t2, keyno(t2.key1))
 
1326
      will return
 
1327
        "cond(t1.field) AND cond(t2.key2)"
 
1328
 
 
1329
  RETURN
 
1330
    Index condition, or NULL if no condition could be inferred.
 
1331
*/
 
1332
static Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
 
1333
{
 
1334
  if (!cond)
 
1335
    return NULL;
 
1336
  if (cond->type() == Item::COND_ITEM)
 
1337
  {
 
1338
    uint32_t n_marked= 0;
 
1339
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
1340
    {
 
1341
      Item_cond_and *new_cond=new Item_cond_and;
 
1342
      if (!new_cond)
 
1343
        return (COND*) 0;
 
1344
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1345
      Item *item;
 
1346
      while ((item=li++))
 
1347
      {
 
1348
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
1349
        if (fix)
 
1350
          new_cond->argument_list()->push_back(fix);
 
1351
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
1352
      }
 
1353
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
1354
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
1355
      switch (new_cond->argument_list()->elements) {
 
1356
      case 0:
 
1357
        return (COND*) 0;
 
1358
      case 1:
 
1359
        return new_cond->argument_list()->head();
 
1360
      default:
 
1361
        new_cond->quick_fix_field();
 
1362
        return new_cond;
 
1363
      }
 
1364
    }
 
1365
    else /* It's OR */
 
1366
    {
 
1367
      Item_cond_or *new_cond=new Item_cond_or;
 
1368
      if (!new_cond)
 
1369
        return (COND*) 0;
 
1370
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1371
      Item *item;
 
1372
      while ((item=li++))
 
1373
      {
 
1374
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
1375
        if (!fix)
 
1376
          return (COND*) 0;
 
1377
        new_cond->argument_list()->push_back(fix);
 
1378
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
1379
      }
 
1380
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
1381
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
1382
      new_cond->quick_fix_field();
 
1383
      new_cond->top_level_item();
 
1384
      return new_cond;
 
1385
    }
 
1386
  }
 
1387
 
 
1388
  if (!uses_index_fields_only(cond, table, keyno, other_tbls_ok))
 
1389
    return (COND*) 0;
 
1390
  cond->marker= ICP_COND_USES_INDEX_ONLY;
 
1391
  return cond;
 
1392
}
 
1393
 
 
1394
 
 
1395
static Item *make_cond_remainder(Item *cond, bool exclude_index)
 
1396
{
 
1397
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
 
1398
    return 0; /* Already checked */
 
1399
 
 
1400
  if (cond->type() == Item::COND_ITEM)
 
1401
  {
 
1402
    table_map tbl_map= 0;
 
1403
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
1404
    {
 
1405
      /* Create new top level AND item */
 
1406
      Item_cond_and *new_cond=new Item_cond_and;
 
1407
      if (!new_cond)
 
1408
        return (COND*) 0;
 
1409
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1410
      Item *item;
 
1411
      while ((item=li++))
 
1412
      {
 
1413
        Item *fix= make_cond_remainder(item, exclude_index);
 
1414
        if (fix)
 
1415
        {
 
1416
          new_cond->argument_list()->push_back(fix);
 
1417
          tbl_map |= fix->used_tables();
 
1418
        }
 
1419
      }
 
1420
      switch (new_cond->argument_list()->elements) {
 
1421
      case 0:
 
1422
        return (COND*) 0;
 
1423
      case 1:
 
1424
        return new_cond->argument_list()->head();
 
1425
      default:
 
1426
        new_cond->quick_fix_field();
 
1427
        ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
1428
        return new_cond;
 
1429
      }
 
1430
    }
 
1431
    else /* It's OR */
 
1432
    {
 
1433
      Item_cond_or *new_cond=new Item_cond_or;
 
1434
      if (!new_cond)
 
1435
        return (COND*) 0;
 
1436
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1437
      Item *item;
 
1438
      while ((item=li++))
 
1439
      {
 
1440
        Item *fix= make_cond_remainder(item, false);
 
1441
        if (!fix)
 
1442
          return (COND*) 0;
 
1443
        new_cond->argument_list()->push_back(fix);
 
1444
        tbl_map |= fix->used_tables();
 
1445
      }
 
1446
      new_cond->quick_fix_field();
 
1447
      ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
1448
      new_cond->top_level_item();
 
1449
      return new_cond;
 
1450
    }
 
1451
  }
 
1452
  return cond;
 
1453
}
1214
1454
 
1215
1455
/**
1216
1456
  cleanup JoinTable.
1222
1462
  delete quick;
1223
1463
  quick= 0;
1224
1464
  if (cache.buff)
1225
 
  {
1226
 
    size_t size= cache.end - cache.buff;
1227
 
    global_join_buffer.sub(size);
1228
1465
    free(cache.buff);
1229
 
  }
1230
1466
  cache.buff= 0;
1231
1467
  limit= 0;
1232
1468
  if (table)
1246
1482
  read_record.end_read_record();
1247
1483
}
1248
1484
 
1249
 
bool only_eq_ref_tables(Join *join,Order *order,table_map tables)
 
1485
bool only_eq_ref_tables(Join *join,order_st *order,table_map tables)
1250
1486
{
1251
1487
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
1252
1488
  {
1275
1511
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
1276
1512
  @endcode
1277
1513
*/
1278
 
bool eq_ref_table(Join *join, Order *start_order, JoinTable *tab)
 
1514
bool eq_ref_table(Join *join, order_st *start_order, JoinTable *tab)
1279
1515
{
1280
1516
  if (tab->cached_eq_ref_table)                 // If cached
1281
1517
    return tab->eq_ref_table;
1294
1530
  {
1295
1531
    if (! (*ref_item)->const_item())
1296
1532
    {                                           // Not a const ref
1297
 
      Order *order;
 
1533
      order_st *order;
1298
1534
      for (order=start_order ; order ; order=order->next)
1299
1535
      {
1300
1536
        if ((*ref_item)->eq(order->item[0],0))
2308
2544
  @param cond       condition whose multiple equalities are to be checked
2309
2545
  @param table      constant table that has been read
2310
2546
*/
2311
 
void update_const_equal_items(COND *cond, JoinTable *tab)
 
2547
static void update_const_equal_items(COND *cond, JoinTable *tab)
2312
2548
{
2313
2549
  if (!(cond->used_tables() & tab->table->map))
2314
2550
    return;
2365
2601
  and_level
2366
2602
*/
2367
2603
static void change_cond_ref_to_const(Session *session,
2368
 
                                     list<COND_CMP>& save_list,
 
2604
                                     vector<COND_CMP>& save_list,
2369
2605
                                     Item *and_father,
2370
2606
                                     Item *cond,
2371
2607
                                     Item *field,
2378
2614
    Item *item;
2379
2615
    while ((item=li++))
2380
2616
      change_cond_ref_to_const(session, save_list, and_level ? cond : item, item, field, value);
2381
 
 
2382
2617
    return;
2383
2618
  }
2384
2619
  if (cond->eq_cmp_result() == Item::COND_OK)
2471
2706
}
2472
2707
 
2473
2708
static void propagate_cond_constants(Session *session, 
2474
 
                                     list<COND_CMP>& save_list, 
 
2709
                                     vector<COND_CMP>& save_list, 
2475
2710
                                     COND *and_father, 
2476
2711
                                     COND *cond)
2477
2712
{
2480
2715
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
2481
2716
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
2482
2717
    Item *item;
2483
 
    list<COND_CMP> save;
 
2718
    vector<COND_CMP> save;
2484
2719
    while ((item=li++))
2485
2720
    {
2486
2721
      propagate_cond_constants(session, save, and_level ? cond : item, item);
2488
2723
    if (and_level)
2489
2724
    {
2490
2725
      // Handle other found items
2491
 
      for (list<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
 
2726
      for (vector<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
2492
2727
      {
2493
 
        Item **args= iter->second->arguments();
2494
 
        if (not args[0]->const_item())
 
2728
        Item **args= iter->cmp_func->arguments();
 
2729
        if (!args[0]->const_item())
2495
2730
        {
2496
 
          change_cond_ref_to_const(session, save, iter->first,
2497
 
                                   iter->first, args[0], args[1] );
 
2731
          change_cond_ref_to_const( session, save, iter->and_level,
 
2732
                                    iter->and_level, args[0], args[1] );
2498
2733
        }
2499
2734
      }
2500
2735
    }
2607
2842
         position:
2608
2843
          1. join->cur_embedding_map - bitmap of pairs of brackets (aka nested
2609
2844
             joins) we've opened but didn't close.
2610
 
          2. {each NestedJoin class not simplified away}->counter - number
 
2845
          2. {each nested_join_st structure not simplified away}->counter - number
2611
2846
             of this nested join's children that have already been added to to
2612
2847
             the partial join order.
2613
2848
  @endverbatim
2685
2920
                             &join->cond_equal);
2686
2921
 
2687
2922
    /* change field = field to field = const for each found field = const */
2688
 
    list<COND_CMP> temp;
 
2923
    vector<COND_CMP> temp;
2689
2924
    propagate_cond_constants(session, temp, conds, conds);
2690
2925
    /*
2691
2926
      Remove all instances of item == item
3054
3289
    table->emptyRecord();
3055
3290
    if (table->group && join->tmp_table_param.sum_func_count &&
3056
3291
        table->getShare()->sizeKeys() && !table->cursor->inited)
3057
 
    {
3058
 
      int tmp_error;
3059
 
      tmp_error= table->cursor->startIndexScan(0, 0);
3060
 
      if (tmp_error != 0)
3061
 
      {
3062
 
        table->print_error(tmp_error, MYF(0));
3063
 
        return -1;
3064
 
      }
3065
 
    }
 
3292
      table->cursor->startIndexScan(0, 0);
3066
3293
  }
3067
3294
  /* Set up select_end */
3068
3295
  Next_select_func end_select= setup_end_select_func(join);
3159
3386
      rc= sub_select(join,join_tab,end_of_records);
3160
3387
    return rc;
3161
3388
  }
3162
 
  if (join->session->getKilled())               // If aborted by user
 
3389
  if (join->session->killed)            // If aborted by user
3163
3390
  {
3164
3391
    join->session->send_kill_message();
3165
3392
    return NESTED_LOOP_KILLED;
3368
3595
  return 0;
3369
3596
}
3370
3597
 
 
3598
int join_read_const_table(JoinTable *tab, optimizer::Position *pos)
 
3599
{
 
3600
  int error;
 
3601
  Table *table=tab->table;
 
3602
  table->const_table=1;
 
3603
  table->null_row=0;
 
3604
  table->status=STATUS_NO_RECORD;
 
3605
 
 
3606
  if (tab->type == AM_SYSTEM)
 
3607
  {
 
3608
    if ((error=join_read_system(tab)))
 
3609
    {                                           // Info for DESCRIBE
 
3610
      tab->info="const row not found";
 
3611
      /* Mark for EXPLAIN that the row was not found */
 
3612
      pos->setFanout(0.0);
 
3613
      pos->clearRefDependMap();
 
3614
      if (! table->maybe_null || error > 0)
 
3615
        return(error);
 
3616
    }
 
3617
  }
 
3618
  else
 
3619
  {
 
3620
    if (! table->key_read && 
 
3621
        table->covering_keys.test(tab->ref.key) && 
 
3622
        ! table->no_keyread &&
 
3623
        (int) table->reginfo.lock_type <= (int) TL_READ_WITH_SHARED_LOCKS)
 
3624
    {
 
3625
      table->key_read=1;
 
3626
      table->cursor->extra(HA_EXTRA_KEYREAD);
 
3627
      tab->index= tab->ref.key;
 
3628
    }
 
3629
    error=join_read_const(tab);
 
3630
    if (table->key_read)
 
3631
    {
 
3632
      table->key_read=0;
 
3633
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
3634
    }
 
3635
    if (error)
 
3636
    {
 
3637
      tab->info="unique row not found";
 
3638
      /* Mark for EXPLAIN that the row was not found */
 
3639
      pos->setFanout(0.0);
 
3640
      pos->clearRefDependMap();
 
3641
      if (!table->maybe_null || error > 0)
 
3642
        return(error);
 
3643
    }
 
3644
  }
 
3645
  if (*tab->on_expr_ref && !table->null_row)
 
3646
  {
 
3647
    if ((table->null_row= test((*tab->on_expr_ref)->val_int() == 0)))
 
3648
      table->mark_as_null_row();
 
3649
  }
 
3650
  if (!table->null_row)
 
3651
    table->maybe_null=0;
 
3652
 
 
3653
  /* Check appearance of new constant items in Item_equal objects */
 
3654
  Join *join= tab->join;
 
3655
  if (join->conds)
 
3656
    update_const_equal_items(join->conds, tab);
 
3657
  TableList *tbl;
 
3658
  for (tbl= join->select_lex->leaf_tables; tbl; tbl= tbl->next_leaf)
 
3659
  {
 
3660
    TableList *embedded;
 
3661
    TableList *embedding= tbl;
 
3662
    do
 
3663
    {
 
3664
      embedded= embedding;
 
3665
      if (embedded->on_expr)
 
3666
         update_const_equal_items(embedded->on_expr, tab);
 
3667
      embedding= embedded->getEmbedding();
 
3668
    }
 
3669
    while (embedding &&
 
3670
           embedding->getNestedJoin()->join_list.head() == embedded);
 
3671
  }
 
3672
 
 
3673
  return(0);
 
3674
}
 
3675
 
 
3676
int join_read_system(JoinTable *tab)
 
3677
{
 
3678
  Table *table= tab->table;
 
3679
  int error;
 
3680
  if (table->status & STATUS_GARBAGE)           // If first read
 
3681
  {
 
3682
    if ((error=table->cursor->read_first_row(table->getInsertRecord(),
 
3683
                                           table->getShare()->getPrimaryKey())))
 
3684
    {
 
3685
      if (error != HA_ERR_END_OF_FILE)
 
3686
        return table->report_error(error);
 
3687
      tab->table->mark_as_null_row();
 
3688
      table->emptyRecord();                     // Make empty record
 
3689
      return -1;
 
3690
    }
 
3691
    table->storeRecord();
 
3692
  }
 
3693
  else if (!table->status)                      // Only happens with left join
 
3694
    table->restoreRecord();                     // restore old record
 
3695
  table->null_row=0;
 
3696
  return table->status ? -1 : 0;
 
3697
}
 
3698
 
3371
3699
/**
3372
3700
  Read a (constant) table when there is at most one matching row.
3373
3701
 
3439
3767
 
3440
3768
  if (!table->cursor->inited)
3441
3769
  {
3442
 
    error= table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3443
 
    if (error != 0)
3444
 
    {
3445
 
      table->print_error(error, MYF(0));
3446
 
    }
 
3770
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3447
3771
  }
3448
3772
 
3449
3773
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
3491
3815
 
3492
3816
  /* Initialize the index first */
3493
3817
  if (!table->cursor->inited)
3494
 
  {
3495
 
    error= table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3496
 
    if (error != 0)
3497
 
      return table->report_error(error);
3498
 
  }
 
3818
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3499
3819
 
3500
3820
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3501
3821
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3529
3849
  Table *table= tab->table;
3530
3850
 
3531
3851
  if (!table->cursor->inited)
3532
 
  {
3533
 
    error= table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3534
 
    if (error != 0)
3535
 
      return table->report_error(error);
3536
 
  }
 
3852
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3537
3853
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3538
3854
    return -1;
3539
3855
  if ((error=table->cursor->index_read_last_map(table->getInsertRecord(),
3648
3964
  if (tab->select && tab->select->quick && tab->select->quick->reset())
3649
3965
    return 1;
3650
3966
 
3651
 
  if (tab->read_record.init_read_record(tab->join->session, tab->table, tab->select, 1, true))
3652
 
    return 1;
 
3967
  tab->read_record.init_read_record(tab->join->session, tab->table, tab->select, 1, true);
3653
3968
 
3654
3969
  return (*tab->read_record.read_record)(&tab->read_record);
3655
3970
}
3682
3997
  }
3683
3998
 
3684
3999
  if (!table->cursor->inited)
3685
 
  {
3686
 
    error= table->cursor->startIndexScan(tab->index, tab->sorted);
3687
 
    if (error != 0)
3688
 
    {
3689
 
      table->report_error(error);
3690
 
      return -1;
3691
 
    }
3692
 
  }
 
4000
    table->cursor->startIndexScan(tab->index, tab->sorted);
3693
4001
  if ((error=tab->table->cursor->index_first(tab->table->getInsertRecord())))
3694
4002
  {
3695
4003
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3748
4056
  tab->read_record.index=tab->index;
3749
4057
  tab->read_record.record=table->getInsertRecord();
3750
4058
  if (!table->cursor->inited)
3751
 
  {
3752
 
    error= table->cursor->startIndexScan(tab->index, 1);
3753
 
    if (error != 0)
3754
 
      return table->report_error(error);
3755
 
  }
 
4059
    table->cursor->startIndexScan(tab->index, 1);
3756
4060
  if ((error= tab->table->cursor->index_last(tab->table->getInsertRecord())))
3757
4061
    return table->report_error(error);
3758
4062
 
3832
4136
              error=join->result->send_data(*join->fields) ? 1 : 0;
3833
4137
            join->send_records++;
3834
4138
          }
3835
 
          if (join->rollup.getState() != Rollup::STATE_NONE && error <= 0)
 
4139
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
3836
4140
          {
3837
4141
            if (join->rollup_send_data((uint32_t) (idx+1)))
3838
4142
              error= 1;
3893
4197
  Table *table=join->tmp_table;
3894
4198
  int     idx= -1;
3895
4199
 
3896
 
  if (join->session->getKilled())
 
4200
  if (join->session->killed)
3897
4201
  {                                             // Aborted by user
3898
4202
    join->session->send_kill_message();
3899
4203
    return NESTED_LOOP_KILLED;
3922
4226
            return NESTED_LOOP_ERROR;
3923
4227
          }
3924
4228
        }
3925
 
        if (join->rollup.getState() != Rollup::STATE_NONE)
 
4229
        if (join->rollup.state != ROLLUP::STATE_NONE)
3926
4230
        {
3927
4231
          if (join->rollup_write_data((uint32_t) (idx+1), table))
3928
4232
            return NESTED_LOOP_ERROR;
3941
4245
    if (idx < (int) join->send_group_parts)
3942
4246
    {
3943
4247
      copy_fields(&join->tmp_table_param);
3944
 
      if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
3945
 
        return NESTED_LOOP_ERROR;
 
4248
      copy_funcs(join->tmp_table_param.items_to_copy);
3946
4249
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
3947
4250
        return NESTED_LOOP_ERROR;
3948
4251
      return NESTED_LOOP_OK;
4197
4500
  @retval
4198
4501
    -1   Reverse key can be used
4199
4502
*/
4200
 
static int test_if_order_by_key(Order *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
 
4503
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
4201
4504
{
4202
4505
  KeyPartInfo *key_part= NULL;
4203
4506
  KeyPartInfo *key_part_end= NULL;
4303
4606
    - MAX_KEY                   If we can't use other key
4304
4607
    - the number of found key   Otherwise
4305
4608
*/
4306
 
static uint32_t test_if_subkey(Order *order,
 
4609
static uint32_t test_if_subkey(order_st *order,
4307
4610
                               Table *table,
4308
4611
                               uint32_t ref,
4309
4612
                               uint32_t ref_key_parts,
4405
4708
*/
4406
4709
bool find_field_in_order_list (Field *field, void *data)
4407
4710
{
4408
 
  Order *group= (Order *) data;
 
4711
  order_st *group= (order_st *) data;
4409
4712
  bool part_found= 0;
4410
 
  for (Order *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
 
4713
  for (order_st *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
4411
4714
  {
4412
4715
    Item *item= (*tmp_group->item)->real_item();
4413
4716
    if (item->type() == Item::FIELD_ITEM &&
4477
4780
  @retval
4478
4781
    1    We can use an index.
4479
4782
*/
4480
 
bool test_if_skip_sort_order(JoinTable *tab, Order *order, ha_rows select_limit, bool no_changes, const key_map *map)
 
4783
bool test_if_skip_sort_order(JoinTable *tab, order_st *order, ha_rows select_limit, bool no_changes, const key_map *map)
4481
4784
{
4482
4785
  int32_t ref_key;
4483
4786
  uint32_t ref_key_parts;
4494
4797
  */
4495
4798
  usable_keys= *map;
4496
4799
 
4497
 
  for (Order *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
 
4800
  for (order_st *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
4498
4801
  {
4499
4802
    Item *item= (*tmp_order->item)->real_item();
4500
4803
    if (item->type() != Item::FIELD_ITEM)
4920
5223
    -1          Some fatal error
4921
5224
    1           No records
4922
5225
*/
4923
 
int create_sort_index(Session *session, Join *join, Order *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
 
5226
int create_sort_index(Session *session, Join *join, order_st *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
4924
5227
{
4925
5228
  uint32_t length= 0;
4926
5229
  ha_rows examined_rows;
4947
5250
                              is_order_by ?  &table->keys_in_use_for_order_by :
4948
5251
                              &table->keys_in_use_for_group_by))
4949
5252
    return(0);
4950
 
  for (Order *ord= join->order; ord; ord= ord->next)
 
5253
  for (order_st *ord= join->order; ord; ord= ord->next)
4951
5254
    length++;
4952
 
  if (!(join->sortorder= make_unireg_sortorder(order, &length, join->sortorder)))
4953
 
  {
4954
 
    return(-1);
4955
 
  }
 
5255
  if (!(join->sortorder=
 
5256
        make_unireg_sortorder(order, &length, join->sortorder)))
 
5257
    goto err;
4956
5258
 
4957
5259
  table->sort.io_cache= new internal::IO_CACHE;
4958
5260
  table->status=0;                              // May be wrong if quick_select
4987
5289
                                                                 &tab->ref,
4988
5290
                                                                 tab->found_records))))
4989
5291
      {
4990
 
        return(-1);
 
5292
        goto err;
4991
5293
      }
4992
5294
    }
4993
5295
  }
4994
5296
 
4995
5297
  if (table->getShare()->getType())
4996
5298
    table->cursor->info(HA_STATUS_VARIABLE);    // Get record count
4997
 
 
4998
 
  FileSort filesort(*session);
4999
 
  table->sort.found_records=filesort.run(table,join->sortorder, length,
5000
 
                                         select, filesort_limit, 0,
5001
 
                                         examined_rows);
 
5299
  table->sort.found_records=filesort(session, table,join->sortorder, length,
 
5300
                                     select, filesort_limit, 0,
 
5301
                                     &examined_rows);
5002
5302
  tab->records= table->sort.found_records;      // For SQL_CALC_ROWS
5003
5303
  if (select)
5004
5304
  {
5016
5316
    table->key_read=0;
5017
5317
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
5018
5318
  }
5019
 
 
5020
5319
  return(table->sort.found_records == HA_POS_ERROR);
 
5320
err:
 
5321
  return(-1);
5021
5322
}
5022
5323
 
5023
5324
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
5031
5332
  org_record=(char*) (record=table->getInsertRecord())+offset;
5032
5333
  new_record=(char*) table->getUpdateRecord()+offset;
5033
5334
 
5034
 
  if ((error= cursor->startTableScan(1)))
5035
 
    goto err;
5036
 
 
 
5335
  cursor->startTableScan(1);
5037
5336
  error=cursor->rnd_next(record);
5038
5337
  for (;;)
5039
5338
  {
5040
 
    if (session->getKilled())
 
5339
    if (session->killed)
5041
5340
    {
5042
5341
      session->send_kill_message();
5043
5342
      error=0;
5150
5449
    return(1);
5151
5450
  }
5152
5451
 
5153
 
  if ((error= cursor->startTableScan(1)))
5154
 
    goto err;
5155
 
 
 
5452
  cursor->startTableScan(1);
5156
5453
  key_pos= &key_buffer[0];
5157
5454
  for (;;)
5158
5455
  {
5159
5456
    unsigned char *org_key_pos;
5160
 
    if (session->getKilled())
 
5457
    if (session->killed)
5161
5458
    {
5162
5459
      session->send_kill_message();
5163
5460
      error=0;
5211
5508
  return(1);
5212
5509
}
5213
5510
 
5214
 
SortField *make_unireg_sortorder(Order *order, uint32_t *length, SortField *sortorder)
 
5511
SortField *make_unireg_sortorder(order_st *order, uint32_t *length, SortField *sortorder)
5215
5512
{
5216
5513
  uint32_t count;
5217
5514
  SortField *sort,*pos;
5218
5515
 
5219
5516
  count=0;
5220
 
  for (Order *tmp = order; tmp; tmp=tmp->next)
 
5517
  for (order_st *tmp = order; tmp; tmp=tmp->next)
5221
5518
    count++;
5222
5519
  if (!sortorder)
5223
5520
    sortorder= (SortField*) memory::sql_alloc(sizeof(SortField) *
5342
5639
static bool find_order_in_list(Session *session, 
5343
5640
                               Item **ref_pointer_array, 
5344
5641
                               TableList *tables,
5345
 
                               Order *order,
 
5642
                               order_st *order,
5346
5643
                               List<Item> &fields,
5347
5644
                               List<Item> &all_fields,
5348
5645
                               bool is_group_field)
5364
5661
    if (!count || count > fields.elements)
5365
5662
    {
5366
5663
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
5367
 
               order_item->full_name(), session->where());
 
5664
               order_item->full_name(), session->where);
5368
5665
      return true;
5369
5666
    }
5370
5667
    order->item= ref_pointer_array + count - 1;
5441
5738
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
5442
5739
                          ER(ER_NON_UNIQ_ERROR),
5443
5740
                          ((Item_ident*) order_item)->field_name,
5444
 
                          session->where());
 
5741
                          session->where);
5445
5742
    }
5446
5743
  }
5447
5744
 
5481
5778
                TableList *tables,
5482
5779
                            List<Item> &fields,
5483
5780
                List<Item> &all_fields,
5484
 
                Order *order)
 
5781
                order_st *order)
5485
5782
{
5486
 
  session->setWhere("order clause");
 
5783
  session->where="order clause";
5487
5784
  for (; order; order=order->next)
5488
5785
  {
5489
5786
    if (find_order_in_list(session, ref_pointer_array, tables, order, fields,
5523
5820
                TableList *tables,
5524
5821
                      List<Item> &fields,
5525
5822
                List<Item> &all_fields,
5526
 
                Order *order,
 
5823
                order_st *order,
5527
5824
                      bool *hidden_group_fields)
5528
5825
{
5529
5826
  *hidden_group_fields=0;
5530
 
  Order *ord;
 
5827
  order_st *ord;
5531
5828
 
5532
5829
  if (!order)
5533
5830
    return 0;                           /* Everything is ok */
5534
5831
 
5535
5832
  uint32_t org_fields=all_fields.elements;
5536
5833
 
5537
 
  session->setWhere("group statement");
 
5834
  session->where="group statement";
5538
5835
  for (ord= order; ord; ord= ord->next)
5539
5836
  {
5540
5837
    if (find_order_in_list(session, ref_pointer_array, tables, ord, fields,
5617
5914
  Try to use the fields in the order given by 'order' to allow one to
5618
5915
  optimize away 'order by'.
5619
5916
*/
5620
 
Order *create_distinct_group(Session *session,
 
5917
order_st *create_distinct_group(Session *session,
5621
5918
                                Item **ref_pointer_array,
5622
 
                                Order *order_list,
 
5919
                                order_st *order_list,
5623
5920
                                List<Item> &fields,
5624
5921
                                List<Item> &,
5625
5922
                                bool *all_order_by_fields_used)
5626
5923
{
5627
5924
  List_iterator<Item> li(fields);
5628
5925
  Item *item;
5629
 
  Order *order,*group,**prev;
 
5926
  order_st *order,*group,**prev;
5630
5927
 
5631
5928
  *all_order_by_fields_used= 1;
5632
5929
  while ((item=li++))
5637
5934
  {
5638
5935
    if (order->in_field_list)
5639
5936
    {
5640
 
      Order *ord=(Order*) session->getMemRoot()->duplicate((char*) order,sizeof(Order));
 
5937
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
5641
5938
      if (!ord)
5642
5939
        return 0;
5643
5940
      *prev=ord;
5657
5954
        Don't put duplicate columns from the SELECT list into the
5658
5955
        GROUP BY list.
5659
5956
      */
5660
 
      Order *ord_iter;
 
5957
      order_st *ord_iter;
5661
5958
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
5662
5959
        if ((*ord_iter->item)->eq(item, 1))
5663
5960
          goto next_item;
5664
5961
 
5665
 
      Order *ord=(Order*) session->calloc(sizeof(Order));
 
5962
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
5666
5963
      if (!ord)
5667
5964
        return 0;
5668
5965
 
6134
6431
}
6135
6432
 
6136
6433
/** Copy result of functions to record in tmp_table. */
6137
 
bool copy_funcs(Item **func_ptr, const Session *session)
 
6434
void copy_funcs(Item **func_ptr)
6138
6435
{
6139
6436
  Item *func;
6140
6437
  for (; (func = *func_ptr) ; func_ptr++)
6141
 
  {
6142
6438
    func->save_in_result_field(1);
6143
 
    /*
6144
 
      Need to check the THD error state because Item::val_xxx() don't
6145
 
      return error code, but can generate errors
6146
 
      TODO: change it for a real status check when Item::val_xxx()
6147
 
      are extended to return status code.
6148
 
    */
6149
 
    if (session->is_error())
6150
 
      return true;
6151
 
  }
6152
 
  return false;
6153
6439
}
6154
6440
 
6155
6441
/**
6209
6495
  @retval
6210
6496
    1   on error
6211
6497
*/
6212
 
bool change_group_ref(Session *session, Item_func *expr, Order *group_list, bool *changed)
 
6498
bool change_group_ref(Session *session, Item_func *expr, order_st *group_list, bool *changed)
6213
6499
{
6214
6500
  if (expr->arg_count)
6215
6501
  {
6223
6509
      Item *item= *arg;
6224
6510
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
6225
6511
      {
6226
 
        Order *group_tmp;
 
6512
        order_st *group_tmp;
6227
6513
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
6228
6514
        {
6229
6515
          if (item->eq(*group_tmp->item,0))
6292
6578
{
6293
6579
  /* List is reversed => we should reverse it before using */
6294
6580
  List_iterator_fast<TableList> ti(*tables);
6295
 
  TableList **table= (TableList **)session->getMemRoot()->allocate(sizeof(TableList*) *
 
6581
  TableList **table= (TableList **)session->alloc(sizeof(TableList*) *
6296
6582
                                                tables->elements);
6297
6583
  if (table == 0)
6298
6584
    return;  // out of memory
6375
6661
  if (group_list.elements)
6376
6662
  {
6377
6663
    str->append(STRING_WITH_LEN(" group by "));
6378
 
    print_order(str, (Order *) group_list.first, query_type);
 
6664
    print_order(str, (order_st *) group_list.first, query_type);
6379
6665
    switch (olap)
6380
6666
    {
6381
6667
      case CUBE_TYPE:
6406
6692
  if (order_list.elements)
6407
6693
  {
6408
6694
    str->append(STRING_WITH_LEN(" order by "));
6409
 
    print_order(str, (Order *) order_list.first, query_type);
 
6695
    print_order(str, (order_st *) order_list.first, query_type);
6410
6696
  }
6411
6697
 
6412
6698
  // limit