~jlukas79/+junk/mysql-server

« back to all changes in this revision

Viewing changes to sql/sql_prepare.cc

manual merge 6.0-main --> 6.0-bka-review

Show diffs side-by-side

added added

removed removed

Lines of Context:
155
155
  virtual void cleanup_stmt();
156
156
  bool set_name(LEX_STRING *name);
157
157
  inline void close_cursor() { delete cursor; cursor= 0; }
158
 
 
 
158
  inline bool is_in_use() { return flags & (uint) IS_IN_USE; }
 
159
  inline bool is_protocol_text() const { return protocol == &thd->protocol_text; }
159
160
  bool prepare(const char *packet, uint packet_length);
160
 
  bool execute(String *expanded_query, bool open_cursor);
 
161
  bool execute_loop(String *expanded_query,
 
162
                    bool open_cursor,
 
163
                    uchar *packet_arg, uchar *packet_end_arg);
161
164
  /* Destroy this statement */
162
 
  bool deallocate();
 
165
  void deallocate();
163
166
private:
164
167
  /**
165
 
    Store the parsed tree of a prepared statement here.
166
 
  */
167
 
  LEX main_lex;
168
 
  /**
169
168
    The memory root to allocate parsed tree elements (instances of Item,
170
169
    SELECT_LEX and other classes).
171
170
  */
172
171
  MEM_ROOT main_mem_root;
 
172
  /* Version of the stored functions cache at the time of prepare. */
 
173
  ulong m_sp_cache_version;
 
174
private:
 
175
  bool set_db(const char *db, uint db_length);
 
176
  bool set_parameters(String *expanded_query,
 
177
                      uchar *packet, uchar *packet_end);
 
178
  bool execute(String *expanded_query, bool open_cursor);
 
179
  bool reprepare();
 
180
  bool validate_metadata(Prepared_statement  *copy);
 
181
  void swap_prepared_statement(Prepared_statement *copy);
173
182
};
174
183
 
175
184
 
198
207
*/
199
208
 
200
209
static Prepared_statement *
201
 
find_prepared_statement(THD *thd, ulong id, const char *where)
 
210
find_prepared_statement(THD *thd, ulong id)
202
211
{
203
212
  /*
204
213
    To strictly separate namespaces of SQL prepared statements and C API
208
217
  Statement *stmt= thd->stmt_map.find(id);
209
218
 
210
219
  if (stmt == 0 || stmt->type() != Query_arena::PREPARED_STATEMENT)
211
 
  {
212
 
    char llbuf[22];
213
 
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf), llstr(id, llbuf),
214
 
             where);
215
 
    return 0;
216
 
  }
 
220
    return NULL;
 
221
 
217
222
  return (Prepared_statement *) stmt;
218
223
}
219
224
 
945
950
 
946
951
#endif /*!EMBEDDED_LIBRARY*/
947
952
 
 
953
/**
 
954
  Setup data conversion routines using an array of parameter
 
955
  markers from the original prepared statement.
 
956
  Swap the parameter data of the original prepared
 
957
  statement to the new one.
 
958
 
 
959
  Used only when we re-prepare a prepared statement.
 
960
  There are two reasons for this function to exist:
 
961
 
 
962
  1) In the binary client/server protocol, parameter metadata
 
963
  is sent only at first execute. Consequently, if we need to
 
964
  reprepare a prepared statement at a subsequent execution,
 
965
  we may not have metadata information in the packet.
 
966
  In that case we use the parameter array of the original
 
967
  prepared statement to setup parameter types of the new
 
968
  prepared statement.
 
969
 
 
970
  2) In the binary client/server protocol, we may supply
 
971
  long data in pieces. When the last piece is supplied,
 
972
  we assemble the pieces and convert them from client
 
973
  character set to the connection character set. After
 
974
  that the parameter value is only available inside
 
975
  the parameter, the original pieces are lost, and thus
 
976
  we can only assign the corresponding parameter of the
 
977
  reprepared statement from the original value.
 
978
 
 
979
  @param[out]  param_array_dst  parameter markers of the new statement
 
980
  @param[in]   param_array_src  parameter markers of the original
 
981
                                statement
 
982
  @param[in]   param_count      total number of parameters. Is the
 
983
                                same in src and dst arrays, since
 
984
                                the statement query is the same
 
985
 
 
986
  @return this function never fails
 
987
*/
 
988
 
 
989
static void
 
990
swap_parameter_array(Item_param **param_array_dst,
 
991
                     Item_param **param_array_src,
 
992
                     uint param_count)
 
993
{
 
994
  Item_param **dst= param_array_dst;
 
995
  Item_param **src= param_array_src;
 
996
  Item_param **end= param_array_dst + param_count;
 
997
 
 
998
  for (; dst < end; ++src, ++dst)
 
999
    (*dst)->set_param_type_and_swap_value(*src);
 
1000
}
 
1001
 
948
1002
 
949
1003
/**
950
1004
  Assign prepared statement parameters from user variables.
1102
1156
    if (table_list->lock_type == TL_WRITE_DELAYED &&
1103
1157
        !(table_list->table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED))
1104
1158
    {
1105
 
      my_error(ER_ILLEGAL_HA, MYF(0), (table_list->view ?
1106
 
                                       table_list->view_name.str :
1107
 
                                       table_list->table_name));
 
1159
      my_error(ER_DELAYED_NOT_SUPPORTED, MYF(0), (table_list->view ?
 
1160
                                                  table_list->view_name.str :
 
1161
                                                  table_list->table_name));
1108
1162
      goto error;
1109
1163
    }
1110
1164
    while ((values= its++))
1268
1322
*/
1269
1323
 
1270
1324
static int mysql_test_select(Prepared_statement *stmt,
1271
 
                             TABLE_LIST *tables, bool text_protocol)
 
1325
                             TABLE_LIST *tables)
1272
1326
{
1273
1327
  THD *thd= stmt->thd;
1274
1328
  LEX *lex= stmt->lex;
1296
1350
    goto error;
1297
1351
 
1298
1352
  thd->used_tables= 0;                        // Updated by setup_fields
1299
 
  thd->thd_marker= 0;
 
1353
  thd->thd_marker.emb_on_expr_nest= 0;
1300
1354
 
1301
1355
  /*
1302
1356
    JOIN::prepare calls
1305
1359
  */
1306
1360
  if (unit->prepare(thd, 0, 0))
1307
1361
    goto error;
1308
 
  if (!lex->describe && !text_protocol)
 
1362
  if (!lex->describe && !stmt->is_protocol_text())
1309
1363
  {
1310
1364
    /* Make copy of item list, as change_columns may change it */
1311
1365
    List<Item> fields(lex->select_lex.item_list);
1397
1451
 
1398
1452
 
1399
1453
/**
 
1454
  Validate and prepare for execution CALL statement expressions.
 
1455
 
 
1456
  @param stmt               prepared statement
 
1457
  @param tables             list of tables used in this query
 
1458
  @param value_list         list of expressions
 
1459
 
 
1460
  @retval FALSE             success
 
1461
  @retval TRUE              error, error message is set in THD
 
1462
*/
 
1463
 
 
1464
static bool mysql_test_call_fields(Prepared_statement *stmt,
 
1465
                                   TABLE_LIST *tables,
 
1466
                                   List<Item> *value_list)
 
1467
{
 
1468
  DBUG_ENTER("mysql_test_call_fields");
 
1469
 
 
1470
  List_iterator<Item> it(*value_list);
 
1471
  THD *thd= stmt->thd;
 
1472
  Item *item;
 
1473
 
 
1474
  if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE, FALSE,
 
1475
                                   UINT_MAX) ||
 
1476
      open_normal_and_derived_tables(thd, tables, 0))
 
1477
    goto err;
 
1478
 
 
1479
  while ((item= it++))
 
1480
  {
 
1481
    if (!item->fixed && item->fix_fields(thd, it.ref()) ||
 
1482
        item->check_cols(1))
 
1483
      goto err;
 
1484
  }
 
1485
  DBUG_RETURN(FALSE);
 
1486
err:
 
1487
  DBUG_RETURN(TRUE);
 
1488
}
 
1489
 
 
1490
 
 
1491
/**
1400
1492
  Check internal SELECT of the prepared command.
1401
1493
 
1402
1494
  @param stmt                      prepared statement
1504
1596
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
1505
1597
    {
1506
1598
      lex->link_first_table_back(create_table, link_to_local);
1507
 
      create_table->create= TRUE;
 
1599
      create_table->open_type= TABLE_LIST::OPEN_OR_CREATE;
1508
1600
    }
1509
1601
 
1510
1602
    if (open_normal_and_derived_tables(stmt->thd, lex->query_tables, 0))
1517
1609
 
1518
1610
    res= select_like_stmt_test(stmt, 0, 0);
1519
1611
  }
 
1612
  else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE)
 
1613
  {
 
1614
    /*
 
1615
      Check that the source table exist, and also record
 
1616
      its metadata version. Even though not strictly necessary,
 
1617
      we validate metadata of all CREATE TABLE statements,
 
1618
      which keeps metadata validation code simple.
 
1619
    */
 
1620
    if (open_normal_and_derived_tables(stmt->thd, lex->query_tables, 0))
 
1621
      DBUG_RETURN(TRUE);
 
1622
  }
1520
1623
 
1521
1624
  /* put tables back for PS rexecuting */
1522
1625
  lex->link_first_table_back(create_table, link_to_local);
1713
1816
    TRUE              error, error message is set in THD (but not sent)
1714
1817
*/
1715
1818
 
1716
 
static bool check_prepared_statement(Prepared_statement *stmt,
1717
 
                                     bool text_protocol)
 
1819
static bool check_prepared_statement(Prepared_statement *stmt)
1718
1820
{
1719
1821
  THD *thd= stmt->thd;
1720
1822
  LEX *lex= stmt->lex;
1733
1835
  lex->select_lex.context.resolve_in_table_list_only(select_lex->
1734
1836
                                                     get_table_list());
1735
1837
 
 
1838
  /* Reset warning count for each query that uses tables */
 
1839
  if ((tables || !lex->is_single_level_stmt()) && !thd->spcont)
 
1840
    mysql_reset_errors(thd, 0);
 
1841
 
1736
1842
  switch (sql_command) {
1737
1843
  case SQLCOM_REPLACE:
1738
1844
  case SQLCOM_INSERT:
1755
1861
  case SQLCOM_DELETE:
1756
1862
    res= mysql_test_delete(stmt, tables);
1757
1863
    break;
1758
 
 
 
1864
  /* The following allow WHERE clause, so they must be tested like SELECT */
 
1865
  case SQLCOM_SHOW_DATABASES:
 
1866
  case SQLCOM_SHOW_TABLES:
 
1867
  case SQLCOM_SHOW_TRIGGERS:
 
1868
  case SQLCOM_SHOW_EVENTS:
 
1869
  case SQLCOM_SHOW_OPEN_TABLES:
 
1870
  case SQLCOM_SHOW_FIELDS:
 
1871
  case SQLCOM_SHOW_KEYS:
 
1872
  case SQLCOM_SHOW_COLLATIONS:
 
1873
  case SQLCOM_SHOW_CHARSETS:
 
1874
  case SQLCOM_SHOW_VARIABLES:
 
1875
  case SQLCOM_SHOW_STATUS:
 
1876
  case SQLCOM_SHOW_TABLE_STATUS:
 
1877
  case SQLCOM_SHOW_STATUS_PROC:
 
1878
  case SQLCOM_SHOW_STATUS_FUNC:
1759
1879
  case SQLCOM_SELECT:
1760
 
    res= mysql_test_select(stmt, tables, text_protocol);
 
1880
    res= mysql_test_select(stmt, tables);
1761
1881
    if (res == 2)
1762
1882
    {
1763
1883
      /* Statement and field info has already been sent */
1780
1900
    res= mysql_test_do_fields(stmt, tables, lex->insert_list);
1781
1901
    break;
1782
1902
 
 
1903
  case SQLCOM_CALL:
 
1904
    res= mysql_test_call_fields(stmt, tables, &lex->value_list);
 
1905
    break;
1783
1906
  case SQLCOM_SET_OPTION:
1784
1907
    res= mysql_test_set_fields(stmt, tables, &lex->var_list);
1785
1908
    break;
1800
1923
  case SQLCOM_SHOW_PROCESSLIST:
1801
1924
  case SQLCOM_SHOW_STORAGE_ENGINES:
1802
1925
  case SQLCOM_SHOW_PRIVILEGES:
1803
 
  case SQLCOM_SHOW_COLUMN_TYPES:
1804
1926
  case SQLCOM_SHOW_ENGINE_LOGS:
1805
1927
  case SQLCOM_SHOW_ENGINE_STATUS:
1806
1928
  case SQLCOM_SHOW_ENGINE_MUTEX:
1829
1951
  case SQLCOM_DROP_INDEX:
1830
1952
  case SQLCOM_ROLLBACK:
1831
1953
  case SQLCOM_TRUNCATE:
1832
 
  case SQLCOM_CALL:
1833
1954
  case SQLCOM_DROP_VIEW:
1834
1955
  case SQLCOM_REPAIR:
1835
1956
  case SQLCOM_ANALYZE:
1872
1993
    break;
1873
1994
  }
1874
1995
  if (res == 0)
1875
 
    DBUG_RETURN(text_protocol? FALSE : (send_prep_stmt(stmt, 0) ||
1876
 
                                        thd->protocol->flush()));
 
1996
    DBUG_RETURN(stmt->is_protocol_text() ?
 
1997
                FALSE : (send_prep_stmt(stmt, 0) || thd->protocol->flush()));
1877
1998
error:
1878
1999
  DBUG_RETURN(TRUE);
1879
2000
}
1963
2084
    DBUG_VOID_RETURN;
1964
2085
  }
1965
2086
 
1966
 
  /* Reset warnings from previous command */
1967
 
  mysql_reset_errors(thd, 0);
1968
2087
  sp_cache_flush_obsolete(&thd->sp_proc_cache);
1969
2088
  sp_cache_flush_obsolete(&thd->sp_func_cache);
1970
2089
 
2122
2241
      If there is a statement with the same name, remove it. It is ok to
2123
2242
      remove old and fail to insert a new one at the same time.
2124
2243
    */
2125
 
    if (stmt->deallocate())
 
2244
    if (stmt->is_in_use())
 
2245
    {
 
2246
      my_error(ER_PS_NO_RECURSION, MYF(0));
2126
2247
      DBUG_VOID_RETURN;
 
2248
    }
 
2249
 
 
2250
    stmt->deallocate();
2127
2251
  }
2128
2252
 
2129
2253
  if (! (query= get_dynamic_sql_string(lex, &query_len)) ||
2309
2433
  ulong flags= (ulong) packet[4];
2310
2434
  /* Query text for binary, general or slow log, if any of them is open */
2311
2435
  String expanded_query;
2312
 
#ifndef EMBEDDED_LIBRARY
2313
2436
  uchar *packet_end= packet + packet_length;
2314
 
#endif
2315
2437
  Prepared_statement *stmt;
2316
 
  bool error;
 
2438
  bool open_cursor;
2317
2439
  DBUG_ENTER("mysql_stmt_execute");
2318
2440
 
2319
2441
  packet+= 9;                               /* stmt_id + 5 bytes of flags */
2321
2443
  /* First of all clear possible warnings from the previous command */
2322
2444
  mysql_reset_thd_for_next_command(thd);
2323
2445
 
2324
 
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_execute")))
 
2446
  if (!(stmt= find_prepared_statement(thd, stmt_id)))
 
2447
  {
 
2448
    char llbuf[22];
 
2449
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
 
2450
             llstr(stmt_id, llbuf), "mysql_stmt_execute");
2325
2451
    DBUG_VOID_RETURN;
 
2452
  }
2326
2453
 
2327
2454
#if defined(ENABLED_PROFILING)
2328
2455
  thd->profiling.set_query_source(stmt->query, stmt->query_length);
2329
2456
#endif
2330
2457
  DBUG_PRINT("exec_query", ("%s", stmt->query));
2331
 
  DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt));
 
2458
  DBUG_PRINT("info",("stmt: %p", stmt));
2332
2459
 
2333
2460
  sp_cache_flush_obsolete(&thd->sp_proc_cache);
2334
2461
  sp_cache_flush_obsolete(&thd->sp_func_cache);
2335
2462
 
2336
 
#ifndef EMBEDDED_LIBRARY
2337
 
  if (stmt->param_count)
2338
 
  {
2339
 
    uchar *null_array= packet;
2340
 
    if (setup_conversion_functions(stmt, &packet, packet_end) ||
2341
 
        stmt->set_params(stmt, null_array, packet, packet_end,
2342
 
                         &expanded_query))
2343
 
      goto set_params_data_err;
2344
 
  }
2345
 
#else
2346
 
  /*
2347
 
    In embedded library we re-install conversion routines each time
2348
 
    we set params, and also we don't need to parse packet.
2349
 
    So we do it in one function.
2350
 
  */
2351
 
  if (stmt->param_count && stmt->set_params_data(stmt, &expanded_query))
2352
 
    goto set_params_data_err;
2353
 
#endif
2354
 
  if (!(specialflag & SPECIAL_NO_PRIOR))
2355
 
    my_pthread_setprio(pthread_self(),QUERY_PRIOR);
2356
 
 
2357
 
  /*
2358
 
    If the free_list is not empty, we'll wrongly free some externally
2359
 
    allocated items when cleaning up after validation of the prepared
2360
 
    statement.
2361
 
  */
2362
 
  DBUG_ASSERT(thd->free_list == NULL);
2363
 
 
2364
 
  error= stmt->execute(&expanded_query,
2365
 
                       test(flags & (ulong) CURSOR_TYPE_READ_ONLY));
2366
 
  if (!(specialflag & SPECIAL_NO_PRIOR))
2367
 
    my_pthread_setprio(pthread_self(), WAIT_PRIOR);
2368
 
  DBUG_VOID_RETURN;
2369
 
 
2370
 
set_params_data_err:
2371
 
  my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysql_stmt_execute");
2372
 
  reset_stmt_params(stmt);
2373
 
  DBUG_VOID_RETURN;
 
2463
  open_cursor= test(flags & (ulong) CURSOR_TYPE_READ_ONLY);
 
2464
 
 
2465
  stmt->execute_loop(&expanded_query, open_cursor, packet, packet_end);
 
2466
 
 
2467
  DBUG_VOID_RETURN;
 
2468
 
2374
2469
}
2375
2470
 
2376
2471
 
2414
2509
    DBUG_VOID_RETURN;
2415
2510
  }
2416
2511
 
2417
 
  DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt));
2418
 
 
2419
 
  /*
2420
 
    If the free_list is not empty, we'll wrongly free some externally
2421
 
    allocated items when cleaning up after validation of the prepared
2422
 
    statement.
2423
 
  */
2424
 
  DBUG_ASSERT(thd->free_list == NULL);
2425
 
 
2426
 
  if (stmt->set_params_from_vars(stmt, lex->prepared_stmt_params,
2427
 
                                 &expanded_query))
2428
 
    goto set_params_data_err;
2429
 
 
2430
 
  (void) stmt->execute(&expanded_query, FALSE);
2431
 
 
2432
 
  DBUG_VOID_RETURN;
2433
 
 
2434
 
set_params_data_err:
2435
 
  my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
2436
 
  reset_stmt_params(stmt);
 
2512
  DBUG_PRINT("info",("stmt: %p", stmt));
 
2513
 
 
2514
  (void) stmt->execute_loop(&expanded_query, FALSE, NULL, NULL);
 
2515
 
2437
2516
  DBUG_VOID_RETURN;
2438
2517
}
2439
2518
 
2459
2538
  /* First of all clear possible warnings from the previous command */
2460
2539
  mysql_reset_thd_for_next_command(thd);
2461
2540
  status_var_increment(thd->status_var.com_stmt_fetch);
2462
 
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_fetch")))
 
2541
  if (!(stmt= find_prepared_statement(thd, stmt_id)))
 
2542
  {
 
2543
    char llbuf[22];
 
2544
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
 
2545
             llstr(stmt_id, llbuf), "mysql_stmt_fetch");
2463
2546
    DBUG_VOID_RETURN;
 
2547
  }
2464
2548
 
2465
2549
  cursor= stmt->cursor;
2466
2550
  if (!cursor)
2521
2605
  mysql_reset_thd_for_next_command(thd);
2522
2606
 
2523
2607
  status_var_increment(thd->status_var.com_stmt_reset);
2524
 
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_reset")))
 
2608
  if (!(stmt= find_prepared_statement(thd, stmt_id)))
 
2609
  {
 
2610
    char llbuf[22];
 
2611
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
 
2612
             llstr(stmt_id, llbuf), "mysql_stmt_reset");
2525
2613
    DBUG_VOID_RETURN;
 
2614
  }
2526
2615
 
2527
2616
  stmt->close_cursor();
2528
2617
 
2558
2647
 
2559
2648
  thd->main_da.disable_status();
2560
2649
 
2561
 
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_close")))
 
2650
  if (!(stmt= find_prepared_statement(thd, stmt_id)))
2562
2651
    DBUG_VOID_RETURN;
2563
2652
 
2564
2653
  /*
2565
2654
    The only way currently a statement can be deallocated when it's
2566
2655
    in use is from within Dynamic SQL.
2567
2656
  */
2568
 
  DBUG_ASSERT(! (stmt->flags & (uint) Prepared_statement::IS_IN_USE));
2569
 
  (void) stmt->deallocate();
 
2657
  DBUG_ASSERT(! stmt->is_in_use());
 
2658
  stmt->deallocate();
2570
2659
  general_log_print(thd, thd->command, NullS);
2571
2660
 
2572
2661
  DBUG_VOID_RETURN;
2593
2682
                      name->str));
2594
2683
 
2595
2684
  if (! (stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
2596
 
  {
2597
2685
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
2598
2686
             name->length, name->str, "DEALLOCATE PREPARE");
2599
 
    return;
2600
 
  }
2601
 
 
2602
 
  if (stmt->deallocate() == 0)
 
2687
  else if (stmt->is_in_use())
 
2688
    my_error(ER_PS_NO_RECURSION, MYF(0));
 
2689
  else
 
2690
  {
 
2691
    stmt->deallocate();
2603
2692
    my_ok(thd);
 
2693
  }
2604
2694
}
2605
2695
 
2606
2696
/**
2634
2724
#ifndef EMBEDDED_LIBRARY
2635
2725
  /* Minimal size of long data packet is 6 bytes */
2636
2726
  if (packet_length < MYSQL_LONG_DATA_HEADER)
2637
 
  {
2638
 
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysql_stmt_send_long_data");
2639
2727
    DBUG_VOID_RETURN;
2640
 
  }
2641
2728
#endif
2642
2729
 
2643
2730
  stmt_id= uint4korr(packet);
2644
2731
  packet+= 4;
2645
2732
 
2646
 
  if (!(stmt=find_prepared_statement(thd, stmt_id,
2647
 
                                     "mysql_stmt_send_long_data")))
 
2733
  if (!(stmt=find_prepared_statement(thd, stmt_id)))
2648
2734
    DBUG_VOID_RETURN;
2649
2735
 
2650
2736
  param_number= uint2korr(packet);
2730
2816
****************************************************************************/
2731
2817
 
2732
2818
Prepared_statement::Prepared_statement(THD *thd_arg, Protocol *protocol_arg)
2733
 
  :Statement(&main_lex, &main_mem_root,
 
2819
  :Statement(NULL, &main_mem_root,
2734
2820
             INITIALIZED, ++thd_arg->statement_id_counter),
2735
2821
  thd(thd_arg),
2736
2822
  result(thd_arg),
2738
2824
  param_array(0),
2739
2825
  param_count(0),
2740
2826
  last_errno(0),
2741
 
  flags((uint) IS_IN_USE)
 
2827
  flags((uint) IS_IN_USE),
 
2828
  m_sp_cache_version(0)
2742
2829
{
2743
2830
  init_sql_alloc(&main_mem_root, thd_arg->variables.query_alloc_block_size,
2744
2831
                  thd_arg->variables.query_prealloc_size);
2793
2880
Prepared_statement::~Prepared_statement()
2794
2881
{
2795
2882
  DBUG_ENTER("Prepared_statement::~Prepared_statement");
2796
 
  DBUG_PRINT("enter",("stmt: 0x%lx  cursor: 0x%lx",
2797
 
                      (long) this, (long) cursor));
 
2883
  DBUG_PRINT("enter",("stmt: %p  cursor: %p",
 
2884
                      this, cursor));
2798
2885
  delete cursor;
2799
2886
  /*
2800
2887
    We have to call free on the items even if cleanup is called as some items,
2801
2888
    like Item_param, don't free everything until free_items()
2802
2889
  */
2803
2890
  free_items();
2804
 
  delete lex->result;
 
2891
  if (lex)
 
2892
  {
 
2893
    delete lex->result;
 
2894
    delete (st_lex_local *) lex;
 
2895
  }
2805
2896
  free_root(&main_mem_root, MYF(0));
2806
2897
  DBUG_VOID_RETURN;
2807
2898
}
2816
2907
void Prepared_statement::cleanup_stmt()
2817
2908
{
2818
2909
  DBUG_ENTER("Prepared_statement::cleanup_stmt");
2819
 
  DBUG_PRINT("enter",("stmt: 0x%lx", (long) this));
 
2910
  DBUG_PRINT("enter",("stmt: %p", this));
2820
2911
 
2821
2912
  DBUG_ASSERT(lex->sphead == 0);
2822
2913
  /* The order is important */
2837
2928
  return name.str == 0;
2838
2929
}
2839
2930
 
 
2931
 
 
2932
/**
 
2933
  Remember the current database.
 
2934
 
 
2935
  We must reset/restore the current database during execution of
 
2936
  a prepared statement since it affects execution environment:
 
2937
  privileges, @@character_set_database, and other.
 
2938
 
 
2939
  @return Returns an error if out of memory.
 
2940
*/
 
2941
 
 
2942
bool
 
2943
Prepared_statement::set_db(const char *db_arg, uint db_length_arg)
 
2944
{
 
2945
  /* Remember the current database. */
 
2946
  if (db_arg && db_length_arg)
 
2947
  {
 
2948
    db= this->strmake(db_arg, db_length_arg);
 
2949
    db_length= db_length_arg;
 
2950
  }
 
2951
  else
 
2952
  {
 
2953
    db= NULL;
 
2954
    db_length= 0;
 
2955
  }
 
2956
  return db_arg != NULL && db == NULL;
 
2957
}
 
2958
 
2840
2959
/**************************************************************************
2841
2960
  Common parts of mysql_[sql]_stmt_prepare, mysql_[sql]_stmt_execute.
2842
2961
  Essentially, these functions do all the magic of preparing/executing
2878
2997
  */
2879
2998
  status_var_increment(thd->status_var.com_stmt_prepare);
2880
2999
 
 
3000
  if (! (lex= new (mem_root) st_lex_local))
 
3001
    DBUG_RETURN(TRUE);
 
3002
 
 
3003
  if (set_db(thd->db, thd->db_length))
 
3004
    DBUG_RETURN(TRUE);
 
3005
 
2881
3006
  /*
2882
3007
    alloc_query() uses thd->memroot && thd->query, so we should call
2883
3008
    both of backup_statement() and backup_query_arena() here.
2905
3030
 
2906
3031
  lex->set_trg_event_type_for_tables();
2907
3032
 
2908
 
  /* Remember the current database. */
2909
 
 
2910
 
  if (thd->db && thd->db_length)
2911
 
  {
2912
 
    db= this->strmake(thd->db, thd->db_length);
2913
 
    db_length= thd->db_length;
2914
 
  }
2915
 
  else
2916
 
  {
2917
 
    db= NULL;
2918
 
    db_length= 0;
2919
 
  }
2920
 
 
2921
3033
  /*
2922
3034
    While doing context analysis of the query (in check_prepared_statement)
2923
3035
    we allocate a lot of additional memory: for open tables, JOINs, derived
2941
3053
  */
2942
3054
 
2943
3055
  if (error == 0)
2944
 
    error= check_prepared_statement(this, name.str != 0);
 
3056
    error= check_prepared_statement(this);
2945
3057
 
2946
3058
  /*
2947
3059
    Currently CREATE PROCEDURE/TRIGGER/EVENT are prohibited in prepared
2966
3078
    init_stmt_after_parse(lex);
2967
3079
    state= Query_arena::PREPARED;
2968
3080
    flags&= ~ (uint) IS_IN_USE;
 
3081
    /*
 
3082
      This is for prepared statement validation purposes.
 
3083
      A statement looks up and pre-loads all its stored functions
 
3084
      at prepare. Later on, if a function is gone from the cache,
 
3085
      execute may fail.
 
3086
      Remember the cache version to be able to invalidate the prepared
 
3087
      statement at execute if it changes.
 
3088
      We only need to care about version of the stored functions cache:
 
3089
      if a prepared statement uses a stored procedure, it's indirect,
 
3090
      via a stored function. The only exception is SQLCOM_CALL,
 
3091
      but the latter one looks up the stored procedure each time
 
3092
      it's invoked, rather than once at prepare.
 
3093
    */
 
3094
    m_sp_cache_version= sp_cache_version(&thd->sp_func_cache);
2969
3095
 
2970
3096
    /* 
2971
3097
      Log COM_EXECUTE to the general log. Note, that in case of SQL
2988
3114
  DBUG_RETURN(error);
2989
3115
}
2990
3116
 
 
3117
 
 
3118
/**
 
3119
  Assign parameter values either from variables, in case of SQL PS
 
3120
  or from the execute packet.
 
3121
 
 
3122
  @param expanded_query  a container with the original SQL statement.
 
3123
                         '?' placeholders will be replaced with
 
3124
                         their values in case of success.
 
3125
                         The result is used for logging and replication
 
3126
  @param packet          pointer to execute packet.
 
3127
                         NULL in case of SQL PS
 
3128
  @param packet_end      end of the packet. NULL in case of SQL PS
 
3129
 
 
3130
  @todo Use a paremeter source class family instead of 'if's, and
 
3131
  support stored procedure variables.
 
3132
 
 
3133
  @retval TRUE an error occurred when assigning a parameter (likely
 
3134
          a conversion error or out of memory, or malformed packet)
 
3135
  @retval FALSE success
 
3136
*/
 
3137
 
 
3138
bool
 
3139
Prepared_statement::set_parameters(String *expanded_query,
 
3140
                                   uchar *packet, uchar *packet_end)
 
3141
{
 
3142
  bool is_sql_ps= packet == NULL;
 
3143
  bool res= FALSE;
 
3144
 
 
3145
  if (is_sql_ps)
 
3146
  {
 
3147
    /* SQL prepared statement */
 
3148
    res= set_params_from_vars(this, thd->lex->prepared_stmt_params,
 
3149
                              expanded_query);
 
3150
  }
 
3151
  else if (param_count)
 
3152
  {
 
3153
#ifndef EMBEDDED_LIBRARY
 
3154
    uchar *null_array= packet;
 
3155
    res= (setup_conversion_functions(this, &packet, packet_end) ||
 
3156
          set_params(this, null_array, packet, packet_end, expanded_query));
 
3157
#else
 
3158
    /*
 
3159
      In embedded library we re-install conversion routines each time
 
3160
      we set parameters, and also we don't need to parse packet.
 
3161
      So we do it in one function.
 
3162
    */
 
3163
    res= set_params_data(this, expanded_query);
 
3164
#endif
 
3165
  }
 
3166
  if (res)
 
3167
  {
 
3168
    my_error(ER_WRONG_ARGUMENTS, MYF(0),
 
3169
             is_sql_ps ? "EXECUTE" : "mysql_stmt_execute");
 
3170
    reset_stmt_params(this);
 
3171
  }
 
3172
  return res;
 
3173
}
 
3174
 
 
3175
 
 
3176
/**
 
3177
  Execute a prepared statement. Re-prepare it a limited number
 
3178
  of times if necessary.
 
3179
 
 
3180
  Try to execute a prepared statement. If there is a metadata
 
3181
  validation error, prepare a new copy of the prepared statement,
 
3182
  swap the old and the new statements, and try again.
 
3183
  If there is a validation error again, repeat the above, but
 
3184
  perform no more than MAX_REPREPARE_ATTEMPTS.
 
3185
 
 
3186
  @note We have to try several times in a loop since we
 
3187
  release metadata locks on tables after prepared statement
 
3188
  prepare. Therefore, a DDL statement may sneak in between prepare
 
3189
  and execute of a new statement. If this happens repeatedly
 
3190
  more than MAX_REPREPARE_ATTEMPTS times, we give up.
 
3191
 
 
3192
  In future we need to be able to keep the metadata locks between
 
3193
  prepare and execute, but right now open_and_lock_tables(), as
 
3194
  well as close_thread_tables() are buried deep inside
 
3195
  execution code (mysql_execute_command()).
 
3196
 
 
3197
  @return TRUE if an error, FALSE if success
 
3198
  @retval  TRUE    either MAX_REPREPARE_ATTEMPTS has been reached,
 
3199
                   or some general error
 
3200
  @retval  FALSE   successfully executed the statement, perhaps
 
3201
                   after having reprepared it a few times.
 
3202
*/
 
3203
 
 
3204
bool
 
3205
Prepared_statement::execute_loop(String *expanded_query,
 
3206
                                 bool open_cursor,
 
3207
                                 uchar *packet,
 
3208
                                 uchar *packet_end)
 
3209
{
 
3210
  const int MAX_REPREPARE_ATTEMPTS= 3;
 
3211
  Reprepare_observer reprepare_observer;
 
3212
  bool error;
 
3213
  int reprepare_attempt= 0;
 
3214
 
 
3215
  if (set_parameters(expanded_query, packet, packet_end))
 
3216
    return TRUE;
 
3217
 
 
3218
reexecute:
 
3219
  reprepare_observer.reset_reprepare_observer();
 
3220
 
 
3221
  /*
 
3222
    If the free_list is not empty, we'll wrongly free some externally
 
3223
    allocated items when cleaning up after validation of the prepared
 
3224
    statement.
 
3225
  */
 
3226
  DBUG_ASSERT(thd->free_list == NULL);
 
3227
 
 
3228
  /*
 
3229
    Install the metadata observer. If some metadata version is
 
3230
    different from prepare time and an observer is installed,
 
3231
    the observer method will be invoked to push an error into
 
3232
    the error stack.
 
3233
  */
 
3234
  if (sql_command_flags[lex->sql_command] &
 
3235
      CF_REEXECUTION_FRAGILE)
 
3236
  {
 
3237
    DBUG_ASSERT(thd->m_reprepare_observer == NULL);
 
3238
    thd->m_reprepare_observer = &reprepare_observer;
 
3239
  }
 
3240
 
 
3241
  if (!(specialflag & SPECIAL_NO_PRIOR))
 
3242
    my_pthread_setprio(pthread_self(),QUERY_PRIOR);
 
3243
 
 
3244
  error= execute(expanded_query, open_cursor) || thd->is_error();
 
3245
 
 
3246
  if (!(specialflag & SPECIAL_NO_PRIOR))
 
3247
    my_pthread_setprio(pthread_self(), WAIT_PRIOR);
 
3248
 
 
3249
  thd->m_reprepare_observer= NULL;
 
3250
 
 
3251
  if (error && !thd->is_fatal_error && !thd->killed &&
 
3252
      reprepare_observer.is_invalidated() &&
 
3253
      reprepare_attempt++ < MAX_REPREPARE_ATTEMPTS)
 
3254
  {
 
3255
    DBUG_ASSERT(thd->main_da.sql_errno() == ER_NEED_REPREPARE);
 
3256
    thd->clear_error();
 
3257
 
 
3258
    error= reprepare();
 
3259
 
 
3260
    if (! error)                                /* Success */
 
3261
      goto reexecute;
 
3262
  }
 
3263
  reset_stmt_params(this);
 
3264
 
 
3265
  return error;
 
3266
}
 
3267
 
 
3268
 
 
3269
/**
 
3270
  Reprepare this prepared statement.
 
3271
 
 
3272
  Currently this is implemented by creating a new prepared
 
3273
  statement, preparing it with the original query and then
 
3274
  swapping the new statement and the original one.
 
3275
 
 
3276
  @retval  TRUE   an error occurred. Possible errors include
 
3277
                  incompatibility of new and old result set
 
3278
                  metadata
 
3279
  @retval  FALSE  success, the statement has been reprepared
 
3280
*/
 
3281
 
 
3282
bool
 
3283
Prepared_statement::reprepare()
 
3284
{
 
3285
  char saved_cur_db_name_buf[NAME_LEN+1];
 
3286
  LEX_STRING saved_cur_db_name=
 
3287
    { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
 
3288
  LEX_STRING stmt_db_name= { db, db_length };
 
3289
  bool cur_db_changed;
 
3290
  bool error;
 
3291
 
 
3292
  Prepared_statement copy(thd, &thd->protocol_text);
 
3293
 
 
3294
  status_var_increment(thd->status_var.com_stmt_reprepare);
 
3295
 
 
3296
  if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE,
 
3297
                          &cur_db_changed))
 
3298
    return TRUE;
 
3299
 
 
3300
  error= (name.str && copy.set_name(&name) ||
 
3301
          copy.prepare(query, query_length) ||
 
3302
          validate_metadata(&copy));
 
3303
 
 
3304
  if (cur_db_changed)
 
3305
    mysql_change_db(thd, &saved_cur_db_name, TRUE);
 
3306
 
 
3307
  if (! error)
 
3308
  {
 
3309
    swap_prepared_statement(&copy);
 
3310
    swap_parameter_array(param_array, copy.param_array, param_count);
 
3311
#ifndef DBUG_OFF
 
3312
    is_reprepared= TRUE;
 
3313
#endif
 
3314
    /*
 
3315
      Clear possible warnings during reprepare, it has to be completely
 
3316
      transparent to the user. We use mysql_reset_errors() since
 
3317
      there were no separate query id issued for re-prepare.
 
3318
      Sic: we can't simply silence warnings during reprepare, because if
 
3319
      it's failed, we need to return all the warnings to the user.
 
3320
    */
 
3321
    mysql_reset_errors(thd, TRUE);
 
3322
  }
 
3323
  return error;
 
3324
}
 
3325
 
 
3326
 
 
3327
/**
 
3328
  Validate statement result set metadata (if the statement returns
 
3329
  a result set).
 
3330
 
 
3331
  Currently we only check that the number of columns of the result
 
3332
  set did not change.
 
3333
  This is a helper method used during re-prepare.
 
3334
 
 
3335
  @param[in]  copy  the re-prepared prepared statement to verify
 
3336
                    the metadata of
 
3337
 
 
3338
  @retval TRUE  error, ER_PS_REBIND is reported
 
3339
  @retval FALSE statement return no or compatible metadata
 
3340
*/
 
3341
 
 
3342
 
 
3343
bool Prepared_statement::validate_metadata(Prepared_statement *copy)
 
3344
{
 
3345
  /**
 
3346
    If this is an SQL prepared statement or EXPLAIN,
 
3347
    return FALSE -- the metadata of the original SELECT,
 
3348
    if any, has not been sent to the client.
 
3349
  */
 
3350
  if (is_protocol_text() || lex->describe)
 
3351
    return FALSE;
 
3352
 
 
3353
  if (lex->select_lex.item_list.elements !=
 
3354
      copy->lex->select_lex.item_list.elements)
 
3355
  {
 
3356
    /** Column counts mismatch, update the client */
 
3357
    thd->server_status|= SERVER_STATUS_METADATA_CHANGED;
 
3358
  }
 
3359
 
 
3360
  return FALSE;
 
3361
}
 
3362
 
 
3363
 
 
3364
/**
 
3365
  Replace the original prepared statement with a prepared copy.
 
3366
 
 
3367
  This is a private helper that is used as part of statement
 
3368
  reprepare
 
3369
 
 
3370
  @return This function does not return any errors.
 
3371
*/
 
3372
 
 
3373
void
 
3374
Prepared_statement::swap_prepared_statement(Prepared_statement *copy)
 
3375
{
 
3376
  Statement tmp_stmt;
 
3377
 
 
3378
  /* Swap memory roots. */
 
3379
  swap_variables(MEM_ROOT, main_mem_root, copy->main_mem_root);
 
3380
 
 
3381
  /* Swap the arenas */
 
3382
  tmp_stmt.set_query_arena(this);
 
3383
  set_query_arena(copy);
 
3384
  copy->set_query_arena(&tmp_stmt);
 
3385
 
 
3386
  /* Swap the statement parent classes */
 
3387
  tmp_stmt.set_statement(this);
 
3388
  set_statement(copy);
 
3389
  copy->set_statement(&tmp_stmt);
 
3390
 
 
3391
  /* Swap ids back, we need the original id */
 
3392
  swap_variables(ulong, id, copy->id);
 
3393
  /* Swap mem_roots back, they must continue pointing at the main_mem_roots */
 
3394
  swap_variables(MEM_ROOT *, mem_root, copy->mem_root);
 
3395
  /*
 
3396
    Swap the old and the new parameters array. The old array
 
3397
    is allocated in the old arena.
 
3398
  */
 
3399
  swap_variables(Item_param **, param_array, copy->param_array);
 
3400
  /* Swap flags: this is perhaps unnecessary */
 
3401
  swap_variables(uint, flags, copy->flags);
 
3402
  /* Swap names, the old name is allocated in the wrong memory root */
 
3403
  swap_variables(LEX_STRING, name, copy->name);
 
3404
  /* Ditto */
 
3405
  swap_variables(char *, db, copy->db);
 
3406
  swap_variables(ulong, m_sp_cache_version, copy->m_sp_cache_version);
 
3407
 
 
3408
  DBUG_ASSERT(db_length == copy->db_length);
 
3409
  DBUG_ASSERT(param_count == copy->param_count);
 
3410
  DBUG_ASSERT(thd == copy->thd);
 
3411
  last_error[0]= '\0';
 
3412
  last_errno= 0;
 
3413
  /* Do not swap protocols, the copy always has protocol_text */
 
3414
}
 
3415
 
 
3416
 
2991
3417
/**
2992
3418
  Execute a prepared statement.
2993
3419
 
3038
3464
  }
3039
3465
 
3040
3466
  /*
 
3467
    Reprepare the statement if we're using stored functions
 
3468
    and the version of the stored routines cache has changed.
 
3469
  */
 
3470
  if (lex->uses_stored_routines() &&
 
3471
      m_sp_cache_version != sp_cache_version(&thd->sp_func_cache) &&
 
3472
      thd->m_reprepare_observer &&
 
3473
      thd->m_reprepare_observer->report_error(thd))
 
3474
  {
 
3475
    return TRUE;
 
3476
  }
 
3477
 
 
3478
 
 
3479
  /*
3041
3480
    For SHOW VARIABLES lex->result is NULL, as it's a non-SELECT
3042
3481
    command. For such queries we don't return an error and don't
3043
3482
    open a cursor -- the client library will recognize this case and
3150
3589
  DBUG_ASSERT(! (error && cursor));
3151
3590
 
3152
3591
  if (! cursor)
3153
 
  {
3154
3592
    cleanup_stmt();
3155
 
    reset_stmt_params(this);
3156
 
  }
3157
3593
 
3158
3594
  thd->set_statement(&stmt_backup);
3159
3595
  thd->stmt_arena= old_stmt_arena;
3187
3623
 
3188
3624
/** Common part of DEALLOCATE PREPARE and mysql_stmt_close. */
3189
3625
 
3190
 
bool Prepared_statement::deallocate()
 
3626
void Prepared_statement::deallocate()
3191
3627
{
3192
3628
  /* We account deallocate in the same manner as mysql_stmt_close */
3193
3629
  status_var_increment(thd->status_var.com_stmt_close);
3194
 
  if (flags & (uint) IS_IN_USE)
3195
 
  {
3196
 
    my_error(ER_PS_NO_RECURSION, MYF(0));
3197
 
    return TRUE;
3198
 
  }
3199
3630
  /* Statement map calls delete stmt on erase */
3200
3631
  thd->stmt_map.erase(this);
3201
 
  return FALSE;
3202
3632
}