mariadb/sql/sql_handler.cc
unknown ac9f68b9fa Better approach for prelocking of tables for stored routines execution
and some SP-related cleanups.

- We don't have separate stage for calculation of list of tables
  to be prelocked and doing implicit LOCK/UNLOCK any more.
  Instead we calculate this list at open_tables() and do implicit
  LOCK in lock_tables() (and UNLOCK in close_thread_tables()).
  Also now we support cases when same table (with same alias) is
  used several times in the same query in SP.

- Cleaned up execution of SP. Moved all common code which handles
  LEX and does preparations before statement execution or complex
  expression evaluation to auxilary sp_lex_keeper class. Now 
  all statements in SP (and corresponding instructions) that
  evaluate expression which can contain subquery have their
  own LEX.


mysql-test/r/lock.result:
  Replaced wrong error code with the correct one after fixing bug in
  SP-locking.
mysql-test/r/mysqldump.result:
  Added dropping of view which is used in test to its beginning.
mysql-test/r/sp.result:
  Added tests for improved SP-locking.
  Temporarily disabled tests for SHOW PROCEDURE STATUS and alike
  (Until Monty will allow to open mysql.proc under LOCK TABLES without
  mentioning it in lock list).
  Replaced wrong results of test for bug #5240 with correct results after
  fixing bug in handling of cursors.
mysql-test/t/lock.test:
  Replaced wrong error code with the correct one after fixing bug in
  SP-locking.
mysql-test/t/mysqldump.test:
  Added dropping of view which is used in test to its beginning.
mysql-test/t/sp.test:
  Added tests for improved SP-locking.
  Temporarily disabled tests for SHOW PROCEDURE STATUS and alike
  (Until Monty will allow to open mysql.proc under LOCK TABLES without
  mentioning it in lock list).
  Removed test for bug #1654 since we already test exactly this function
  in one of SP-locking tests.
  Removed comment about cursor's wrong behavior in test for bug #5240
  after fixing bug which was its cause.
sql/item_func.cc:
  Removed comment which is no longer true.
sql/mysql_priv.h:
  Changed open_tables() signature.
  Now its 2nd parameter is in/out since it can add elements to table list.
sql/sp.cc:
  sp_find_procedure():
   Added one more parameter which enforces cache only lookup.
  
  sp_merge_hash():
   Now uses its return value to indicate that first of two hashes changed
   as result of merge.
  
  sp_cache_routines():
   This function caches all stored routines used in query now.
sql/sp.h:
  - sp_find_procedure() now has one more parameter which enforces cache only
    lookup.
  - sp_merge_hash() now uses its return value to indicate that first of two
    hashes changed as result of merge.
  - sp_cache_routines() caches all stored routines now. So it does not need
    third argument any more.
sql/sp_head.cc:
  sp_head::sp_head():
   Added initialization of new m_spfuns and m_spprocs members.
  
  sp_head::execute():
   Let us save/restore part of thread context which can be damaged by
   execution of instructions.
  sp_head::execute_function()/execute_procedure():
   Now it is responsibility of caller to close tables used in
   subqueries which are passed as routine parameters.
  
  sp_head::restore_lex():
   Let us accumulate information about routines used by this one
   in new m_spfuns, m_spprocs hashes.
  
  sp_lex_keeper::reset_lex_and_exec_core()
   Main method of new auxilary sp_lex_keeper class to which instructions 
   delegate responsibility for handling LEX and preparations before
   executing statement or calculating complex expression.
  
  Since all instructions which calculate complex expression or execute
  command now use sp_lex_keeper they have to implement
  sp_instr::exec_core() method. Most of instruction specific logic
  has moved from sp_instr::execute() to this new method.
  
  Removed sp_instr_set_user_var class which is no longer used, because
  nowdays we allow execution of statements in stored functions and
  triggers.
  
  sp_merge_table_list() became sp_head::merge_table_list() method. It
  also treats sp_head::m_sptabs as multi-set of tables now.
  
  sp_hash_to_table_list() became sp_head::add_used_tables_to_table_list().
  It takes into account that sp_head::m_sptabs is multi-set and allocates
  object into persistent arena of PS.
  
  Removed sp_merge_table_hash(), sp_open_and_lock_tables(),
  sp_unlock_tables(), sp_merge_routine_tables() methods since they are not
  used by new prelocking mechanism.
  
  Added sp_add_sp_tables_to_table_list() which serves for adding tables needed
  by routines used in query to the query table list for prelocking.
sql/sp_head.h:
  class sp_head:
  - Added m_spfuns, m_spprocs members for storing names of routines used
    by this routine.
  - Added add_used_tables_to_table_list() method which allows to add
    tables needed by this routine to query's table list.
  - Converted sp_merge_table_list() to sp_head::merge_table_list() method.
  - Changed semantics of THD::m_sptabs. Now it is multi-set which contains
    only tables which are used by this routine and not routines that are
    called from this one.
  
  Removed sp_merge_routine_tables(), sp_merge_table_hash(),
  sp_open_and_lock_tables(), sp_unlock_tables() calls since they are not
  used for our prelocking list calculation.
  
  Added auxilary sp_lex_keeper class to which instructions delegate
  responsibility for handling LEX and preparations before executing
  statement or calculating complex expression. This class uses
  new sp_instr::exec_core() method which is responsible for executing
  instruction's core function after all preparations were made.
  
  All instructions which hold and calculate complex expression now have
  their own LEX (by aggregating sp_lex_keeper instance). sp_instr_stmt
  now uses sp_lex_keeper too.
  
  Removed sp_instr_set_user_var class which is no longer used, because
  nowdays we allow execution of statements in stored functions and
  triggers.
sql/sp_rcontext.cc:
  Now sp_cursor holds pointer to sp_lex_keeper instead of LEX.
sql/sp_rcontext.h:
  Now sp_cursor holds pointer to sp_lex_keeper instead of LEX.
sql/sql_acl.cc:
  acl_init(), grant_init():
    Now we use simple_open_n_lock_tables() instead of explicit
    calls to open_tables() and mysql_lock_tables().
sql/sql_base.cc:
  Implemented support for execution of statements in "prelocked" mode.
  
  When we have statement which uses stored routines explicitly or
  implicitly (via views or triggers) we have to open and lock all tables
  for these routines at the same time as tables for the main statement.
  In fact we have to do implicit LOCK TABLES at the begining of such
  statement and implict UNLOCK TABLES at its end. We call such mode
  "prelocked".
  
  When open_tables() is called for the statement tables which are needed
  for execution of routines used by it are added to its tables list
  (this process also caches all routines used). Implicit use of routines
  is discovered when we open view or table with trigger and apropriate
  tables are added to the table list at this moment. Statement which has
  such extra tables in its list (well actually any that uses functions)
  is marked as requiring prelocked mode for its execution.
  
  When lock_tables() sees such statement it will issue implicit LOCK TABLES
  for this extended table list instead of doing usual locking, it will also
  set THD::prelocked_mode to indicate that we are in prelocked mode.
  
  When open_tables()/lock_tables() are called for statement of stored
  routine (substatement), they notice that we are running in prelocked mode
  and use one of prelocked tables from those that are not used by upper
  levels of execution.
  
  close_thread_tables() for substatement won't really close tables used
  but will mark them as free for reuse instead.
  
  Finally when close_thread_tables() is called for the main statement it
  really unlocks and closes all tables used.
  
  Everything will work even if one uses such statement under real LOCK
  TABLES (we are simply not doing implicit LOCK/UNLOCK in this case).
sql/sql_class.cc:
  Added initialization of THD::prelocked_mode member.
sql/sql_class.h:
  - Added prelocked_mode_type enum and THD::prelocked_mode member
    which are used for indication whenever "prelocked mode" is on 
    (i.e. that statement uses stored routines and is executed under
     implicit LOCK TABLES).
  - Removed THD::shortcut_make_view which is no longer needed.
    We use TABLE_LIST::prelocking_placeholder for the same purprose
    now.
sql/sql_handler.cc:
  Changed open_tables() invocation.
  Now its 2nd parameter is in/out since it can add elements to table list.
sql/sql_lex.cc:
  lex_start():
    Added initialization of LEX::query_tables_own_last.
    Unused LEX::sptabs member was removed.
  st_lex::unlink_first_table()/link_first_table_back():
    We should update LEX::query_tables_last properly if table list
    contains(ed) only one element.
sql/sql_lex.h:
  LEX:
  - Removed sptabs member since it is no longer used.
  - Added query_tables_own_last member, which if non-0 indicates that
    statement requires prelocking (implicit LOCK TABLES) for its execution
    and points to last own element in query table list. If it is zero
    then this query does not need prelocking.
  - Added requires_prelocking(), mark_as_requiring_prelocking(),
    first_not_own_table() inline methods to incapsulate and simplify
    usage of this new member.
sql/sql_parse.cc:
  dispatch_command():
    To properly leave prelocked mode when needed we should call
    close_thread_tables() even if there are no open tables.
  mysql_execute_command():
  - Removed part of function which were responsible for doing implicit
    LOCK TABLES before statement execution if statement used stored 
    routines (and doing UNLOCK TABLES at the end).
    Now we do all this in open_tables()/lock_tables()/close_thread_tables()
    instead.
  - It is also sensible to reset errors before execution of statement
    which uses routines.
  - SQLCOM_DO, SQLCOM_SET_OPTION, SQLCOM_CALL
    We should always try to open tables because even if statement has empty
    table list, it can call routines using tables, which should be preopened
    before statement execution.
  - SQLCOM_CALL
    We should not look up routine called in mysql.proc, since it should be
    already cached by this moment by open_tables() call.
  - SQLCOM_LOCK_TABLES
    it is better to use simple_open_n_lock_tables() since we want to avoid
    materialization of derived tables for this command.
sql/sql_prepare.cc:
  mysql_test_update():
    Changed open_tables() invocations. Now its 2nd parameter is in/out
    since it can add elements to table list.
  check_prepared_statement():
    Since now we cache all routines used by statement in open_tables() we 
    don't need to do it explicitly.
  mysql_stmt_prepare():
    Now we should call close_thread_tables() when THD::lex points to the
    LEX of statement which opened tables.
  reset_stmt_for_execute():
    Commented why we are resetting all tables in table list.
sql/sql_trigger.h:
  Table_triggers_list::process_triggers():
    We should surpress sending of ok packet when we are calling trigger's
    routine, since now we allow statements in them.
sql/sql_update.cc:
  Changed open_tables() invocations.
  Now its 2nd parameter is in/out since it can add elements to table list.
sql/sql_view.cc:
  mysql_make_view():
  - Removed handling of routines used in view. Instead we add tables which
    are needed for their execution to statement's table list in 
    open_tables().
  - Now we use TABLE_LIST::prelocking_placeholder instead of 
    THD::shortcut_make_view for indicating that view is opened
    only to discover which tables and routines it uses (this happens
    when we build extended table list for prelocking). Also now we try
    to avoid to modify main LEX in this case (except of its table list).
  - Corrected small error we added tables to the table list of the main
    LEX without updating its query_tables_last member properly.
sql/sql_yacc.yy:
  Now each expression which is used in SP statements and can contain
  subquery has its own LEX. This LEX is stored in corresponding sp_instr
  object and used along with Item tree for expression calculation.
  
  We don't need sp_instr_set_user_var() anymore since now we allow
  execution of statements in stored functions and triggers.
sql/table.h:
  Added TABLE_LIST::prelocking_placeholder member for distinguishing
  elements of table list which does not belong to the statement itself
  and added there only for prelocking (as they are to be used by routines
  called by this statement).
sql/tztime.cc:
  my_tz_init():
    Now we use more simplier simple_open_n_lock_tables() call instead of 
    open_tables()/lock_tables() pair.
2005-03-04 16:35:28 +03:00

707 lines
21 KiB
C++

/* Copyright (C) 2000-2004 MySQL AB
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; either version 2 of the License, or
(at your option) any later version.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* HANDLER ... commands - direct access to ISAM */
/* TODO:
HANDLER blabla OPEN [ AS foobar ] [ (column-list) ]
the most natural (easiest, fastest) way to do it is to
compute List<Item> field_list not in mysql_ha_read
but in mysql_ha_open, and then store it in TABLE structure.
The problem here is that mysql_parse calls free_item to free all the
items allocated at the end of every query. The workaround would to
keep two item lists per THD - normal free_list and handler_items.
The second is to be freeed only on thread end. mysql_ha_open should
then do { handler_items=concat(handler_items, free_list); free_list=0; }
But !!! do_command calls free_root at the end of every query and frees up
all the sql_alloc'ed memory. It's harder to work around...
*/
/*
There are two containers holding information about open handler tables.
The first is 'thd->handler_tables'. It is a linked list of TABLE objects.
It is used like 'thd->open_tables' in the table cache. The trick is to
exchange these two lists during open and lock of tables. Thus the normal
table cache code can be used.
The second container is a HASH. It holds objects of the type TABLE_LIST.
Despite its name, no lists of tables but only single structs are hashed
(the 'next' pointer is always NULL). The reason for theis second container
is, that we want handler tables to survive FLUSH TABLE commands. A table
affected by FLUSH TABLE must be closed so that other threads are not
blocked by handler tables still in use. Since we use the normal table cache
functions with 'thd->handler_tables', the closed tables are removed from
this list. Hence we need the original open information for the handler
table in the case that it is used again. This information is handed over
to mysql_ha_open() as a TABLE_LIST. So we store this information in the
second container, where it is not affected by FLUSH TABLE. The second
container is implemented as a hash for performance reasons. Consequently,
we use it not only for re-opening a handler table, but also for the
HANDLER ... READ commands. For this purpose, we store a pointer to the
TABLE structure (in the first container) in the TBALE_LIST object in the
second container. When the table is flushed, the pointer is cleared.
*/
#include "mysql_priv.h"
#include "sql_select.h"
#include <assert.h>
#define HANDLER_TABLES_HASH_SIZE 120
static enum enum_ha_read_modes rkey_to_rnext[]=
{ RNEXT_SAME, RNEXT, RPREV, RNEXT, RPREV, RNEXT, RPREV, RPREV };
#define HANDLER_TABLES_HACK(thd) { \
TABLE *tmp=thd->open_tables; \
thd->open_tables=thd->handler_tables; \
thd->handler_tables=tmp; }
static int mysql_ha_flush_table(THD *thd, TABLE **table_ptr, uint mode_flags);
/*
Get hash key and hash key length.
SYNOPSIS
mysql_ha_hash_get_key()
tables Pointer to the hash object.
key_len_p (out) Pointer to the result for key length.
first Unused.
DESCRIPTION
The hash object is an TABLE_LIST struct.
The hash key is the alias name.
The hash key length is the alias name length plus one for the
terminateing NUL character.
RETURN
Pointer to the TABLE_LIST struct.
*/
static char *mysql_ha_hash_get_key(TABLE_LIST *tables, uint *key_len_p,
my_bool first __attribute__((unused)))
{
*key_len_p= strlen(tables->alias) + 1 ; /* include '\0' in comparisons */
return tables->alias;
}
/*
Free an hash object.
SYNOPSIS
mysql_ha_hash_free()
tables Pointer to the hash object.
DESCRIPTION
The hash object is an TABLE_LIST struct.
RETURN
Nothing
*/
static void mysql_ha_hash_free(TABLE_LIST *tables)
{
my_free((char*) tables, MYF(0));
}
/*
Open a HANDLER table.
SYNOPSIS
mysql_ha_open()
thd Thread identifier.
tables A list of tables with the first entry to open.
reopen Re-open a previously opened handler table.
DESCRIPTION
Though this function takes a list of tables, only the first list entry
will be opened.
'reopen' is set when a handler table is to be re-opened. In this case,
'tables' is the pointer to the hashed TABLE_LIST object which has been
saved on the original open.
'reopen' is also used to suppress the sending of an 'ok' message or
error messages.
RETURN
FALSE OK
TRUE Error
*/
bool mysql_ha_open(THD *thd, TABLE_LIST *tables, bool reopen)
{
TABLE_LIST *hash_tables;
char *db, *name, *alias;
uint dblen, namelen, aliaslen, counter;
int error;
DBUG_ENTER("mysql_ha_open");
DBUG_PRINT("enter",("'%s'.'%s' as '%s' reopen: %d",
tables->db, tables->table_name, tables->alias,
(int) reopen));
if (! hash_inited(&thd->handler_tables_hash))
{
/*
HASH entries are of type TABLE_LIST.
*/
if (hash_init(&thd->handler_tables_hash, &my_charset_latin1,
HANDLER_TABLES_HASH_SIZE, 0, 0,
(hash_get_key) mysql_ha_hash_get_key,
(hash_free_key) mysql_ha_hash_free, 0))
goto err;
}
else if (! reopen) /* Otherwise we have 'tables' already. */
{
if (hash_search(&thd->handler_tables_hash, (byte*) tables->alias,
strlen(tables->alias) + 1))
{
DBUG_PRINT("info",("duplicate '%s'", tables->alias));
if (! reopen)
my_error(ER_NONUNIQ_TABLE, MYF(0), tables->alias);
goto err;
}
}
/*
open_tables() will set 'tables->table' if successful.
It must be NULL for a real open when calling open_tables().
*/
DBUG_ASSERT(! tables->table);
HANDLER_TABLES_HACK(thd);
/* for now HANDLER can be used only for real TABLES */
tables->required_type= FRMTYPE_TABLE;
error= open_tables(thd, &tables, &counter);
HANDLER_TABLES_HACK(thd);
if (error)
goto err;
/* There can be only one table in '*tables'. */
if (! (tables->table->file->table_flags() & HA_CAN_SQL_HANDLER))
{
if (! reopen)
my_error(ER_ILLEGAL_HA, MYF(0), tables->alias);
mysql_ha_close(thd, tables);
goto err;
}
if (! reopen)
{
/* copy the TABLE_LIST struct */
dblen= strlen(tables->db) + 1;
namelen= strlen(tables->table_name) + 1;
aliaslen= strlen(tables->alias) + 1;
if (!(my_multi_malloc(MYF(MY_WME),
&hash_tables, sizeof(*hash_tables),
&db, dblen,
&name, namelen,
&alias, aliaslen,
NullS)))
goto err;
/* structure copy */
*hash_tables= *tables;
hash_tables->db= db;
hash_tables->table_name= name;
hash_tables->alias= alias;
memcpy(hash_tables->db, tables->db, dblen);
memcpy(hash_tables->table_name, tables->table_name, namelen);
memcpy(hash_tables->alias, tables->alias, aliaslen);
/* add to hash */
if (my_hash_insert(&thd->handler_tables_hash, (byte*) hash_tables))
{
mysql_ha_close(thd, tables);
goto err;
}
}
if (! reopen)
send_ok(thd);
DBUG_PRINT("exit",("OK"));
DBUG_RETURN(FALSE);
err:
DBUG_PRINT("exit",("ERROR"));
DBUG_RETURN(TRUE);
}
/*
Close a HANDLER table.
SYNOPSIS
mysql_ha_close()
thd Thread identifier.
tables A list of tables with the first entry to close.
DESCRIPTION
Though this function takes a list of tables, only the first list entry
will be closed. Broadcasts a COND_refresh condition.
RETURN
FALSE ok
TRUE error
*/
bool mysql_ha_close(THD *thd, TABLE_LIST *tables)
{
TABLE_LIST *hash_tables;
TABLE **table_ptr;
DBUG_ENTER("mysql_ha_close");
DBUG_PRINT("enter",("'%s'.'%s' as '%s'",
tables->db, tables->table_name, tables->alias));
if ((hash_tables= (TABLE_LIST*) hash_search(&thd->handler_tables_hash,
(byte*) tables->alias,
strlen(tables->alias) + 1)))
{
/*
Though we could take the table pointer from hash_tables->table,
we must follow the thd->handler_tables chain anyway, as we need the
address of the 'next' pointer referencing this table
for close_thread_table().
*/
for (table_ptr= &(thd->handler_tables);
*table_ptr && (*table_ptr != hash_tables->table);
table_ptr= &(*table_ptr)->next)
;
if (*table_ptr)
{
(*table_ptr)->file->ha_index_or_rnd_end();
VOID(pthread_mutex_lock(&LOCK_open));
if (close_thread_table(thd, table_ptr))
{
/* Tell threads waiting for refresh that something has happened */
VOID(pthread_cond_broadcast(&COND_refresh));
}
VOID(pthread_mutex_unlock(&LOCK_open));
}
hash_delete(&thd->handler_tables_hash, (byte*) hash_tables);
}
else
{
my_error(ER_UNKNOWN_TABLE, MYF(0), tables->alias, "HANDLER");
DBUG_PRINT("exit",("ERROR"));
DBUG_RETURN(TRUE);
}
send_ok(thd);
DBUG_PRINT("exit", ("OK"));
DBUG_RETURN(FALSE);
}
/*
Read from a HANDLER table.
SYNOPSIS
mysql_ha_read()
thd Thread identifier.
tables A list of tables with the first entry to read.
mode
keyname
key_expr
ha_rkey_mode
cond
select_limit
offset_limit
RETURN
FALSE ok
TRUE error
*/
bool mysql_ha_read(THD *thd, TABLE_LIST *tables,
enum enum_ha_read_modes mode, char *keyname,
List<Item> *key_expr,
enum ha_rkey_function ha_rkey_mode, Item *cond,
ha_rows select_limit,ha_rows offset_limit)
{
TABLE_LIST *hash_tables;
TABLE *table;
MYSQL_LOCK *lock;
List<Item> list;
Protocol *protocol= thd->protocol;
char buff[MAX_FIELD_WIDTH];
String buffer(buff, sizeof(buff), system_charset_info);
int error, keyno= -1;
uint num_rows;
byte *key;
uint key_len;
DBUG_ENTER("mysql_ha_read");
DBUG_PRINT("enter",("'%s'.'%s' as '%s'",
tables->db, tables->table_name, tables->alias));
LINT_INIT(key);
LINT_INIT(key_len);
list.push_front(new Item_field(NULL,NULL,"*"));
List_iterator<Item> it(list);
it++;
if ((hash_tables= (TABLE_LIST*) hash_search(&thd->handler_tables_hash,
(byte*) tables->alias,
strlen(tables->alias) + 1)))
{
table= hash_tables->table;
DBUG_PRINT("info-in-hash",("'%s'.'%s' as '%s' tab %p",
hash_tables->db, hash_tables->table_name,
hash_tables->alias, table));
if (!table)
{
/*
The handler table has been closed. Re-open it.
*/
if (mysql_ha_open(thd, hash_tables, 1))
{
DBUG_PRINT("exit",("reopen failed"));
goto err0;
}
table= hash_tables->table;
DBUG_PRINT("info",("re-opened '%s'.'%s' as '%s' tab %p",
hash_tables->db, hash_tables->table_name,
hash_tables->alias, table));
}
#if MYSQL_VERSION_ID < 40100
if (*tables->db && strcmp(table->table_cache_key, tables->db))
{
DBUG_PRINT("info",("wrong db"));
table= NULL;
}
#endif
}
else
table= NULL;
if (!table)
{
#if MYSQL_VERSION_ID < 40100
char buff[MAX_DBKEY_LENGTH];
if (*tables->db)
strxnmov(buff, sizeof(buff), tables->db, ".", tables->table_name, NullS);
else
strncpy(buff, tables->alias, sizeof(buff));
my_error(ER_UNKNOWN_TABLE, MYF(0), buff, "HANDLER");
#else
my_error(ER_UNKNOWN_TABLE, MYF(0), tables->alias, "HANDLER");
#endif
goto err0;
}
tables->table=table;
if (cond && ((!cond->fixed &&
cond->fix_fields(thd, tables, &cond)) || cond->check_cols(1)))
goto err0;
table->file->init_table_handle_for_HANDLER(); // Only InnoDB requires it
if (keyname)
{
if ((keyno=find_type(keyname, &table->s->keynames, 1+2)-1)<0)
{
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), keyname, tables->alias);
goto err0;
}
table->file->ha_index_or_rnd_end();
table->file->ha_index_init(keyno);
}
if (insert_fields(thd, tables, tables->db, tables->alias, &it, 0, 0))
goto err0;
select_limit+=offset_limit;
protocol->send_fields(&list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
HANDLER_TABLES_HACK(thd);
lock= mysql_lock_tables(thd, &tables->table, 1);
HANDLER_TABLES_HACK(thd);
if (!lock)
goto err0; // mysql_lock_tables() printed error message already
/*
In ::external_lock InnoDB resets the fields which tell it that
the handle is used in the HANDLER interface. Tell it again that
we are using it for HANDLER.
*/
table->file->init_table_handle_for_HANDLER();
for (num_rows=0; num_rows < select_limit; )
{
switch (mode) {
case RFIRST:
if (keyname)
error= table->file->index_first(table->record[0]);
else
{
table->file->ha_index_or_rnd_end();
if (!(error= table->file->ha_rnd_init(1)))
error= table->file->rnd_next(table->record[0]);
}
mode=RNEXT;
break;
case RLAST:
DBUG_ASSERT(keyname != 0);
error= table->file->index_last(table->record[0]);
mode=RPREV;
break;
case RNEXT:
error= (keyname ?
table->file->index_next(table->record[0]) :
table->file->rnd_next(table->record[0]));
break;
case RPREV:
DBUG_ASSERT(keyname != 0);
error= table->file->index_prev(table->record[0]);
break;
case RNEXT_SAME:
/* Continue scan on "(keypart1,keypart2,...)=(c1, c2, ...) */
DBUG_ASSERT(keyname != 0);
error= table->file->index_next_same(table->record[0], key, key_len);
break;
case RKEY:
{
DBUG_ASSERT(keyname != 0);
KEY *keyinfo=table->key_info+keyno;
KEY_PART_INFO *key_part=keyinfo->key_part;
if (key_expr->elements > keyinfo->key_parts)
{
my_error(ER_TOO_MANY_KEY_PARTS, MYF(0), keyinfo->key_parts);
goto err;
}
List_iterator<Item> it_ke(*key_expr);
Item *item;
for (key_len=0 ; (item=it_ke++) ; key_part++)
{
// 'item' can be changed by fix_fields() call
if ((!item->fixed &&
item->fix_fields(thd, tables, it_ke.ref())) ||
(item= *it_ke.ref())->check_cols(1))
goto err;
if (item->used_tables() & ~RAND_TABLE_BIT)
{
my_error(ER_WRONG_ARGUMENTS,MYF(0),"HANDLER ... READ");
goto err;
}
(void) item->save_in_field(key_part->field, 1);
key_len+=key_part->store_length;
}
if (!(key= (byte*) thd->calloc(ALIGN_SIZE(key_len))))
goto err;
key_copy(key, table->record[0], table->key_info + keyno, key_len);
error= table->file->index_read(table->record[0],
key,key_len,ha_rkey_mode);
mode=rkey_to_rnext[(int)ha_rkey_mode];
break;
}
default:
my_message(ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA), MYF(0));
goto err;
}
if (error)
{
if (error == HA_ERR_RECORD_DELETED)
continue;
if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
{
sql_print_error("mysql_ha_read: Got error %d when reading table '%s'",
error, tables->table_name);
table->file->print_error(error,MYF(0));
goto err;
}
goto ok;
}
if (cond && !cond->val_int())
continue;
if (num_rows >= offset_limit)
{
Item *item;
protocol->prepare_for_resend();
it.rewind();
while ((item=it++))
{
if (item->send(thd->protocol, &buffer))
{
protocol->free(); // Free used
my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
goto err;
}
}
protocol->write();
}
num_rows++;
}
ok:
mysql_unlock_tables(thd,lock);
send_eof(thd);
DBUG_PRINT("exit",("OK"));
DBUG_RETURN(FALSE);
err:
mysql_unlock_tables(thd,lock);
err0:
DBUG_PRINT("exit",("ERROR"));
DBUG_RETURN(TRUE);
}
/*
Flush (close) a list of HANDLER tables.
SYNOPSIS
mysql_ha_flush()
thd Thread identifier.
tables The list of tables to close. If NULL,
close all HANDLER tables [marked as flushed].
mode_flags MYSQL_HA_CLOSE_FINAL finally close the table.
MYSQL_HA_REOPEN_ON_USAGE mark for reopen.
MYSQL_HA_FLUSH_ALL flush all tables, not only
those marked for flush.
DESCRIPTION
The list of HANDLER tables may be NULL, in which case all HANDLER
tables are closed (if MYSQL_HA_FLUSH_ALL) is set.
If 'tables' is NULL and MYSQL_HA_FLUSH_ALL is not set,
all HANDLER tables marked for flush are closed.
Broadcasts a COND_refresh condition, for every table closed.
The caller must lock LOCK_open.
NOTE
Since mysql_ha_flush() is called when the base table has to be closed,
we compare real table names, not aliases. Hence, database names matter.
RETURN
0 ok
*/
int mysql_ha_flush(THD *thd, TABLE_LIST *tables, uint mode_flags)
{
TABLE_LIST *tmp_tables;
TABLE **table_ptr;
DBUG_ENTER("mysql_ha_flush");
DBUG_PRINT("enter", ("tables: %p mode_flags: 0x%02x", tables, mode_flags));
if (tables)
{
/* Close all tables in the list. */
for (tmp_tables= tables ; tmp_tables; tmp_tables= tmp_tables->next_local)
{
DBUG_PRINT("info-in-tables-list",("'%s'.'%s' as '%s'",
tmp_tables->db, tmp_tables->table_name,
tmp_tables->alias));
/* Close all currently open handler tables with the same base table. */
table_ptr= &(thd->handler_tables);
while (*table_ptr)
{
if ((!*tmp_tables->db ||
!my_strcasecmp(&my_charset_latin1, (*table_ptr)->s->db,
tmp_tables->db)) &&
! my_strcasecmp(&my_charset_latin1, (*table_ptr)->s->table_name,
tmp_tables->table_name))
{
DBUG_PRINT("info",("*table_ptr '%s'.'%s' as '%s'",
(*table_ptr)->s->db,
(*table_ptr)->s->table_name,
(*table_ptr)->alias));
mysql_ha_flush_table(thd, table_ptr, mode_flags);
continue;
}
table_ptr= &(*table_ptr)->next;
}
/* end of handler_tables list */
}
/* end of flush tables list */
}
else
{
/* Close all currently open tables [which are marked for flush]. */
table_ptr= &(thd->handler_tables);
while (*table_ptr)
{
if ((mode_flags & MYSQL_HA_FLUSH_ALL) ||
((*table_ptr)->s->version != refresh_version))
{
mysql_ha_flush_table(thd, table_ptr, mode_flags);
continue;
}
table_ptr= &(*table_ptr)->next;
}
}
DBUG_RETURN(0);
}
/*
Flush (close) a table.
SYNOPSIS
mysql_ha_flush_table()
thd Thread identifier.
table The table to close.
mode_flags MYSQL_HA_CLOSE_FINAL finally close the table.
MYSQL_HA_REOPEN_ON_USAGE mark for reopen.
DESCRIPTION
Broadcasts a COND_refresh condition, for every table closed.
The caller must lock LOCK_open.
RETURN
0 ok
*/
static int mysql_ha_flush_table(THD *thd, TABLE **table_ptr, uint mode_flags)
{
TABLE_LIST *hash_tables;
TABLE *table= *table_ptr;
DBUG_ENTER("mysql_ha_flush_table");
DBUG_PRINT("enter",("'%s'.'%s' as '%s' flags: 0x%02x",
table->s->db, table->s->table_name,
table->alias, mode_flags));
if ((hash_tables= (TABLE_LIST*) hash_search(&thd->handler_tables_hash,
(byte*) (*table_ptr)->alias,
strlen((*table_ptr)->alias) + 1)))
{
if (! (mode_flags & MYSQL_HA_REOPEN_ON_USAGE))
{
/* This is a final close. Remove from hash. */
hash_delete(&thd->handler_tables_hash, (byte*) hash_tables);
}
else
{
/* Mark table as closed, ready for re-open. */
hash_tables->table= NULL;
}
}
(*table_ptr)->file->ha_index_or_rnd_end();
if (close_thread_table(thd, table_ptr))
{
/* Tell threads waiting for refresh that something has happened */
VOID(pthread_cond_broadcast(&COND_refresh));
}
DBUG_RETURN(0);
}