diff options
Diffstat (limited to 'sql')
86 files changed, 2955 insertions, 1891 deletions
diff --git a/sql/Makefile.am b/sql/Makefile.am index 78eb4857620..b0824110792 100644 --- a/sql/Makefile.am +++ b/sql/Makefile.am @@ -65,7 +65,8 @@ noinst_HEADERS = item.h item_func.h item_sum.h item_cmpfunc.h \ sp_head.h sp_pcontext.h sp_rcontext.h sp.h sp_cache.h \ parse_file.h sql_view.h sql_trigger.h \ sql_array.h sql_cursor.h event.h event_priv.h \ - sql_plugin.h authors.h + sql_plugin.h authors.h sql_partition.h \ + partition_info.h partition_element.h mysqld_SOURCES = sql_lex.cc sql_handler.cc sql_partition.cc \ item.cc item_sum.cc item_buff.cc item_func.cc \ item_cmpfunc.cc item_strfunc.cc item_timefunc.cc \ @@ -101,7 +102,7 @@ mysqld_SOURCES = sql_lex.cc sql_handler.cc sql_partition.cc \ sp_cache.cc parse_file.cc sql_trigger.cc \ event_executor.cc event.cc event_timed.cc \ sql_plugin.cc sql_binlog.cc \ - handlerton.cc sql_tablespace.cc + handlerton.cc sql_tablespace.cc partition_info.cc EXTRA_mysqld_SOURCES = ha_innodb.cc ha_berkeley.cc ha_archive.cc \ ha_innodb.h ha_berkeley.h ha_archive.h \ ha_blackhole.cc ha_federated.cc ha_ndbcluster.cc \ diff --git a/sql/event.cc b/sql/event.cc index 3fa41996995..8eca4b1dcd3 100644 --- a/sql/event.cc +++ b/sql/event.cc @@ -49,11 +49,11 @@ - Consider using conditional variable when doing shutdown instead of waiting till all worker threads end. - - Make event_timed::get_show_create_event() work + - Make Event_timed::get_show_create_event() work - Add logging to file - - Move comparison code to class event_timed + - Move comparison code to class Event_timed Warning: - For now parallel execution is not possible because the same sp_head cannot be @@ -69,7 +69,7 @@ time_t mysql_event_last_create_time= 0L; static TABLE_FIELD_W_TYPE event_table_fields[EVEX_FIELD_COUNT] = { { - {(char *) STRING_WITH_LEN("db")}, + {(char *) STRING_WITH_LEN("db")}, {(char *) STRING_WITH_LEN("char(64)")}, {(char *) STRING_WITH_LEN("utf8")} }, @@ -120,6 +120,7 @@ static TABLE_FIELD_W_TYPE event_table_fields[EVEX_FIELD_COUNT] = { { {(char *) STRING_WITH_LEN("last_executed")}, {(char *) STRING_WITH_LEN("datetime")}, + {NULL, 0} }, { {(char *) STRING_WITH_LEN("starts")}, @@ -162,25 +163,25 @@ static TABLE_FIELD_W_TYPE event_table_fields[EVEX_FIELD_COUNT] = { LEX_STRING interval_type_to_name[] = { - {(char *) STRING_WITH_LEN("YEAR")}, - {(char *) STRING_WITH_LEN("QUARTER")}, - {(char *) STRING_WITH_LEN("MONTH")}, - {(char *) STRING_WITH_LEN("DAY")}, - {(char *) STRING_WITH_LEN("HOUR")}, - {(char *) STRING_WITH_LEN("MINUTE")}, - {(char *) STRING_WITH_LEN("WEEK")}, - {(char *) STRING_WITH_LEN("SECOND")}, - {(char *) STRING_WITH_LEN("MICROSECOND")}, - {(char *) STRING_WITH_LEN("YEAR_MONTH")}, - {(char *) STRING_WITH_LEN("DAY_HOUR")}, - {(char *) STRING_WITH_LEN("DAY_MINUTE")}, - {(char *) STRING_WITH_LEN("DAY_SECOND")}, - {(char *) STRING_WITH_LEN("HOUR_MINUTE")}, - {(char *) STRING_WITH_LEN("HOUR_SECOND")}, - {(char *) STRING_WITH_LEN("MINUTE_SECOND")}, - {(char *) STRING_WITH_LEN("DAY_MICROSECOND")}, - {(char *) STRING_WITH_LEN("HOUR_MICROSECOND")}, - {(char *) STRING_WITH_LEN("MINUTE_MICROSECOND")}, + {(char *) STRING_WITH_LEN("YEAR")}, + {(char *) STRING_WITH_LEN("QUARTER")}, + {(char *) STRING_WITH_LEN("MONTH")}, + {(char *) STRING_WITH_LEN("DAY")}, + {(char *) STRING_WITH_LEN("HOUR")}, + {(char *) STRING_WITH_LEN("MINUTE")}, + {(char *) STRING_WITH_LEN("WEEK")}, + {(char *) STRING_WITH_LEN("SECOND")}, + {(char *) STRING_WITH_LEN("MICROSECOND")}, + {(char *) STRING_WITH_LEN("YEAR_MONTH")}, + {(char *) STRING_WITH_LEN("DAY_HOUR")}, + {(char *) STRING_WITH_LEN("DAY_MINUTE")}, + {(char *) STRING_WITH_LEN("DAY_SECOND")}, + {(char *) STRING_WITH_LEN("HOUR_MINUTE")}, + {(char *) STRING_WITH_LEN("HOUR_SECOND")}, + {(char *) STRING_WITH_LEN("MINUTE_SECOND")}, + {(char *) STRING_WITH_LEN("DAY_MICROSECOND")}, + {(char *) STRING_WITH_LEN("HOUR_MICROSECOND")}, + {(char *) STRING_WITH_LEN("MINUTE_MICROSECOND")}, {(char *) STRING_WITH_LEN("SECOND_MICROSECOND")} }; @@ -188,10 +189,10 @@ LEX_STRING interval_type_to_name[] = { /* Inits the scheduler queue - prioritized queue from mysys/queue.c - + Synopsis evex_queue_init() - + queue - pointer the the memory to be initialized as queue. has to be allocated from the caller @@ -211,10 +212,10 @@ evex_queue_init(EVEX_QUEUE_TYPE *queue) /* Compares 2 LEX strings regarding case. - + Synopsis my_time_compare() - + s - first LEX_STRING t - second LEX_STRING cs - charset @@ -223,7 +224,7 @@ evex_queue_init(EVEX_QUEUE_TYPE *queue) -1 - s < t 0 - s == t 1 - s > t - + Notes TIME.second_part is not considered during comparison */ @@ -237,18 +238,18 @@ int sortcmp_lex_string(LEX_STRING s, LEX_STRING t, CHARSET_INFO *cs) /* Compares 2 TIME structures - + Synopsis my_time_compare() - + a - first TIME b - second time - + RETURNS: -1 - a < b 0 - a == b 1 - a > b - + Notes TIME.second_part is not considered during comparison */ @@ -275,42 +276,42 @@ my_time_compare(TIME *a, TIME *b) /* - Compares the execute_at members of 2 event_timed instances - + Compares the execute_at members of 2 Event_timed instances + Synopsis event_timed_compare() - - a - first event_timed object - b - second event_timed object - + + a - first Event_timed object + b - second Event_timed object + RETURNS: -1 - a->execute_at < b->execute_at 0 - a->execute_at == b->execute_at 1 - a->execute_at > b->execute_at - + Notes execute_at.second_part is not considered during comparison */ int -event_timed_compare(event_timed *a, event_timed *b) +event_timed_compare(Event_timed *a, Event_timed *b) { return my_time_compare(&a->execute_at, &b->execute_at); } /* - Compares the execute_at members of 2 event_timed instances. + Compares the execute_at members of 2 Event_timed instances. Used as callback for the prioritized queue when shifting elements inside. - + Synopsis event_timed_compare() vptr - not used (set it to NULL) - a - first event_timed object - b - second event_timed object - + a - first Event_timed object + b - second Event_timed object + RETURNS: -1 - a->execute_at < b->execute_at 0 - a->execute_at == b->execute_at @@ -323,7 +324,7 @@ event_timed_compare(event_timed *a, event_timed *b) int event_timed_compare_q(void *vptr, byte* a, byte *b) { - return event_timed_compare((event_timed *)a, (event_timed *)b); + return event_timed_compare((Event_timed *)a, (Event_timed *)b); } @@ -333,18 +334,16 @@ event_timed_compare_q(void *vptr, byte* a, byte *b) For YEAR_MONTH - expression is in months DAY_MINUTE - expression is in minutes - + Synopsis event_reconstruct_interval_expression() buf - preallocated String buffer to add the value to interval - the interval type (for instance YEAR_MONTH) expression - the value in the lowest entity - + RETURNS 0 - OK 1 - Error - - */ int @@ -369,7 +368,7 @@ event_reconstruct_interval_expression(String *buf, goto common_1_lev_code; case INTERVAL_HOUR_MINUTE: case INTERVAL_MINUTE_SECOND: - multipl= 60; + multipl= 60; common_1_lev_code: buf->append('\''); end= longlong10_to_str(expression/multipl, tmp_buff, 10); @@ -378,7 +377,7 @@ common_1_lev_code: break; case INTERVAL_DAY_MINUTE: { - int tmp_expr= expr; + ulonglong tmp_expr= expr; tmp_expr/=(24*60); buf->append('\''); @@ -396,7 +395,7 @@ common_1_lev_code: break; case INTERVAL_HOUR_SECOND: { - int tmp_expr= expr; + ulonglong tmp_expr= expr; buf->append('\''); end= longlong10_to_str(tmp_expr/3600, tmp_buff, 10); @@ -413,7 +412,7 @@ common_1_lev_code: break; case INTERVAL_DAY_SECOND: { - int tmp_expr= expr; + ulonglong tmp_expr= expr; tmp_expr/=(24*3600); buf->append('\''); @@ -438,6 +437,7 @@ common_1_lev_code: case INTERVAL_HOUR_MICROSECOND: case INTERVAL_MINUTE_MICROSECOND: case INTERVAL_SECOND_MICROSECOND: + case INTERVAL_MICROSECOND: my_error(ER_NOT_SUPPORTED_YET, MYF(0), "MICROSECOND"); return 1; break; @@ -472,16 +472,15 @@ common_1_lev_code: table The table pointer RETURN - 1 Cannot lock table + 1 Cannot lock table 2 The table is corrupted - different number of fields - 0 OK + 0 OK */ int evex_open_event_table(THD *thd, enum thr_lock_type lock_type, TABLE **table) { TABLE_LIST tables; - bool not_used; DBUG_ENTER("open_proc_table"); bzero((char*) &tables, sizeof(tables)); @@ -494,7 +493,7 @@ evex_open_event_table(THD *thd, enum thr_lock_type lock_type, TABLE **table) if (table_check_intact(tables.table, EVEX_FIELD_COUNT, event_table_fields, &mysql_event_last_create_time, - ER_EVENT_CANNOT_LOAD_FROM_TABLE)) + ER_CANNOT_LOAD_FROM_TABLE)) { close_thread_tables(thd); DBUG_RETURN(2); @@ -520,7 +519,7 @@ evex_open_event_table(THD *thd, enum thr_lock_type lock_type, TABLE **table) */ inline int -evex_db_find_event_aux(THD *thd, event_timed *et, TABLE *table) +evex_db_find_event_aux(THD *thd, Event_timed *et, TABLE *table) { return evex_db_find_event_by_name(thd, et->dbname, et->name, et->definer, table); @@ -589,26 +588,26 @@ evex_db_find_event_by_name(THD *thd, const LEX_STRING dbname, thd THD table the row to fill out et Event's data - + Returns 0 - ok EVEX_GENERAL_ERROR - bad data - EVEX_GET_FIELD_FAILED - field count does not match. table corrupted? + EVEX_GET_FIELD_FAILED - field count does not match. table corrupted? DESCRIPTION Used both when an event is created and when it is altered. */ static int -evex_fill_row(THD *thd, TABLE *table, event_timed *et, my_bool is_update) +evex_fill_row(THD *thd, TABLE *table, Event_timed *et, my_bool is_update) { enum evex_table_field field_num; DBUG_ENTER("evex_fill_row"); - DBUG_PRINT("info", ("dbname=[%s]", et->dbname.str)); - DBUG_PRINT("info", ("name =[%s]", et->name.str)); - DBUG_PRINT("info", ("body =[%s]", et->body.str)); + DBUG_PRINT("info", ("dbname=[%s]", et->dbname.str)); + DBUG_PRINT("info", ("name =[%s]", et->name.str)); + DBUG_PRINT("info", ("body =[%s]", et->body.str)); if (table->field[field_num= EVEX_FIELD_DB]-> store(et->dbname.str, et->dbname.length, system_charset_info)) @@ -618,10 +617,11 @@ evex_fill_row(THD *thd, TABLE *table, event_timed *et, my_bool is_update) store(et->name.str, et->name.length, system_charset_info)) goto trunc_err; - // both ON_COMPLETION and STATUS are NOT NULL thus not calling set_notnull() - table->field[EVEX_FIELD_ON_COMPLETION]->store((longlong)et->on_completion); + /* both ON_COMPLETION and STATUS are NOT NULL thus not calling set_notnull() */ + table->field[EVEX_FIELD_ON_COMPLETION]->store((longlong)et->on_completion, + true); - table->field[EVEX_FIELD_STATUS]->store((longlong)et->status); + table->field[EVEX_FIELD_STATUS]->store((longlong)et->status, true); /* Change the SQL_MODE only if body was present in an ALTER EVENT and of course @@ -629,70 +629,76 @@ evex_fill_row(THD *thd, TABLE *table, event_timed *et, my_bool is_update) */ if (et->body.str) { - table->field[EVEX_FIELD_SQL_MODE]->store((longlong)thd->variables.sql_mode); + table->field[EVEX_FIELD_SQL_MODE]->store((longlong)thd->variables.sql_mode, + true); if (table->field[field_num= EVEX_FIELD_BODY]-> store(et->body.str, et->body.length, system_charset_info)) goto trunc_err; } - if (et->starts.year) - { - table->field[EVEX_FIELD_STARTS]->set_notnull();// set NULL flag to OFF - table->field[EVEX_FIELD_STARTS]-> - store_time(&et->starts, MYSQL_TIMESTAMP_DATETIME); - } - - if (et->ends.year) - { - table->field[EVEX_FIELD_ENDS]->set_notnull(); - table->field[EVEX_FIELD_ENDS]-> - store_time(&et->ends, MYSQL_TIMESTAMP_DATETIME); - } - if (et->expression) { table->field[EVEX_FIELD_INTERVAL_EXPR]->set_notnull(); - table->field[EVEX_FIELD_INTERVAL_EXPR]->store((longlong)et->expression); + table->field[EVEX_FIELD_INTERVAL_EXPR]->store((longlong)et->expression,true); table->field[EVEX_FIELD_TRANSIENT_INTERVAL]->set_notnull(); /* In the enum (C) intervals start from 0 but in mysql enum valid values start from 1. Thus +1 offset is needed! */ - table->field[EVEX_FIELD_TRANSIENT_INTERVAL]->store((longlong)et->interval+1); + table->field[EVEX_FIELD_TRANSIENT_INTERVAL]->store((longlong)et->interval+1, + true); table->field[EVEX_FIELD_EXECUTE_AT]->set_null(); + + if (!et->starts_null) + { + table->field[EVEX_FIELD_STARTS]->set_notnull(); + table->field[EVEX_FIELD_STARTS]-> + store_time(&et->starts, MYSQL_TIMESTAMP_DATETIME); + } + + if (!et->ends_null) + { + table->field[EVEX_FIELD_ENDS]->set_notnull(); + table->field[EVEX_FIELD_ENDS]-> + store_time(&et->ends, MYSQL_TIMESTAMP_DATETIME); + } } else if (et->execute_at.year) { - // fix_fields already called in init_execute_at table->field[EVEX_FIELD_INTERVAL_EXPR]->set_null(); table->field[EVEX_FIELD_TRANSIENT_INTERVAL]->set_null(); - + table->field[EVEX_FIELD_STARTS]->set_null(); + table->field[EVEX_FIELD_ENDS]->set_null(); + table->field[EVEX_FIELD_EXECUTE_AT]->set_notnull(); table->field[EVEX_FIELD_EXECUTE_AT]->store_time(&et->execute_at, - MYSQL_TIMESTAMP_DATETIME); - - table->field[EVEX_FIELD_TRANSIENT_INTERVAL]->set_null(); + MYSQL_TIMESTAMP_DATETIME); } else { DBUG_ASSERT(is_update); - // it is normal to be here when the action is update - // this is an error if the action is create. something is borked + /* + it is normal to be here when the action is update + this is an error if the action is create. something is borked + */ } ((Field_timestamp *)table->field[EVEX_FIELD_MODIFIED])->set_time(); - if (et->comment.length) - if (table->field[field_num= EVEX_FIELD_COMMENT]-> - store(et->comment.str, et->comment.length, system_charset_info)) + if (et->comment.str) + { + if (table->field[field_num= EVEX_FIELD_COMMENT]->store(et->comment.str, + et->comment.length, + system_charset_info)) goto trunc_err; + } DBUG_RETURN(0); trunc_err: - my_error(ER_EVENT_DATA_TOO_LONG, MYF(0)); + my_error(ER_EVENT_DATA_TOO_LONG, MYF(0), table->field[field_num]->field_name); DBUG_RETURN(EVEX_GENERAL_ERROR); } @@ -703,25 +709,24 @@ trunc_err: SYNOPSIS db_create_event() thd THD - et event_timed object containing information for the event + et Event_timed object containing information for the event create_if_not - if an warning should be generated in case event exists rows_affected - how many rows were affected - + Return value 0 - OK EVEX_GENERAL_ERROR - Failure DESCRIPTION - Creates an event. Relies on evex_fill_row which is shared with + Creates an event. Relies on evex_fill_row which is shared with db_update_event. The name of the event is inside "et". */ static int -db_create_event(THD *thd, event_timed *et, my_bool create_if_not, +db_create_event(THD *thd, Event_timed *et, my_bool create_if_not, uint *rows_affected) { int ret= 0; TABLE *table; - char definer[HOSTNAME_LENGTH+USERNAME_LENGTH+2]; char olddb[128]; bool dbchanged= false; DBUG_ENTER("db_create_event"); @@ -734,16 +739,16 @@ db_create_event(THD *thd, event_timed *et, my_bool create_if_not, my_error(ER_EVENT_OPEN_TABLE_FAILED, MYF(0)); goto err; } - + DBUG_PRINT("info", ("check existance of an event with the same name")); if (!evex_db_find_event_aux(thd, et, table)) { if (create_if_not) { push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, - ER_EVENT_ALREADY_EXISTS, ER(ER_EVENT_ALREADY_EXISTS), - et->name.str); - goto ok; + ER_EVENT_ALREADY_EXISTS, ER(ER_EVENT_ALREADY_EXISTS), + et->name.str); + goto ok; } my_error(ER_EVENT_ALREADY_EXISTS, MYF(0), et->name.str); goto err; @@ -755,8 +760,8 @@ db_create_event(THD *thd, event_timed *et, my_bool create_if_not, my_error(ER_BAD_DB_ERROR, MYF(0)); goto err; } - - restore_record(table, s->default_values); // Get default values for fields + + restore_record(table, s->default_values); // Get default values for fields if (system_charset_info->cset->numchars(system_charset_info, et->dbname.str, et->dbname.str + et->dbname.length) @@ -782,7 +787,7 @@ db_create_event(THD *thd, event_timed *et, my_bool create_if_not, if (!(et->expression) && !(et->execute_at.year)) { DBUG_PRINT("error", ("neither expression nor execute_at are set!")); - my_error(ER_EVENT_NEITHER_M_EXPR_NOR_M_AT, MYF(0)); + my_error(ER_EVENT_NEITHER_M_EXPR_NOR_M_AT, MYF(0)); goto err; } @@ -796,7 +801,10 @@ db_create_event(THD *thd, event_timed *et, my_bool create_if_not, ((Field_timestamp *)table->field[EVEX_FIELD_CREATED])->set_time(); - // evex_fill_row() calls my_error() in case of error so no need to handle it here + /* + evex_fill_row() calls my_error() in case of error so no need to + handle it here + */ if ((ret= evex_fill_row(thd, table, et, false))) goto err; @@ -805,7 +813,8 @@ db_create_event(THD *thd, event_timed *et, my_bool create_if_not, my_error(ER_EVENT_STORE_FAILED, MYF(0), et->name.str, ret); goto err; } - + +#ifdef USE_THIS_CODE_AS_TEMPLATE_WHEN_EVENT_REPLICATION_IS_AGREED if (mysql_bin_log.is_open()) { thd->clear_error(); @@ -813,7 +822,8 @@ db_create_event(THD *thd, event_timed *et, my_bool create_if_not, thd->binlog_query(THD::MYSQL_QUERY_TYPE, thd->query, thd->query_length, FALSE, FALSE); } - +#endif + *rows_affected= 1; ok: if (dbchanged) @@ -839,14 +849,14 @@ err: thd THD sp_name the name of the event to alter et event's data - + NOTES sp_name is passed since this is the name of the event to alter in case of RENAME TO. */ static int -db_update_event(THD *thd, event_timed *et, sp_name *new_name) +db_update_event(THD *thd, Event_timed *et, sp_name *new_name) { TABLE *table; int ret= EVEX_OPEN_TABLE_FAILED; @@ -864,7 +874,7 @@ db_update_event(THD *thd, event_timed *et, sp_name *new_name) goto err; } - // first look whether we overwrite + /* first look whether we overwrite */ if (new_name) { if (!sortcmp_lex_string(et->name, new_name->m_name, system_charset_info) && @@ -890,19 +900,18 @@ db_update_event(THD *thd, event_timed *et, sp_name *new_name) if (EVEX_KEY_NOT_FOUND == evex_db_find_event_aux(thd, et, table)) { my_error(ER_EVENT_DOES_NOT_EXIST, MYF(0), et->name.str); - goto err; + goto err; } - store_record(table,record[1]); - - // Don't update create on row update. + + /* Don't update create on row update. */ table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET; - // evex_fill_row() calls my_error() in case of error so no need to handle it here + /* evex_fill_row() calls my_error() in case of error so no need to handle it here */ if ((ret= evex_fill_row(thd, table, et, true))) goto err; - + if (new_name) { table->field[EVEX_FIELD_DB]-> @@ -917,7 +926,7 @@ db_update_event(THD *thd, event_timed *et, sp_name *new_name) goto err; } - // close mysql.event or we crash later when loading the event from disk + /* close mysql.event or we crash later when loading the event from disk */ close_thread_tables(thd); DBUG_RETURN(0); @@ -939,20 +948,19 @@ err: definer who owns the event ett event's data if event is found tbl TABLE object to use when not NULL - + NOTES 1) Use sp_name for look up, return in **ett if found 2) tbl is not closed at exit */ static int -db_find_event(THD *thd, sp_name *name, LEX_STRING *definer, event_timed **ett, +db_find_event(THD *thd, sp_name *name, LEX_STRING *definer, Event_timed **ett, TABLE *tbl, MEM_ROOT *root) { TABLE *table; int ret; - char *ptr; - event_timed *et=NULL; + Event_timed *et=NULL; DBUG_ENTER("db_find_event"); DBUG_PRINT("enter", ("name: %*s", name->m_name.length, name->m_name.str)); @@ -974,7 +982,7 @@ db_find_event(THD *thd, sp_name *name, LEX_STRING *definer, event_timed **ett, my_error(ER_EVENT_DOES_NOT_EXIST, MYF(0), name->m_name.str); goto done; } - et= new event_timed; + et= new Event_timed; /* 1)The table should not be closed beforehand. ::load_from_row() only loads @@ -984,7 +992,7 @@ db_find_event(THD *thd, sp_name *name, LEX_STRING *definer, event_timed **ett, */ if ((ret= et->load_from_row(root, table))) { - my_error(ER_EVENT_CANNOT_LOAD_FROM_TABLE, MYF(0)); + my_error(ER_CANNOT_LOAD_FROM_TABLE, MYF(0)); goto done; } @@ -994,7 +1002,7 @@ done: delete et; et= 0; } - // don't close the table if we haven't opened it ourselves + /* don't close the table if we haven't opened it ourselves */ if (!tbl && table) close_thread_tables(thd); *ett= et; @@ -1012,11 +1020,10 @@ done: spn the name of the event to alter definer who is the owner use_lock whether to obtain a lock on LOCK_event_arrays or not - + RETURN VALUE 0 - OK < 0 - error (in this case underlying functions call my_error()). - */ static int @@ -1025,7 +1032,7 @@ evex_load_and_compile_event(THD * thd, sp_name *spn, LEX_STRING definer, { int ret= 0; MEM_ROOT *tmp_mem_root; - event_timed *ett; + Event_timed *ett; Open_tables_state backup; DBUG_ENTER("db_load_and_compile_event"); @@ -1035,7 +1042,7 @@ evex_load_and_compile_event(THD * thd, sp_name *spn, LEX_STRING definer, thd->mem_root= &evex_mem_root; thd->reset_n_backup_open_tables_state(&backup); - // no need to use my_error() here because db_find_event() has done it + /* no need to use my_error() here because db_find_event() has done it */ ret= db_find_event(thd, spn, &definer, &ett, NULL, NULL); thd->restore_backup_open_tables_state(&backup); if (ret) @@ -1082,12 +1089,12 @@ done: use_lock - whether to lock the mutex LOCK_event_arrays or not in case it has been already locked outside is_drop - if an event is currently being executed then we can also delete - the event_timed instance, so we alarm the event that it should + the Event_timed instance, so we alarm the event that it should drop itself if this parameter is set to TRUE. It's false on ALTER EVENT. RETURNS - 0 - OK (always) + 0 OK (always) */ static int @@ -1109,8 +1116,8 @@ evex_remove_from_cache(LEX_STRING *db, LEX_STRING *name, bool use_lock, for (i= 0; i < evex_queue_num_elements(EVEX_EQ_NAME); ++i) { - event_timed *et= evex_queue_element(&EVEX_EQ_NAME, i, event_timed*); - DBUG_PRINT("info", ("[%s.%s]==[%s.%s]?",db->str,name->str, et->dbname.str, + Event_timed *et= evex_queue_element(&EVEX_EQ_NAME, i, Event_timed*); + DBUG_PRINT("info", ("[%s.%s]==[%s.%s]?",db->str,name->str, et->dbname.str, et->name.str)); if (!sortcmp_lex_string(*name, et->name, system_charset_info) && !sortcmp_lex_string(*db, et->dbname, system_charset_info)) @@ -1130,7 +1137,7 @@ evex_remove_from_cache(LEX_STRING *db, LEX_STRING *name, bool use_lock, } DBUG_PRINT("evex_remove_from_cache", ("delete from queue")); evex_queue_delete_element(&EVEX_EQ_NAME, i); - // ok, we have cleaned + /* ok, we have cleaned */ ret= 0; goto done; } @@ -1154,14 +1161,14 @@ done: create_options Options specified when in the query. We are interested whether there is IF NOT EXISTS rows_affected How many rows were affected - + NOTES - in case there is an event with the same name (db) and IF NOT EXISTS is specified, an warning is put into the W stack. */ int -evex_create_event(THD *thd, event_timed *et, uint create_options, +evex_create_event(THD *thd, Event_timed *et, uint create_options, uint *rows_affected) { int ret = 0; @@ -1184,7 +1191,7 @@ evex_create_event(THD *thd, event_timed *et, uint create_options, VOID(pthread_mutex_unlock(&LOCK_evex_running)); done: - // No need to close the table, it will be closed in sql_parse::do_command + /* No need to close the table, it will be closed in sql_parse::do_command */ DBUG_RETURN(ret); } @@ -1198,7 +1205,7 @@ done: thd THD et event's data new_name set in case of RENAME TO. - + NOTES et contains data about dbname and event name. new_name is the new name of the event, if not null (this means @@ -1206,10 +1213,10 @@ done: */ int -evex_update_event(THD *thd, event_timed *et, sp_name *new_name, +evex_update_event(THD *thd, Event_timed *et, sp_name *new_name, uint *rows_affected) { - int ret, i; + int ret; bool need_second_pass= true; DBUG_ENTER("evex_update_event"); @@ -1258,10 +1265,9 @@ done: et event's name drop_if_exists if set and the event not existing => warning onto the stack rows_affected affected number of rows is returned heres - */ -int db_drop_event(THD *thd, event_timed *et, bool drop_if_exists, +int db_drop_event(THD *thd, Event_timed *et, bool drop_if_exists, uint *rows_affected) { TABLE *table; @@ -1291,8 +1297,8 @@ int db_drop_event(THD *thd, event_timed *et, bool drop_if_exists, if (drop_if_exists) { push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, - ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST), - "Event", et->name.str); + ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST), + "Event", et->name.str); ret= 0; } else my_error(ER_EVENT_DOES_NOT_EXIST, MYF(0), et->name.str); @@ -1302,7 +1308,7 @@ int db_drop_event(THD *thd, event_timed *et, bool drop_if_exists, done: /* - evex_drop_event() is used by event_timed::drop therefore + evex_drop_event() is used by Event_timed::drop therefore we have to close our thread tables. */ close_thread_tables(thd); @@ -1324,10 +1330,9 @@ done: */ int -evex_drop_event(THD *thd, event_timed *et, bool drop_if_exists, +evex_drop_event(THD *thd, Event_timed *et, bool drop_if_exists, uint *rows_affected) { - TABLE *table; int ret= 0; DBUG_ENTER("evex_drop_event"); @@ -1337,7 +1342,7 @@ evex_drop_event(THD *thd, event_timed *et, bool drop_if_exists, if (evex_is_running) ret= evex_remove_from_cache(&et->dbname, &et->name, true, true); VOID(pthread_mutex_unlock(&LOCK_evex_running)); - + if (ret == 1) ret= 0; else if (ret == 0) @@ -1357,18 +1362,17 @@ evex_drop_event(THD *thd, event_timed *et, bool drop_if_exists, thd THD spn the name of the event (db, name) definer the definer of the event - + RETURNS 0 - OK 1 - Error during writing to the wire - */ int evex_show_create_event(THD *thd, sp_name *spn, LEX_STRING definer) { int ret; - event_timed *et= NULL; + Event_timed *et= NULL; Open_tables_state backup; DBUG_ENTER("evex_update_event"); @@ -1379,14 +1383,14 @@ evex_show_create_event(THD *thd, sp_name *spn, LEX_STRING definer) thd->restore_backup_open_tables_state(&backup); if (!ret && et) - { + { Protocol *protocol= thd->protocol; char show_str_buf[768]; String show_str(show_str_buf, sizeof(show_str_buf), system_charset_info); List<Item> field_list; byte *sql_mode_str; ulong sql_mode_len=0; - + show_str.length(0); show_str.set_charset(system_charset_info); @@ -1412,19 +1416,18 @@ evex_show_create_event(THD *thd, sp_name *spn, LEX_STRING definer) protocol->store((char*) sql_mode_str, sql_mode_len, system_charset_info); - protocol->store(show_str.c_ptr(), show_str.length(), system_charset_info); ret= protocol->write(); send_eof(thd); } - + DBUG_RETURN(ret); } /* evex_drop_db_events - Drops all events in the selected database - + thd - Thread db - ASCIIZ the name of the database @@ -1438,17 +1441,16 @@ evex_show_create_event(THD *thd, sp_name *spn, LEX_STRING definer) 1. Go through the in-memory cache, if the scheduler is working and for every event whose dbname matches the database we drop check whether is currently in execution: - - event_timed::can_spawn() returns true -> the event is not + - Event_timed::can_spawn() returns true -> the event is not being executed in a child thread. The reason not to use - event_timed::is_running() is that the latter shows only if + Event_timed::is_running() is that the latter shows only if it is being executed, which is 99% of the time in the thread but there are some initiliazations before and after the anonymous SP is being called. So if we delete in this moment -=> *boom*, so we have to check whether the thread has been spawned and can_spawn() is the right method. - - event_timed::can_spawn() returns false -> being runned ATM + - Event_timed::can_spawn() returns false -> being runned ATM just set the flags so it should drop itself. - */ int @@ -1456,7 +1458,6 @@ evex_drop_db_events(THD *thd, char *db) { TABLE *table; READ_RECORD read_record_info; - MYSQL_LOCK *lock; int ret= 0; uint i; LEX_STRING db_lex= {db, strlen(db)}; @@ -1464,7 +1465,6 @@ evex_drop_db_events(THD *thd, char *db) DBUG_ENTER("evex_drop_db_events"); DBUG_PRINT("info",("dropping events from %s", db)); - VOID(pthread_mutex_lock(&LOCK_event_arrays)); if ((ret= evex_open_event_table(thd, TL_WRITE, &table))) @@ -1482,7 +1482,7 @@ evex_drop_db_events(THD *thd, char *db) for (i= 0; i < evex_queue_num_elements(EVEX_EQ_NAME); ++i) { - event_timed *et= evex_queue_element(&EVEX_EQ_NAME, i, event_timed*); + Event_timed *et= evex_queue_element(&EVEX_EQ_NAME, i, Event_timed*); if (sortcmp_lex_string(et->dbname, db_lex, system_charset_info)) continue; @@ -1505,7 +1505,7 @@ evex_drop_db_events(THD *thd, char *db) else if (ret == EVEX_KEY_NOT_FOUND) { sql_print_error("Expected to find event %s.%s of %s on disk-not there.", - et->dbname.str, et->name.str, et->definer.str); + et->dbname.str, et->name.str, et->definer.str); } et->free_sp(); delete et; @@ -1521,7 +1521,7 @@ evex_drop_db_events(THD *thd, char *db) } DBUG_PRINT("info",("%d elements in the queue", evex_queue_num_elements(EVEX_EQ_NAME))); - evex_queue_delete_element(&EVEX_EQ_NAME, i);// 1 is top + evex_queue_delete_element(&EVEX_EQ_NAME, i);// 0 is top DBUG_PRINT("info",("%d elements in the queue", evex_queue_num_elements(EVEX_EQ_NAME))); /* @@ -1559,7 +1559,7 @@ skip_memory: LEX_STRING et_db_lex= {et_db, strlen(et_db)}; if (!sortcmp_lex_string(et_db_lex, db_lex, system_charset_info)) { - event_timed ett; + Event_timed ett; char *ptr; if ((ptr= get_field(thd->mem_root, table->field[EVEX_FIELD_STATUS])) @@ -1598,7 +1598,7 @@ end: VOID(pthread_mutex_unlock(&LOCK_event_arrays)); end_read_record(&read_record_info); - thd->version--; // Force close to free memory + thd->version--; /* Force close to free memory */ close_thread_tables(thd); diff --git a/sql/event.h b/sql/event.h index 4adacdd4e3a..d070f93c575 100644 --- a/sql/event.h +++ b/sql/event.h @@ -35,6 +35,7 @@ #define EVEX_BODY_TOO_LONG SP_BODY_TOO_LONG #define EVEX_BAD_PARAMS -21 #define EVEX_NOT_RUNNING -22 +#define EVEX_MICROSECOND_UNSUP -23 #define EVENT_EXEC_NO_MORE (1L << 0) #define EVENT_NOT_USED (1L << 1) @@ -75,10 +76,10 @@ enum evex_table_field EVEX_FIELD_COUNT /* a cool trick to count the number of fields :) */ } ; -class event_timed +class Event_timed { - event_timed(const event_timed &); /* Prevent use of these */ - void operator=(event_timed &); + Event_timed(const Event_timed &); /* Prevent use of these */ + void operator=(Event_timed &); my_bool in_spawned_thread; ulong locked_by_thread_id; my_bool running; @@ -102,6 +103,9 @@ public: TIME starts; TIME ends; TIME execute_at; + my_bool starts_null; + my_bool ends_null; + my_bool execute_at_null; longlong expression; interval_type interval; @@ -118,7 +122,7 @@ public: bool free_sphead_on_delete; uint flags;//all kind of purposes - event_timed():in_spawned_thread(0),locked_by_thread_id(0), + Event_timed():in_spawned_thread(0),locked_by_thread_id(0), running(0), status_changed(false), last_executed_changed(false), expression(0), created(0), modified(0), on_completion(MYSQL_EVENT_ON_COMPLETION_DROP), @@ -131,7 +135,7 @@ public: init(); } - ~event_timed() + ~Event_timed() { pthread_mutex_destroy(&this->LOCK_running); if (free_sphead_on_delete) @@ -255,15 +259,15 @@ protected: int -evex_create_event(THD *thd, event_timed *et, uint create_options, +evex_create_event(THD *thd, Event_timed *et, uint create_options, uint *rows_affected); int -evex_update_event(THD *thd, event_timed *et, sp_name *new_name, +evex_update_event(THD *thd, Event_timed *et, sp_name *new_name, uint *rows_affected); int -evex_drop_event(THD *thd, event_timed *et, bool drop_if_exists, +evex_drop_event(THD *thd, Event_timed *et, bool drop_if_exists, uint *rows_affected); int @@ -292,7 +296,7 @@ shutdown_events(); // auxiliary int -event_timed_compare(event_timed **a, event_timed **b); +event_timed_compare(Event_timed **a, Event_timed **b); diff --git a/sql/event_executor.cc b/sql/event_executor.cc index b6c6981fd7d..92acf154c75 100644 --- a/sql/event_executor.cc +++ b/sql/event_executor.cc @@ -38,9 +38,9 @@ extern ulong thread_created; extern const char *my_localhost; extern pthread_attr_t connection_attrib; -pthread_mutex_t LOCK_event_arrays, // mutex for when working with the queue - LOCK_workers_count, // mutex for when inc/dec uint workers_count - LOCK_evex_running; // mutes for managing bool evex_is_running +pthread_mutex_t LOCK_event_arrays, // mutex for when working with the queue + LOCK_workers_count, // mutex for when inc/dec uint workers_count + LOCK_evex_running; // mutes for managing bool evex_is_running bool evex_is_running= false; @@ -48,14 +48,14 @@ bool evex_is_running= false; ulonglong evex_main_thread_id= 0; ulong opt_event_executor; my_bool event_executor_running_global_var; -static my_bool evex_mutexes_initted= false; +static my_bool evex_mutexes_initted= FALSE; static uint workers_count; static int evex_load_events_from_db(THD *thd); bool -evex_print_warnings(THD *thd, event_timed *et); +evex_print_warnings(THD *thd, Event_timed *et); /* TODO Andrey: Check for command line option whether to start @@ -107,7 +107,7 @@ evex_init_mutexes() if (evex_mutexes_initted) return; - evex_mutexes_initted= true; + evex_mutexes_initted= TRUE; pthread_mutex_init(&LOCK_event_arrays, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_workers_count, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_evex_running, MY_MUTEX_INIT_FAST); @@ -132,10 +132,9 @@ evex_check_system_tables() { THD *thd= current_thd; TABLE_LIST tables; - bool not_used; Open_tables_state backup; - // thd is 0x0 during boot of the server. Later it's !=0x0 + /* thd is 0x0 during boot of the server. Later it's !=0x0 */ if (!thd) return; @@ -151,7 +150,7 @@ evex_check_system_tables() else { table_check_intact(tables.table, MYSQL_DB_FIELD_COUNT, mysql_db_table_fields, - &mysql_db_table_last_check,ER_EVENT_CANNOT_LOAD_FROM_TABLE); + &mysql_db_table_last_check,ER_CANNOT_LOAD_FROM_TABLE); close_thread_tables(thd); } @@ -182,7 +181,7 @@ evex_check_system_tables() SYNOPSIS init_events() - + NOTES Inits the mutexes used by the scheduler. Done at server start. */ @@ -191,11 +190,10 @@ int init_events() { pthread_t th; - DBUG_ENTER("init_events"); DBUG_PRINT("info",("Starting events main thread")); - + evex_check_system_tables(); evex_init_mutexes(); @@ -207,7 +205,7 @@ init_events() if (event_executor_running_global_var) { #ifndef DBUG_FAULTY_THR - //TODO Andrey: Change the error code returned! + /* TODO Andrey: Change the error code returned! */ if (pthread_create(&th, &connection_attrib, event_executor_main,(void*)NULL)) DBUG_RETURN(ER_SLAVE_THREAD); #else @@ -224,7 +222,7 @@ init_events() SYNOPSIS shutdown_events() - + NOTES Destroys the mutexes. */ @@ -233,14 +231,17 @@ void shutdown_events() { DBUG_ENTER("shutdown_events"); - - VOID(pthread_mutex_lock(&LOCK_evex_running)); - VOID(pthread_mutex_unlock(&LOCK_evex_running)); - pthread_mutex_destroy(&LOCK_event_arrays); - pthread_mutex_destroy(&LOCK_workers_count); - pthread_mutex_destroy(&LOCK_evex_running); - + if (evex_mutexes_initted) + { + evex_mutexes_initted= FALSE; + VOID(pthread_mutex_lock(&LOCK_evex_running)); + VOID(pthread_mutex_unlock(&LOCK_evex_running)); + + pthread_mutex_destroy(&LOCK_event_arrays); + pthread_mutex_destroy(&LOCK_workers_count); + pthread_mutex_destroy(&LOCK_evex_running); + } DBUG_VOID_RETURN; } @@ -251,11 +252,11 @@ shutdown_events() SYNOPSIS init_event_thread() thd - the THD of the thread. Has to be allocated by the caller. - + NOTES 1. The host of the thead is my_localhost 2. thd->net is initted with NULL - no communication. - + Returns 0 - OK -1 - Error @@ -272,7 +273,7 @@ init_event_thread(THD* thd) my_net_init(&thd->net, 0); thd->net.read_timeout = slave_net_timeout; thd->slave_thread= 0; - thd->options= OPTION_AUTO_IS_NULL; + thd->options|= OPTION_AUTO_IS_NULL; thd->client_capabilities= CLIENT_LOCAL_FILES; thd->real_id=pthread_self(); VOID(pthread_mutex_lock(&LOCK_thread_count)); @@ -302,7 +303,7 @@ init_event_thread(THD* thd) /* This function waits till the time next event in the queue should be executed. - + Returns WAIT_STATUS_READY There is an event to be executed right now WAIT_STATUS_EMPTY_QUEUE No events or the last event was dropped. @@ -314,7 +315,7 @@ init_event_thread(THD* thd) static int executor_wait_till_next_event_exec(THD *thd) { - event_timed *et; + Event_timed *et; TIME time_now; int t2sleep; @@ -327,9 +328,9 @@ executor_wait_till_next_event_exec(THD *thd) if (!evex_queue_num_elements(EVEX_EQ_NAME)) { VOID(pthread_mutex_unlock(&LOCK_event_arrays)); - DBUG_RETURN(1); + DBUG_RETURN(WAIT_STATUS_EMPTY_QUEUE); } - et= evex_queue_first_element(&EVEX_EQ_NAME, event_timed*); + et= evex_queue_first_element(&EVEX_EQ_NAME, Event_timed*); DBUG_ASSERT(et); if (et->status == MYSQL_EVENT_DISABLED) { @@ -337,14 +338,14 @@ executor_wait_till_next_event_exec(THD *thd) if (et->dropped) et->drop(thd); delete et; - evex_queue_delete_element(&EVEX_EQ_NAME, 1);// 1 is top + evex_queue_delete_element(&EVEX_EQ_NAME, 0);// 0 is top, internally 1 VOID(pthread_mutex_unlock(&LOCK_event_arrays)); sql_print_information("Event found disabled, dropping."); DBUG_RETURN(1); } - + DBUG_PRINT("evex main thread",("computing time to sleep till next exec")); - // set the internal clock of thd + /* set the internal clock of thd */ thd->end_time(); my_tz_UTC->gmt_sec_to_TIME(&time_now, thd->query_start()); t2sleep= evex_time_diff(&et->execute_at, &time_now); @@ -353,26 +354,33 @@ executor_wait_till_next_event_exec(THD *thd) DBUG_PRINT("evex main thread",("unlocked LOCK_event_arrays")); if (t2sleep > 0) { + ulonglong modified= et->modified; /* We sleep t2sleep seconds but we check every second whether this thread has been killed, or there is a new candidate */ while (t2sleep-- && !thd->killed && event_executor_running_global_var && evex_queue_num_elements(EVEX_EQ_NAME) && - (evex_queue_first_element(&EVEX_EQ_NAME, event_timed*) == et)) + (evex_queue_first_element(&EVEX_EQ_NAME, Event_timed*) == et && + evex_queue_first_element(&EVEX_EQ_NAME, Event_timed*)->modified == + modified)) { - DBUG_PRINT("evex main thread",("will sleep a bit more")); + DBUG_PRINT("evex main thread",("will sleep a bit more.")); my_sleep(1000000); } + DBUG_PRINT("info",("saved_modified=%llu current=%llu", modified, + evex_queue_num_elements(EVEX_EQ_NAME)? + evex_queue_first_element(&EVEX_EQ_NAME, Event_timed*)->modified: + (ulonglong)~0)); } - int ret= 0; + int ret= WAIT_STATUS_READY; if (!evex_queue_num_elements(EVEX_EQ_NAME)) - ret= 1; - else if (evex_queue_first_element(&EVEX_EQ_NAME, event_timed*) != et) - ret= 2; + ret= WAIT_STATUS_EMPTY_QUEUE; + else if (evex_queue_first_element(&EVEX_EQ_NAME, Event_timed*) != et) + ret= WAIT_STATUS_NEW_TOP_EVENT; if (thd->killed && event_executor_running_global_var) - ret= 3; + ret= WAIT_STATUS_STOP_EXECUTOR; DBUG_RETURN(ret); } @@ -385,8 +393,8 @@ executor_wait_till_next_event_exec(THD *thd) SYNOPSIS event_executor_main() - arg - unused - + arg unused + NOTES 1. The host of the thead is my_localhost 2. thd->net is initted with NULL - no communication. @@ -399,17 +407,15 @@ event_executor_main(void *arg) THD *thd; /* needs to be first for thread_stack */ uint i=0, j=0; my_ulonglong cnt= 0; - TIME time_now; DBUG_ENTER("event_executor_main"); - DBUG_PRINT("event_executor_main", ("EVEX thread started")); + DBUG_PRINT("event_executor_main", ("EVEX thread started")); - // init memory root + /* init memory root */ init_alloc_root(&evex_mem_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC); - - // needs to call my_thread_init(), otherwise we get a coredump in DBUG_ stuff + /* needs to call my_thread_init(), otherwise we get a coredump in DBUG_ stuff*/ my_thread_init(); if (sizeof(my_time_t) != sizeof(time_t)) @@ -420,14 +426,14 @@ event_executor_main(void *arg) goto err_no_thd; } - //TODO Andrey: Check for NULL - if (!(thd = new THD)) // note that contructor of THD uses DBUG_ ! + /* note that contructor of THD uses DBUG_ ! */ + if (!(thd = new THD)) { sql_print_error("SCHEDULER: Cannot create THD for the main thread."); goto err_no_thd; } - thd->thread_stack = (char*)&thd; // remember where our stack is - + thd->thread_stack = (char*)&thd; // remember where our stack is + pthread_detach_this_thread(); if (init_event_thread(thd)) @@ -469,8 +475,8 @@ event_executor_main(void *arg) while (!thd->killed) { TIME time_now; - event_timed *et; - + Event_timed *et; + cnt++; DBUG_PRINT("info", ("EVEX External Loop %d thd->k", cnt)); @@ -486,7 +492,7 @@ event_executor_main(void *arg) my_sleep(1000000);// sleep 1s continue; } - + restart_ticking: switch (executor_wait_till_next_event_exec(thd)) { case WAIT_STATUS_READY: // time to execute the event on top @@ -496,7 +502,7 @@ restart_ticking: DBUG_PRINT("evex main thread",("no more events")); continue; break; - case WAIT_STATUS_NEW_TOP_EVENT: // new event on top in the queue + case WAIT_STATUS_NEW_TOP_EVENT: // new event on top in the queue DBUG_PRINT("evex main thread",("restart ticking")); goto restart_ticking; case WAIT_STATUS_STOP_EXECUTOR: @@ -518,11 +524,10 @@ restart_ticking: DBUG_PRINT("evex main thread",("empty queue")); continue; } - et= evex_queue_first_element(&EVEX_EQ_NAME, event_timed*); + et= evex_queue_first_element(&EVEX_EQ_NAME, Event_timed*); DBUG_PRINT("evex main thread",("got event from the queue")); - if (et->execute_at.year > 1969 && - my_time_compare(&time_now, &et->execute_at) == -1) + if (!et->execute_at_null && my_time_compare(&time_now,&et->execute_at) == -1) { DBUG_PRINT("evex main thread",("still not the time for execution")); VOID(pthread_mutex_unlock(&LOCK_event_arrays)); @@ -569,8 +574,11 @@ restart_ticking: #else event_executor_worker((void *) et); #endif - if ((et->execute_at.year && !et->expression) || - TIME_to_ulonglong_datetime(&et->execute_at) == 0) + /* + 1. For one-time event : year is > 0 and expression is 0 + 2. For recurring, expression is != -=> check execute_at_null in this case + */ + if ((et->execute_at.year && !et->expression) || et->execute_at_null) et->flags |= EVENT_EXEC_NO_MORE; if ((et->flags & EVENT_EXEC_NO_MORE) || et->status == MYSQL_EVENT_DISABLED) @@ -580,10 +588,10 @@ restart_ticking: } DBUG_PRINT("evex main thread",("unlocking")); VOID(pthread_mutex_unlock(&LOCK_event_arrays)); - }// while + }/* while */ finish: - // First manifest that this thread does not work and then destroy + /* First manifest that this thread does not work and then destroy */ VOID(pthread_mutex_lock(&LOCK_evex_running)); evex_is_running= false; evex_main_thread_id= 0; @@ -607,7 +615,7 @@ finish: break; } VOID(pthread_mutex_unlock(&LOCK_workers_count)); - my_sleep(1000000);// 1s + my_sleep(1000000);// 1s } /* @@ -618,14 +626,14 @@ finish: VOID(pthread_mutex_lock(&LOCK_event_arrays)); for (i= 0; i < evex_queue_num_elements(EVEX_EQ_NAME); ++i) { - event_timed *et= evex_queue_element(&EVEX_EQ_NAME, i, event_timed*); + Event_timed *et= evex_queue_element(&EVEX_EQ_NAME, i, Event_timed*); et->free_sp(); delete et; } VOID(pthread_mutex_unlock(&LOCK_event_arrays)); - // ... then we can thrash the whole queue at once + /* ... then we can thrash the whole queue at once */ evex_queue_destroy(&EVEX_EQ_NAME); - + thd->proc_info = "Clearing"; DBUG_ASSERT(thd->net.buff != 0); net_end(&thd->net); // destructor will not free it, because we are weird @@ -653,7 +661,7 @@ err_no_thd: my_thread_end(); pthread_exit(0); #endif - DBUG_RETURN(0);// Can't return anything here + DBUG_RETURN(0); // Can't return anything here } @@ -663,14 +671,14 @@ err_no_thd: SYNOPSIS event_executor_worker() - arg - the event_timed object to be processed + arg The Event_timed object to be processed */ pthread_handler_t event_executor_worker(void *event_void) { THD *thd; /* needs to be first for thread_stack */ - event_timed *event = (event_timed *) event_void; + Event_timed *event = (Event_timed *) event_void; MEM_ROOT worker_mem_root; DBUG_ENTER("event_executor_worker"); @@ -680,12 +688,12 @@ event_executor_worker(void *event_void) #ifndef DBUG_FAULTY_THR my_thread_init(); - if (!(thd = new THD)) // note that contructor of THD uses DBUG_ ! + if (!(thd = new THD)) /* note that contructor of THD uses DBUG_ ! */ { sql_print_error("SCHEDULER: Cannot create a THD structure in an worker."); goto err_no_thd; } - thd->thread_stack = (char*)&thd; // remember where our stack is + thd->thread_stack = (char*)&thd; // remember where our stack is thd->mem_root= &worker_mem_root; pthread_detach_this_thread(); @@ -695,7 +703,7 @@ event_executor_worker(void *event_void) thd->init_for_queries(); - // make this thread visible it has no vio -> show processlist needs this flag + /* make this thread visible it has no vio -> show processlist needs this flag */ thd->system_thread= 1; VOID(pthread_mutex_lock(&LOCK_thread_count)); @@ -707,6 +715,7 @@ event_executor_worker(void *event_void) thd= current_thd; #endif + thd->enable_slow_log= TRUE; { int ret; sql_print_information("SCHEDULER: Executing event %s.%s of %s [EXPR:%d]", @@ -723,6 +732,8 @@ event_executor_worker(void *event_void) sql_print_information("SCHEDULER: COMPILE ERROR for event %s.%s of", event->dbname.str, event->name.str, event->definer.str); + else if (ret == EVEX_MICROSECOND_UNSUP) + sql_print_information("SCHEDULER: MICROSECOND is not supported"); } event->spawn_thread_finish(thd); @@ -743,7 +754,7 @@ err: DBUG_ASSERT(thd->net.buff != 0); net_end(&thd->net); // destructor will not free it, because we are weird THD_CHECK_SENTRY(thd); - + VOID(pthread_mutex_lock(&LOCK_thread_count)); THD_CHECK_SENTRY(thd); delete thd; @@ -766,7 +777,7 @@ err_no_thd: /* Loads all ENABLED events from mysql.event into the prioritized queue. Called during scheduler main thread initialization. Compiles - the events. Creates event_timed instances for every ENABLED event + the events. Creates Event_timed instances for every ENABLED event from mysql.event. SYNOPSIS @@ -774,9 +785,9 @@ err_no_thd: thd - Thread context. Used for memory allocation in some cases. RETURNS - 0 - OK - -1 - Error - + 0 OK + !0 Error + NOTES Reports the error to the console */ @@ -786,10 +797,9 @@ evex_load_events_from_db(THD *thd) { TABLE *table; READ_RECORD read_record_info; - MYSQL_LOCK *lock; int ret= -1; uint count= 0; - + DBUG_ENTER("evex_load_events_from_db"); if ((ret= evex_open_event_table(thd, TL_READ, &table))) @@ -803,8 +813,8 @@ evex_load_events_from_db(THD *thd) init_read_record(&read_record_info, thd, table ,NULL,1,0); while (!(read_record_info.read_record(&read_record_info))) { - event_timed *et; - if (!(et= new event_timed)) + Event_timed *et; + if (!(et= new Event_timed)) { DBUG_PRINT("evex_load_events_from_db", ("Out of memory")); ret= -1; @@ -824,18 +834,24 @@ evex_load_events_from_db(THD *thd) delete et; continue; } - + DBUG_PRINT("evex_load_events_from_db", ("Event %s loaded from row. Time to compile", et->name.str)); - if ((ret= et->compile(thd, &evex_mem_root))) - { + switch (ret= et->compile(thd, &evex_mem_root)) { + case EVEX_MICROSECOND_UNSUP: + sql_print_error("SCHEDULER: mysql.event is tampered. MICROSECOND is not " + "supported but found in mysql.event"); + goto end; + case EVEX_COMPILE_ERROR: sql_print_error("SCHEDULER: Error while compiling %s.%s. Aborting load.", et->dbname.str, et->name.str); goto end; + default: + break; } - - // let's find when to be executed + + /* let's find when to be executed */ if (et->compute_next_execution_time()) { sql_print_error("SCHEDULER: Error while computing execution time of %s.%s." @@ -856,11 +872,13 @@ evex_load_events_from_db(THD *thd) end: VOID(pthread_mutex_unlock(&LOCK_event_arrays)); end_read_record(&read_record_info); - - thd->version--; // Force close to free memory + + /* Force close to free memory */ + thd->version--; close_thread_tables(thd); - sql_print_information("SCHEDULER: Loaded %d event%s", count, (count == 1)?"":"s"); + if (!ret) + sql_print_information("SCHEDULER: Loaded %d event%s", count, (count == 1)?"":"s"); DBUG_PRINT("info", ("Status code %d. Loaded %d event(s)", ret, count)); DBUG_RETURN(ret); @@ -876,15 +894,15 @@ end: event_executor_worker() thd - Thread context (unused) car - the new value - + Returns - 0 - OK (always) + 0 OK (always) */ bool sys_var_event_executor::update(THD *thd, set_var *var) { - // here start the thread if not running. + /* here start the thread if not running. */ DBUG_ENTER("sys_var_event_executor::update"); VOID(pthread_mutex_lock(&LOCK_evex_running)); *value= var->save_result.ulong_value; @@ -916,32 +934,33 @@ static sql_print_xxx_func sql_print_xxx_handlers[3] = Prints the stack of infos, warnings, errors from thd to the console so it can be fetched by the logs-into-tables and checked later. - + Synopsis evex_print_warnings thd - thread used during the execution of the event et - the event itself - + Returns 0 - OK (always) */ bool -evex_print_warnings(THD *thd, event_timed *et) -{ +evex_print_warnings(THD *thd, Event_timed *et) +{ MYSQL_ERROR *err; DBUG_ENTER("evex_show_warnings"); char msg_buf[1024]; char prefix_buf[512]; String prefix(prefix_buf, sizeof(prefix_buf), system_charset_info); prefix.length(0); - + List_iterator_fast<MYSQL_ERROR> it(thd->warn_list); while ((err= it++)) { String err_msg(msg_buf, sizeof(msg_buf), system_charset_info); - err_msg.length(0);// set it to 0 or we start adding at the end + /* set it to 0 or we start adding at the end. That's the trick ;) */ + err_msg.length(0); if (!prefix.length()) { prefix.append("SCHEDULER: ["); @@ -955,7 +974,7 @@ evex_print_warnings(THD *thd, event_timed *et) append_identifier(thd,&prefix, et->name.str, et->name.length); prefix.append("] ", 2); } - + err_msg.append(prefix); err_msg.append(err->msg, strlen(err->msg), system_charset_info); err_msg.append("]"); diff --git a/sql/event_priv.h b/sql/event_priv.h index 4f575a96212..6b23136847e 100644 --- a/sql/event_priv.h +++ b/sql/event_priv.h @@ -44,7 +44,7 @@ evex_db_find_event_by_name(THD *thd, const LEX_STRING dbname, int event_timed_compare_q(void *vptr, byte* a, byte *b); -int db_drop_event(THD *thd, event_timed *et, bool drop_if_exists, +int db_drop_event(THD *thd, Event_timed *et, bool drop_if_exists, uint *rows_affected); diff --git a/sql/event_timed.cc b/sql/event_timed.cc index a1ec7f6b718..a8620197668 100644 --- a/sql/event_timed.cc +++ b/sql/event_timed.cc @@ -26,13 +26,13 @@ extern int yyparse(void *thd); Init all member variables SYNOPSIS - event_timed::init() + Event_timed::init() */ void -event_timed::init() +Event_timed::init() { - DBUG_ENTER("event_timed::init"); + DBUG_ENTER("Event_timed::init"); dbname.str= name.str= body.str= comment.str= 0; dbname.length= name.length= body.length= comment.length= 0; @@ -41,6 +41,7 @@ event_timed::init() set_zero_time(&ends, MYSQL_TIMESTAMP_DATETIME); set_zero_time(&execute_at, MYSQL_TIMESTAMP_DATETIME); set_zero_time(&last_executed, MYSQL_TIMESTAMP_DATETIME); + starts_null= ends_null= execute_at_null= TRUE; definer_user.str= definer_host.str= 0; definer_user.length= definer_host.length= 0; @@ -55,16 +56,15 @@ event_timed::init() Set a name of the event SYNOPSIS - event_timed::init_name() + Event_timed::init_name() thd THD spn the name extracted in the parser */ void -event_timed::init_name(THD *thd, sp_name *spn) +Event_timed::init_name(THD *thd, sp_name *spn) { - DBUG_ENTER("event_timed::init_name"); - uint n; /* Counter for nul trimming */ + DBUG_ENTER("Event_timed::init_name"); /* During parsing, we must use thd->mem_root */ MEM_ROOT *root= thd->mem_root; @@ -99,7 +99,7 @@ event_timed::init_name(THD *thd, sp_name *spn) Set body of the event - what should be executed. SYNOPSIS - event_timed::init_body() + Event_timed::init_body() thd THD NOTE @@ -108,14 +108,14 @@ event_timed::init_name(THD *thd, sp_name *spn) */ void -event_timed::init_body(THD *thd) +Event_timed::init_body(THD *thd) { - DBUG_ENTER("event_timed::init_body"); + DBUG_ENTER("Event_timed::init_body"); DBUG_PRINT("info", ("body=[%s] body_begin=0x%ld end=0x%ld", body_begin, body_begin, thd->lex->ptr)); body.length= thd->lex->ptr - body_begin; - // Trim nuls at the end + /* Trim nuls at the end */ while (body.length && body_begin[body.length-1] == '\0') body.length--; @@ -135,7 +135,7 @@ event_timed::init_body(THD *thd) Set time for execution for one time events. SYNOPSIS - event_timed::init_execute_at() + Event_timed::init_execute_at() expr when (datetime) RETURN VALUE @@ -146,23 +146,26 @@ event_timed::init_body(THD *thd) */ int -event_timed::init_execute_at(THD *thd, Item *expr) +Event_timed::init_execute_at(THD *thd, Item *expr) { my_bool not_used; TIME ltime; - my_time_t my_time_tmp; TIME time_tmp; - DBUG_ENTER("event_timed::init_execute_at"); + DBUG_ENTER("Event_timed::init_execute_at"); if (expr->fix_fields(thd, &expr)) DBUG_RETURN(EVEX_PARSE_ERROR); - - /* Let's check whether time is in the past */ - thd->variables.time_zone->gmt_sec_to_TIME(&time_tmp, + + /* no starts and/or ends in case of execute_at */ + DBUG_PRINT("info", ("starts_null && ends_null should be 1 is %d", + (starts_null && ends_null))); + DBUG_ASSERT(starts_null && ends_null); + + /* let's check whether time is in the past */ + thd->variables.time_zone->gmt_sec_to_TIME(&time_tmp, (my_time_t) thd->query_start()); - if ((not_used= expr->get_date(<ime, TIME_NO_ZERO_DATE))) DBUG_RETURN(ER_WRONG_VALUE); @@ -177,7 +180,7 @@ event_timed::init_execute_at(THD *thd, Item *expr) */ my_tz_UTC->gmt_sec_to_TIME(<ime, TIME_to_timestamp(thd,<ime, ¬_used)); - + execute_at_null= FALSE; execute_at= ltime; DBUG_RETURN(0); } @@ -187,7 +190,7 @@ event_timed::init_execute_at(THD *thd, Item *expr) Set time for execution for transient events. SYNOPSIS - event_timed::init_interval() + Event_timed::init_interval() expr how much? new_interval what is the interval @@ -195,16 +198,16 @@ event_timed::init_execute_at(THD *thd, Item *expr) 0 OK EVEX_PARSE_ERROR fix_fields failed EVEX_BAD_PARAMS Interval is not positive + EVEX_MICROSECOND_UNSUP Microseconds are not supported. */ int -event_timed::init_interval(THD *thd, Item *expr, interval_type new_interval) +Event_timed::init_interval(THD *thd, Item *expr, interval_type new_interval) { - longlong tmp; String value; INTERVAL interval; - DBUG_ENTER("event_timed::init_interval"); + DBUG_ENTER("Event_timed::init_interval"); if (expr->fix_fields(thd, &expr)) DBUG_RETURN(EVEX_PARSE_ERROR); @@ -245,15 +248,16 @@ event_timed::init_interval(THD *thd, Item *expr, interval_type new_interval) case INTERVAL_DAY_MINUTE: expression= (interval.day* 24 + interval.hour) * 60 + interval.minute; break; - case INTERVAL_HOUR_SECOND: // day is anyway 0 + case INTERVAL_HOUR_SECOND: /* day is anyway 0 */ case INTERVAL_DAY_SECOND: /* DAY_SECOND having problems because of leap seconds? */ expression= ((interval.day* 24 + interval.hour) * 60 + interval.minute)*60 + interval.second; break; - case INTERVAL_MINUTE_MICROSECOND: // day and hour are 0 - case INTERVAL_HOUR_MICROSECOND:// day is anyway 0 + case INTERVAL_MINUTE_MICROSECOND: /* day and hour are 0 */ + case INTERVAL_HOUR_MICROSECOND: /* day is anyway 0 */ case INTERVAL_DAY_MICROSECOND: + DBUG_RETURN(EVEX_MICROSECOND_UNSUP); expression= ((((interval.day*24) + interval.hour)*60+interval.minute)*60 + interval.second) * 1000000L + interval.second_part; break; @@ -264,10 +268,11 @@ event_timed::init_interval(THD *thd, Item *expr, interval_type new_interval) expression= interval.minute * 60 + interval.second; break; case INTERVAL_SECOND_MICROSECOND: + DBUG_RETURN(EVEX_MICROSECOND_UNSUP); expression= interval.second * 1000000L + interval.second_part; break; - default: - break; + case INTERVAL_MICROSECOND: + DBUG_RETURN(EVEX_MICROSECOND_UNSUP); } if (interval.neg || expression > EVEX_MAX_INTERVAL_VALUE) DBUG_RETURN(EVEX_BAD_PARAMS); @@ -281,7 +286,7 @@ event_timed::init_interval(THD *thd, Item *expr, interval_type new_interval) Set activation time. SYNOPSIS - event_timed::init_starts() + Event_timed::init_starts() expr how much? interval what is the interval @@ -299,12 +304,12 @@ event_timed::init_interval(THD *thd, Item *expr, interval_type new_interval) */ int -event_timed::init_starts(THD *thd, Item *new_starts) +Event_timed::init_starts(THD *thd, Item *new_starts) { my_bool not_used; TIME ltime, time_tmp; - DBUG_ENTER("event_timed::init_starts"); + DBUG_ENTER("Event_timed::init_starts"); if (new_starts->fix_fields(thd, &new_starts)) DBUG_RETURN(EVEX_PARSE_ERROR); @@ -329,6 +334,7 @@ event_timed::init_starts(THD *thd, Item *new_starts) my_tz_UTC->gmt_sec_to_TIME(<ime, TIME_to_timestamp(thd, <ime, ¬_used)); starts= ltime; + starts_null= FALSE; DBUG_RETURN(0); } @@ -337,7 +343,7 @@ event_timed::init_starts(THD *thd, Item *new_starts) Set deactivation time. SYNOPSIS - event_timed::init_ends() + Event_timed::init_ends() thd THD new_ends when? @@ -356,31 +362,44 @@ event_timed::init_starts(THD *thd, Item *new_starts) */ int -event_timed::init_ends(THD *thd, Item *new_ends) +Event_timed::init_ends(THD *thd, Item *new_ends) { - TIME ltime; - my_time_t my_time_tmp; + TIME ltime, ltime_now; my_bool not_used; - DBUG_ENTER("event_timed::init_ends"); + DBUG_ENTER("Event_timed::init_ends"); if (new_ends->fix_fields(thd, &new_ends)) DBUG_RETURN(EVEX_PARSE_ERROR); - /* The field was already fixed in init_ends */ + DBUG_PRINT("info", ("convert to TIME")); if ((not_used= new_ends->get_date(<ime, TIME_NO_ZERO_DATE))) DBUG_RETURN(EVEX_BAD_PARAMS); /* - This may result in a 1970-01-01 date if ltime is > 2037-xx-xx. - CONVERT_TZ has similar problem. + This may result in a 1970-01-01 date if ltime is > 2037-xx-xx ? + CONVERT_TZ has similar problem ? */ + DBUG_PRINT("info", ("get the UTC time")); my_tz_UTC->gmt_sec_to_TIME(<ime, TIME_to_timestamp(thd, <ime, ¬_used)); - if (starts.year && my_time_compare(&starts, <ime) != -1) + /* Check whether ends is after starts */ + DBUG_PRINT("info", ("ENDS after STARTS?")); + if (!starts_null && my_time_compare(&starts, <ime) != -1) + DBUG_RETURN(EVEX_BAD_PARAMS); + + /* + The parser forces starts to be provided but one day STARTS could be + set before NOW() and in this case the following check should be done. + Check whether ENDS is not in the past. + */ + DBUG_PRINT("info", ("ENDS after NOW?")); + my_tz_UTC->gmt_sec_to_TIME(<ime_now, thd->query_start()); + if (my_time_compare(<ime_now, <ime) == 1) DBUG_RETURN(EVEX_BAD_PARAMS); ends= ltime; + ends_null= FALSE; DBUG_RETURN(0); } @@ -389,18 +408,18 @@ event_timed::init_ends(THD *thd, Item *new_ends) Sets comment. SYNOPSIS - event_timed::init_comment() + Event_timed::init_comment() thd THD - used for memory allocation comment the string. */ void -event_timed::init_comment(THD *thd, LEX_STRING *set_comment) +Event_timed::init_comment(THD *thd, LEX_STRING *set_comment) { - DBUG_ENTER("event_timed::init_comment"); + DBUG_ENTER("Event_timed::init_comment"); comment.str= strmake_root(thd->mem_root, set_comment->str, - comment.length= set_comment->length); + comment.length= set_comment->length); DBUG_VOID_RETURN; } @@ -410,13 +429,13 @@ event_timed::init_comment(THD *thd, LEX_STRING *set_comment) Inits definer (definer_user and definer_host) during parsing. SYNOPSIS - event_timed::init_definer() + Event_timed::init_definer() */ int -event_timed::init_definer(THD *thd) +Event_timed::init_definer(THD *thd) { - DBUG_ENTER("event_timed::init_definer"); + DBUG_ENTER("Event_timed::init_definer"); DBUG_PRINT("info",("init definer_user thd->mem_root=0x%lx " "thd->sec_ctx->priv_user=0x%lx", thd->mem_root, @@ -451,7 +470,7 @@ event_timed::init_definer(THD *thd) Loads an event from a row from mysql.event SYNOPSIS - event_timed::load_from_row(MEM_ROOT *mem_root, TABLE *table) + Event_timed::load_from_row(MEM_ROOT *mem_root, TABLE *table) NOTES This method is silent on errors and should behave like that. Callers @@ -460,16 +479,14 @@ event_timed::init_definer(THD *thd) */ int -event_timed::load_from_row(MEM_ROOT *mem_root, TABLE *table) +Event_timed::load_from_row(MEM_ROOT *mem_root, TABLE *table) { - longlong created; - longlong modified; char *ptr; - event_timed *et; + Event_timed *et; uint len; bool res1, res2; - DBUG_ENTER("event_timed::load_from_row"); + DBUG_ENTER("Event_timed::load_from_row"); if (!table) goto error; @@ -511,35 +528,44 @@ event_timed::load_from_row(MEM_ROOT *mem_root, TABLE *table) et->definer_user.str= strmake_root(mem_root, et->definer.str, len); et->definer_user.length= len; - len= et->definer.length - len - 1; //1 is because of @ - et->definer_host.str= strmake_root(mem_root, ptr + 1, len);//1: because of @ + len= et->definer.length - len - 1; //1 is because of @ + et->definer_host.str= strmake_root(mem_root, ptr + 1, len);/* 1:because of @*/ et->definer_host.length= len; + + et->starts_null= table->field[EVEX_FIELD_STARTS]->is_null(); + res1= table->field[EVEX_FIELD_STARTS]->get_date(&et->starts,TIME_NO_ZERO_DATE); - res1= table->field[EVEX_FIELD_STARTS]-> - get_date(&et->starts, TIME_NO_ZERO_DATE); - - res2= table->field[EVEX_FIELD_ENDS]-> - get_date(&et->ends, TIME_NO_ZERO_DATE); - - et->expression= table->field[EVEX_FIELD_INTERVAL_EXPR]->val_int(); - + et->ends_null= table->field[EVEX_FIELD_ENDS]->is_null(); + res2= table->field[EVEX_FIELD_ENDS]->get_date(&et->ends, TIME_NO_ZERO_DATE); + + if (!table->field[EVEX_FIELD_INTERVAL_EXPR]->is_null()) + et->expression= table->field[EVEX_FIELD_INTERVAL_EXPR]->val_int(); + else + et->expression= 0; /* If res1 and res2 are true then both fields are empty. Hence if EVEX_FIELD_EXECUTE_AT is empty there is an error. */ - if (res1 && res2 && !et->expression && table->field[EVEX_FIELD_EXECUTE_AT]-> - get_date(&et->execute_at, TIME_NO_ZERO_DATE)) + et->execute_at_null= table->field[EVEX_FIELD_EXECUTE_AT]->is_null(); + DBUG_ASSERT(!(et->starts_null && et->ends_null && !et->expression && + et->execute_at_null)); + if (!et->expression && + table->field[EVEX_FIELD_EXECUTE_AT]->get_date(&et->execute_at, + TIME_NO_ZERO_DATE)) goto error; /* In DB the values start from 1 but enum interval_type starts from 0 */ - et->interval= (interval_type) + if (!table->field[EVEX_FIELD_TRANSIENT_INTERVAL]->is_null()) + et->interval= (interval_type) ((ulonglong) table->field[EVEX_FIELD_TRANSIENT_INTERVAL]->val_int() - 1); + else + et->interval= (interval_type) 0; - et->modified= table->field[EVEX_FIELD_CREATED]->val_int(); - et->created= table->field[EVEX_FIELD_MODIFIED]->val_int(); + et->created= table->field[EVEX_FIELD_CREATED]->val_int(); + et->modified= table->field[EVEX_FIELD_MODIFIED]->val_int(); /* ToDo Andrey : Ask PeterG & Serg what to do in this case. @@ -565,20 +591,20 @@ event_timed::load_from_row(MEM_ROOT *mem_root, TABLE *table) #endif last_executed_changed= false; - // ToDo : Andrey . Find a way not to allocate ptr on event_mem_root + /* ToDo : Andrey . Find a way not to allocate ptr on event_mem_root */ if ((ptr= get_field(mem_root, table->field[EVEX_FIELD_STATUS])) == NullS) goto error; DBUG_PRINT("load_from_row", ("Event [%s] is [%s]", et->name.str, ptr)); et->status= (ptr[0]=='E'? MYSQL_EVENT_ENABLED:MYSQL_EVENT_DISABLED); - // ToDo : Andrey . Find a way not to allocate ptr on event_mem_root + /* ToDo : Andrey . Find a way not to allocate ptr on event_mem_root */ if ((ptr= get_field(mem_root, table->field[EVEX_FIELD_ON_COMPLETION])) == NullS) goto error; et->on_completion= (ptr[0]=='D'? MYSQL_EVENT_ON_COMPLETION_DROP: - MYSQL_EVENT_ON_COMPLETION_PRESERVE); + MYSQL_EVENT_ON_COMPLETION_PRESERVE); et->comment.str= get_field(mem_root, table->field[EVEX_FIELD_COMMENT]); if (et->comment.str != NullS) @@ -667,7 +693,7 @@ bool get_next_time(TIME *next, TIME *start, int i_value, interval_type i_type) Computes next execution time. SYNOPSIS - event_timed::compute_next_execution_time() + Event_timed::compute_next_execution_time() NOTES The time is set in execute_at, if no more executions the latter is set to @@ -675,13 +701,13 @@ bool get_next_time(TIME *next, TIME *start, int i_value, interval_type i_type) */ bool -event_timed::compute_next_execution_time() +Event_timed::compute_next_execution_time() { TIME time_now; my_time_t now; int tmp; - DBUG_ENTER("event_timed::compute_next_execution_time"); + DBUG_ENTER("Event_timed::compute_next_execution_time"); if (status == MYSQL_EVENT_DISABLED) { @@ -695,14 +721,11 @@ event_timed::compute_next_execution_time() /* Let's check whether it was executed */ if (last_executed.year) { - DBUG_PRINT("compute_next_execution_time", - ("One-time event %s was already executed", name.str)); - if (on_completion == MYSQL_EVENT_ON_COMPLETION_DROP) - { - DBUG_PRINT("compute_next_execution_time", - ("One-time event will be dropped.")); - dropped= true; - } + DBUG_PRINT("info",("One-time event %s.%s of was already executed", + dbname.str, name.str, definer.str)); + dropped= (on_completion == MYSQL_EVENT_ON_COMPLETION_DROP); + DBUG_PRINT("info",("One-time event will be dropped=%d.", dropped)); + status= MYSQL_EVENT_DISABLED; status_changed= true; } @@ -728,11 +751,12 @@ event_timed::compute_next_execution_time() last_executed.second); #endif - /* If time_now is after ends don't execute anymore */ - if (ends.year && (tmp= my_time_compare(&ends, &time_now)) == -1) + /* if time_now is after ends don't execute anymore */ + if (!ends_null && (tmp= my_time_compare(&ends, &time_now)) == -1) { /* time_now is after ends. don't execute anymore */ set_zero_time(&execute_at, MYSQL_TIMESTAMP_DATETIME); + execute_at_null= TRUE; if (on_completion == MYSQL_EVENT_ON_COMPLETION_DROP) dropped= true; status= MYSQL_EVENT_DISABLED; @@ -746,7 +770,7 @@ event_timed::compute_next_execution_time() Let's check whether time_now is before starts. If so schedule for starts. */ - if (starts.year && (tmp= my_time_compare(&time_now, &starts)) < 1) + if (!starts_null && (tmp= my_time_compare(&time_now, &starts)) < 1) { if (tmp == 0 && my_time_compare(&starts, &last_executed) == 0) { @@ -762,11 +786,12 @@ event_timed::compute_next_execution_time() time_now before starts. Scheduling for starts */ execute_at= starts; + execute_at_null= FALSE; goto ret; } } - if (starts.year && ends.year) + if (!starts_null && !ends_null) { /* Both starts and m_ends are set and time_now is between them (incl.) @@ -775,7 +800,10 @@ event_timed::compute_next_execution_time() If not set then schedule for now. */ if (!last_executed.year) + { execute_at= time_now; + execute_at_null= FALSE; + } else { TIME next_exec; @@ -788,15 +816,19 @@ event_timed::compute_next_execution_time() { /* Next execution after ends. No more executions */ set_zero_time(&execute_at, MYSQL_TIMESTAMP_DATETIME); + execute_at_null= TRUE; if (on_completion == MYSQL_EVENT_ON_COMPLETION_DROP) dropped= true; } else + { execute_at= next_exec; + execute_at_null= FALSE; + } } goto ret; } - else if (!starts.year && !ends.year) + else if (starts_null && ends_null) { /* Both starts and m_ends are not set, so we schedule for the next @@ -812,11 +844,12 @@ event_timed::compute_next_execution_time() /* last_executed not set. Schedule the event for now */ execute_at= time_now; } + execute_at_null= FALSE; } else { - /* Either starts or m_ends is set */ - if (starts.year) + /* either starts or m_ends is set */ + if (!starts_null) { /* - starts is set. @@ -831,6 +864,7 @@ event_timed::compute_next_execution_time() } else execute_at= starts; + execute_at_null= FALSE; } else { @@ -853,11 +887,15 @@ event_timed::compute_next_execution_time() if (my_time_compare(&ends, &next_exec) == -1) { set_zero_time(&execute_at, MYSQL_TIMESTAMP_DATETIME); + execute_at_null= TRUE; if (on_completion == MYSQL_EVENT_ON_COMPLETION_DROP) dropped= true; } else + { execute_at= next_exec; + execute_at_null= FALSE; + } } } goto ret; @@ -875,19 +913,19 @@ err: time according to thd->query_start(), so the THD's clock. SYNOPSIS - event_timed::drop() + Event_timed::drop() thd thread context */ void -event_timed::mark_last_executed(THD *thd) +Event_timed::mark_last_executed(THD *thd) { TIME time_now; thd->end_time(); my_tz_UTC->gmt_sec_to_TIME(&time_now, (my_time_t) thd->query_start()); - last_executed= time_now; // was execute_at + last_executed= time_now; /* was execute_at */ #ifdef ANDREY_0 last_executed= execute_at; #endif @@ -899,7 +937,7 @@ event_timed::mark_last_executed(THD *thd) Drops the event SYNOPSIS - event_timed::drop() + Event_timed::drop() thd thread context RETURN VALUE @@ -912,11 +950,10 @@ event_timed::mark_last_executed(THD *thd) */ int -event_timed::drop(THD *thd) +Event_timed::drop(THD *thd) { - TABLE *table; uint tmp= 0; - DBUG_ENTER("event_timed::drop"); + DBUG_ENTER("Event_timed::drop"); DBUG_RETURN(db_drop_event(thd, this, false, &tmp)); } @@ -926,7 +963,7 @@ event_timed::drop(THD *thd) Saves status and last_executed_at to the disk if changed. SYNOPSIS - event_timed::update_fields() + Event_timed::update_fields() thd - thread context RETURN VALUE @@ -939,14 +976,13 @@ event_timed::drop(THD *thd) */ bool -event_timed::update_fields(THD *thd) +Event_timed::update_fields(THD *thd) { TABLE *table; Open_tables_state backup; int ret= 0; - bool opened; - DBUG_ENTER("event_timed::update_time_fields"); + DBUG_ENTER("Event_timed::update_time_fields"); DBUG_PRINT("enter", ("name: %*s", name.length, name.str)); @@ -980,7 +1016,7 @@ event_timed::update_fields(THD *thd) if (status_changed) { table->field[EVEX_FIELD_STATUS]->set_notnull(); - table->field[EVEX_FIELD_STATUS]->store((longlong)status); + table->field[EVEX_FIELD_STATUS]->store((longlong)status, true); status_changed= false; } @@ -1000,18 +1036,19 @@ extern LEX_STRING interval_type_to_name[]; Get SHOW CREATE EVENT as string SYNOPSIS - event_timed::get_create_event(THD *thd, String *buf) + Event_timed::get_create_event(THD *thd, String *buf) thd Thread buf String*, should be already allocated. CREATE EVENT goes inside. RETURN VALUE - 0 OK - 1 Error (for now if mysql.event has been tampered and MICROSECONDS - interval or derivative has been put there. + 0 OK + EVEX_MICROSECOND_UNSUP Error (for now if mysql.event has been + tampered and MICROSECONDS interval or + derivative has been put there. */ int -event_timed::get_create_event(THD *thd, String *buf) +Event_timed::get_create_event(THD *thd, String *buf) { int multipl= 0; char tmp_buff[128]; @@ -1023,7 +1060,7 @@ event_timed::get_create_event(THD *thd, String *buf) if (expression && event_reconstruct_interval_expression(&expr_buf, interval, expression)) - DBUG_RETURN(1); + DBUG_RETURN(EVEX_MICROSECOND_UNSUP); buf->append(STRING_WITH_LEN("CREATE EVENT ")); append_identifier(thd, buf, dbname.str, dbname.length); @@ -1041,7 +1078,7 @@ event_timed::get_create_event(THD *thd, String *buf) } else { - char dtime_buff[20*2+32];// +32 to make my_snprintf_{8bit|ucs2} happy + char dtime_buff[20*2+32];/* +32 to make my_snprintf_{8bit|ucs2} happy */ buf->append(STRING_WITH_LEN("AT '")); /* Pass the buffer and the second param tells fills the buffer and @@ -1089,14 +1126,14 @@ event_timed::get_create_event(THD *thd, String *buf) */ int -event_timed::execute(THD *thd, MEM_ROOT *mem_root) +Event_timed::execute(THD *thd, MEM_ROOT *mem_root) { Security_context *save_ctx; /* this one is local and not needed after exec */ Security_context security_ctx; int ret= 0; - DBUG_ENTER("event_timed::execute"); + DBUG_ENTER("Event_timed::execute"); DBUG_PRINT("info", (" EVEX EXECUTING event %s.%s [EXPR:%d]", dbname.str, name.str, (int) expression)); @@ -1119,12 +1156,21 @@ event_timed::execute(THD *thd, MEM_ROOT *mem_root) goto done; /* Now we are sure we have valid this->sphead so we can copy the context */ sphead->m_security_ctx= security_ctx; - thd->db= dbname.str; + /* + THD::~THD will clean this or if there is DROP DATABASE in the SP then + it will be free there. It should not point to our buffer which is allocated + on a mem_root. + */ + thd->db= my_strdup(dbname.str, MYF(0)); thd->db_length= dbname.length; if (!check_access(thd, EVENT_ACL,dbname.str, 0, 0, 0,is_schema_db(dbname.str))) { List<Item> empty_item_list; empty_item_list.empty(); + if (thd->enable_slow_log) + sphead->m_flags|= sp_head::LOG_SLOW_STATEMENTS; + sphead->m_flags|= sp_head::LOG_GENERAL_LOG; + ret= sphead->execute_procedure(thd, &empty_item_list); } else @@ -1136,7 +1182,6 @@ event_timed::execute(THD *thd, MEM_ROOT *mem_root) restore_security_context(thd, save_ctx); DBUG_PRINT("info", ("master_access=%d db_access=%d", thd->security_ctx->master_access, thd->security_ctx->db_access)); - thd->db= 0; VOID(pthread_mutex_lock(&this->LOCK_running)); running= false; @@ -1163,7 +1208,7 @@ done: /* Switches the security context Synopsis - event_timed::change_security_context() + Event_timed::change_security_context() thd - thread backup - where to store the old context @@ -1172,10 +1217,10 @@ done: 1 - Error (generates error too) */ bool -event_timed::change_security_context(THD *thd, Security_context *s_ctx, +Event_timed::change_security_context(THD *thd, Security_context *s_ctx, Security_context **backup) { - DBUG_ENTER("event_timed::change_security_context"); + DBUG_ENTER("Event_timed::change_security_context"); DBUG_PRINT("info",("%s@%s@%s",definer_user.str,definer_host.str, dbname.str)); #ifndef NO_EMBEDDED_ACCESS_CHECKS s_ctx->init(); @@ -1196,15 +1241,15 @@ event_timed::change_security_context(THD *thd, Security_context *s_ctx, /* Restores the security context Synopsis - event_timed::restore_security_context() + Event_timed::restore_security_context() thd - thread backup - switch to this context - */ +*/ void -event_timed::restore_security_context(THD *thd, Security_context *backup) +Event_timed::restore_security_context(THD *thd, Security_context *backup) { - DBUG_ENTER("event_timed::change_security_context"); + DBUG_ENTER("Event_timed::restore_security_context"); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (backup) thd->security_ctx= backup; @@ -1218,29 +1263,27 @@ event_timed::restore_security_context(THD *thd, Security_context *backup) sp_head object held by the event SYNOPSIS - event_timed::compile() + Event_timed::compile() thd thread context, used for memory allocation mostly mem_root if != NULL then this memory root is used for allocs instead of thd->mem_root RETURN VALUE - 0 success - EVEX_COMPILE_ERROR error during compilation + 0 success + EVEX_COMPILE_ERROR error during compilation + EVEX_MICROSECOND_UNSUP mysql.event was tampered */ int -event_timed::compile(THD *thd, MEM_ROOT *mem_root) +Event_timed::compile(THD *thd, MEM_ROOT *mem_root) { int ret= 0; MEM_ROOT *tmp_mem_root= 0; LEX *old_lex= thd->lex, lex; char *old_db; int old_db_length; - event_timed *ett; - sp_name *spn; char *old_query; uint old_query_len; - st_sp_chistics *p; ulong old_sql_mode= thd->variables.sql_mode; char create_buf[2048]; String show_create(create_buf, sizeof(create_buf), system_charset_info); @@ -1248,7 +1291,20 @@ event_timed::compile(THD *thd, MEM_ROOT *mem_root) *old_collation_connection, *old_character_set_results; + DBUG_ENTER("Event_timed::compile"); + show_create.length(0); + + switch (get_create_event(thd, &show_create)) { + case EVEX_MICROSECOND_UNSUP: + sql_print_error("Scheduler"); + DBUG_RETURN(EVEX_MICROSECOND_UNSUP); + case 0: + break; + default: + DBUG_ASSERT(0); + } + old_character_set_client= thd->variables.character_set_client; old_character_set_results= thd->variables.character_set_results; old_collation_connection= thd->variables.collation_connection; @@ -1260,7 +1316,6 @@ event_timed::compile(THD *thd, MEM_ROOT *mem_root) thd->update_charset(); - DBUG_ENTER("event_timed::compile"); DBUG_PRINT("info",("old_sql_mode=%d new_sql_mode=%d",old_sql_mode, sql_mode)); thd->variables.sql_mode= this->sql_mode; /* Change the memory root for the execution time */ @@ -1276,11 +1331,9 @@ event_timed::compile(THD *thd, MEM_ROOT *mem_root) thd->db= dbname.str; thd->db_length= dbname.length; - get_create_event(thd, &show_create); - thd->query= show_create.c_ptr(); thd->query_length= show_create.length(); - DBUG_PRINT("event_timed::compile", ("query:%s",thd->query)); + DBUG_PRINT("Event_timed::compile", ("query:%s",thd->query)); thd->lex= &lex; lex_start(thd, (uchar*)thd->query, thd->query_length); @@ -1309,10 +1362,7 @@ event_timed::compile(THD *thd, MEM_ROOT *mem_root) sphead= lex.et->sphead; sphead->m_db= dbname; - /* - Ccopy also chistics since they will vanish otherwise we get 0x0 pointer - TODO: Handle sql_mode!! - */ + sphead->set_definer(definer.str, definer.length); sphead->set_info(0, 0, &lex.sp_chistics, sql_mode); sphead->optimize(); @@ -1355,7 +1405,7 @@ done: */ my_bool -event_timed::can_spawn_now_n_lock(THD *thd) +Event_timed::can_spawn_now_n_lock(THD *thd) { my_bool ret= FALSE; VOID(pthread_mutex_lock(&this->LOCK_running)); @@ -1374,7 +1424,7 @@ extern pthread_attr_t connection_attrib; /* Checks whether is possible and forks a thread. Passes self as argument. - + Returns EVENT_EXEC_STARTED - OK EVENT_EXEC_ALREADY_EXEC - Thread not forked, already working @@ -1382,11 +1432,11 @@ extern pthread_attr_t connection_attrib; */ int -event_timed::spawn_now(void * (*thread_func)(void*)) +Event_timed::spawn_now(void * (*thread_func)(void*)) { int ret= EVENT_EXEC_STARTED; static uint exec_num= 0; - DBUG_ENTER("event_timed::spawn_now"); + DBUG_ENTER("Event_timed::spawn_now"); DBUG_PRINT("info", ("[%s.%s]", dbname.str, name.str)); VOID(pthread_mutex_lock(&this->LOCK_running)); @@ -1420,9 +1470,9 @@ event_timed::spawn_now(void * (*thread_func)(void*)) void -event_timed::spawn_thread_finish(THD *thd) +Event_timed::spawn_thread_finish(THD *thd) { - DBUG_ENTER("event_timed::spawn_thread_finish"); + DBUG_ENTER("Event_timed::spawn_thread_finish"); VOID(pthread_mutex_lock(&this->LOCK_running)); in_spawned_thread= false; if ((flags & EVENT_EXEC_NO_MORE) || status == MYSQL_EVENT_DISABLED) @@ -1445,12 +1495,10 @@ event_timed::spawn_thread_finish(THD *thd) Returns 0 - ok 1 - not locked by this thread - */ - int -event_timed::spawn_unlock(THD *thd) +Event_timed::spawn_unlock(THD *thd) { int ret= 0; VOID(pthread_mutex_lock(&this->LOCK_running)); @@ -1471,5 +1519,5 @@ event_timed::spawn_unlock(THD *thd) } } VOID(pthread_mutex_unlock(&this->LOCK_running)); - return ret; + return ret; } diff --git a/sql/field.cc b/sql/field.cc index 72e28cbda9c..65c0d1b9397 100644 --- a/sql/field.cc +++ b/sql/field.cc @@ -5266,7 +5266,7 @@ int Field_date::store(longlong nr, bool unsigned_val) } if (nr >= 19000000000000.0 && nr <= 99991231235959.0) - nr=floor(nr/1000000.0); // Timestamp to date + nr= (longlong) floor(nr/1000000.0); // Timestamp to date if (error) set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, @@ -8297,13 +8297,11 @@ void Field_bit_as_char::sql_type(String &res) const create_field::create_length_to_internal_length() DESCRIPTION - Convert create_field::length from number of characters to number of bytes, - save original value in chars_length. + Convert create_field::length from number of characters to number of bytes. */ void create_field::create_length_to_internal_length(void) { - chars_length= length; switch (sql_type) { case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: @@ -8355,7 +8353,7 @@ void create_field::init_for_tmp_table(enum_field_types sql_type_arg, { field_name= ""; sql_type= sql_type_arg; - length= length_arg;; + char_length= length= length_arg;; unireg_check= Field::NONE; interval= 0; charset= &my_charset_bin; @@ -8683,6 +8681,8 @@ bool create_field::init(THD *thd, char *fld_name, enum_field_types fld_type, case FIELD_TYPE_DECIMAL: DBUG_ASSERT(0); /* Was obsolete */ } + /* Remember the value of length */ + char_length= length; if (!(flags & BLOB_FLAG) && ((length > max_field_charlength && fld_type != FIELD_TYPE_SET && @@ -9023,6 +9023,7 @@ create_field::create_field(Field *old_field,Field *orig_field) else interval=0; def=0; + char_length= length; if (!(flags & (NO_DEFAULT_VALUE_FLAG | BLOB_FLAG)) && old_field->ptr && orig_field && diff --git a/sql/field.h b/sql/field.h index 15c54f65ef7..3fbdc0d0aa9 100644 --- a/sql/field.h +++ b/sql/field.h @@ -173,8 +173,9 @@ public: virtual int cmp(const char *,const char *)=0; virtual int cmp_binary(const char *a,const char *b, uint32 max_length=~0L) { return memcmp(a,b,pack_length()); } - int cmp_offset(uint row_offset) { return cmp(ptr,ptr+row_offset); } - int cmp_binary_offset(uint row_offset) + virtual int cmp_offset(uint row_offset) + { return cmp(ptr,ptr+row_offset); } + virtual int cmp_binary_offset(uint row_offset) { return cmp_binary(ptr, ptr+row_offset); }; virtual int key_cmp(const byte *a,const byte *b) { return cmp((char*) a,(char*) b); } @@ -1317,6 +1318,20 @@ public: }; +/* + Note: + To use Field_bit::cmp_binary() you need to copy the bits stored in + the beginning of the record (the NULL bytes) to each memory you + want to compare (where the arguments point). + + This is the reason: + - Field_bit::cmp_binary() is only implemented in the base class + (Field::cmp_binary()). + - Field::cmp_binary() currenly use pack_length() to calculate how + long the data is. + - pack_length() includes size of the bits stored in the NULL bytes + of the record. +*/ class Field_bit :public Field { public: uchar *bit_ptr; // position in record where 'uneven' bits store @@ -1342,6 +1357,8 @@ public: my_decimal *val_decimal(my_decimal *); int cmp(const char *a, const char *b) { return cmp_binary(a, b); } + int cmp_binary_offset(uint row_offset) + { return cmp_offset(row_offset); } int cmp_max(const char *a, const char *b, uint max_length); int key_cmp(const byte *a, const byte *b) { return cmp_binary((char *) a, (char *) b); } @@ -1410,9 +1427,10 @@ public: */ ulong length; /* - The value of 'length' before a call to create_length_to_internal_length + The value of `length' as set by parser: is the number of characters + for most of the types, or of bytes for BLOBs or numeric types. */ - uint32 chars_length; + uint32 char_length; uint decimals, flags, pack_length, key_length; Field::utype unireg_check; TYPELIB *interval; // Which interval to use diff --git a/sql/field_conv.cc b/sql/field_conv.cc index d46a3aa8be3..0c385efd10b 100644 --- a/sql/field_conv.cc +++ b/sql/field_conv.cc @@ -378,6 +378,16 @@ static void do_cut_string_complex(Copy_field *copy) +static void do_expand_binary(Copy_field *copy) +{ + CHARSET_INFO *cs= copy->from_field->charset(); + memcpy(copy->to_ptr,copy->from_ptr,copy->from_length); + cs->cset->fill(cs, copy->to_ptr+copy->from_length, + copy->to_length-copy->from_length, '\0'); +} + + + static void do_expand_string(Copy_field *copy) { CHARSET_INFO *cs= copy->from_field->charset(); @@ -582,7 +592,13 @@ void (*Copy_field::get_copy_func(Field *to,Field *from))(Copy_field*) return (from->charset()->mbmaxlen == 1 ? do_cut_string : do_cut_string_complex); else if (to_length > from_length) - return do_expand_string; + { + if ((to->flags & BINARY_FLAG) != 0) + return do_expand_binary; + else + return do_expand_string; + } + } else if (to->real_type() != from->real_type() || to_length != from_length || diff --git a/sql/ha_archive.cc b/sql/ha_archive.cc index 8ed16949edd..a8bc0822a85 100644 --- a/sql/ha_archive.cc +++ b/sql/ha_archive.cc @@ -177,9 +177,10 @@ handlerton archive_hton = { NULL, /* Partition flags */ NULL, /* Alter table flags */ NULL, /* Alter interface */ + NULL, /* fill_files_table */ HTON_NO_FLAGS, - NULL, /* binlog_func */ - NULL /* binlog_log_query */ + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; static handler *archive_create_handler(TABLE_SHARE *table) diff --git a/sql/ha_berkeley.cc b/sql/ha_berkeley.cc index 6866b50fd19..910a703fdeb 100644 --- a/sql/ha_berkeley.cc +++ b/sql/ha_berkeley.cc @@ -153,7 +153,9 @@ handlerton berkeley_hton = { NULL, /* Alter table flags */ NULL, /* Alter Tablespace */ NULL, /* Fill Files Table */ - HTON_CLOSE_CURSORS_AT_COMMIT | HTON_FLUSH_AFTER_RENAME + HTON_CLOSE_CURSORS_AT_COMMIT | HTON_FLUSH_AFTER_RENAME, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; handler *berkeley_create_handler(TABLE_SHARE *table) diff --git a/sql/ha_blackhole.cc b/sql/ha_blackhole.cc index 42c785e2003..7d28344a0a4 100644 --- a/sql/ha_blackhole.cc +++ b/sql/ha_blackhole.cc @@ -61,7 +61,9 @@ handlerton blackhole_hton= { NULL, /* Alter table flags */ NULL, /* Alter Tablespace */ NULL, /* Fill FILES table */ - HTON_CAN_RECREATE + HTON_CAN_RECREATE, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; diff --git a/sql/ha_federated.cc b/sql/ha_federated.cc index f7e0c1242fe..976f3739386 100644 --- a/sql/ha_federated.cc +++ b/sql/ha_federated.cc @@ -398,7 +398,9 @@ handlerton federated_hton= { NULL, /* Alter table flags */ NULL, /* Alter Tablespace */ NULL, /* Fill FILES table */ - HTON_ALTER_NOT_SUPPORTED + HTON_ALTER_NOT_SUPPORTED, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; diff --git a/sql/ha_heap.cc b/sql/ha_heap.cc index d4790cf7d01..96f760a7a44 100644 --- a/sql/ha_heap.cc +++ b/sql/ha_heap.cc @@ -58,7 +58,9 @@ handlerton heap_hton= { NULL, /* Alter table flags */ NULL, /* Alter Tablespace */ NULL, /* Fill Files Table */ - HTON_CAN_RECREATE + HTON_CAN_RECREATE, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; static handler *heap_create_handler(TABLE_SHARE *table) diff --git a/sql/ha_innodb.cc b/sql/ha_innodb.cc index 0002ab0123f..153c456c06c 100644 --- a/sql/ha_innodb.cc +++ b/sql/ha_innodb.cc @@ -237,8 +237,11 @@ handlerton innobase_hton = { innobase_show_status, /* Show status */ NULL, /* Partition flags */ NULL, /* Alter table flags */ + NULL, /* alter_tablespace */ NULL, /* Fill FILES table */ - HTON_NO_FLAGS + HTON_NO_FLAGS, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; diff --git a/sql/ha_myisam.cc b/sql/ha_myisam.cc index 4b84d3efa7f..fba36450d81 100644 --- a/sql/ha_myisam.cc +++ b/sql/ha_myisam.cc @@ -90,7 +90,9 @@ handlerton myisam_hton= { NULL, /* Alter table flags */ NULL, /* Alter Tablespace */ NULL, /* Fill Files Table */ - HTON_CAN_RECREATE + HTON_CAN_RECREATE, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; diff --git a/sql/ha_myisammrg.cc b/sql/ha_myisammrg.cc index 32b67cd23e5..ec015c5e320 100644 --- a/sql/ha_myisammrg.cc +++ b/sql/ha_myisammrg.cc @@ -68,7 +68,9 @@ handlerton myisammrg_hton= { NULL, /* Alter table flags */ NULL, /* Alter Tablespace */ NULL, /* Fill Files Table */ - HTON_CAN_RECREATE + HTON_CAN_RECREATE, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; static handler *myisammrg_create_handler(TABLE_SHARE *table) @@ -306,7 +308,27 @@ void ha_myisammrg::info(uint flag) table->s->keys_in_use.set_prefix(table->s->keys); table->s->db_options_in_use= info.options; mean_rec_length= info.reclength; - block_size=0; + + /* + The handler::block_size is used all over the code in index scan cost + calculations. It is used to get number of disk seeks required to + retrieve a number of index tuples. + If the merge table has N underlying tables, then (assuming underlying + tables have equal size, the only "simple" approach we can use) + retrieving X index records from a merge table will require N times more + disk seeks compared to doing the same on a MyISAM table with equal + number of records. + In the edge case (file_tables > myisam_block_size) we'll get + block_size==0, and index calculation code will act as if we need one + disk seek to retrieve one index tuple. + + TODO: In 5.2 index scan cost calculation will be factored out into a + virtual function in class handler and we'll be able to remove this hack. + */ + block_size= 0; + if (file->tables) + block_size= myisam_block_size / file->tables; + update_time=0; #if SIZEOF_OFF_T > 4 ref_length=6; // Should be big enough diff --git a/sql/ha_ndbcluster.cc b/sql/ha_ndbcluster.cc index 642199890e6..ff8a1221052 100644 --- a/sql/ha_ndbcluster.cc +++ b/sql/ha_ndbcluster.cc @@ -519,6 +519,7 @@ void ha_ndbcluster::invalidate_dictionary_cache(bool global) { NDBINDEX *index = (NDBINDEX *) m_index[i].index; NDBINDEX *unique_index = (NDBINDEX *) m_index[i].unique_index; + if (!index && !unique_index) continue; NDB_INDEX_TYPE idx_type= m_index[i].type; switch (idx_type) { @@ -991,8 +992,8 @@ bool ha_ndbcluster::uses_blob_value() -2 Meta data has changed; Re-read data and try again */ -static int cmp_frm(const NDBTAB *ndbtab, const void *pack_data, - uint pack_length) +int cmp_frm(const NDBTAB *ndbtab, const void *pack_data, + uint pack_length) { DBUG_ENTER("cmp_frm"); /* @@ -1076,7 +1077,7 @@ int ha_ndbcluster::get_metadata(const char *path) m_table= (void *)tab; m_table_info= NULL; // Set in external lock - DBUG_RETURN(open_indexes(ndb, table)); + DBUG_RETURN(open_indexes(ndb, table, FALSE)); } static int fix_unique_index_attr_order(NDB_INDEX_DATA &data, @@ -1249,7 +1250,7 @@ int ha_ndbcluster::add_index_handle(THD *thd, NDBDICT *dict, KEY *key_info, /* Associate index handles for each index of a table */ -int ha_ndbcluster::open_indexes(Ndb *ndb, TABLE *tab) +int ha_ndbcluster::open_indexes(Ndb *ndb, TABLE *tab, bool ignore_error) { uint i; int error= 0; @@ -1263,7 +1264,10 @@ int ha_ndbcluster::open_indexes(Ndb *ndb, TABLE *tab) for (i= 0; i < tab->s->keys; i++, key_info++, key_name++) { if ((error= add_index_handle(thd, dict, key_info, *key_name, i))) - break; + if (ignore_error) + m_index[i].index= m_index[i].unique_index= NULL; + else + break; } DBUG_RETURN(error); @@ -1680,15 +1684,16 @@ int ha_ndbcluster::pk_read(const byte *key, uint key_len, byte *buf, /* Read one complementing record from NDB using primary key from old_data + or hidden key */ -int ha_ndbcluster::complemented_pk_read(const byte *old_data, byte *new_data, - uint32 old_part_id) +int ha_ndbcluster::complemented_read(const byte *old_data, byte *new_data, + uint32 old_part_id) { uint no_fields= table_share->fields, i; NdbTransaction *trans= m_active_trans; NdbOperation *op; - DBUG_ENTER("complemented_pk_read"); + DBUG_ENTER("complemented_read"); m_write_op= FALSE; if (ha_get_all_bit_in_read_set()) @@ -1702,9 +1707,17 @@ int ha_ndbcluster::complemented_pk_read(const byte *old_data, byte *new_data, if (!(op= trans->getNdbOperation((const NDBTAB *) m_table)) || op->readTuple(lm) != 0) ERR_RETURN(trans->getNdbError()); - int res; - if ((res= set_primary_key_from_record(op, old_data))) - ERR_RETURN(trans->getNdbError()); + if (table_share->primary_key != MAX_KEY) + { + if (set_primary_key_from_record(op, old_data)) + ERR_RETURN(trans->getNdbError()); + } + else + { + // This table has no primary key, use "hidden" primary key + if (set_hidden_key(op, table->s->fields, m_ref)) + ERR_RETURN(op->getNdbError()); + } if (m_use_partition_function) op->setPartitionId(old_part_id); @@ -2214,7 +2227,7 @@ int ha_ndbcluster::full_table_scan(byte *buf) if (m_use_partition_function) { part_spec.start_part= 0; - part_spec.end_part= get_tot_partitions(m_part_info) - 1; + part_spec.end_part= m_part_info->get_tot_partitions() - 1; prune_partition_set(table, &part_spec); DBUG_PRINT("info", ("part_spec.start_part = %u, part_spec.end_part = %u", part_spec.start_part, part_spec.end_part)); @@ -2497,19 +2510,23 @@ int ha_ndbcluster::update_row(const byte *old_data, byte *new_data) DBUG_RETURN(error); } - /* Check for update of primary key for special handling */ - if ((table_share->primary_key != MAX_KEY) && - (key_cmp(table_share->primary_key, old_data, new_data)) || + /* + * Check for update of primary key or partition change + * for special handling + */ + if (((table_share->primary_key != MAX_KEY) && + key_cmp(table_share->primary_key, old_data, new_data)) || (old_part_id != new_part_id)) { int read_res, insert_res, delete_res, undo_res; - DBUG_PRINT("info", ("primary key update, doing pk read+delete+insert")); + DBUG_PRINT("info", ("primary key update or partition change, " + "doing read+delete+insert")); // Get all old fields, since we optimize away fields not in query - read_res= complemented_pk_read(old_data, new_data, old_part_id); + read_res= complemented_read(old_data, new_data, old_part_id); if (read_res) { - DBUG_PRINT("info", ("pk read failed")); + DBUG_PRINT("info", ("read failed")); DBUG_RETURN(read_res); } // Delete old row @@ -3377,8 +3394,13 @@ int ha_ndbcluster::extra(enum ha_extra_function operation) DBUG_PRINT("info", ("HA_EXTRA_RESET")); DBUG_PRINT("info", ("Clearing condition stack")); cond_clear(); + /* + * Regular partition pruning will set the bitmap appropriately. + * Some queries like ALTER TABLE doesn't use partition pruning and + * thus the 'used_partitions' bitmap needs to be initialized + */ if (m_part_info) - bitmap_clear_all(&m_part_info->used_partitions); + bitmap_set_all(&m_part_info->used_partitions); break; case HA_EXTRA_IGNORE_DUP_KEY: /* Dup keys don't rollback everything*/ DBUG_PRINT("info", ("HA_EXTRA_IGNORE_DUP_KEY")); @@ -3739,7 +3761,7 @@ int ha_ndbcluster::external_lock(THD *thd, int lock_type) { m_table= (void *)tab; m_table_version = tab->getObjectVersion(); - if (!(my_errno= open_indexes(ndb, table))) + if (!(my_errno= open_indexes(ndb, table, FALSE))) DBUG_RETURN(my_errno); } m_table_info= tab_info; @@ -4706,13 +4728,14 @@ int ha_ndbcluster::final_drop_index(TABLE *table_arg) int ha_ndbcluster::rename_table(const char *from, const char *to) { NDBDICT *dict; + char old_dbname[FN_HEADLEN]; char new_tabname[FN_HEADLEN]; const NDBTAB *orig_tab; int result; DBUG_ENTER("ha_ndbcluster::rename_table"); DBUG_PRINT("info", ("Renaming %s to %s", from, to)); - set_dbname(from); + set_dbname(from, old_dbname); set_tabname(from); set_tabname(to, new_tabname); @@ -4720,6 +4743,7 @@ int ha_ndbcluster::rename_table(const char *from, const char *to) DBUG_RETURN(my_errno= HA_ERR_NO_CONNECTION); Ndb *ndb= get_ndb(); + ndb->setDatabaseName(old_dbname); dict= ndb->getDictionary(); if (!(orig_tab= dict->getTable(m_tabname))) ERR_RETURN(dict->getNdbError()); @@ -4811,7 +4835,8 @@ int ha_ndbcluster::rename_table(const char *from, const char *to) current_thd->query, current_thd->query_length, m_dbname, new_tabname, 0, 0, - SOT_RENAME_TABLE); + SOT_RENAME_TABLE, + old_dbname, m_tabname); } if (share) free_share(&share); @@ -5191,7 +5216,7 @@ void ha_ndbcluster::set_part_info(partition_info *part_info) m_part_info= part_info; if (!(m_part_info->part_type == HASH_PARTITION && m_part_info->list_of_part_fields && - !is_sub_partitioned(m_part_info))) + !m_part_info->is_sub_partitioned())) m_use_partition_function= TRUE; } @@ -5984,8 +6009,11 @@ void ha_ndbcluster::print_error(int error, myf errflag) DBUG_PRINT("enter", ("error = %d", error)); if (error == HA_ERR_NO_PARTITION_FOUND) + { + char buf[100]; my_error(ER_NO_PARTITION_FOR_GIVEN_VALUE, MYF(0), - (int)m_part_info->part_expr->val_int()); + llstr(m_part_info->part_expr->val_int(), buf)); + } else handler::print_error(error, errflag); DBUG_VOID_RETURN; @@ -6696,6 +6724,7 @@ NDB_SHARE *ndbcluster_get_share(NDB_SHARE *share) return share; } + /* Get a share object for key @@ -6710,17 +6739,19 @@ NDB_SHARE *ndbcluster_get_share(NDB_SHARE *share) have_lock == TRUE, pthread_mutex_lock(&ndbcluster_mutex) already taken */ + NDB_SHARE *ndbcluster_get_share(const char *key, TABLE *table, bool create_if_not_exists, bool have_lock) { - DBUG_ENTER("get_share"); - DBUG_PRINT("info", ("get_share: key %s", key)); THD *thd= current_thd; NDB_SHARE *share; + uint length= (uint) strlen(key); + DBUG_ENTER("ndbcluster_get_share"); + DBUG_PRINT("enter", ("key: '%s'", key)); + if (!have_lock) pthread_mutex_lock(&ndbcluster_mutex); - uint length= (uint) strlen(key); if (!(share= (NDB_SHARE*) hash_search(&ndbcluster_open_tables, (byte*) key, length))) @@ -6780,10 +6811,10 @@ NDB_SHARE *ndbcluster_get_share(const char *key, TABLE *table, dbug_print_open_tables(); - DBUG_PRINT("get_share", + DBUG_PRINT("info", ("0x%lx key: %s key_length: %d key: %s", share, share->key, share->key_length, key)); - DBUG_PRINT("get_share", + DBUG_PRINT("info", ("db.tablename: %s.%s use_count: %d commit_count: %d", share->db, share->table_name, share->use_count, share->commit_count)); @@ -6792,8 +6823,10 @@ NDB_SHARE *ndbcluster_get_share(const char *key, TABLE *table, DBUG_RETURN(share); } + void ndbcluster_real_free_share(NDB_SHARE **share) { + DBUG_ENTER("ndbcluster_real_free_share"); DBUG_PRINT("real_free_share", ("0x%lx key: %s key_length: %d", (*share), (*share)->key, (*share)->key_length)); @@ -6831,6 +6864,7 @@ void ndbcluster_real_free_share(NDB_SHARE **share) *share= 0; dbug_print_open_tables(); + DBUG_VOID_RETURN; } /* @@ -7418,7 +7452,7 @@ pthread_handler_t ndb_util_thread_func(void *arg __attribute__((unused))) ndb_util_thread= pthread_self(); thd->thread_stack= (char*)&thd; /* remember where our stack is */ - if (thd->store_globals() && (ndb->init() != -1)) + if (thd->store_globals() || (ndb->init() != 0)) { thd->cleanup(); delete thd; @@ -9304,7 +9338,7 @@ uint ha_ndbcluster::set_up_partition_info(partition_info *part_info, { uint ng; part_elem= part_it++; - if (!is_sub_partitioned(part_info)) + if (!part_info->is_sub_partitioned()) { ng= part_elem->nodegroup_id; if (first && ng == UNDEF_NODEGROUP) diff --git a/sql/ha_ndbcluster.h b/sql/ha_ndbcluster.h index 1eb8ac1ea70..7498d2bb624 100644 --- a/sql/ha_ndbcluster.h +++ b/sql/ha_ndbcluster.h @@ -691,6 +691,10 @@ static void set_tabname(const char *pathname, char *tabname); private: friend int ndbcluster_drop_database_impl(const char *path); + friend int ndb_handle_schema_change(THD *thd, + Ndb *ndb, NdbEventOperation *pOp, + NDB_SHARE *share); + int alter_table_name(const char *to); static int delete_table(ha_ndbcluster *h, Ndb *ndb, const char *path, @@ -708,7 +712,7 @@ private: int create_indexes(Ndb *ndb, TABLE *tab); void clear_index(int i); void clear_indexes(); - int open_indexes(Ndb *ndb, TABLE *tab); + int open_indexes(Ndb *ndb, TABLE *tab, bool ignore_error); void renumber_indexes(Ndb *ndb, TABLE *tab); int drop_indexes(Ndb *ndb, TABLE *tab); int add_index_handle(THD *thd, NdbDictionary::Dictionary *dict, @@ -727,8 +731,8 @@ private: char* get_tablespace_name(THD *thd); int set_range_data(void *tab, partition_info* part_info); int set_list_data(void *tab, partition_info* part_info); - int complemented_pk_read(const byte *old_data, byte *new_data, - uint32 old_part_id); + int complemented_read(const byte *old_data, byte *new_data, + uint32 old_part_id); int pk_read(const byte *key, uint key_len, byte *buf, uint32 part_id); int ordered_index_scan(const key_range *start_key, const key_range *end_key, diff --git a/sql/ha_ndbcluster_binlog.cc b/sql/ha_ndbcluster_binlog.cc index 28756c54c7f..f88c118b46e 100644 --- a/sql/ha_ndbcluster_binlog.cc +++ b/sql/ha_ndbcluster_binlog.cc @@ -184,8 +184,8 @@ static void dbug_print_table(const char *info, TABLE *table) Run a query through mysql_parse Used to: - - purging the cluster_replication.binlog_index - - creating the cluster_replication.apply_status table + - purging the binlog_index + - creating the apply_status table */ static void run_query(THD *thd, char *buf, char *end, my_bool print_error, my_bool disable_binlog) @@ -230,6 +230,70 @@ static void run_query(THD *thd, char *buf, char *end, } } +int +ndbcluster_binlog_open_table(THD *thd, NDB_SHARE *share, + TABLE_SHARE *table_share, TABLE *table) +{ + int error; + MEM_ROOT *mem_root= &share->mem_root; + DBUG_ENTER("ndbcluster_binlog_open_table"); + + init_tmp_table_share(table_share, share->db, 0, share->table_name, + share->key); + if ((error= open_table_def(thd, table_share, 0))) + { + sql_print_error("Unable to get table share for %s, error=%d", + share->key, error); + DBUG_PRINT("error", ("open_table_def failed %d", error)); + free_table_share(table_share); + my_free((gptr) table_share, MYF(0)); + my_free((gptr) table, MYF(0)); + DBUG_RETURN(error); + } + if ((error= open_table_from_share(thd, table_share, "", 0, + (uint) READ_ALL, 0, table, FALSE))) + { + sql_print_error("Unable to open table for %s, error=%d(%d)", + share->key, error, my_errno); + DBUG_PRINT("error", ("open_table_from_share failed %d", error)); + free_table_share(table_share); + my_free((gptr) table_share, MYF(0)); + my_free((gptr) table, MYF(0)); + DBUG_RETURN(error); + } + assign_new_table_id(table_share); + if (!table->record[1] || table->record[1] == table->record[0]) + { + table->record[1]= alloc_root(&table->mem_root, + table->s->rec_buff_length); + } + table->in_use= injector_thd; + + table->s->db.str= share->db; + table->s->db.length= strlen(share->db); + table->s->table_name.str= share->table_name; + table->s->table_name.length= strlen(share->table_name); + + share->table_share= table_share; + share->table= table; +#ifndef DBUG_OFF + dbug_print_table("table", table); +#endif + /* + ! do not touch the contents of the table + it may be in use by the injector thread + */ + share->ndb_value[0]= (NdbValue*) + alloc_root(mem_root, sizeof(NdbValue) * + (table->s->fields + 2 /*extra for hidden key and part key*/)); + share->ndb_value[1]= (NdbValue*) + alloc_root(mem_root, sizeof(NdbValue) * + (table->s->fields + 2 /*extra for hidden key and part key*/)); + + DBUG_RETURN(0); +} + + /* Initialize the binlog part of the NDB_SHARE */ @@ -238,6 +302,7 @@ void ndbcluster_binlog_init_share(NDB_SHARE *share, TABLE *_table) THD *thd= current_thd; MEM_ROOT *mem_root= &share->mem_root; int do_event_op= ndb_binlog_running; + DBUG_ENTER("ndbcluster_binlog_init_share"); share->op= 0; share->table= 0; @@ -276,74 +341,23 @@ void ndbcluster_binlog_init_share(NDB_SHARE *share, TABLE *_table) { share->flags|= NSF_NO_BINLOG; } - return; + DBUG_VOID_RETURN; } while (1) { + int error; TABLE_SHARE *table_share= (TABLE_SHARE *) my_malloc(sizeof(*table_share), MYF(MY_WME)); TABLE *table= (TABLE*) my_malloc(sizeof(*table), MYF(MY_WME)); - int error; - - init_tmp_table_share(table_share, share->db, 0, share->table_name, - share->key); - if ((error= open_table_def(thd, table_share, 0))) - { - sql_print_error("Unable to get table share for %s, error=%d", - share->key, error); - DBUG_PRINT("error", ("open_table_def failed %d", error)); - my_free((gptr) table_share, MYF(0)); - table_share= 0; - my_free((gptr) table, MYF(0)); - table= 0; + if ((error= ndbcluster_binlog_open_table(thd, share, table_share, table))) break; - } - if ((error= open_table_from_share(thd, table_share, "", 0, - (uint) READ_ALL, 0, table, FALSE))) - { - sql_print_error("Unable to open table for %s, error=%d(%d)", - share->key, error, my_errno); - DBUG_PRINT("error", ("open_table_from_share failed %d", error)); - my_free((gptr) table_share, MYF(0)); - table_share= 0; - my_free((gptr) table, MYF(0)); - table= 0; - break; - } - assign_new_table_id(table); - if (!table->record[1] || table->record[1] == table->record[0]) - { - table->record[1]= alloc_root(&table->mem_root, - table->s->rec_buff_length); - } - table->in_use= injector_thd; - - table->s->db.str= share->db; - table->s->db.length= strlen(share->db); - table->s->table_name.str= share->table_name; - table->s->table_name.length= strlen(share->table_name); - - share->table_share= table_share; - share->table= table; -#ifndef DBUG_OFF - dbug_print_table("table", table); -#endif - /* - ! do not touch the contents of the table - it may be in use by the injector thread - */ - share->ndb_value[0]= (NdbValue*) - alloc_root(mem_root, sizeof(NdbValue) * table->s->fields - + 1 /*extra for hidden key*/); - share->ndb_value[1]= (NdbValue*) - alloc_root(mem_root, sizeof(NdbValue) * table->s->fields - +1 /*extra for hidden key*/); if (table->s->primary_key == MAX_KEY) share->flags|= NSF_HIDDEN_PK; if (table->s->blob_fields != 0) share->flags|= NSF_BLOB_FLAG; break; } + DBUG_VOID_RETURN; } /***************************************************************** @@ -592,7 +606,7 @@ void ndbcluster_binlog_init_handlerton() /* - check the availability af the cluster_replication.apply_status share + check the availability af the apply_status share - return share, but do not increase refcount - return 0 if there is no share */ @@ -610,7 +624,7 @@ static NDB_SHARE *ndbcluster_check_apply_status_share() } /* - check the availability af the cluster_replication.schema share + check the availability af the schema share - return share, but do not increase refcount - return 0 if there is no share */ @@ -628,7 +642,7 @@ static NDB_SHARE *ndbcluster_check_schema_share() } /* - Create the cluster_replication.apply_status table + Create the apply_status table */ static int ndbcluster_create_apply_status_table(THD *thd) { @@ -677,7 +691,7 @@ static int ndbcluster_create_apply_status_table(THD *thd) /* - Create the cluster_replication.schema table + Create the schema table */ static int ndbcluster_create_schema_table(THD *thd) { @@ -871,7 +885,8 @@ int ndbcluster_log_schema_op(THD *thd, NDB_SHARE *share, const char *db, const char *table_name, uint32 ndb_table_id, uint32 ndb_table_version, - enum SCHEMA_OP_TYPE type) + enum SCHEMA_OP_TYPE type, + const char *old_db, const char *old_table_name) { DBUG_ENTER("ndbcluster_log_schema_op"); Thd_ndb *thd_ndb= get_thd_ndb(thd); @@ -905,10 +920,19 @@ int ndbcluster_log_schema_op(THD *thd, NDB_SHARE *share, query= tmp_buf2; query_length= (uint) (strxmov(tmp_buf2, "drop table `", table_name, "`", NullS) - tmp_buf2); - // fall through - case SOT_CREATE_TABLE: - // fall through + if (!share) + get_a_share= 1; + break; case SOT_RENAME_TABLE: + /* redo the rename table query as is may contain several tables */ + query= tmp_buf2; + query_length= (uint) (strxmov(tmp_buf2, "rename table `", + old_db, ".", old_table_name, "` to `", + db, ".", table_name, "`", NullS) - tmp_buf2); + if (!share) + get_a_share= 1; + break; + case SOT_CREATE_TABLE: // fall through case SOT_ALTER_TABLE: if (!share) @@ -969,8 +993,8 @@ int ndbcluster_log_schema_op(THD *thd, NDB_SHARE *share, } Ndb *ndb= thd_ndb->ndb; - char old_db[FN_REFLEN]; - strcpy(old_db, ndb->getDatabaseName()); + char save_db[FN_REFLEN]; + strcpy(save_db, ndb->getDatabaseName()); char tmp_buf[SCHEMA_QUERY_SIZE]; NDBDICT *dict= ndb->getDictionary(); @@ -1077,7 +1101,7 @@ end: if (trans) ndb->closeTransaction(trans); - ndb->setDatabaseName(old_db); + ndb->setDatabaseName(save_db); /* Wait for other mysqld's to acknowledge the table operation @@ -1155,8 +1179,8 @@ ndbcluster_update_slock(THD *thd, const NdbError *ndb_error= 0; uint32 node_id= g_ndb_cluster_connection->node_id(); Ndb *ndb= check_ndb_in_thd(thd); - char old_db[128]; - strcpy(old_db, ndb->getDatabaseName()); + char save_db[FN_HEADLEN]; + strcpy(save_db, ndb->getDatabaseName()); char tmp_buf[SCHEMA_QUERY_SIZE]; NDBDICT *dict= ndb->getDictionary(); @@ -1278,31 +1302,98 @@ end: db, table_name); if (trans) ndb->closeTransaction(trans); - ndb->setDatabaseName(old_db); + ndb->setDatabaseName(save_db); DBUG_RETURN(0); } /* Handle _non_ data events from the storage nodes */ -static int +int ndb_handle_schema_change(THD *thd, Ndb *ndb, NdbEventOperation *pOp, NDB_SHARE *share) { + DBUG_ENTER("ndb_handle_schema_change"); int remote_drop_table= 0, do_close_cached_tables= 0; + const char *dbname= share->table->s->db.str; + const char *tabname= share->table->s->table_name.str; + bool online_alter_table= (pOp->getEventType() == NDBEVENT::TE_ALTER && + pOp->tableFrmChanged()); if (pOp->getEventType() != NDBEVENT::TE_CLUSTER_FAILURE && - pOp->getReqNodeId() != g_ndb_cluster_connection->node_id()) + (uint) pOp->getReqNodeId() != g_ndb_cluster_connection->node_id()) { + TABLE_SHARE *table_share= share->table->s; + TABLE* table= share->table; + + /* + Invalidate table and all it's indexes + */ ndb->setDatabaseName(share->table->s->db.str); - ha_ndbcluster::invalidate_dictionary_cache(share->table->s, - ndb, - share->table->s->db.str, - share->table->s->table_name.str, - TRUE); + Thd_ndb *thd_ndb= get_thd_ndb(thd); + DBUG_ASSERT(thd_ndb != NULL); + Ndb* old_ndb= thd_ndb->ndb; + thd_ndb->ndb= ndb; + ha_ndbcluster table_handler(table_share); + table_handler.set_dbname(share->key); + table_handler.set_tabname(share->key); + table_handler.open_indexes(ndb, table, TRUE); + table_handler.invalidate_dictionary_cache(TRUE); + thd_ndb->ndb= old_ndb; + + if (online_alter_table) + { + char key[FN_REFLEN]; + const void *data= 0, *pack_data= 0; + uint length, pack_length; + int error; + NDBDICT *dict= ndb->getDictionary(); + const NDBTAB *altered_table= pOp->getTable(); + + DBUG_PRINT("info", ("Detected frm change of table %s.%s", + dbname, tabname)); + build_table_filename(key, FN_LEN-1, dbname, tabname, NullS); + /* + If the frm of the altered table is different than the one on + disk then overwrite it with the new table definition + */ + if (readfrm(key, &data, &length) == 0 && + packfrm(data, length, &pack_data, &pack_length) == 0 && + cmp_frm(altered_table, pack_data, pack_length)) + { + DBUG_DUMP("frm", (char*)altered_table->getFrmData(), + altered_table->getFrmLength()); + pthread_mutex_lock(&LOCK_open); + const NDBTAB *old= dict->getTable(tabname); + if (!old && + old->getObjectVersion() != altered_table->getObjectVersion()) + dict->putTable(altered_table); + + if ((error= unpackfrm(&data, &length, altered_table->getFrmData())) || + (error= writefrm(key, data, length))) + { + sql_print_information("NDB: Failed write frm for %s.%s, error %d", + dbname, tabname, error); + } + close_cached_tables((THD*) 0, 0, (TABLE_LIST*) 0, TRUE); + if ((error= ndbcluster_binlog_open_table(thd, share, + table_share, table))) + sql_print_information("NDB: Failed to re-open table %s.%s", + dbname, tabname); + pthread_mutex_unlock(&LOCK_open); + } + } remote_drop_table= 1; } + // If only frm was changed continue replicating + if (online_alter_table) + { + /* Signal ha_ndbcluster::alter_table that drop is done */ + (void) pthread_cond_signal(&injector_cond); + DBUG_RETURN(0); + } + (void) pthread_mutex_lock(&share->mutex); DBUG_ASSERT(share->op == pOp || share->op_old == pOp); if (share->op_old == pOp) @@ -1481,11 +1572,16 @@ ndb_binlog_thread_handle_schema_event(THD *thd, Ndb *ndb, // skip break; case NDBEVENT::TE_ALTER: - /* do the rename of the table in the share */ - share->table->s->db.str= share->db; - share->table->s->db.length= strlen(share->db); - share->table->s->table_name.str= share->table_name; - share->table->s->table_name.length= strlen(share->table_name); + if (pOp->tableNameChanged()) + { + DBUG_PRINT("info", ("Detected name change of table %s.%s", + share->db, share->table_name)); + /* do the rename of the table in the share */ + share->table->s->db.str= share->db; + share->table->s->db.length= strlen(share->db); + share->table->s->table_name.str= share->table_name; + share->table->s->table_name.length= strlen(share->table_name); + } ndb_handle_schema_change(thd, ndb, pOp, share); break; case NDBEVENT::TE_CLUSTER_FAILURE: @@ -1569,13 +1665,13 @@ ndb_binlog_thread_handle_schema_event(THD *thd, Ndb *ndb, /********************************************************************* Internal helper functions for handeling of the cluster replication tables - - cluster_replication.binlog_index - - cluster_replication.apply_status + - binlog_index + - apply_status *********************************************************************/ /* struct to hold the data to be inserted into the - cluster_replication.binlog_index table + binlog_index table */ struct Binlog_index_row { ulonglong gci; @@ -1588,7 +1684,7 @@ struct Binlog_index_row { }; /* - Open the cluster_replication.binlog_index table + Open the binlog_index table */ static int open_binlog_index(THD *thd, TABLE_LIST *tables, TABLE **binlog_index) @@ -1619,7 +1715,7 @@ static int open_binlog_index(THD *thd, TABLE_LIST *tables, } /* - Insert one row in the cluster_replication.binlog_index + Insert one row in the binlog_index declared friend in handler.h to be able to call write_row directly so that this insert is not replicated @@ -1641,7 +1737,8 @@ int ndb_add_binlog_index(THD *thd, void *_row) { if (need_reopen) { - close_tables_for_reopen(thd, &binlog_tables); + TABLE_LIST *p_binlog_tables= &binlog_tables; + close_tables_for_reopen(thd, &p_binlog_tables); binlog_index= 0; continue; } @@ -1766,6 +1863,7 @@ int ndbcluster_create_binlog_setup(Ndb *ndb, const char *key, /* Handle any trailing share */ NDB_SHARE *share= (NDB_SHARE*) hash_search(&ndbcluster_open_tables, (byte*) key, key_len); + if (share && share_may_exist) { if (share->flags & NSF_NO_BINLOG || @@ -2091,7 +2189,6 @@ ndbcluster_create_event_ops(NDB_SHARE *share, const NDBTAB *ndbtab, op= ndb->createEventOperation(event_name); // reset to catch errors ndb->setDatabaseName(""); - ndb->setDatabaseSchemaName(""); } if (!op) { @@ -2372,17 +2469,22 @@ ndb_binlog_thread_handle_non_data_event(Ndb *ndb, NdbEventOperation *pOp, share->key, share, pOp, share->op, share->op_old)); break; case NDBEVENT::TE_ALTER: - /* ToDo: remove printout */ - if (ndb_extra_logging) - sql_print_information("NDB Binlog: rename table %s%s/%s -> %s.", - share_prefix, share->table->s->db.str, - share->table->s->table_name.str, - share->key); - /* do the rename of the table in the share */ - share->table->s->db.str= share->db; - share->table->s->db.length= strlen(share->db); - share->table->s->table_name.str= share->table_name; - share->table->s->table_name.length= strlen(share->table_name); + if (pOp->tableNameChanged()) + { + DBUG_PRINT("info", ("Detected name change of table %s.%s", + share->db, share->table_name)); + /* ToDo: remove printout */ + if (ndb_extra_logging) + sql_print_information("NDB Binlog: rename table %s%s/%s -> %s.", + share_prefix, share->table->s->db.str, + share->table->s->table_name.str, + share->key); + /* do the rename of the table in the share */ + share->table->s->db.str= share->db; + share->table->s->db.length= strlen(share->db); + share->table->s->table_name.str= share->table_name; + share->table->s->table_name.length= strlen(share->table_name); + } goto drop_alter_common; case NDBEVENT::TE_DROP: if (apply_status_share == share) @@ -2659,8 +2761,8 @@ pthread_handler_t ndb_binlog_thread_func(void *arg) goto err; } - // empty database and schema - if (!(ndb= new Ndb(g_ndb_cluster_connection, "", "")) || + // empty database + if (!(ndb= new Ndb(g_ndb_cluster_connection, "")) || ndb->init()) { sql_print_error("NDB Binlog: Getting Ndb object failed"); @@ -2682,7 +2784,7 @@ pthread_handler_t ndb_binlog_thread_func(void *arg) ndb_binlog_thread_running= 1; if (opt_bin_log) { - if (binlog_row_based) + if (global_system_variables.binlog_format == BINLOG_FORMAT_ROW) { ndb_binlog_running= TRUE; } @@ -2924,7 +3026,6 @@ pthread_handler_t ndb_binlog_thread_func(void *arg) ndb_binlog_thread_handle_non_data_event(ndb, pOp, row); // reset to catch errors ndb->setDatabaseName(""); - ndb->setDatabaseSchemaName(""); } pOp= ndb->nextEvent(); diff --git a/sql/ha_ndbcluster_binlog.h b/sql/ha_ndbcluster_binlog.h index d222a7d848b..91ef53edd6b 100644 --- a/sql/ha_ndbcluster_binlog.h +++ b/sql/ha_ndbcluster_binlog.h @@ -95,7 +95,9 @@ int ndbcluster_log_schema_op(THD *thd, NDB_SHARE *share, const char *db, const char *table_name, uint32 ndb_table_id, uint32 ndb_table_version, - enum SCHEMA_OP_TYPE type); + enum SCHEMA_OP_TYPE type, + const char *old_db= 0, + const char *old_table_name= 0); int ndbcluster_handle_drop_table(Ndb *ndb, const char *event_name, NDB_SHARE *share); void ndb_rep_event_name(String *event_name, @@ -123,6 +125,8 @@ ndbcluster_show_status_binlog(THD* thd, stat_print_fn *stat_print, prototypes for ndb handler utility function also needed by the ndb binlog code */ +int cmp_frm(const NDBTAB *ndbtab, const void *pack_data, + uint pack_length); int ndbcluster_find_all_files(THD *thd); #endif /* HAVE_NDB_BINLOG */ diff --git a/sql/ha_ndbcluster_tables.h b/sql/ha_ndbcluster_tables.h index d726fd63e1d..12124cd8820 100644 --- a/sql/ha_ndbcluster_tables.h +++ b/sql/ha_ndbcluster_tables.h @@ -15,7 +15,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -#define NDB_REP_DB "cluster_replication" +#define NDB_REP_DB "cluster" #define NDB_REP_TABLE "binlog_index" #define NDB_APPLY_TABLE "apply_status" #define NDB_SCHEMA_TABLE "schema" diff --git a/sql/ha_partition.cc b/sql/ha_partition.cc index 5d4d1570044..e7a324481db 100644 --- a/sql/ha_partition.cc +++ b/sql/ha_partition.cc @@ -102,7 +102,9 @@ handlerton partition_hton = { alter_table_flags, /* Partition flags */ NULL, /* Alter Tablespace */ NULL, /* Fill FILES table */ - HTON_NOT_USER_SELECTABLE | HTON_HIDDEN + HTON_NOT_USER_SELECTABLE | HTON_HIDDEN, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; /* @@ -186,7 +188,7 @@ ha_partition::ha_partition(TABLE_SHARE *share) ha_partition::ha_partition(partition_info *part_info) :handler(&partition_hton, NULL), m_part_info(part_info), m_create_handler(TRUE), - m_is_sub_partitioned(is_sub_partitioned(m_part_info)) + m_is_sub_partitioned(m_part_info->is_sub_partitioned()) { DBUG_ENTER("ha_partition::ha_partition(part_info)"); @@ -331,7 +333,7 @@ int ha_partition::ha_initialise() if (m_create_handler) { - m_tot_parts= get_tot_partitions(m_part_info); + m_tot_parts= m_part_info->get_tot_partitions(); DBUG_ASSERT(m_tot_parts > 0); if (new_handlers_from_part_info()) DBUG_RETURN(1); @@ -1290,7 +1292,7 @@ int ha_partition::change_partitions(HA_CREATE_INFO *create_info, DBUG_ENTER("ha_partition::change_partitions"); m_reorged_parts= 0; - if (!is_sub_partitioned(m_part_info)) + if (!m_part_info->is_sub_partitioned()) no_subparts= 1; /* @@ -1453,7 +1455,7 @@ int ha_partition::change_partitions(HA_CREATE_INFO *create_info, if (part_elem->part_state == PART_CHANGED || (part_elem->part_state == PART_TO_BE_ADDED && temp_partitions)) name_variant= TEMP_PART_NAME; - if (is_sub_partitioned(m_part_info)) + if (m_part_info->is_sub_partitioned()) { List_iterator<partition_element> sub_it(part_elem->subpartitions); uint j= 0, part; @@ -2609,7 +2611,7 @@ void ha_partition::unlock_row() ADDITIONAL INFO: Most handlers set timestamp when calling write row if any such fields - exists. Since we are calling an underlying handler we assume the´ + exists. Since we are calling an underlying handler we assume the´ underlying handler will assume this responsibility. Underlying handlers will also call update_auto_increment to calculate diff --git a/sql/ha_partition.h b/sql/ha_partition.h index 35435844064..40306ba7da8 100644 --- a/sql/ha_partition.h +++ b/sql/ha_partition.h @@ -135,7 +135,7 @@ public: virtual void set_part_info(partition_info *part_info) { m_part_info= part_info; - m_is_sub_partitioned= is_sub_partitioned(part_info); + m_is_sub_partitioned= part_info->is_sub_partitioned(); } /* ------------------------------------------------------------------------- diff --git a/sql/handler.cc b/sql/handler.cc index 68ca3855158..3c79a1af8bd 100644 --- a/sql/handler.cc +++ b/sql/handler.cc @@ -64,7 +64,11 @@ const handlerton default_hton = NULL, NULL, NULL, create_default, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - HTON_NO_FLAGS + NULL, /* alter_tablespace */ + NULL, /* fill_files_table */ + HTON_NO_FLAGS, /* flags */ + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; static SHOW_COMP_OPTION have_yes= SHOW_OPTION_YES; @@ -3147,7 +3151,7 @@ namespace { bool check_table_binlog_row_based(THD *thd, TABLE *table) { return - binlog_row_based && + thd->current_stmt_binlog_row_based && thd && (thd->options & OPTION_BIN_LOG) && (table->s->tmp_table == NO_TMP_TABLE) && binlog_filter->db_ok(table->s->db.str); diff --git a/sql/handler.h b/sql/handler.h index fa4450544e9..d71841fe6b0 100644 --- a/sql/handler.h +++ b/sql/handler.h @@ -98,13 +98,6 @@ #define HA_ANY_INDEX_MAY_BE_UNIQUE (1 << 30) #define HA_NO_COPY_ON_ALTER (1 << 31) -/* Flags for partition handlers */ -#define HA_CAN_PARTITION (1 << 0) /* Partition support */ -#define HA_CAN_UPDATE_PARTITION_KEY (1 << 1) -#define HA_CAN_PARTITION_UNIQUE (1 << 2) -#define HA_USE_AUTO_PARTITION (1 << 3) - - /* bits in index_flags(index_number) for what you can do with index */ #define HA_READ_NEXT 1 /* TODO really use this flag */ #define HA_READ_PREV 2 /* supports ::index_prev */ @@ -307,6 +300,7 @@ struct xid_t { long bqual_length; char data[XIDDATASIZE]; // not \0-terminated ! + xid_t() {} /* Remove gcc warning */ bool eq(struct xid_t *xid) { return eq(xid->gtrid_length, xid->bqual_length, xid->data); } bool eq(long g, long b, const char *d) @@ -578,10 +572,9 @@ typedef struct struct st_table_list *tables, class Item *cond); uint32 flags; /* global handler flags */ - /* - Handlerton functions are not set in the different storage - engines static initialization. They are initialized at handler init. - Thus, leave them last in the struct. + /* + Those handlerton functions below are properly initialized at handler + init. */ int (*binlog_func)(THD *thd, enum_binlog_func fn, void *arg); void (*binlog_log_query)(THD *thd, enum_binlog_command binlog_command, @@ -622,33 +615,6 @@ enum enum_tx_isolation { ISO_READ_UNCOMMITTED, ISO_READ_COMMITTED, enum ndb_distribution { ND_KEYHASH= 0, ND_LINHASH= 1 }; -typedef struct { - uint32 start_part; - uint32 end_part; -} part_id_range; - - -/** - * An enum and a struct to handle partitioning and subpartitioning. - */ -enum partition_type { - NOT_A_PARTITION= 0, - RANGE_PARTITION, - HASH_PARTITION, - LIST_PARTITION -}; - -enum partition_state { - PART_NORMAL= 0, - PART_IS_DROPPED= 1, - PART_TO_BE_DROPPED= 2, - PART_TO_BE_ADDED= 3, - PART_TO_BE_REORGED= 4, - PART_REORGED_DROPPED= 5, - PART_CHANGED= 6, - PART_IS_CHANGED= 7, - PART_IS_ADDED= 8 -}; typedef struct { ulonglong data_file_length; @@ -666,400 +632,12 @@ typedef struct { #define UNDEF_NODEGROUP 65535 class Item; -class partition_element :public Sql_alloc { -public: - List<partition_element> subpartitions; - List<longlong> list_val_list; - ulonglong part_max_rows; - ulonglong part_min_rows; - char *partition_name; - char *tablespace_name; - longlong range_value; - char* part_comment; - char* data_file_name; - char* index_file_name; - handlerton *engine_type; - enum partition_state part_state; - uint16 nodegroup_id; - - partition_element() - : part_max_rows(0), part_min_rows(0), partition_name(NULL), - tablespace_name(NULL), range_value(0), part_comment(NULL), - data_file_name(NULL), index_file_name(NULL), - engine_type(NULL),part_state(PART_NORMAL), - nodegroup_id(UNDEF_NODEGROUP) - { - subpartitions.empty(); - list_val_list.empty(); - } - ~partition_element() {} -}; - -typedef struct { - longlong list_value; - uint32 partition_id; -} LIST_PART_ENTRY; - class partition_info; -typedef int (*get_part_id_func)(partition_info *part_info, - uint32 *part_id, - longlong *func_value); -typedef uint32 (*get_subpart_id_func)(partition_info *part_info); - - struct st_partition_iter; #define NOT_A_PARTITION_ID ((uint32)-1) -/* - A "Get next" function for partition iterator. - SYNOPSIS - partition_iter_func() - part_iter Partition iterator, you call only "iter.get_next(&iter)" - - RETURN - NOT_A_PARTITION_ID if there are no more partitions. - [sub]partition_id of the next partition -*/ -typedef uint32 (*partition_iter_func)(st_partition_iter* part_iter); - - -/* - Partition set iterator. Used to enumerate a set of [sub]partitions - obtained in partition interval analysis (see get_partitions_in_range_iter). - - For the user, the only meaningful field is get_next, which may be used as - follows: - part_iterator.get_next(&part_iterator); - - Initialization is done by any of the following calls: - - get_partitions_in_range_iter-type function call - - init_single_partition_iterator() - - init_all_partitions_iterator() - Cleanup is not needed. -*/ - -typedef struct st_partition_iter -{ - partition_iter_func get_next; - - struct st_part_num_range - { - uint32 start; - uint32 end; - }; - - struct st_field_value_range - { - longlong start; - longlong end; - }; - - union - { - struct st_part_num_range part_nums; - struct st_field_value_range field_vals; - }; - partition_info *part_info; -} PARTITION_ITERATOR; - - -/* - Get an iterator for set of partitions that match given field-space interval - - SYNOPSIS - get_partitions_in_range_iter() - part_info Partitioning info - is_subpart - min_val Left edge, field value in opt_range_key format. - max_val Right edge, field value in opt_range_key format. - flags Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE, - NO_MAX_RANGE. - part_iter Iterator structure to be initialized - - DESCRIPTION - Functions with this signature are used to perform "Partitioning Interval - Analysis". This analysis is applicable for any type of [sub]partitioning - by some function of a single fieldX. The idea is as follows: - Given an interval "const1 <=? fieldX <=? const2", find a set of partitions - that may contain records with value of fieldX within the given interval. - - The min_val, max_val and flags parameters specify the interval. - The set of partitions is returned by initializing an iterator in *part_iter - - NOTES - There are currently two functions of this type: - - get_part_iter_for_interval_via_walking - - get_part_iter_for_interval_via_mapping - - RETURN - 0 - No matching partitions, iterator not initialized - 1 - Some partitions would match, iterator intialized for traversing them - -1 - All partitions would match, iterator not initialized -*/ - -typedef int (*get_partitions_in_range_iter)(partition_info *part_info, - bool is_subpart, - char *min_val, char *max_val, - uint flags, - PARTITION_ITERATOR *part_iter); - - -class partition_info : public Sql_alloc -{ -public: - /* - * Here comes a set of definitions needed for partitioned table handlers. - */ - List<partition_element> partitions; - List<partition_element> temp_partitions; - - List<char> part_field_list; - List<char> subpart_field_list; - - /* - If there is no subpartitioning, use only this func to get partition ids. - If there is subpartitioning, use the this func to get partition id when - you have both partition and subpartition fields. - */ - get_part_id_func get_partition_id; - - /* Get partition id when we don't have subpartition fields */ - get_part_id_func get_part_partition_id; - - /* - Get subpartition id when we have don't have partition fields by we do - have subpartition ids. - Mikael said that for given constant tuple - {subpart_field1, ..., subpart_fieldN} the subpartition id will be the - same in all subpartitions - */ - get_subpart_id_func get_subpartition_id; - - /* NULL-terminated array of fields used in partitioned expression */ - Field **part_field_array; - /* NULL-terminated array of fields used in subpartitioned expression */ - Field **subpart_field_array; - - /* - Array of all fields used in partition and subpartition expression, - without duplicates, NULL-terminated. - */ - Field **full_part_field_array; - - Item *part_expr; - Item *subpart_expr; - - Item *item_free_list; - - /* - A bitmap of partitions used by the current query. - Usage pattern: - * The handler->extra(HA_EXTRA_RESET) call at query start/end sets all - partitions to be unused. - * Before index/rnd_init(), partition pruning code sets the bits for used - partitions. - */ - MY_BITMAP used_partitions; - - union { - longlong *range_int_array; - LIST_PART_ENTRY *list_array; - }; - - /******************************************** - * INTERVAL ANALYSIS - ********************************************/ - /* - Partitioning interval analysis function for partitioning, or NULL if - interval analysis is not supported for this kind of partitioning. - */ - get_partitions_in_range_iter get_part_iter_for_interval; - /* - Partitioning interval analysis function for subpartitioning, or NULL if - interval analysis is not supported for this kind of partitioning. - */ - get_partitions_in_range_iter get_subpart_iter_for_interval; - - /* - Valid iff - get_part_iter_for_interval=get_part_iter_for_interval_via_walking: - controls how we'll process "field < C" and "field > C" intervals. - If the partitioning function F is strictly increasing, then for any x, y - "x < y" => "F(x) < F(y)" (*), i.e. when we get interval "field < C" - we can perform partition pruning on the equivalent "F(field) < F(C)". - - If the partitioning function not strictly increasing (it is simply - increasing), then instead of (*) we get "x < y" => "F(x) <= F(y)" - i.e. for interval "field < C" we can perform partition pruning for - "F(field) <= F(C)". - */ - bool range_analysis_include_bounds; - /******************************************** - * INTERVAL ANALYSIS ENDS - ********************************************/ - - char* part_info_string; - - char *part_func_string; - char *subpart_func_string; - - uchar *part_state; - - partition_element *curr_part_elem; - partition_element *current_partition; - /* - These key_map's are used for Partitioning to enable quick decisions - on whether we can derive more information about which partition to - scan just by looking at what index is used. - */ - key_map all_fields_in_PF, all_fields_in_PPF, all_fields_in_SPF; - key_map some_fields_in_PF; - - handlerton *default_engine_type; - Item_result part_result_type; - partition_type part_type; - partition_type subpart_type; - - uint part_info_len; - uint part_state_len; - uint part_func_len; - uint subpart_func_len; - - uint no_parts; - uint no_subparts; - uint count_curr_subparts; - - uint part_error_code; - - uint no_list_values; - - uint no_part_fields; - uint no_subpart_fields; - uint no_full_part_fields; - - /* - This variable is used to calculate the partition id when using - LINEAR KEY/HASH. This functionality is kept in the MySQL Server - but mainly of use to handlers supporting partitioning. - */ - uint16 linear_hash_mask; - - bool use_default_partitions; - bool use_default_no_partitions; - bool use_default_subpartitions; - bool use_default_no_subpartitions; - bool default_partitions_setup; - bool defined_max_value; - bool list_of_part_fields; - bool list_of_subpart_fields; - bool linear_hash_ind; - bool fixed; - bool from_openfrm; - - partition_info() - : get_partition_id(NULL), get_part_partition_id(NULL), - get_subpartition_id(NULL), - part_field_array(NULL), subpart_field_array(NULL), - full_part_field_array(NULL), - part_expr(NULL), subpart_expr(NULL), item_free_list(NULL), - list_array(NULL), - part_info_string(NULL), - part_func_string(NULL), subpart_func_string(NULL), - part_state(NULL), - curr_part_elem(NULL), current_partition(NULL), - default_engine_type(NULL), - part_result_type(INT_RESULT), - part_type(NOT_A_PARTITION), subpart_type(NOT_A_PARTITION), - part_info_len(0), part_state_len(0), - part_func_len(0), subpart_func_len(0), - no_parts(0), no_subparts(0), - count_curr_subparts(0), part_error_code(0), - no_list_values(0), no_part_fields(0), no_subpart_fields(0), - no_full_part_fields(0), linear_hash_mask(0), - use_default_partitions(TRUE), - use_default_no_partitions(TRUE), - use_default_subpartitions(TRUE), - use_default_no_subpartitions(TRUE), - default_partitions_setup(FALSE), - defined_max_value(FALSE), - list_of_part_fields(FALSE), list_of_subpart_fields(FALSE), - linear_hash_ind(FALSE), - fixed(FALSE), - from_openfrm(FALSE) - { - all_fields_in_PF.clear_all(); - all_fields_in_PPF.clear_all(); - all_fields_in_SPF.clear_all(); - some_fields_in_PF.clear_all(); - partitions.empty(); - temp_partitions.empty(); - part_field_list.empty(); - subpart_field_list.empty(); - } - ~partition_info() {} -}; - - -#ifdef WITH_PARTITION_STORAGE_ENGINE -uint32 get_next_partition_id_range(struct st_partition_iter* part_iter); - -/* Initialize the iterator to return a single partition with given part_id */ - -static inline void init_single_partition_iterator(uint32 part_id, - PARTITION_ITERATOR *part_iter) -{ - part_iter->part_nums.start= part_id; - part_iter->part_nums.end= part_id+1; - part_iter->get_next= get_next_partition_id_range; -} - -/* Initialize the iterator to enumerate all partitions */ -static inline -void init_all_partitions_iterator(partition_info *part_info, - PARTITION_ITERATOR *part_iter) -{ - part_iter->part_nums.start= 0; - part_iter->part_nums.end= part_info->no_parts; - part_iter->get_next= get_next_partition_id_range; -} - -/* - Answers the question if subpartitioning is used for a certain table - SYNOPSIS - is_sub_partitioned() - part_info A reference to the partition_info struct - RETURN VALUE - Returns true if subpartitioning used and false otherwise - DESCRIPTION - A routine to check for subpartitioning for improved readability of code -*/ -static inline -bool is_sub_partitioned(partition_info *part_info) -{ return (part_info->subpart_type == NOT_A_PARTITION ? FALSE : TRUE); } - - -/* - Returns the total number of partitions on the leaf level. - SYNOPSIS - get_tot_partitions() - part_info A reference to the partition_info struct - RETURN VALUE - Returns the number of partitions - DESCRIPTION - A routine to check for number of partitions for improved readability - of code -*/ -static inline -uint get_tot_partitions(partition_info *part_info) -{ - return part_info->no_parts * - (is_sub_partitioned(part_info) ? part_info->no_subparts : 1); -} - - -#endif typedef struct st_ha_create_information { @@ -1096,6 +674,7 @@ typedef class Item COND; typedef struct st_ha_check_opt { + st_ha_check_opt() {} /* Remove gcc warning */ ulong sort_buffer_size; uint flags; /* isam layer flags (e.g. for myisamchk) */ uint sql_flags; /* sql layer flags - for something myisamchk cannot do */ @@ -1104,54 +683,6 @@ typedef struct st_ha_check_opt } HA_CHECK_OPT; -#ifdef WITH_PARTITION_STORAGE_ENGINE -bool is_partition_in_list(char *part_name, List<char> list_part_names); -char *are_partitions_in_table(partition_info *new_part_info, - partition_info *old_part_info); -bool check_reorganise_list(partition_info *new_part_info, - partition_info *old_part_info, - List<char> list_part_names); -bool set_up_defaults_for_partitioning(partition_info *part_info, - handler *file, - ulonglong max_rows, - uint start_no); -handler *get_ha_partition(partition_info *part_info); -int get_parts_for_update(const byte *old_data, byte *new_data, - const byte *rec0, partition_info *part_info, - uint32 *old_part_id, uint32 *new_part_id, - longlong *func_value); -int get_part_for_delete(const byte *buf, const byte *rec0, - partition_info *part_info, uint32 *part_id); -bool check_partition_info(partition_info *part_info,handlerton **eng_type, - handler *file, ulonglong max_rows); -bool fix_partition_func(THD *thd, const char *name, TABLE *table, - bool create_table_ind); -char *generate_partition_syntax(partition_info *part_info, - uint *buf_length, bool use_sql_alloc, - bool write_all); -bool partition_key_modified(TABLE *table, List<Item> &fields); -void prune_partition_set(const TABLE *table, part_id_range *part_spec); -void get_partition_set(const TABLE *table, byte *buf, const uint index, - const key_range *key_spec, - part_id_range *part_spec); -void get_full_part_id_from_key(const TABLE *table, byte *buf, - KEY *key_info, - const key_range *key_spec, - part_id_range *part_spec); -bool mysql_unpack_partition(THD *thd, const uchar *part_buf, - uint part_info_len, - uchar *part_state, uint part_state_len, - TABLE *table, bool is_create_table_ind, - handlerton *default_db_type); -void make_used_partitions_str(partition_info *part_info, String *parts_str); -uint32 get_list_array_idx_for_endpoint(partition_info *part_info, - bool left_endpoint, - bool include_endpoint); -uint32 get_partition_id_range_for_endpoint(partition_info *part_info, - bool left_endpoint, - bool include_endpoint); -#endif - /* This is a buffer area that the handler can use to store rows. @@ -1169,11 +700,15 @@ typedef struct st_handler_buffer typedef struct system_status_var SSV; +/* + The handler class is the interface for dynamically loadable + storage engines. Do not add ifdefs and take care when adding or + changing virtual functions to avoid vtable confusion + */ class handler :public Sql_alloc { -#ifdef WITH_PARTITION_STORAGE_ENGINE - friend class ha_partition; -#endif + friend class ha_partition; + protected: struct st_table_share *table_share; /* The table definition */ struct st_table *table; /* The current open table */ @@ -1751,7 +1286,7 @@ public: virtual const char *table_type() const =0; virtual const char **bas_ext() const =0; virtual ulong table_flags(void) const =0; -#ifdef WITH_PARTITION_STORAGE_ENGINE + virtual int get_default_no_partitions(ulonglong max_rows) { return 1;} virtual void set_auto_partitions(partition_info *part_info) { return; } virtual bool get_no_parts(const char *name, @@ -1761,7 +1296,7 @@ public: return 0; } virtual void set_part_info(partition_info *part_info) {return;} -#endif + virtual ulong index_flags(uint idx, uint part, bool all_parts) const =0; virtual int add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys) diff --git a/sql/item.cc b/sql/item.cc index 9f09a8fa02c..bbe7f3d2f9e 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -375,9 +375,6 @@ void Item::print_item_w_name(String *str) void Item::cleanup() { DBUG_ENTER("Item::cleanup"); - DBUG_PRINT("info", ("Item: 0x%lx, name %s, original name %s", - this, name ? name : "(null)", - orig_name ? orig_name : "null")); fixed=0; marker= 0; if (orig_name) @@ -5151,9 +5148,9 @@ bool Item_direct_view_ref::eq(const Item *item, bool binary_cmp) const if (item_ref->ref_type() == VIEW_REF) { Item *item_ref_ref= *(item_ref->ref); - DBUG_ASSERT((*ref)->type() == FIELD_ITEM && - (item_ref_ref->type() == FIELD_ITEM)); - return (*ref == item_ref_ref); + DBUG_ASSERT((*ref)->real_item()->type() == FIELD_ITEM && + (item_ref_ref->real_item()->type() == FIELD_ITEM)); + return ((*ref)->real_item() == item_ref_ref->real_item()); } } return FALSE; diff --git a/sql/item.h b/sql/item.h index ae6aaeb82f0..b9ce418858c 100644 --- a/sql/item.h +++ b/sql/item.h @@ -164,7 +164,8 @@ struct Hybrid_type_traits virtual my_decimal *val_decimal(Hybrid_type *val, my_decimal *buf) const; virtual String *val_str(Hybrid_type *val, String *buf, uint8 decimals) const; static const Hybrid_type_traits *instance(); - Hybrid_type_traits() {}; + Hybrid_type_traits() {} + virtual ~Hybrid_type_traits() {} }; @@ -339,6 +340,7 @@ private: bool save_resolve_in_select_list; public: + Name_resolution_context_state() {} /* Remove gcc warning */ TABLE_LIST *save_next_local; public: @@ -1055,6 +1057,7 @@ bool agg_item_charsets(DTCollation &c, const char *name, class Item_num: public Item { public: + Item_num() {} /* Remove gcc warning */ virtual Item_num *neg()= 0; Item *safe_charset_converter(CHARSET_INFO *tocs); }; @@ -1626,7 +1629,6 @@ public: str_value.length(), collation.collation); } Item *safe_charset_converter(CHARSET_INFO *tocs); - String *const_string() { return &str_value; } inline void append(char *str, uint length) { str_value.append(str, length); } void print(String *str); // to prevent drop fixed flag (no need parent cleanup call) @@ -1928,9 +1930,10 @@ class Item_int_with_ref :public Item_int { Item *ref; public: - Item_int_with_ref(longlong i, Item *ref_arg) :Item_int(i), ref(ref_arg) + Item_int_with_ref(longlong i, Item *ref_arg, my_bool unsigned_arg) : + Item_int(i), ref(ref_arg) { - unsigned_flag= ref_arg->unsigned_flag; + unsigned_flag= unsigned_arg; } int save_in_field(Field *field, bool no_conversions) { diff --git a/sql/item_cmpfunc.cc b/sql/item_cmpfunc.cc index 2014f646356..592b7e9dc6c 100644 --- a/sql/item_cmpfunc.cc +++ b/sql/item_cmpfunc.cc @@ -216,7 +216,8 @@ static bool convert_constant_item(THD *thd, Field *field, Item **item) field->table->in_use->variables.sql_mode|= MODE_INVALID_DATES; if (!(*item)->save_in_field(field, 1) && !((*item)->null_value)) { - Item *tmp=new Item_int_with_ref(field->val_int(), *item); + Item *tmp=new Item_int_with_ref(field->val_int(), *item, + test(field->flags & UNSIGNED_FLAG)); field->table->in_use->variables.sql_mode= orig_sql_mode; if (tmp) thd->change_item_tree(item, tmp); diff --git a/sql/item_cmpfunc.h b/sql/item_cmpfunc.h index 15aebd2492c..89aafa5721e 100644 --- a/sql/item_cmpfunc.h +++ b/sql/item_cmpfunc.h @@ -128,6 +128,8 @@ public: class Comp_creator { public: + Comp_creator() {} /* Remove gcc warning */ + virtual ~Comp_creator() {} /* Remove gcc warning */ virtual Item_bool_func2* create(Item *a, Item *b) const = 0; virtual const char* symbol(bool invert) const = 0; virtual bool eqne_op() const = 0; @@ -137,6 +139,8 @@ public: class Eq_creator :public Comp_creator { public: + Eq_creator() {} /* Remove gcc warning */ + virtual ~Eq_creator() {} /* Remove gcc warning */ virtual Item_bool_func2* create(Item *a, Item *b) const; virtual const char* symbol(bool invert) const { return invert? "<>" : "="; } virtual bool eqne_op() const { return 1; } @@ -146,6 +150,8 @@ public: class Ne_creator :public Comp_creator { public: + Ne_creator() {} /* Remove gcc warning */ + virtual ~Ne_creator() {} /* Remove gcc warning */ virtual Item_bool_func2* create(Item *a, Item *b) const; virtual const char* symbol(bool invert) const { return invert? "=" : "<>"; } virtual bool eqne_op() const { return 1; } @@ -155,6 +161,8 @@ public: class Gt_creator :public Comp_creator { public: + Gt_creator() {} /* Remove gcc warning */ + virtual ~Gt_creator() {} /* Remove gcc warning */ virtual Item_bool_func2* create(Item *a, Item *b) const; virtual const char* symbol(bool invert) const { return invert? "<=" : ">"; } virtual bool eqne_op() const { return 0; } @@ -164,6 +172,8 @@ public: class Lt_creator :public Comp_creator { public: + Lt_creator() {} /* Remove gcc warning */ + virtual ~Lt_creator() {} /* Remove gcc warning */ virtual Item_bool_func2* create(Item *a, Item *b) const; virtual const char* symbol(bool invert) const { return invert? ">=" : "<"; } virtual bool eqne_op() const { return 0; } @@ -173,6 +183,8 @@ public: class Ge_creator :public Comp_creator { public: + Ge_creator() {} /* Remove gcc warning */ + virtual ~Ge_creator() {} /* Remove gcc warning */ virtual Item_bool_func2* create(Item *a, Item *b) const; virtual const char* symbol(bool invert) const { return invert? "<" : ">="; } virtual bool eqne_op() const { return 0; } @@ -182,6 +194,8 @@ public: class Le_creator :public Comp_creator { public: + Le_creator() {} /* Remove gcc warning */ + virtual ~Le_creator() {} /* Remove gcc warning */ virtual Item_bool_func2* create(Item *a, Item *b) const; virtual const char* symbol(bool invert) const { return invert? ">" : "<="; } virtual bool eqne_op() const { return 0; } @@ -739,6 +753,7 @@ class cmp_item_int :public cmp_item { longlong value; public: + cmp_item_int() {} /* Remove gcc warning */ void store_value(Item *item) { value= item->val_int(); @@ -759,6 +774,7 @@ class cmp_item_real :public cmp_item { double value; public: + cmp_item_real() {} /* Remove gcc warning */ void store_value(Item *item) { value= item->val_real(); @@ -780,6 +796,7 @@ class cmp_item_decimal :public cmp_item { my_decimal value; public: + cmp_item_decimal() {} /* Remove gcc warning */ void store_value(Item *item); int cmp(Item *arg); int compare(cmp_item *c); diff --git a/sql/item_func.cc b/sql/item_func.cc index 22200732861..d2e0911557f 100644 --- a/sql/item_func.cc +++ b/sql/item_func.cc @@ -2657,6 +2657,7 @@ udf_handler::fix_fields(THD *thd, Item_result_field *func, u_d->name.str, ER(ER_UNKNOWN_ERROR)); DBUG_RETURN(TRUE); } + thd->set_current_stmt_binlog_row_based_if_mixed(); DBUG_RETURN(FALSE); } diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index a3e47154bc3..eb89eb7708c 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -3002,6 +3002,7 @@ String *Item_func_uuid::val_str(String *str) char *s; THD *thd= current_thd; + thd->set_current_stmt_binlog_row_based_if_mixed(); pthread_mutex_lock(&LOCK_uuid_generator); if (! uuid_time) /* first UUID() call. initializing data */ { diff --git a/sql/item_sum.h b/sql/item_sum.h index a8242d76287..a38530a502c 100644 --- a/sql/item_sum.h +++ b/sql/item_sum.h @@ -1116,6 +1116,13 @@ public: enum Sumfunctype sum_func () const {return GROUP_CONCAT_FUNC;} const char *func_name() const { return "group_concat"; } virtual Item_result result_type () const { return STRING_RESULT; } + enum_field_types field_type() const + { + if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB) + return FIELD_TYPE_BLOB; + else + return MYSQL_TYPE_VARCHAR; + } void clear(); bool add(); void reset_field() { DBUG_ASSERT(0); } // not used diff --git a/sql/item_timefunc.cc b/sql/item_timefunc.cc index 2effe3a615c..c4f7dec70d0 100644 --- a/sql/item_timefunc.cc +++ b/sql/item_timefunc.cc @@ -1656,9 +1656,15 @@ longlong Item_func_sec_to_time::val_int() void Item_func_date_format::fix_length_and_dec() { + /* + Must use this_item() in case it's a local SP variable + (for ->max_length and ->str_value) + */ + Item *arg1= args[1]->this_item(); + decimals=0; collation.set(&my_charset_bin); - if (args[1]->type() == STRING_ITEM) + if (arg1->type() == STRING_ITEM) { // Optimize the normal case fixed_length=1; @@ -1666,13 +1672,13 @@ void Item_func_date_format::fix_length_and_dec() The result is a binary string (no reason to use collation->mbmaxlen This is becasue make_date_time() only returns binary strings */ - max_length= format_length(((Item_string*) args[1])->const_string()); + max_length= format_length(&arg1->str_value); } else { fixed_length=0; /* The result is a binary string (no reason to use collation->mbmaxlen */ - max_length=min(args[1]->max_length,MAX_BLOB_WIDTH) * 10; + max_length=min(arg1->max_length, MAX_BLOB_WIDTH) * 10; set_if_smaller(max_length,MAX_BLOB_WIDTH); } maybe_null=1; // If wrong date @@ -1682,6 +1688,7 @@ void Item_func_date_format::fix_length_and_dec() bool Item_func_date_format::eq(const Item *item, bool binary_cmp) const { Item_func_date_format *item_func; + if (item->type() != FUNC_ITEM) return 0; if (func_name() != ((Item_func*) item)->func_name()) diff --git a/sql/item_xmlfunc.cc b/sql/item_xmlfunc.cc index d86b6acfc56..8ad7e2f9661 100644 --- a/sql/item_xmlfunc.cc +++ b/sql/item_xmlfunc.cc @@ -206,7 +206,11 @@ public: return str; } enum Item_result result_type () const { return STRING_RESULT; } - void fix_length_and_dec() { max_length= MAX_BLOB_WIDTH; } + void fix_length_and_dec() + { + max_length= MAX_BLOB_WIDTH; + collation.collation= pxml->charset(); + } const char *func_name() const { return "nodeset"; } }; @@ -252,6 +256,18 @@ public: }; +/* Returns self */ +class Item_nodeset_func_selfbyname: public Item_nodeset_func_axisbyname +{ +public: + Item_nodeset_func_selfbyname(Item *a, const char *n_arg, uint l_arg, + String *pxml): + Item_nodeset_func_axisbyname(a, n_arg, l_arg, pxml) {} + const char *func_name() const { return "xpath_selfbyname"; } + String *val_nodeset(String *nodeset); +}; + + /* Returns children */ class Item_nodeset_func_childbyname: public Item_nodeset_func_axisbyname { @@ -572,6 +588,20 @@ String * Item_nodeset_func_union::val_nodeset(String *nodeset) } +String *Item_nodeset_func_selfbyname::val_nodeset(String *nodeset) +{ + prepare(nodeset); + for (MY_XPATH_FLT *flt= fltbeg; flt < fltend; flt++) + { + uint pos= 0; + MY_XML_NODE *self= &nodebeg[flt->num]; + if (validname(self)) + ((XPathFilter*)nodeset)->append_element(flt->num,pos++); + } + return nodeset; +} + + String *Item_nodeset_func_childbyname::val_nodeset(String *nodeset) { prepare(nodeset); @@ -945,6 +975,9 @@ static Item* nametestfunc(MY_XPATH *xpath, case MY_XPATH_AXIS_ATTRIBUTE: res= new Item_nodeset_func_attributebyname(arg, beg, len, xpath->pxml); break; + case MY_XPATH_AXIS_SELF: + res= new Item_nodeset_func_selfbyname(arg, beg, len, xpath->pxml); + break; default: res= new Item_nodeset_func_childbyname(arg, beg, len, xpath->pxml); } @@ -1272,7 +1305,7 @@ my_xident_body(int c) return (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || ((c) >= '0' && (c) <= '9') || - ((c)=='-')); + ((c)=='-') || ((c) == '_')); } @@ -1976,8 +2009,17 @@ static int my_xpath_parse_AndExpr(MY_XPATH *xpath) */ static int my_xpath_parse_ne(MY_XPATH *xpath) { - return my_xpath_parse_term(xpath, MY_XPATH_LEX_EXCL) && - my_xpath_parse_term(xpath, MY_XPATH_LEX_EQ); + MY_XPATH_LEX prevtok= xpath->prevtok; + if (!my_xpath_parse_term(xpath, MY_XPATH_LEX_EXCL)) + return 0; + if (!my_xpath_parse_term(xpath, MY_XPATH_LEX_EQ)) + { + /* Unget the exclamation mark */ + xpath->lasttok= xpath->prevtok; + xpath->prevtok= prevtok; + return 0; + } + return 1; } static int my_xpath_parse_EqualityOperator(MY_XPATH *xpath) { @@ -2335,6 +2377,7 @@ void Item_xml_str_func::fix_length_and_dec() xpath.cs= collation.collation; xpath.debug= 0; xpath.pxml= &pxml; + pxml.set_charset(collation.collation); rc= my_xpath_parse(&xpath, xp->ptr(), xp->ptr() + xp->length()); diff --git a/sql/log.cc b/sql/log.cc index 323b6df86d9..ff14b986aa4 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -102,7 +102,9 @@ handlerton binlog_hton = { NULL, /* Alter table flags */ NULL, /* Alter Tablespace */ NULL, /* Fill FILES table */ - HTON_NOT_USER_SELECTABLE | HTON_HIDDEN + HTON_NOT_USER_SELECTABLE | HTON_HIDDEN, + NULL, /* binlog_func */ + NULL /* binlog_log_query */ }; @@ -2630,7 +2632,7 @@ THD::binlog_set_pending_rows_event(Rows_log_event* ev) int MYSQL_LOG::flush_and_set_pending_rows_event(THD *thd, Rows_log_event* event) { DBUG_ENTER("MYSQL_LOG::flush_and_set_pending_rows_event(event)"); - DBUG_ASSERT(binlog_row_based && mysql_bin_log.is_open()); + DBUG_ASSERT(thd->current_stmt_binlog_row_based && mysql_bin_log.is_open()); DBUG_PRINT("enter", ("event=%p", event)); int error= 0; @@ -2847,7 +2849,7 @@ bool MYSQL_LOG::write(Log_event *event_info) */ if (thd) { - if (!binlog_row_based) + if (!thd->current_stmt_binlog_row_based) { if (thd->last_insert_id_used) { @@ -3517,7 +3519,7 @@ bool MYSQL_LOG::write_table_map(THD *thd, IO_CACHE *file, TABLE* table, table, table->s->table_name, table->s->table_map_id)); /* Pre-conditions */ - DBUG_ASSERT(binlog_row_based && is_open()); + DBUG_ASSERT(thd->current_stmt_binlog_row_based && is_open()); DBUG_ASSERT(table->s->table_map_id != ULONG_MAX); #ifndef DBUG_OFF diff --git a/sql/log.h b/sql/log.h index 98a86072fca..8a83e7b66d0 100644 --- a/sql/log.h +++ b/sql/log.h @@ -507,4 +507,24 @@ public: void init_general_log(uint general_log_printer); }; + +enum enum_binlog_format { + BINLOG_FORMAT_STMT= 0, // statement-based +#ifdef HAVE_ROW_BASED_REPLICATION + BINLOG_FORMAT_ROW= 1, // row_based + /* + statement-based except for cases where only row-based can work (UUID() + etc): + */ + BINLOG_FORMAT_MIXED= 2, +#endif +/* + This value is last, after the end of binlog_format_typelib: it has no + corresponding cell in this typelib. We use this value to be able to know if + the user has explicitely specified a binlog format at startup or not. +*/ + BINLOG_FORMAT_UNSPEC= 3 +}; +extern TYPELIB binlog_format_typelib; + #endif /* LOG_H */ diff --git a/sql/log_event.cc b/sql/log_event.cc index cd16745df90..e589f46e0e0 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -28,7 +28,6 @@ #endif /* MYSQL_CLIENT */ #include <base64.h> #include <my_bitmap.h> -#include <my_vle.h> #define log_cs &my_charset_latin1 @@ -5128,7 +5127,8 @@ Rows_log_event::Rows_log_event(const char *buf, uint event_len, byte const *const var_start= (const byte *)buf + common_header_len + post_header_len; byte const *const ptr_width= var_start; - byte const *const ptr_after_width= my_vle_decode(&m_width, ptr_width); + uchar *ptr_after_width= (uchar*) ptr_width; + m_width = net_field_length(&ptr_after_width); const uint byte_count= (m_width + 7) / 8; const byte* const ptr_rows_data= var_start + byte_count + 1; @@ -5281,6 +5281,7 @@ int Rows_log_event::exec_event(st_relay_log_info *rli) tested replicate-* rules). */ TABLE_LIST table_list; + TABLE_LIST *tables= &table_list; bool need_reopen; uint count= 1; bzero(&table_list, sizeof(table_list)); @@ -5330,13 +5331,12 @@ int Rows_log_event::exec_event(st_relay_log_info *rli) */ thd->binlog_flush_pending_rows_event(false); - close_tables_for_reopen(thd, &table_list); + close_tables_for_reopen(thd, &tables); /* open the table again, same as in Table_map_event::exec_event */ table_list.db= const_cast<char*>(db); table_list.alias= table_list.table_name= const_cast<char*>(table_name); table_list.updating= 1; - TABLE_LIST *tables= &table_list; if ((error= open_tables(thd, &tables, &count, 0)) == 0) { /* reset some variables for the table list*/ @@ -5598,13 +5598,14 @@ bool Rows_log_event::write_data_body(IO_CACHE*file) Note that this should be the number of *bits*, not the number of bytes. */ - byte sbuf[my_vle_sizeof(m_width)]; + char sbuf[sizeof(m_width)]; my_ptrdiff_t const data_size= m_rows_cur - m_rows_buf; - char *const sbuf_end= (char *const)my_vle_encode(sbuf, sizeof(sbuf), m_width); - DBUG_ASSERT(static_cast<my_size_t>(sbuf_end - (char *const)sbuf) <= sizeof(sbuf)); + char *const sbuf_end= net_store_length((char*) sbuf, (uint) m_width); + DBUG_ASSERT(static_cast<my_size_t>(sbuf_end - sbuf) <= sizeof(sbuf)); - return (my_b_safe_write(file, sbuf, sbuf_end - (char *const)sbuf) || + return (my_b_safe_write(file, reinterpret_cast<byte*>(sbuf), + sbuf_end - sbuf) || my_b_safe_write(file, reinterpret_cast<byte*>(m_cols.bitmap), no_bytes_in_map(&m_cols)) || my_b_safe_write(file, m_rows_buf, data_size)); @@ -5731,7 +5732,8 @@ Table_map_log_event::Table_map_log_event(const char *buf, uint event_len, /* Length of table name + counter + terminating null */ byte const* const ptr_colcnt= ptr_tbllen + m_tbllen + 2; - byte const* const ptr_after_colcnt= my_vle_decode(&m_colcnt, ptr_colcnt); + uchar *ptr_after_colcnt= (uchar*) ptr_colcnt; + m_colcnt= net_field_length(&ptr_after_colcnt); DBUG_PRINT("info",("m_dblen=%d off=%d m_tbllen=%d off=%d m_colcnt=%d off=%d", m_dblen, ptr_dblen-(const byte*)vpart, @@ -5854,13 +5856,17 @@ int Table_map_log_event::exec_event(st_relay_log_info *rli) (!rpl_filter->is_on() || rpl_filter->tables_ok("", &table_list))) { /* + TODO: Mats will soon change this test below so that a SBR slave always + accepts RBR events from the master (and binlogs them RBR). + */ + /* Check if the slave is set to use SBR. If so, the slave should stop immediately since it is not possible to daisy-chain from RBR to SBR. Once RBR is used, the rest of the chain has to use RBR. */ if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG) && - !binlog_row_based) + !thd->current_stmt_binlog_row_based) { slave_print_msg(ERROR_LEVEL, rli, ER_BINLOG_ROW_RBR_TO_SBR, "It is not possible to use statement-based binlogging " @@ -6043,15 +6049,16 @@ bool Table_map_log_event::write_data_body(IO_CACHE *file) byte const dbuf[]= { m_dblen }; byte const tbuf[]= { m_tbllen }; - byte cbuf[my_vle_sizeof(m_colcnt)]; - byte *const cbuf_end= my_vle_encode(cbuf, sizeof(cbuf), m_colcnt); + char cbuf[sizeof(m_colcnt)]; + char *const cbuf_end= net_store_length((char*) cbuf, (uint) m_colcnt); DBUG_ASSERT(static_cast<my_size_t>(cbuf_end - cbuf) <= sizeof(cbuf)); return (my_b_safe_write(file, dbuf, sizeof(dbuf)) || my_b_safe_write(file, (const byte*)m_dbnam, m_dblen+1) || my_b_safe_write(file, tbuf, sizeof(tbuf)) || my_b_safe_write(file, (const byte*)m_tblnam, m_tbllen+1) || - my_b_safe_write(file, cbuf, cbuf_end - cbuf) || + my_b_safe_write(file, reinterpret_cast<byte*>(cbuf), + cbuf_end - (char*) cbuf) || my_b_safe_write(file, reinterpret_cast<byte*>(m_coltype), m_colcnt)); } #endif @@ -6358,18 +6365,27 @@ void Write_rows_log_event::print(FILE *file, PRINT_EVENT_INFO* print_event_info) **************************************************************************/ #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) -static int record_compare(TABLE *table, char const *a, char const *b) +/* + Compares table->record[0] and table->record[1] + + Returns TRUE if different. +*/ +static bool record_compare(TABLE *table) { - for (my_size_t i= 0 ; i < table->s->fields ; ++i) + if (table->s->blob_fields + table->s->varchar_fields == 0) + return cmp_record(table,record[1]); + /* Compare null bits */ + if (memcmp(table->null_flags, + table->null_flags+table->s->rec_buff_length, + table->s->null_bytes)) + return TRUE; // Diff in NULL value + /* Compare updated fields */ + for (Field **ptr=table->field ; *ptr ; ptr++) { - uint const off= table->field[i]->offset(); - uint const res= table->field[i]->cmp_binary(a + off, - b + off); - if (res != 0) { - return res; - } + if ((*ptr)->cmp_binary_offset(table->s->rec_buff_length)) + return TRUE; } - return 0; + return FALSE; } @@ -6377,15 +6393,12 @@ static int record_compare(TABLE *table, char const *a, char const *b) Find the row given by 'key', if the table has keys, or else use a table scan to find (and fetch) the row. If the engine allows random access of the records, a combination of position() and rnd_pos() will be used. - - The 'record_buf' will be used as buffer for records while locating the - correct row. */ -static int find_and_fetch_row(TABLE *table, byte *key, byte *record_buf) +static int find_and_fetch_row(TABLE *table, byte *key) { DBUG_ENTER("find_and_fetch_row(TABLE *table, byte *key, byte *record)"); DBUG_PRINT("enter", ("table=%p, key=%p, record=%p", - table, key, record_buf)); + table, key, table->record[1])); DBUG_ASSERT(table->in_use != NULL); @@ -6403,7 +6416,7 @@ static int find_and_fetch_row(TABLE *table, byte *key, byte *record_buf) DBUG_RETURN(table->file->rnd_pos(table->record[0], table->file->ref)); } - DBUG_ASSERT(record_buf); + DBUG_ASSERT(table->record[1]); /* We need to retrieve all fields */ table->file->ha_set_all_bits_in_read_set(); @@ -6411,7 +6424,7 @@ static int find_and_fetch_row(TABLE *table, byte *key, byte *record_buf) if (table->s->keys > 0) { int error; - if ((error= table->file->index_read_idx(record_buf, 0, key, + if ((error= table->file->index_read_idx(table->record[1], 0, key, table->key_info->key_length, HA_READ_KEY_EXACT))) { @@ -6436,10 +6449,10 @@ static int find_and_fetch_row(TABLE *table, byte *key, byte *record_buf) if (table->key_info->flags & HA_NOSAME) DBUG_RETURN(0); - while (record_compare(table, (const char*)table->record[0], (const char*)record_buf) != 0) + while (record_compare(table)) { int error; - if ((error= table->file->index_next(record_buf))) + if ((error= table->file->index_next(table->record[1]))) { table->file->print_error(error, MYF(0)); DBUG_RETURN(error); @@ -6453,7 +6466,7 @@ static int find_and_fetch_row(TABLE *table, byte *key, byte *record_buf) int error= 0; do { - error= table->file->rnd_next(record_buf); + error= table->file->rnd_next(table->record[1]); switch (error) { case 0: @@ -6470,9 +6483,7 @@ static int find_and_fetch_row(TABLE *table, byte *key, byte *record_buf) DBUG_RETURN(error); } } - while (restart_count < 2 && - record_compare(table, (const char*)table->record[0], - (const char*)record_buf) != 0); + while (restart_count < 2 && record_compare(table)); DBUG_ASSERT(error == HA_ERR_END_OF_FILE || error == 0); DBUG_RETURN(error); @@ -6492,7 +6503,7 @@ Delete_rows_log_event::Delete_rows_log_event(THD *thd_arg, TABLE *tbl_arg, bool is_transactional) : Rows_log_event(thd_arg, tbl_arg, tid, cols, is_transactional) #ifdef HAVE_REPLICATION - ,m_memory(NULL), m_key(NULL), m_search_record(NULL) + ,m_memory(NULL), m_key(NULL), m_after_image(NULL) #endif { } @@ -6509,7 +6520,7 @@ Delete_rows_log_event::Delete_rows_log_event(const char *buf, uint event_len, : Rows_log_event(buf, event_len, DELETE_ROWS_EVENT, description_event) #else : Rows_log_event(buf, event_len, DELETE_ROWS_EVENT, description_event), - m_memory(NULL), m_key(NULL), m_search_record(NULL) + m_memory(NULL), m_key(NULL), m_after_image(NULL) #endif { } @@ -6524,7 +6535,7 @@ int Delete_rows_log_event::do_before_row_operations(TABLE *table) table->s->primary_key < MAX_KEY) { /* - We don't need to allocate any memory for m_search_record and + We don't need to allocate any memory for m_after_image and m_key since they are not used. */ return 0; @@ -6536,14 +6547,14 @@ int Delete_rows_log_event::do_before_row_operations(TABLE *table) { m_memory= my_multi_malloc(MYF(MY_WME), - &m_search_record, table->s->reclength, + &m_after_image, table->s->reclength, &m_key, table->key_info->key_length, NULL); } else { - m_search_record= (byte*)my_malloc(table->s->reclength, MYF(MY_WME)); - m_memory= (gptr)m_search_record; + m_after_image= (byte*)my_malloc(table->s->reclength, MYF(MY_WME)); + m_memory= (gptr)m_after_image; m_key= NULL; } if (!m_memory) @@ -6570,7 +6581,7 @@ int Delete_rows_log_event::do_after_row_operations(TABLE *table, int error) table->file->ha_index_or_rnd_end(); my_free(m_memory, MYF(MY_ALLOW_ZERO_PTR)); // Free for multi_malloc m_memory= NULL; - m_search_record= NULL; + m_after_image= NULL; m_key= NULL; return error; @@ -6608,7 +6619,7 @@ int Delete_rows_log_event::do_exec_row(TABLE *table) { DBUG_ASSERT(table != NULL); - int error= find_and_fetch_row(table, m_key, m_search_record); + int error= find_and_fetch_row(table, m_key); if (error) return error; @@ -6680,30 +6691,20 @@ int Update_rows_log_event::do_before_row_operations(TABLE *table) { DBUG_ASSERT(m_memory == NULL); - if ((table->file->table_flags() & HA_PRIMARY_KEY_ALLOW_RANDOM_ACCESS) && - table->s->primary_key < MAX_KEY) - { - /* - We don't need to allocate any memory for m_search_record and - m_key since they are not used. - */ - return 0; - } - int error= 0; if (table->s->keys > 0) { m_memory= my_multi_malloc(MYF(MY_WME), - &m_search_record, table->s->reclength, + &m_after_image, table->s->reclength, &m_key, table->key_info->key_length, NULL); } else { - m_search_record= (byte*)my_malloc(table->s->reclength, MYF(MY_WME)); - m_memory= (gptr)m_search_record; + m_after_image= (byte*)my_malloc(table->s->reclength, MYF(MY_WME)); + m_memory= (gptr)m_after_image; m_key= NULL; } if (!m_memory) @@ -6731,7 +6732,7 @@ int Update_rows_log_event::do_after_row_operations(TABLE *table, int error) table->file->ha_index_or_rnd_end(); my_free(m_memory, MYF(MY_ALLOW_ZERO_PTR)); m_memory= NULL; - m_search_record= NULL; + m_after_image= NULL; m_key= NULL; return error; @@ -6751,8 +6752,8 @@ char const *Update_rows_log_event::do_prepare_row(THD *thd, TABLE *table, /* record[0] is the before image for the update */ ptr= unpack_row(table, table->record[0], ptr, &m_cols); DBUG_ASSERT(ptr != NULL); - /* record[1] is the after image for the update */ - ptr= unpack_row(table, table->record[1], ptr, &m_cols); + /* m_after_image is the after image for the update */ + ptr= unpack_row(table, m_after_image, ptr, &m_cols); /* If we will access rows using the random access method, m_key will @@ -6772,11 +6773,20 @@ int Update_rows_log_event::do_exec_row(TABLE *table) { DBUG_ASSERT(table != NULL); - int error= find_and_fetch_row(table, m_key, m_search_record); + int error= find_and_fetch_row(table, m_key); if (error) return error; /* + This is only a precaution to make sure that the call to + ha_update_row is using record[1]. + + If this is not needed/required, then we could use m_after_image in + that call instead. + */ + bmove_align(table->record[1], m_after_image,(size_t) table->s->reclength); + + /* Now we should have the right row to update. The record that has been fetched is guaranteed to be in record[0], so we use that. */ diff --git a/sql/log_event.h b/sql/log_event.h index a7c532d4c24..dd68e969ff1 100644 --- a/sql/log_event.h +++ b/sql/log_event.h @@ -28,14 +28,6 @@ #include <my_bitmap.h> -#if !defined(MYSQL_CLIENT) -#ifdef HAVE_ROW_BASED_REPLICATION -extern my_bool binlog_row_based; -#else -extern const my_bool binlog_row_based; -#endif -#endif - #define LOG_READ_EOF -1 #define LOG_READ_BOGUS -2 #define LOG_READ_IO -3 @@ -131,6 +123,7 @@ struct old_sql_ex ****************************************************************************/ struct sql_ex_info { + sql_ex_info() {} /* Remove gcc warning */ char* field_term; char* enclosed; char* line_term; @@ -2012,7 +2005,7 @@ private: #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) gptr m_memory; - byte *m_search_record; + byte *m_after_image; virtual int do_before_row_operations(TABLE *table); virtual int do_after_row_operations(TABLE *table, int error); @@ -2076,7 +2069,7 @@ private: #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) gptr m_memory; byte *m_key; - byte *m_search_record; + byte *m_after_image; virtual int do_before_row_operations(TABLE *table); virtual int do_after_row_operations(TABLE *table, int error); @@ -2146,7 +2139,7 @@ private: #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) gptr m_memory; byte *m_key; - byte *m_search_record; + byte *m_after_image; virtual int do_before_row_operations(TABLE *table); virtual int do_after_row_operations(TABLE *table, int error); diff --git a/sql/mysql_priv.h b/sql/mysql_priv.h index fc777c47818..b3c3e4d9211 100644 --- a/sql/mysql_priv.h +++ b/sql/mysql_priv.h @@ -92,6 +92,15 @@ char* query_table_status(THD *thd,const char *db,const char *table_name); #define PREV_BITS(type,A) ((type) (((type) 1 << (A)) -1)) #define all_bits_set(A,B) ((A) & (B) != (B)) +#define WARN_DEPRECATED(Thd,Ver,Old,New) \ + do { \ + DBUG_ASSERT(strncmp(Ver, MYSQL_SERVER_VERSION, sizeof(Ver)-1) >= 0); \ + push_warning_printf(((THD *)Thd), MYSQL_ERROR::WARN_LEVEL_WARN, \ + ER_WARN_DEPRECATED, ER(ER_WARN_DEPRECATED), \ + (Old), (Ver), (New)); \ + } while(0) + + extern CHARSET_INFO *system_charset_info, *files_charset_info ; extern CHARSET_INFO *national_charset_info, *table_alias_charset; @@ -434,6 +443,7 @@ typedef struct st_sql_list { byte *first; byte **next; + st_sql_list() {} /* Remove gcc warning */ inline void empty() { elements=0; @@ -503,6 +513,8 @@ typedef my_bool (*qc_engine_callback)(THD *thd, char *table_key, #include "protocol.h" #include "sql_plugin.h" #include "sql_udf.h" +#include "sql_partition.h" + class user_var_entry; class Security_context; enum enum_var_type @@ -657,7 +669,7 @@ bool table_cache_init(void); void table_cache_free(void); bool table_def_init(void); void table_def_free(void); -void assign_new_table_id(TABLE *table); +void assign_new_table_id(TABLE_SHARE *share); uint cached_open_tables(void); uint cached_table_definitions(void); void kill_mysql(void); @@ -1036,9 +1048,9 @@ void free_io_cache(TABLE *entry); void intern_close_table(TABLE *entry); bool close_thread_table(THD *thd, TABLE **table_ptr); void close_temporary_tables(THD *thd); -void close_tables_for_reopen(THD *thd, TABLE_LIST *tables); +void close_tables_for_reopen(THD *thd, TABLE_LIST **tables); TABLE_LIST *find_table_in_list(TABLE_LIST *table, - uint offset_to_list, + st_table_list *TABLE_LIST::*link, const char *db_name, const char *table_name); TABLE_LIST *unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list); @@ -1128,7 +1140,7 @@ inline TABLE_LIST *find_table_in_global_list(TABLE_LIST *table, const char *db_name, const char *table_name) { - return find_table_in_list(table, offsetof(TABLE_LIST, next_global), + return find_table_in_list(table, &TABLE_LIST::next_global, db_name, table_name); } @@ -1136,7 +1148,7 @@ inline TABLE_LIST *find_table_in_local_list(TABLE_LIST *table, const char *db_name, const char *table_name) { - return find_table_in_list(table, offsetof(TABLE_LIST, next_local), + return find_table_in_list(table, &TABLE_LIST::next_local, db_name, table_name); } @@ -1286,12 +1298,8 @@ extern ulong what_to_log,flush_time; extern ulong query_buff_size, thread_stack; extern ulong binlog_cache_size, max_binlog_cache_size, open_files_limit; extern ulong max_binlog_size, max_relay_log_size; -extern const char *opt_binlog_format; #ifdef HAVE_ROW_BASED_REPLICATION -extern my_bool binlog_row_based; extern ulong opt_binlog_rows_event_max_size; -#else -extern const my_bool binlog_row_based; #endif extern ulong rpl_recovery_rank, thread_cache_size; extern ulong back_log; diff --git a/sql/mysqld.cc b/sql/mysqld.cc index e1c8ed966ee..4f8944593bc 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -465,31 +465,14 @@ my_bool opt_noacl; my_bool sp_automatic_privileges= 1; #ifdef HAVE_ROW_BASED_REPLICATION -/* - This variable below serves as an optimization for (opt_binlog_format == - BF_ROW) as we need to do this test for every row. Stmt-based is default. -*/ -my_bool binlog_row_based= FALSE; ulong opt_binlog_rows_event_max_size; -const char *binlog_format_names[]= {"STATEMENT", "ROW", NullS}; -/* - Note that BF_UNSPECIFIED is last, after the end of binlog_format_names: it - has no corresponding cell in this array. We use this value to be able to - know if the user has explicitely specified a binlog format (then we require - also --log-bin) or not (then we fall back to statement-based). -*/ -enum binlog_format { BF_STMT= 0, BF_ROW= 1, BF_UNSPECIFIED= 2 }; +const char *binlog_format_names[]= {"STATEMENT", "ROW", "MIXED", NullS}; #else -const my_bool binlog_row_based= FALSE; const char *binlog_format_names[]= {"STATEMENT", NullS}; -enum binlog_format { BF_STMT= 0, BF_UNSPECIFIED= 2 }; #endif - TYPELIB binlog_format_typelib= { array_elements(binlog_format_names)-1,"", binlog_format_names, NULL }; -const char *opt_binlog_format= 0; -enum binlog_format opt_binlog_format_id= BF_UNSPECIFIED; #ifdef HAVE_INITGROUPS static bool calling_initgroups= FALSE; /* Used in SIGSEGV handler. */ @@ -3070,6 +3053,8 @@ static int init_server_components() #ifdef HAVE_REPLICATION init_slave_list(); #endif + init_events(); + /* Setup logs */ /* enable old-fashioned error log */ @@ -3187,42 +3172,25 @@ with --log-bin instead."); unireg_abort(1); } - if (!opt_bin_log && (opt_binlog_format_id != BF_UNSPECIFIED)) + if (!opt_bin_log && (global_system_variables.binlog_format != BINLOG_FORMAT_UNSPEC)) { sql_print_warning("You need to use --log-bin to make " "--binlog-format work."); unireg_abort(1); } - if (opt_binlog_format_id == BF_UNSPECIFIED) + if (global_system_variables.binlog_format == BINLOG_FORMAT_UNSPEC) { #ifdef HAVE_NDB_BINLOG if (opt_bin_log && have_ndbcluster == SHOW_OPTION_YES) - opt_binlog_format_id= BF_ROW; + global_system_variables.binlog_format= BINLOG_FORMAT_ROW; else #endif - opt_binlog_format_id= BF_STMT; - } -#ifdef HAVE_ROW_BASED_REPLICATION - if (opt_binlog_format_id == BF_ROW) - { - binlog_row_based= TRUE; - /* - Row-based binlogging turns on InnoDB unsafe locking, because the locks - are not needed when using row-based binlogging. In fact - innodb-locks-unsafe-for-binlog is unsafe only for stmt-based, it's - safe for row-based. - */ -#ifdef HAVE_INNOBASE_DB - innobase_locks_unsafe_for_binlog= TRUE; -#endif - /* Trust stored function creators because they can do no harm */ - trust_function_creators= 1; + global_system_variables.binlog_format= BINLOG_FORMAT_STMT; } -#endif + /* Check that we have not let the format to unspecified at this point */ - DBUG_ASSERT((uint)opt_binlog_format_id <= + DBUG_ASSERT((uint)global_system_variables.binlog_format <= array_elements(binlog_format_names)-1); - opt_binlog_format= binlog_format_names[opt_binlog_format_id]; #ifdef HAVE_REPLICATION if (opt_log_slave_updates && replicate_same_server_id) @@ -3698,8 +3666,6 @@ we force server id to 2, but this MySQL server will not act as a slave."); } } - init_events(); - create_shutdown_thread(); create_maintenance_thread(); @@ -4864,8 +4830,6 @@ struct my_option my_long_options[] = (gptr*) &abort_slave_event_count, (gptr*) &abort_slave_event_count, 0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, #endif /* HAVE_REPLICATION */ - {"ansi", 'a', "Use ANSI SQL syntax instead of MySQL syntax. This mode will also set transaction isolation level 'serializable'.", 0, 0, 0, - GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, {"allow-suspicious-udfs", OPT_ALLOW_SUSPICIOUS_UDFS, "Allows use of UDFs consisting of only one symbol xxx() " "without corresponding xxx_init() or xxx_deinit(). That also means " @@ -4873,6 +4837,8 @@ struct my_option my_long_options[] = "from libc.so", (gptr*) &opt_allow_suspicious_udfs, (gptr*) &opt_allow_suspicious_udfs, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"ansi", 'a', "Use ANSI SQL syntax instead of MySQL syntax. This mode will also set transaction isolation level 'serializable'.", 0, 0, 0, + GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, {"auto-increment-increment", OPT_AUTO_INCREMENT, "Auto-increment columns are incremented by this", (gptr*) &global_system_variables.auto_increment_increment, @@ -4929,23 +4895,23 @@ Disable with --skip-bdb (will save memory).", {"bind-address", OPT_BIND_ADDRESS, "IP address to bind to.", (gptr*) &my_bind_addr_str, (gptr*) &my_bind_addr_str, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, - {"binlog-format", OPT_BINLOG_FORMAT, + {"binlog_format", OPT_BINLOG_FORMAT, #ifdef HAVE_ROW_BASED_REPLICATION "Tell the master the form of binary logging to use: either 'row' for " - "row-based binary logging (which automatically turns on " - "innodb_locks_unsafe_for_binlog as it is safe in this case), or " - "'statement' for statement-based logging. " + "row-based binary logging, or 'statement' for statement-based binary " + "logging, or 'mixed'. 'mixed' is statement-based binary logging except " + "for those statements where only row-based is correct: those which " + "involve user-defined functions (i.e. UDFs) or the UUID() function; for " + "those, row-based binary logging is automatically used. " #ifdef HAVE_NDB_BINLOG - "If ndbcluster is enabled, the default will be set to 'row'." + "If ndbcluster is enabled, the default is 'row'." #endif - , #else - "Tell the master the form of binary logging to use: this release build " + "Tell the master the form of binary logging to use: this build " "supports only statement-based binary logging, so only 'statement' is " - "a legal value; MySQL-Max release builds support row-based binary logging " - "in addition.", + "a legal value." #endif - 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, + , 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 }, {"binlog-do-db", OPT_BINLOG_DO_DB, "Tells the master it should log updates for the specified database, and exclude all others not explicitly mentioned.", 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, @@ -5148,9 +5114,7 @@ Disable with --skip-innodb-doublewrite.", (gptr*) &innobase_use_doublewrite, (gptr*) &innobase_unix_file_flush_method, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"innodb_locks_unsafe_for_binlog", OPT_INNODB_LOCKS_UNSAFE_FOR_BINLOG, - "Force InnoDB not to use next-key locking, to use only row-level locking." - " This is unsafe if you are using statement-based binary logging, and safe" - " if you are using row-based binary logging.", + "Force InnoDB to not use next-key locking, to use only row-level locking.", (gptr*) &innobase_locks_unsafe_for_binlog, (gptr*) &innobase_locks_unsafe_for_binlog, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, {"innodb_log_arch_dir", OPT_INNODB_LOG_ARCH_DIR, @@ -5175,16 +5139,16 @@ Disable with --skip-innodb-doublewrite.", (gptr*) &innobase_use_doublewrite, "Enable SHOW INNODB STATUS output in the innodb_status.<pid> file", (gptr*) &innobase_create_status_file, (gptr*) &innobase_create_status_file, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, - {"innodb_table_locks", OPT_INNODB_TABLE_LOCKS, - "Enable InnoDB locking in LOCK TABLES", - (gptr*) &global_system_variables.innodb_table_locks, - (gptr*) &global_system_variables.innodb_table_locks, - 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, {"innodb_support_xa", OPT_INNODB_SUPPORT_XA, "Enable InnoDB support for the XA two-phase commit", (gptr*) &global_system_variables.innodb_support_xa, (gptr*) &global_system_variables.innodb_support_xa, 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, + {"innodb_table_locks", OPT_INNODB_TABLE_LOCKS, + "Enable InnoDB locking in LOCK TABLES", + (gptr*) &global_system_variables.innodb_table_locks, + (gptr*) &global_system_variables.innodb_table_locks, + 0, GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, 0}, #endif /* End WITH_INNOBASE_STORAGE_ENGINE */ {"isam", OPT_ISAM, "Obsolete. ISAM storage engine is no longer supported.", (gptr*) &opt_isam, (gptr*) &opt_isam, 0, GET_BOOL, NO_ARG, 0, 0, 0, @@ -5231,8 +5195,9 @@ Disable with --skip-innodb-doublewrite.", (gptr*) &innobase_use_doublewrite, "a stored function (or trigger) is allowed only to users having the SUPER privilege " "and only if this stored function (trigger) may not break binary logging." #ifdef HAVE_ROW_BASED_REPLICATION - " If using --binlog-format=row, the security issues do not exist and the " - "binary logging cannot break so this option is automatically set to 1." + "Note that if ALL connections to this server ALWAYS use row-based binary " + "logging, the security issues do not exist and the binary logging cannot " + "break, so you can safely set this to 1." #endif ,(gptr*) &trust_function_creators, (gptr*) &trust_function_creators, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, @@ -5535,12 +5500,6 @@ thread is in the relay logs.", {"replicate-rewrite-db", OPT_REPLICATE_REWRITE_DB, "Updates to a database with a different name than the original. Example: replicate-rewrite-db=master_db_name->slave_db_name.", 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, - {"replicate-wild-do-table", OPT_REPLICATE_WILD_DO_TABLE, - "Tells the slave thread to restrict replication to the tables that match the specified wildcard pattern. To specify more than one table, use the directive multiple times, once for each table. This will work for cross-database updates. Example: replicate-wild-do-table=foo%.bar% will replicate only updates to tables in all databases that start with foo and whose table names start with bar.", - 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, - {"replicate-wild-ignore-table", OPT_REPLICATE_WILD_IGNORE_TABLE, - "Tells the slave thread to not replicate to the tables that match the given wildcard pattern. To specify more than one table to ignore, use the directive multiple times, once for each table. This will work for cross-database updates. Example: replicate-wild-ignore-table=foo%.bar% will not do updates to tables in databases that start with foo and whose table names start with bar.", - 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, #ifdef HAVE_REPLICATION {"replicate-same-server-id", OPT_REPLICATE_SAME_SERVER_ID, "In replication, if set to 1, do not skip events having our server id. \ @@ -5550,6 +5509,12 @@ Can't be set to 1 if --log-slave-updates is used.", (gptr*) &replicate_same_server_id, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, #endif + {"replicate-wild-do-table", OPT_REPLICATE_WILD_DO_TABLE, + "Tells the slave thread to restrict replication to the tables that match the specified wildcard pattern. To specify more than one table, use the directive multiple times, once for each table. This will work for cross-database updates. Example: replicate-wild-do-table=foo%.bar% will replicate only updates to tables in all databases that start with foo and whose table names start with bar.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"replicate-wild-ignore-table", OPT_REPLICATE_WILD_IGNORE_TABLE, + "Tells the slave thread to not replicate to the tables that match the given wildcard pattern. To specify more than one table to ignore, use the directive multiple times, once for each table. This will work for cross-database updates. Example: replicate-wild-ignore-table=foo%.bar% will not do updates to tables in databases that start with foo and whose table names start with bar.", + 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, // In replication, we may need to tell the other servers how to connect {"report-host", OPT_REPORT_HOST, "Hostname or IP of the slave to be reported to to the master during slave registration. Will appear in the output of SHOW SLAVE HOSTS. Leave unset if you do not want the slave to register itself with the master. Note that it is not sufficient for the master to simply read the IP of the slave off the socket once the slave connects. Due to NAT and other routing issues, that IP may not be valid for connecting to the slave from the master or other hosts.", @@ -5791,6 +5756,11 @@ log and this option does nothing anymore.", "What size queue (in rows) should be allocated for handling INSERT DELAYED. If the queue becomes full, any client that does INSERT DELAYED will wait until there is room in the queue again.", (gptr*) &delayed_queue_size, (gptr*) &delayed_queue_size, 0, GET_ULONG, REQUIRED_ARG, DELAYED_QUEUE_SIZE, 1, ~0L, 0, 1, 0}, + {"div_precision_increment", OPT_DIV_PRECINCREMENT, + "Precision of the result of '/' operator will be increased on that value.", + (gptr*) &global_system_variables.div_precincrement, + (gptr*) &max_system_variables.div_precincrement, 0, GET_ULONG, + REQUIRED_ARG, 4, 0, DECIMAL_MAX_SCALE, 0, 0, 0}, {"expire_logs_days", OPT_EXPIRE_LOGS_DAYS, "If non-zero, binary logs will be purged after expire_logs_days " "days; possible purges happen at startup and at binary log rotation.", @@ -5846,6 +5816,10 @@ log and this option does nothing anymore.", (gptr*) &innobase_buffer_pool_size, (gptr*) &innobase_buffer_pool_size, 0, GET_LL, REQUIRED_ARG, 8*1024*1024L, 1024*1024L, LONGLONG_MAX, 0, 1024*1024L, 0}, + {"innodb_commit_concurrency", OPT_INNODB_THREAD_CONCURRENCY, + "Helps in performance tuning in heavily concurrent environments.", + (gptr*) &srv_commit_concurrency, (gptr*) &srv_commit_concurrency, + 0, GET_LONG, REQUIRED_ARG, 0, 0, 1000, 0, 1, 0}, {"innodb_concurrency_tickets", OPT_INNODB_CONCURRENCY_TICKETS, "Number of times a thread is allowed to enter InnoDB within the same \ SQL query after it has once got the ticket", @@ -5895,10 +5869,6 @@ log and this option does nothing anymore.", "Helps in performance tuning in heavily concurrent environments.", (gptr*) &srv_thread_concurrency, (gptr*) &srv_thread_concurrency, 0, GET_LONG, REQUIRED_ARG, 20, 1, 1000, 0, 1, 0}, - {"innodb_commit_concurrency", OPT_INNODB_THREAD_CONCURRENCY, - "Helps in performance tuning in heavily concurrent environments.", - (gptr*) &srv_commit_concurrency, (gptr*) &srv_commit_concurrency, - 0, GET_LONG, REQUIRED_ARG, 0, 0, 1000, 0, 1, 0}, {"innodb_thread_sleep_delay", OPT_INNODB_THREAD_SLEEP_DELAY, "Time of innodb thread sleeping before joining InnoDB queue (usec). Value 0" " disable a sleep", @@ -6019,6 +5989,11 @@ The minimum value for this variable is 4096.", (gptr*) &global_system_variables.max_sort_length, (gptr*) &max_system_variables.max_sort_length, 0, GET_ULONG, REQUIRED_ARG, 1024, 4, 8192*1024L, 0, 1, 0}, + {"max_sp_recursion_depth", OPT_MAX_SP_RECURSION_DEPTH, + "Maximum stored procedure recursion depth. (discussed with docs).", + (gptr*) &global_system_variables.max_sp_recursion_depth, + (gptr*) &max_system_variables.max_sp_recursion_depth, 0, GET_ULONG, + OPT_ARG, 0, 0, 255, 0, 1, 0 }, {"max_tmp_tables", OPT_MAX_TMP_TABLES, "Maximum number of temporary tables a client can keep open at a time.", (gptr*) &global_system_variables.max_tmp_tables, @@ -6183,21 +6158,11 @@ The minimum value for this variable is 4096.", (gptr*) &max_system_variables.read_rnd_buff_size, 0, GET_ULONG, REQUIRED_ARG, 256*1024L, IO_SIZE*2+MALLOC_OVERHEAD, ~0L, MALLOC_OVERHEAD, IO_SIZE, 0}, - {"div_precision_increment", OPT_DIV_PRECINCREMENT, - "Precision of the result of '/' operator will be increased on that value.", - (gptr*) &global_system_variables.div_precincrement, - (gptr*) &max_system_variables.div_precincrement, 0, GET_ULONG, - REQUIRED_ARG, 4, 0, DECIMAL_MAX_SCALE, 0, 0, 0}, {"record_buffer", OPT_RECORD_BUFFER, "Alias for read_buffer_size", (gptr*) &global_system_variables.read_buff_size, (gptr*) &max_system_variables.read_buff_size,0, GET_ULONG, REQUIRED_ARG, 128*1024L, IO_SIZE*2+MALLOC_OVERHEAD, ~0L, MALLOC_OVERHEAD, IO_SIZE, 0}, - {"max_sp_recursion_depth", OPT_MAX_SP_RECURSION_DEPTH, - "Maximum stored procedure recursion depth. (discussed with docs).", - (gptr*) &global_system_variables.max_sp_recursion_depth, - (gptr*) &max_system_variables.max_sp_recursion_depth, 0, GET_ULONG, - OPT_ARG, 0, 0, 255, 0, 1, 0 }, #ifdef HAVE_REPLICATION {"relay_log_purge", OPT_RELAY_LOG_PURGE, "0 = do not purge relay logs. 1 = purge them as soon as they are no more needed.", @@ -7070,6 +7035,7 @@ static void mysql_init_variables(void) max_system_variables.max_join_size= (ulonglong) HA_POS_ERROR; global_system_variables.old_passwords= 0; global_system_variables.old_alter_table= 0; + global_system_variables.binlog_format= BINLOG_FORMAT_UNSPEC; /* Default behavior for 4.1 and 5.0 is to treat NULL values as unequal when collecting index statistics for MyISAM tables. @@ -7314,18 +7280,19 @@ get_one_option(int optid, const struct my_option *opt __attribute__((unused)), #ifdef HAVE_ROW_BASED_REPLICATION fprintf(stderr, "Unknown binary log format: '%s' " - "(should be '%s' or '%s')\n", + "(should be one of '%s', '%s', '%s')\n", argument, - binlog_format_names[BF_STMT], - binlog_format_names[BF_ROW]); + binlog_format_names[BINLOG_FORMAT_STMT], + binlog_format_names[BINLOG_FORMAT_ROW], + binlog_format_names[BINLOG_FORMAT_MIXED]); #else fprintf(stderr, "Unknown binary log format: '%s' (only legal value is '%s')\n", - argument, binlog_format_names[BF_STMT]); + argument, binlog_format_names[BINLOG_FORMAT_STMT]); #endif exit(1); } - opt_binlog_format_id= (enum binlog_format)(id-1); + global_system_variables.binlog_format= id-1; break; } case (int)OPT_BINLOG_DO_DB: diff --git a/sql/net_serv.cc b/sql/net_serv.cc index ef56f0d77e2..c80bb8bad9a 100644 --- a/sql/net_serv.cc +++ b/sql/net_serv.cc @@ -208,23 +208,44 @@ my_bool net_realloc(NET *net, ulong length) RETURN VALUES 0 No data to read 1 Data or EOF to read + -1 Don't know if data is ready or not */ -static my_bool net_data_is_ready(my_socket sd) +static int net_data_is_ready(my_socket sd) { +#ifdef HAVE_POLL + struct pollfd ufds; + int res; + + ufds.fd= sd; + ufds.events= POLLIN | POLLPRI; + if (!(res= poll(&ufds, 1, 0))) + return 0; + if (res < 0 || !(ufds.revents & (POLLIN | POLLPRI))) + return 0; + return 1; +#else fd_set sfds; struct timeval tv; int res; +#ifndef __WIN__ + /* Windows uses an _array_ of 64 fd's as default, so it's safe */ + if (sd >= FD_SETSIZE) + return -1; +#define NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE +#endif + FD_ZERO(&sfds); FD_SET(sd, &sfds); tv.tv_sec= tv.tv_usec= 0; if ((res= select(sd+1, &sfds, NULL, NULL, &tv)) < 0) - return FALSE; + return 0; else return test(res ? FD_ISSET(sd, &sfds) : 0); +#endif } @@ -251,10 +272,10 @@ static my_bool net_data_is_ready(my_socket sd) void net_clear(NET *net) { - int count; + int count, ready; DBUG_ENTER("net_clear"); #if !defined(EMBEDDED_LIBRARY) - while(net_data_is_ready(net->vio->sd)) + while((ready= net_data_is_ready(net->vio->sd)) > 0) { /* The socket is ready */ if ((count= vio_read(net->vio, (char*) (net->buff), @@ -274,6 +295,22 @@ void net_clear(NET *net) break; } } +#ifdef NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE + /* 'net_data_is_ready' returned "don't know" */ + if (ready == -1) + { + /* Read unblocking to clear net */ + my_bool old_mode; + if (!vio_blocking(net->vio, FALSE, &old_mode)) + { + while ((count= vio_read(net->vio, (char*) (net->buff), + (uint32) net->max_packet)) > 0) + DBUG_PRINT("info",("skipped %d bytes from file: %s", + count, vio_description(net->vio))); + vio_blocking(net->vio, TRUE, &old_mode); + } + } +#endif #endif net->pkt_nr=net->compress_pkt_nr=0; /* Ready for new command */ net->write_pos=net->buff; diff --git a/sql/opt_range.cc b/sql/opt_range.cc index 1146ea2428d..e42be40be81 100644 --- a/sql/opt_range.cc +++ b/sql/opt_range.cc @@ -1601,6 +1601,8 @@ public: { return (void*) alloc_root(mem_root, (uint) size); } static void operator delete(void *ptr,size_t size) { TRASH(ptr, size); } static void operator delete(void *ptr, MEM_ROOT *mem_root) { /* Never called */ } + virtual ~TABLE_READ_PLAN() {} /* Remove gcc warning */ + }; class TRP_ROR_INTERSECT; @@ -1624,6 +1626,7 @@ public: TRP_RANGE(SEL_ARG *key_arg, uint idx_arg) : key(key_arg), key_idx(idx_arg) {} + virtual ~TRP_RANGE() {} /* Remove gcc warning */ QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows, MEM_ROOT *parent_alloc) @@ -1645,6 +1648,8 @@ public: class TRP_ROR_INTERSECT : public TABLE_READ_PLAN { public: + TRP_ROR_INTERSECT() {} /* Remove gcc warning */ + virtual ~TRP_ROR_INTERSECT() {} /* Remove gcc warning */ QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows, MEM_ROOT *parent_alloc); @@ -1666,6 +1671,8 @@ public: class TRP_ROR_UNION : public TABLE_READ_PLAN { public: + TRP_ROR_UNION() {} /* Remove gcc warning */ + virtual ~TRP_ROR_UNION() {} /* Remove gcc warning */ QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows, MEM_ROOT *parent_alloc); TABLE_READ_PLAN **first_ror; /* array of ptrs to plans for merged scans */ @@ -1682,6 +1689,8 @@ public: class TRP_INDEX_MERGE : public TABLE_READ_PLAN { public: + TRP_INDEX_MERGE() {} /* Remove gcc warning */ + virtual ~TRP_INDEX_MERGE() {} /* Remove gcc warning */ QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows, MEM_ROOT *parent_alloc); TRP_RANGE **range_scans; /* array of ptrs to plans of merged scans */ @@ -1731,6 +1740,7 @@ public: if (key_infix_len) memcpy(this->key_infix, key_infix_arg, key_infix_len); } + virtual ~TRP_GROUP_MIN_MAX() {} /* Remove gcc warning */ QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows, MEM_ROOT *parent_alloc); @@ -2979,7 +2989,7 @@ static bool create_partition_index_description(PART_PRUNE_PARAM *ppar) ppar->last_subpart_partno= used_subpart_fields?(int)(used_part_fields + used_subpart_fields - 1): -1; - if (is_sub_partitioned(part_info)) + if (part_info->is_sub_partitioned()) { ppar->mark_full_partition_used= mark_full_partition_used_with_parts; ppar->get_top_partition_id_func= part_info->get_part_partition_id; @@ -3108,7 +3118,7 @@ static void dbug_print_segment_range(SEL_ARG *arg, KEY_PART *part) fputs(" < ", DBUG_FILE); else fputs(" <= ", DBUG_FILE); - store_key_image_to_rec(part->field, (char*)(arg->min_value), part->length); + store_key_image_to_rec(part->field, (char*)(arg->max_value), part->length); dbug_print_field(part->field); } fputs("\n", DBUG_FILE); diff --git a/sql/parse_file.h b/sql/parse_file.h index afa88da2ead..0d5a215fe1a 100644 --- a/sql/parse_file.h +++ b/sql/parse_file.h @@ -49,6 +49,8 @@ struct File_option class Unknown_key_hook { public: + Unknown_key_hook() {} /* Remove gcc warning */ + virtual ~Unknown_key_hook() {} /* Remove gcc warning */ virtual bool process_unknown_string(char *&unknown_key, gptr base, MEM_ROOT *mem_root, char *end)= 0; }; @@ -59,6 +61,7 @@ public: class File_parser_dummy_hook: public Unknown_key_hook { public: + File_parser_dummy_hook() {} /* Remove gcc warning */ virtual bool process_unknown_string(char *&unknown_key, gptr base, MEM_ROOT *mem_root, char *end); }; diff --git a/sql/partition_element.h b/sql/partition_element.h new file mode 100644 index 00000000000..8a11c332897 --- /dev/null +++ b/sql/partition_element.h @@ -0,0 +1,66 @@ +/* Copyright (C) 2000,200666666 MySQL AB & MySQL Finland AB & TCX DataKonsult 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 */ + +/** + * An enum and a struct to handle partitioning and subpartitioning. + */ +enum partition_type { + NOT_A_PARTITION= 0, + RANGE_PARTITION, + HASH_PARTITION, + LIST_PARTITION +}; + +enum partition_state { + PART_NORMAL= 0, + PART_IS_DROPPED= 1, + PART_TO_BE_DROPPED= 2, + PART_TO_BE_ADDED= 3, + PART_TO_BE_REORGED= 4, + PART_REORGED_DROPPED= 5, + PART_CHANGED= 6, + PART_IS_CHANGED= 7, + PART_IS_ADDED= 8 +}; + +class partition_element :public Sql_alloc { +public: + List<partition_element> subpartitions; + List<longlong> list_val_list; + ulonglong part_max_rows; + ulonglong part_min_rows; + char *partition_name; + char *tablespace_name; + longlong range_value; + char* part_comment; + char* data_file_name; + char* index_file_name; + handlerton *engine_type; + enum partition_state part_state; + uint16 nodegroup_id; + + partition_element() + : part_max_rows(0), part_min_rows(0), partition_name(NULL), + tablespace_name(NULL), range_value(0), part_comment(NULL), + data_file_name(NULL), index_file_name(NULL), + engine_type(NULL),part_state(PART_NORMAL), + nodegroup_id(UNDEF_NODEGROUP) + { + subpartitions.empty(); + list_val_list.empty(); + } + ~partition_element() {} +}; diff --git a/sql/partition_info.cc b/sql/partition_info.cc new file mode 100644 index 00000000000..66e0d366116 --- /dev/null +++ b/sql/partition_info.cc @@ -0,0 +1,349 @@ +/* Copyright (C) 2006 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 */ + +/* Some general useful functions */ + +#ifdef USE_PRAGMA_IMPLEMENTATION +#pragma implementation +#endif + +#include "mysql_priv.h" +#include "ha_partition.h" + +#ifdef WITH_PARTITION_STORAGE_ENGINE + + +/* + Create a memory area where default partition names are stored and fill it + up with the names. + + SYNOPSIS + create_default_partition_names() + part_no Partition number for subparts + no_parts Number of partitions + start_no Starting partition number + subpart Is it subpartitions + + RETURN VALUE + A pointer to the memory area of the default partition names + + DESCRIPTION + A support routine for the partition code where default values are + generated. + The external routine needing this code is check_partition_info +*/ + +#define MAX_PART_NAME_SIZE 16 + +char *partition_info::create_default_partition_names(uint part_no, uint no_parts, + uint start_no, bool is_subpart) +{ + char *ptr= sql_calloc(no_parts*MAX_PART_NAME_SIZE); + char *move_ptr= ptr; + uint i= 0; + DBUG_ENTER("create_default_partition_names"); + + if (likely(ptr != 0)) + { + do + { + if (is_subpart) + my_sprintf(move_ptr, (move_ptr,"p%usp%u", part_no, (start_no + i))); + else + my_sprintf(move_ptr, (move_ptr,"p%u", (start_no + i))); + move_ptr+=MAX_PART_NAME_SIZE; + } while (++i < no_parts); + } + else + { + mem_alloc_error(no_parts*MAX_PART_NAME_SIZE); + } + DBUG_RETURN(ptr); +} + + +/* + Set up all the default partitions not set-up by the user in the SQL + statement. Also perform a number of checks that the user hasn't tried + to use default values where no defaults exists. + + SYNOPSIS + set_up_default_partitions() + part_info The reference to all partition information + file A reference to a handler of the table + max_rows Maximum number of rows stored in the table + start_no Starting partition number + + RETURN VALUE + TRUE Error, attempted default values not possible + FALSE Ok, default partitions set-up + + DESCRIPTION + The routine uses the underlying handler of the partitioning to define + the default number of partitions. For some handlers this requires + knowledge of the maximum number of rows to be stored in the table. + This routine only accepts HASH and KEY partitioning and thus there is + no subpartitioning if this routine is successful. + The external routine needing this code is check_partition_info +*/ + +bool partition_info::set_up_default_partitions(handler *file, ulonglong max_rows, + uint start_no) +{ + uint i; + char *default_name; + bool result= TRUE; + DBUG_ENTER("partition_info::set_up_default_partitions"); + + if (part_type != HASH_PARTITION) + { + const char *error_string; + if (part_type == RANGE_PARTITION) + error_string= partition_keywords[PKW_RANGE].str; + else + error_string= partition_keywords[PKW_LIST].str; + my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), error_string); + goto end; + } + if (no_parts == 0) + no_parts= file->get_default_no_partitions(max_rows); + if (unlikely(no_parts > MAX_PARTITIONS)) + { + my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0)); + goto end; + } + if (unlikely((!(default_name= create_default_partition_names(0, no_parts, + start_no, + FALSE))))) + goto end; + i= 0; + do + { + partition_element *part_elem= new partition_element(); + if (likely(part_elem != 0 && + (!partitions.push_back(part_elem)))) + { + part_elem->engine_type= default_engine_type; + part_elem->partition_name= default_name; + default_name+=MAX_PART_NAME_SIZE; + } + else + { + mem_alloc_error(sizeof(partition_element)); + goto end; + } + } while (++i < no_parts); + result= FALSE; +end: + DBUG_RETURN(result); +} + + +/* + Set up all the default subpartitions not set-up by the user in the SQL + statement. Also perform a number of checks that the default partitioning + becomes an allowed partitioning scheme. + + SYNOPSIS + set_up_default_subpartitions() + part_info The reference to all partition information + file A reference to a handler of the table + max_rows Maximum number of rows stored in the table + + RETURN VALUE + TRUE Error, attempted default values not possible + FALSE Ok, default partitions set-up + + DESCRIPTION + The routine uses the underlying handler of the partitioning to define + the default number of partitions. For some handlers this requires + knowledge of the maximum number of rows to be stored in the table. + This routine is only called for RANGE or LIST partitioning and those + need to be specified so only subpartitions are specified. + The external routine needing this code is check_partition_info +*/ + +bool partition_info::set_up_default_subpartitions(handler *file, + ulonglong max_rows) +{ + uint i, j; + char *default_name, *name_ptr; + bool result= TRUE; + partition_element *part_elem; + List_iterator<partition_element> part_it(partitions); + DBUG_ENTER("partition_info::set_up_default_subpartitions"); + + if (no_subparts == 0) + no_subparts= file->get_default_no_partitions(max_rows); + if (unlikely((no_parts * no_subparts) > MAX_PARTITIONS)) + { + my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0)); + goto end; + } + i= 0; + do + { + part_elem= part_it++; + j= 0; + name_ptr= create_default_partition_names(i, no_subparts, (uint)0, TRUE); + if (unlikely(!name_ptr)) + goto end; + do + { + partition_element *subpart_elem= new partition_element(); + if (likely(subpart_elem != 0 && + (!part_elem->subpartitions.push_back(subpart_elem)))) + { + subpart_elem->engine_type= default_engine_type; + subpart_elem->partition_name= name_ptr; + name_ptr+= MAX_PART_NAME_SIZE; + } + else + { + mem_alloc_error(sizeof(partition_element)); + goto end; + } + } while (++j < no_subparts); + } while (++i < no_parts); + result= FALSE; +end: + DBUG_RETURN(result); +} + + +/* + Support routine for check_partition_info + + SYNOPSIS + set_up_defaults_for_partitioning() + part_info The reference to all partition information + file A reference to a handler of the table + max_rows Maximum number of rows stored in the table + start_no Starting partition number + + RETURN VALUE + TRUE Error, attempted default values not possible + FALSE Ok, default partitions set-up + + DESCRIPTION + Set up defaults for partition or subpartition (cannot set-up for both, + this will return an error. +*/ + +bool partition_info::set_up_defaults_for_partitioning(handler *file, + ulonglong max_rows, + uint start_no) +{ + DBUG_ENTER("partition_info::set_up_defaults_for_partitioning"); + + if (!default_partitions_setup) + { + default_partitions_setup= TRUE; + if (use_default_partitions) + DBUG_RETURN(set_up_default_partitions(file, max_rows, start_no)); + if (is_sub_partitioned() && + use_default_subpartitions) + DBUG_RETURN(set_up_default_subpartitions(file, max_rows)); + } + DBUG_RETURN(FALSE); +} + + +/* + A support function to check if a partition element's name is unique + + SYNOPSIS + has_unique_name() + partition_element element to check + + RETURN VALUES + TRUE Has unique name + FALSE Doesn't +*/ + +bool partition_info::has_unique_name(partition_element *element) +{ + DBUG_ENTER("partition_info::has_unique_name"); + + const char *name_to_check= element->partition_name; + List_iterator<partition_element> parts_it(partitions); + + partition_element *el; + while ((el= (parts_it++))) + { + if (!(my_strcasecmp(system_charset_info, el->partition_name, + name_to_check)) && el != element) + DBUG_RETURN(FALSE); + + if (!el->subpartitions.is_empty()) + { + partition_element *sub_el; + List_iterator<partition_element> subparts_it(el->subpartitions); + while ((sub_el= (subparts_it++))) + { + if (!(my_strcasecmp(system_charset_info, sub_el->partition_name, + name_to_check)) && sub_el != element) + DBUG_RETURN(FALSE); + } + } + } + DBUG_RETURN(TRUE); +} + + +/* + A support function to check partition names for duplication in a + partitioned table + + SYNOPSIS + has_unique_names() + + RETURN VALUES + TRUE Has unique part and subpart names + FALSE Doesn't + + DESCRIPTION + Checks that the list of names in the partitions doesn't contain any + duplicated names. +*/ + +char *partition_info::has_unique_names() +{ + DBUG_ENTER("partition_info::has_unique_names"); + + List_iterator<partition_element> parts_it(partitions); + + partition_element *el; + while ((el= (parts_it++))) + { + if (! has_unique_name(el)) + DBUG_RETURN(el->partition_name); + + if (!el->subpartitions.is_empty()) + { + List_iterator<partition_element> subparts_it(el->subpartitions); + partition_element *subel; + while ((subel= (subparts_it++))) + { + if (! has_unique_name(subel)) + DBUG_RETURN(subel->partition_name); + } + } + } + DBUG_RETURN(NULL); +} + +#endif /* WITH_PARTITION_STORAGE_ENGINE */ diff --git a/sql/partition_info.h b/sql/partition_info.h new file mode 100644 index 00000000000..c8cb4ae407a --- /dev/null +++ b/sql/partition_info.h @@ -0,0 +1,271 @@ +/* Copyright (C) 2000,2006 MySQL AB & MySQL Finland AB & TCX DataKonsult 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 */ + +#ifdef USE_PRAGMA_INTERFACE +#pragma interface /* gcc class implementation */ +#endif + +#include "partition_element.h" + +class partition_info; + +/* Some function typedefs */ +typedef int (*get_part_id_func)(partition_info *part_info, + uint32 *part_id, + longlong *func_value); +typedef uint32 (*get_subpart_id_func)(partition_info *part_info); + + + +class partition_info : public Sql_alloc +{ +public: + /* + * Here comes a set of definitions needed for partitioned table handlers. + */ + List<partition_element> partitions; + List<partition_element> temp_partitions; + + List<char> part_field_list; + List<char> subpart_field_list; + + /* + If there is no subpartitioning, use only this func to get partition ids. + If there is subpartitioning, use the this func to get partition id when + you have both partition and subpartition fields. + */ + get_part_id_func get_partition_id; + + /* Get partition id when we don't have subpartition fields */ + get_part_id_func get_part_partition_id; + + /* + Get subpartition id when we have don't have partition fields by we do + have subpartition ids. + Mikael said that for given constant tuple + {subpart_field1, ..., subpart_fieldN} the subpartition id will be the + same in all subpartitions + */ + get_subpart_id_func get_subpartition_id; + + /* NULL-terminated array of fields used in partitioned expression */ + Field **part_field_array; + /* NULL-terminated array of fields used in subpartitioned expression */ + Field **subpart_field_array; + + /* + Array of all fields used in partition and subpartition expression, + without duplicates, NULL-terminated. + */ + Field **full_part_field_array; + + Item *part_expr; + Item *subpart_expr; + + Item *item_free_list; + + /* + A bitmap of partitions used by the current query. + Usage pattern: + * The handler->extra(HA_EXTRA_RESET) call at query start/end sets all + partitions to be unused. + * Before index/rnd_init(), partition pruning code sets the bits for used + partitions. + */ + MY_BITMAP used_partitions; + + union { + longlong *range_int_array; + LIST_PART_ENTRY *list_array; + }; + + /******************************************** + * INTERVAL ANALYSIS + ********************************************/ + /* + Partitioning interval analysis function for partitioning, or NULL if + interval analysis is not supported for this kind of partitioning. + */ + get_partitions_in_range_iter get_part_iter_for_interval; + /* + Partitioning interval analysis function for subpartitioning, or NULL if + interval analysis is not supported for this kind of partitioning. + */ + get_partitions_in_range_iter get_subpart_iter_for_interval; + + /* + Valid iff + get_part_iter_for_interval=get_part_iter_for_interval_via_walking: + controls how we'll process "field < C" and "field > C" intervals. + If the partitioning function F is strictly increasing, then for any x, y + "x < y" => "F(x) < F(y)" (*), i.e. when we get interval "field < C" + we can perform partition pruning on the equivalent "F(field) < F(C)". + + If the partitioning function not strictly increasing (it is simply + increasing), then instead of (*) we get "x < y" => "F(x) <= F(y)" + i.e. for interval "field < C" we can perform partition pruning for + "F(field) <= F(C)". + */ + bool range_analysis_include_bounds; + /******************************************** + * INTERVAL ANALYSIS ENDS + ********************************************/ + + char* part_info_string; + + char *part_func_string; + char *subpart_func_string; + + uchar *part_state; + + partition_element *curr_part_elem; + partition_element *current_partition; + /* + These key_map's are used for Partitioning to enable quick decisions + on whether we can derive more information about which partition to + scan just by looking at what index is used. + */ + key_map all_fields_in_PF, all_fields_in_PPF, all_fields_in_SPF; + key_map some_fields_in_PF; + + handlerton *default_engine_type; + Item_result part_result_type; + partition_type part_type; + partition_type subpart_type; + + uint part_info_len; + uint part_state_len; + uint part_func_len; + uint subpart_func_len; + + uint no_parts; + uint no_subparts; + uint count_curr_subparts; + + uint part_error_code; + + uint no_list_values; + + uint no_part_fields; + uint no_subpart_fields; + uint no_full_part_fields; + + /* + This variable is used to calculate the partition id when using + LINEAR KEY/HASH. This functionality is kept in the MySQL Server + but mainly of use to handlers supporting partitioning. + */ + uint16 linear_hash_mask; + + bool use_default_partitions; + bool use_default_no_partitions; + bool use_default_subpartitions; + bool use_default_no_subpartitions; + bool default_partitions_setup; + bool defined_max_value; + bool list_of_part_fields; + bool list_of_subpart_fields; + bool linear_hash_ind; + bool fixed; + bool from_openfrm; + + partition_info() + : get_partition_id(NULL), get_part_partition_id(NULL), + get_subpartition_id(NULL), + part_field_array(NULL), subpart_field_array(NULL), + full_part_field_array(NULL), + part_expr(NULL), subpart_expr(NULL), item_free_list(NULL), + list_array(NULL), + part_info_string(NULL), + part_func_string(NULL), subpart_func_string(NULL), + part_state(NULL), + curr_part_elem(NULL), current_partition(NULL), + default_engine_type(NULL), + part_result_type(INT_RESULT), + part_type(NOT_A_PARTITION), subpart_type(NOT_A_PARTITION), + part_info_len(0), part_state_len(0), + part_func_len(0), subpart_func_len(0), + no_parts(0), no_subparts(0), + count_curr_subparts(0), part_error_code(0), + no_list_values(0), no_part_fields(0), no_subpart_fields(0), + no_full_part_fields(0), linear_hash_mask(0), + use_default_partitions(TRUE), + use_default_no_partitions(TRUE), + use_default_subpartitions(TRUE), + use_default_no_subpartitions(TRUE), + default_partitions_setup(FALSE), + defined_max_value(FALSE), + list_of_part_fields(FALSE), list_of_subpart_fields(FALSE), + linear_hash_ind(FALSE), + fixed(FALSE), + from_openfrm(FALSE) + { + all_fields_in_PF.clear_all(); + all_fields_in_PPF.clear_all(); + all_fields_in_SPF.clear_all(); + some_fields_in_PF.clear_all(); + partitions.empty(); + temp_partitions.empty(); + part_field_list.empty(); + subpart_field_list.empty(); + } + ~partition_info() {} + + /* Answers the question if subpartitioning is used for a certain table */ + bool is_sub_partitioned() + { + return (subpart_type == NOT_A_PARTITION ? FALSE : TRUE); + } + + /* Returns the total number of partitions on the leaf level */ + uint get_tot_partitions() + { + return no_parts * (is_sub_partitioned() ? no_subparts : 1); + } + + bool set_up_defaults_for_partitioning(handler *file, ulonglong max_rows, + uint start_no); + char *has_unique_names(); +private: + bool set_up_default_partitions(handler *file, ulonglong max_rows, + uint start_no); + bool set_up_default_subpartitions(handler *file, ulonglong max_rows); + char *create_default_partition_names(uint part_no, uint no_parts, + uint start_no, bool is_subpart); + bool has_unique_name(partition_element *element); +}; + +uint32 get_next_partition_id_range(struct st_partition_iter* part_iter); + +/* Initialize the iterator to return a single partition with given part_id */ + +static inline void init_single_partition_iterator(uint32 part_id, + PARTITION_ITERATOR *part_iter) +{ + part_iter->part_nums.start= part_id; + part_iter->part_nums.end= part_id+1; + part_iter->get_next= get_next_partition_id_range; +} + +/* Initialize the iterator to enumerate all partitions */ +static inline +void init_all_partitions_iterator(partition_info *part_info, + PARTITION_ITERATOR *part_iter) +{ + part_iter->part_nums.start= 0; + part_iter->part_nums.end= part_info->no_parts; + part_iter->get_next= get_next_partition_id_range; +} diff --git a/sql/set_var.cc b/sql/set_var.cc index 12f3a61aa4e..bf3fdd8c8d7 100644 --- a/sql/set_var.cc +++ b/sql/set_var.cc @@ -141,6 +141,7 @@ static int check_log_update(THD *thd, set_var *var); static bool set_log_update(THD *thd, set_var *var); static int check_pseudo_thread_id(THD *thd, set_var *var); static bool set_log_bin(THD *thd, set_var *var); +void fix_binlog_format_after_update(THD *thd, enum_var_type type); static void fix_low_priority_updates(THD *thd, enum_var_type type); static int check_tx_isolation(THD *thd, set_var *var); static void fix_tx_isolation(THD *thd, enum_var_type type); @@ -185,6 +186,8 @@ sys_var_bool_ptr sys_automatic_sp_privileges("automatic_sp_privileges", sys_var_long_ptr sys_binlog_cache_size("binlog_cache_size", &binlog_cache_size); +sys_var_thd_binlog_format sys_binlog_format("binlog_format", + &SV::binlog_format); sys_var_thd_ulong sys_bulk_insert_buff_size("bulk_insert_buffer_size", &SV::bulk_insert_buff_size); sys_var_character_set_server sys_character_set_server("character_set_server"); @@ -653,11 +656,11 @@ static int show_slave_skip_errors(THD *thd, SHOW_VAR *var, char *buff) var->value= buff; if (!use_slave_mask || bitmap_is_clear_all(&slave_error_mask)) { - var->value= "OFF"; + var->value= const_cast<char *>("OFF"); } else if (bitmap_is_set_all(&slave_error_mask)) { - var->value= "ALL"; + var->value= const_cast<char *>("ALL"); } else { @@ -706,7 +709,7 @@ SHOW_VAR init_vars[]= { {"bdb_shared_data", (char*) &berkeley_shared_data, SHOW_BOOL}, {"bdb_tmpdir", (char*) &berkeley_tmpdir, SHOW_CHAR_PTR}, {sys_binlog_cache_size.name,(char*) &sys_binlog_cache_size, SHOW_SYS}, - {"binlog_format", (char*) &opt_binlog_format, SHOW_CHAR_PTR}, + {sys_binlog_format.name, (char*) &sys_binlog_format, SHOW_SYS}, {sys_bulk_insert_buff_size.name,(char*) &sys_bulk_insert_buff_size,SHOW_SYS}, {sys_character_set_client.name,(char*) &sys_character_set_client, SHOW_SYS}, {sys_character_set_connection.name,(char*) &sys_character_set_connection,SHOW_SYS}, @@ -1243,6 +1246,54 @@ extern void fix_delay_key_write(THD *thd, enum_var_type type) } } + +bool sys_var_thd_binlog_format::is_readonly() const +{ + /* + Under certain circumstances, the variable is read-only (unchangeable): + */ + THD *thd= current_thd; + /* + If RBR and open temporary tables, their CREATE TABLE may not be in the + binlog, so we can't toggle to SBR in this connection. + The test below will also prevent SET GLOBAL, well it was not easy to test + if global or not here. + And this test will also prevent switching from RBR to RBR (a no-op which + should not happen too often). + */ + if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW) && + thd->temporary_tables) + { + my_error(ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR, MYF(0)); + return 1; + } + /* + if in a stored function, it's too late to change mode + */ + if (thd->spcont && thd->prelocked_mode) + { + DBUG_ASSERT(thd->variables.binlog_format != BINLOG_FORMAT_ROW); + my_error(ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT, MYF(0)); + return 1; + } +#ifdef HAVE_NDB_BINLOG + /* + Cluster does not support changing the binlog format on the fly yet. + */ + if (opt_bin_log && (have_ndbcluster == SHOW_OPTION_YES)) + { + my_error(ER_NDB_CANT_SWITCH_BINLOG_FORMAT, MYF(0)); + return 1; + } +#endif + return sys_var_thd_enum::is_readonly(); +} + +void fix_binlog_format_after_update(THD *thd, enum_var_type type) +{ + thd->reset_current_stmt_binlog_row_based(); +} + static void fix_max_binlog_size(THD *thd, enum_var_type type) { DBUG_ENTER("fix_max_binlog_size"); @@ -2724,7 +2775,7 @@ static bool set_log_update(THD *thd, set_var *var) See sql/mysqld.cc/, comments in function init_server_components() for an explaination of the different warnings we send below */ - + if (opt_sql_bin_update) { ((sys_var_thd_bit*) var->var)->bit_flag|= (OPTION_BIN_LOG | @@ -3205,10 +3256,7 @@ bool sys_var_thd_storage_engine::update(THD *thd, set_var *var) void sys_var_thd_table_type::warn_deprecated(THD *thd) { - push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, - ER_WARN_DEPRECATED_SYNTAX, - ER(ER_WARN_DEPRECATED_SYNTAX), "table_type", - "storage_engine"); + WARN_DEPRECATED(thd, "5.2", "table_type", "'storage_engine'"); } void sys_var_thd_table_type::set_default(THD *thd, enum_var_type type) @@ -3465,10 +3513,8 @@ bool process_key_caches(int (* func) (const char *name, KEY_CACHE *)) void sys_var_trust_routine_creators::warn_deprecated(THD *thd) { - push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, - ER_WARN_DEPRECATED_SYNTAX, - ER(ER_WARN_DEPRECATED_SYNTAX), "log_bin_trust_routine_creators", - "log_bin_trust_function_creators"); + WARN_DEPRECATED(thd, "5.2", "log_bin_trust_routine_creators", + "'log_bin_trust_function_creators'"); } void sys_var_trust_routine_creators::set_default(THD *thd, enum_var_type type) diff --git a/sql/set_var.h b/sql/set_var.h index 0961f6d4325..f62d6ce8d2a 100644 --- a/sql/set_var.h +++ b/sql/set_var.h @@ -826,6 +826,18 @@ public: bool update(THD *thd, set_var *var); }; +extern void fix_binlog_format_after_update(THD *thd, enum_var_type type); + +class sys_var_thd_binlog_format :public sys_var_thd_enum +{ +public: + sys_var_thd_binlog_format(const char *name_arg, ulong SV::*offset_arg) + :sys_var_thd_enum(name_arg, offset_arg, + &binlog_format_typelib, + fix_binlog_format_after_update) + {}; + bool is_readonly() const; +}; /**************************************************************************** Classes for parsing of the SET command diff --git a/sql/share/errmsg.txt b/sql/share/errmsg.txt index 35ff2e4222b..d163da30e95 100644 --- a/sql/share/errmsg.txt +++ b/sql/share/errmsg.txt @@ -5018,7 +5018,7 @@ ER_UNKNOWN_STORAGE_ENGINE 42000 ger "Unbekannte Speicher-Engine '%s'" por "Motor de tabela desconhecido '%s'" spa "Desconocido motor de tabla '%s'" -ER_WARN_DEPRECATED_SYNTAX +ER_UNUSED_1 eng "'%s' is deprecated; use '%s' instead" ger "'%s' ist veraltet. Bitte benutzen Sie '%s'" por "'%s' é desatualizado. Use '%s' em seu lugar" @@ -5660,8 +5660,8 @@ ER_PARTITION_NOT_DEFINED_ERROR eng "For the partitioned engine it is necessary to define all %-.64s" swe "För partitioneringsmotorn så är det nödvändigt att definiera alla %-.64s" ER_TOO_MANY_PARTITIONS_ERROR - eng "Too many partitions were defined" - swe "För många partitioner definierades" + eng "Too many partitions (including subpartitions) were defined" + swe "För många partitioner (inkluderande subpartitioner) definierades" ER_SUBPARTITION_ERROR eng "It is only possible to mix RANGE/LIST partitioning with HASH/KEY partitioning for subpartitioning" swe "Det är endast möjligt att blanda RANGE/LIST partitionering med HASH/KEY partitionering för subpartitionering" @@ -5781,7 +5781,7 @@ ER_EVENT_NEITHER_M_EXPR_NOR_M_AT eng "No datetime expression provided" ER_COL_COUNT_DOESNT_MATCH_CORRUPTED eng "Column count of mysql.%s is wrong. Expected %d, found %d. Table probably corrupted" -ER_EVENT_CANNOT_LOAD_FROM_TABLE +ER_CANNOT_LOAD_FROM_TABLE eng "Cannot load from mysql.%s. Table probably corrupted. See error log." ER_EVENT_CANNOT_DELETE eng "Failed to delete the event from mysql.event" @@ -5810,6 +5810,14 @@ ER_ILLEGAL_HA_CREATE_OPTION eng "Table storage engine '%-.64s' does not support the create option '%.64s'" ER_CANT_CHANGE_TX_ISOLATION 25001 eng "Transaction isolation level can't be changed while a transaction is in progress" -ER_WARN_DEPRECATED_STATEMENT - eng "The '%s' statement is deprecated and will be removed in MySQL %s. Please use client programs (e.g. %s) instead." +ER_WARN_DEPRECATED + eng "The syntax '%s' is deprecated and will be removed in MySQL %s. Please use %s instead." +ER_SP_NO_AGGREGATE 42000 + eng "AGGREGATE is not supported for stored functions" +ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR + eng "Cannot switch out of the row-based binary log format when the session has open temporary tables" +ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT + eng "Cannot change the binary logging format inside a stored function or trigger" +ER_NDB_CANT_SWITCH_BINLOG_FORMAT + eng "The NDB cluster engine does not support changing the binlog format on the fly yet" diff --git a/sql/sp.cc b/sql/sp.cc index 4838f839b4e..481d81edfe4 100644 --- a/sql/sp.cc +++ b/sql/sp.cc @@ -1013,6 +1013,7 @@ sp_exist_routines(THD *thd, TABLE_LIST *routines, bool any, bool no_error) { TABLE_LIST *routine; bool result= 0; + bool sp_object_found; DBUG_ENTER("sp_exists_routine"); for (routine= routines; routine; routine= routine->next_global) { @@ -1025,10 +1026,12 @@ sp_exist_routines(THD *thd, TABLE_LIST *routines, bool any, bool no_error) lex_name.str= thd->strmake(routine->table_name, lex_name.length); name= new sp_name(lex_db, lex_name); name->init_qname(thd); - if (sp_find_routine(thd, TYPE_ENUM_PROCEDURE, name, - &thd->sp_proc_cache, FALSE) != NULL || - sp_find_routine(thd, TYPE_ENUM_FUNCTION, name, - &thd->sp_func_cache, FALSE) != NULL) + sp_object_found= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, name, + &thd->sp_proc_cache, FALSE) != NULL || + sp_find_routine(thd, TYPE_ENUM_FUNCTION, name, + &thd->sp_func_cache, FALSE) != NULL; + mysql_reset_errors(thd, TRUE); + if (sp_object_found) { if (any) DBUG_RETURN(1); diff --git a/sql/sp_head.cc b/sql/sp_head.cc index 1f29468a61f..d7490a5ac8e 100644 --- a/sql/sp_head.cc +++ b/sql/sp_head.cc @@ -1301,7 +1301,7 @@ sp_head::execute_function(THD *thd, Item **argp, uint argcount, each substatement be binlogged its way. */ need_binlog_call= mysql_bin_log.is_open() && - (thd->options & OPTION_BIN_LOG) && !binlog_row_based; + (thd->options & OPTION_BIN_LOG) && !thd->current_stmt_binlog_row_based; if (need_binlog_call) { reset_dynamic(&thd->user_var_events); @@ -1412,6 +1412,8 @@ sp_head::execute_procedure(THD *thd, List<Item> *args) uint params = m_pcont->context_pvars(); sp_rcontext *save_spcont, *octx; sp_rcontext *nctx = NULL; + bool save_enable_slow_log= false; + bool save_log_general= false; DBUG_ENTER("sp_head::execute_procedure"); DBUG_PRINT("info", ("procedure %s", m_name.str)); @@ -1510,12 +1512,28 @@ sp_head::execute_procedure(THD *thd, List<Item> *args) DBUG_PRINT("info",(" %.*s: eval args done", m_name.length, m_name.str)); } - + if (!(m_flags & LOG_SLOW_STATEMENTS) && thd->enable_slow_log) + { + DBUG_PRINT("info", ("Disabling slow log for the execution")); + save_enable_slow_log= true; + thd->enable_slow_log= FALSE; + } + if (!(m_flags & LOG_GENERAL_LOG) && !(thd->options & OPTION_LOG_OFF)) + { + DBUG_PRINT("info", ("Disabling general log for the execution")); + save_log_general= true; + /* disable this bit */ + thd->options |= OPTION_LOG_OFF; + } thd->spcont= nctx; - + if (!err_status) err_status= execute(thd); + if (save_log_general) + thd->options &= ~OPTION_LOG_OFF; + if (save_enable_slow_log) + thd->enable_slow_log= true; /* In the case when we weren't able to employ reuse mechanism for OUT/INOUT paranmeters, we should reallocate memory. This @@ -1621,6 +1639,8 @@ sp_head::reset_lex(THD *thd) sublex->trg_table_fields.empty(); sublex->sp_lex_in_use= FALSE; + sublex->in_comment= oldlex->in_comment; + /* Reset type info. */ sublex->charset= NULL; @@ -2292,10 +2312,15 @@ sp_instr_stmt::execute(THD *thd, uint *nextp) (the order of query cache and subst_spvars calls is irrelevant because queries with SP vars can't be cached) */ + if (unlikely((thd->options & OPTION_LOG_OFF)==0)) + general_log_print(thd, COM_QUERY, "%s", thd->query); + if (query_cache_send_result_to_client(thd, thd->query, thd->query_length) <= 0) { res= m_lex_keeper.reset_lex_and_exec_core(thd, nextp, FALSE, this); + if (!res && unlikely(thd->enable_slow_log)) + log_slow_statement(thd); query_cache_end_of_result(thd); } else diff --git a/sql/sp_head.h b/sql/sp_head.h index a637c466041..472e5343991 100644 --- a/sql/sp_head.h +++ b/sql/sp_head.h @@ -124,7 +124,9 @@ public: IS_INVOKED= 32, // Is set if this sp_head is being used HAS_SET_AUTOCOMMIT_STMT= 64,// Is set if a procedure with 'set autocommit' /* Is set if a procedure with COMMIT (implicit or explicit) | ROLLBACK */ - HAS_COMMIT_OR_ROLLBACK= 128 + HAS_COMMIT_OR_ROLLBACK= 128, + LOG_SLOW_STATEMENTS= 256, // Used by events + LOG_GENERAL_LOG= 512 // Used by events }; /* TYPE_ENUM_FUNCTION, TYPE_ENUM_PROCEDURE or TYPE_ENUM_TRIGGER */ diff --git a/sql/sp_rcontext.h b/sql/sp_rcontext.h index c3c05228eef..e7393902e72 100644 --- a/sql/sp_rcontext.h +++ b/sql/sp_rcontext.h @@ -268,6 +268,7 @@ class Select_fetch_into_spvars: public select_result_interceptor List<struct sp_pvar> *spvar_list; uint field_count; public: + Select_fetch_into_spvars() {} /* Remove gcc warning */ uint get_field_count() { return field_count; } void set_spvar_list(List<struct sp_pvar> *vars) { spvar_list= vars; } diff --git a/sql/spatial.h b/sql/spatial.h index 527dc750bdc..a6f74a1ada0 100644 --- a/sql/spatial.h +++ b/sql/spatial.h @@ -165,6 +165,8 @@ struct Geometry_buffer; class Geometry { public: + Geometry() {} /* Remove gcc warning */ + virtual ~Geometry() {} /* Remove gcc warning */ static void *operator new(size_t size, void *buffer) { return buffer; @@ -302,6 +304,8 @@ protected: class Gis_point: public Geometry { public: + Gis_point() {} /* Remove gcc warning */ + virtual ~Gis_point() {} /* Remove gcc warning */ uint32 get_data_size() const; bool init_from_wkt(Gis_read_stream *trs, String *wkb); uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); @@ -349,6 +353,8 @@ public: class Gis_line_string: public Geometry { public: + Gis_line_string() {} /* Remove gcc warning */ + virtual ~Gis_line_string() {} /* Remove gcc warning */ uint32 get_data_size() const; bool init_from_wkt(Gis_read_stream *trs, String *wkb); uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); @@ -375,6 +381,8 @@ public: class Gis_polygon: public Geometry { public: + Gis_polygon() {} /* Remove gcc warning */ + virtual ~Gis_polygon() {} /* Remove gcc warning */ uint32 get_data_size() const; bool init_from_wkt(Gis_read_stream *trs, String *wkb); uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); @@ -401,6 +409,8 @@ public: class Gis_multi_point: public Geometry { public: + Gis_multi_point() {} /* Remove gcc warning */ + virtual ~Gis_multi_point() {} /* Remove gcc warning */ uint32 get_data_size() const; bool init_from_wkt(Gis_read_stream *trs, String *wkb); uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); @@ -423,6 +433,8 @@ public: class Gis_multi_line_string: public Geometry { public: + Gis_multi_line_string() {} /* Remove gcc warning */ + virtual ~Gis_multi_line_string() {} /* Remove gcc warning */ uint32 get_data_size() const; bool init_from_wkt(Gis_read_stream *trs, String *wkb); uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); @@ -447,6 +459,8 @@ public: class Gis_multi_polygon: public Geometry { public: + Gis_multi_polygon() {} /* Remove gcc warning */ + virtual ~Gis_multi_polygon() {} /* Remove gcc warning */ uint32 get_data_size() const; bool init_from_wkt(Gis_read_stream *trs, String *wkb); uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); @@ -471,6 +485,8 @@ public: class Gis_geometry_collection: public Geometry { public: + Gis_geometry_collection() {} /* Remove gcc warning */ + virtual ~Gis_geometry_collection() {} /* Remove gcc warning */ uint32 get_data_size() const; bool init_from_wkt(Gis_read_stream *trs, String *wkb); uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index bebee7df8b2..3c2d1328a57 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -263,7 +263,9 @@ my_bool acl_init(bool dont_read_acl_tables) acl_cache= new hash_filo(ACL_CACHE_SIZE, 0, 0, (hash_get_key) acl_entry_get_key, - (hash_free_key) free, system_charset_info); + (hash_free_key) free, + /* Use the case sensitive "binary" charset */ + &my_charset_bin); if (dont_read_acl_tables) { DBUG_RETURN(0); /* purecov: tested */ @@ -471,10 +473,10 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) /* - if it is pre 5.1.4 privilege table then map CREATE privilege on + if it is pre 5.1.6 privilege table then map CREATE privilege on CREATE|ALTER|DROP|EXECUTE EVENT */ - if (table->s->fields <= 37 && (user.access & CREATE_ACL)) + if (table->s->fields <= 37 && (user.access & SUPER_ACL)) user.access|= EVENT_ACL; /* diff --git a/sql/sql_base.cc b/sql/sql_base.cc index 2d6576bff8b..26d81eccce6 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -313,6 +313,22 @@ TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key, conflicts */ (void) pthread_mutex_lock(&share->mutex); + + /* + We assign a new table id under the protection of the LOCK_open and + the share's own mutex. We do this insted of creating a new mutex + and using it for the sole purpose of serializing accesses to a + static variable, we assign the table id here. We assign it to the + share before inserting it into the table_def_cache to be really + sure that it cannot be read from the cache without having a table + id assigned. + + CAVEAT. This means that the table cannot be used for + binlogging/replication purposes, unless get_table_share() has been + called directly or indirectly. + */ + assign_new_table_id(share); + if (my_hash_insert(&table_def_cache, (byte*) share)) { #ifdef NOT_YET @@ -917,6 +933,15 @@ bool close_cached_tables(THD *thd, bool if_wait_for_refresh, DESCRIPTION Marks all tables in the list which were used by current substatement (they are marked by its query_id) as free for reuse. + + NOTE + The reason we reset query_id is that it's not enough to just test + if table->query_id != thd->query_id to know if a table is in use. + + For example + SELECT f1_that_uses_t1() FROM t1; + In f1_that_uses_t1() we will see one instance of t1 where query_id is + set to query_id of original query. */ static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table) @@ -1189,7 +1214,7 @@ void close_temporary_tables(THD *thd) close_temporary(table, 1, 1); } if (query && found_user_tables && mysql_bin_log.is_open() && - !binlog_row_based) // CREATE TEMP TABLE not binlogged if row-based + !thd->current_stmt_binlog_row_based) // CREATE TEMP TABLE not binlogged if row-based { /* The -1 is to remove last ',' */ thd->clear_error(); @@ -1230,11 +1255,11 @@ void close_temporary_tables(THD *thd) */ TABLE_LIST *find_table_in_list(TABLE_LIST *table, - uint offset, + st_table_list *TABLE_LIST::*link, const char *db_name, const char *table_name) { - for (; table; table= *(TABLE_LIST **) ((char*) table + offset)) + for (; table; table= table->*link ) { if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) && strcmp(table->db, db_name) == 0 && @@ -2383,43 +2408,55 @@ void abort_locked_tables(THD *thd,const char *db, const char *table_name) /* - Function to assign a new table map id to a table. + Function to assign a new table map id to a table share. PARAMETERS - table - Pointer to table structure + share - Pointer to table share structure + + DESCRIPTION + + We are intentionally not checking that share->mutex is locked + since this function should only be called when opening a table + share and before it is entered into the table_def_cache (meaning + that it cannot be fetched by another thread, even accidentally). PRE-CONDITION(S) - table is non-NULL + share is non-NULL The LOCK_open mutex is locked POST-CONDITION(S) - table->s->table_map_id is given a value that with a high certainty - is not used by any other table. + share->table_map_id is given a value that with a high certainty is + not used by any other table (the only case where a table id can be + reused is on wrap-around, which means more than 4 billion table + shares open at the same time). - table->s->table_map_id is not ULONG_MAX. + share->table_map_id is not ULONG_MAX. */ -void assign_new_table_id(TABLE *table) +void assign_new_table_id(TABLE_SHARE *share) { static ulong last_table_id= ULONG_MAX; - DBUG_ENTER("assign_new_table_id(TABLE*)"); + DBUG_ENTER("assign_new_table_id"); /* Preconditions */ - DBUG_ASSERT(table != NULL); + DBUG_ASSERT(share != NULL); safe_mutex_assert_owner(&LOCK_open); ulong tid= ++last_table_id; /* get next id */ - /* There is one reserved number that cannot be used. */ + /* + There is one reserved number that cannot be used. Remember to + change this when 6-byte global table id's are introduced. + */ if (unlikely(tid == ULONG_MAX)) tid= ++last_table_id; - table->s->table_map_id= tid; + share->table_map_id= tid; DBUG_PRINT("info", ("table_id=%lu", tid)); /* Post conditions */ - DBUG_ASSERT(table->s->table_map_id != ULONG_MAX); + DBUG_ASSERT(share->table_map_id != ULONG_MAX); DBUG_VOID_RETURN; } @@ -2573,20 +2610,6 @@ retry: break; } - /* - We assign a new table id under the protection of the LOCK_open - mutex. We assign a new table id here instead of inside openfrm() - since that function can be used without acquiring any lock (e.g., - inside ha_create_table()). Insted of creatint a new mutex and - using it for the sole purpose of serializing accesses to a static - variable, we assign the table id here. - - CAVEAT. This means that the table cannot be used for - binlogging/replication purposes, unless open_table() has been called - directly or indirectly. - */ - assign_new_table_id(entry); - if (Table_triggers_list::check_n_load(thd, share->db.str, share->table_name.str, entry, 0)) { @@ -2692,22 +2715,11 @@ int open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags) statement for which table list for prelocking is already built, let us cache routines and try to build such table list. - NOTE: We can't delay prelocking until we will met some sub-statement - which really uses tables, since this will imply that we have to restore - its table list to be able execute it in some other context. - And current views implementation assumes that view tables are added to - global table list only once during PS preparing/first SP execution. - Also locking at earlier stage is probably faster altough may decrease - concurrency a bit. - NOTE: We will mark statement as requiring prelocking only if we will have non empty table list. But this does not guarantee that in prelocked mode we will have some locked tables, because queries which use only derived/information schema tables and views possible. Thus "counter" may be still zero for prelocked statement... - - NOTE: The above notes may be out of date. Please wait for psergey to - document new prelocked behavior. */ if (!thd->prelocked_mode && !thd->lex->requires_prelocking() && @@ -2793,48 +2805,23 @@ int open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags) if (refresh) // Refresh in progress { - /* close all 'old' tables used by this thread */ - pthread_mutex_lock(&LOCK_open); - // if query_id is not reset, we will get an error - // re-opening a temp table - thd->version=refresh_version; - TABLE **prev_table= &thd->open_tables; - bool found=0; - for (TABLE_LIST *tmp= *start; tmp; tmp= tmp->next_global) - { - /* Close normal (not temporary) changed tables */ - if (tmp->table && ! tmp->table->s->tmp_table != NO_TMP_TABLE) - { - if (tmp->table->s->version != refresh_version || - ! tmp->table->db_stat) - { - VOID(hash_delete(&open_cache,(byte*) tmp->table)); - tmp->table=0; - found=1; - } - else - { - *prev_table= tmp->table; // Relink open list - prev_table= &tmp->table->next; - } - } - } - *prev_table=0; - pthread_mutex_unlock(&LOCK_open); - if (found) - VOID(pthread_cond_broadcast(&COND_refresh)); // Signal to refresh /* - Let us prepare for recalculation of set of prelocked tables. - First we pretend that we have finished calculation which we - were doing currently. Then we restore list of tables to be - opened and set of used routines to the state in which they were - before first open_tables() call for this statement (i.e. before - we have calculated current set of tables for prelocking). + We have met name-locked or old version of table. Now we have + to close all tables which are not up to date. We also have to + throw away set of prelocked tables (and thus close tables from + this set that were open by now) since it possible that one of + tables which determined its content was changed. + + Instead of implementing complex/non-robust logic mentioned + above we simply close and then reopen all tables. + + In order to prepare for recalculation of set of prelocked tables + we pretend that we have finished calculation which we were doing + currently. */ if (query_tables_last_own) thd->lex->mark_as_requiring_prelocking(query_tables_last_own); - thd->lex->chop_off_not_own_tables(); - sp_remove_not_own_routines(thd->lex); + close_tables_for_reopen(thd, start); goto restart; } result= -1; // Fatal error @@ -3045,7 +3032,7 @@ int simple_open_n_lock_tables(THD *thd, TABLE_LIST *tables) break; if (!need_reopen) DBUG_RETURN(-1); - close_tables_for_reopen(thd, tables); + close_tables_for_reopen(thd, &tables); } DBUG_RETURN(0); } @@ -3082,7 +3069,7 @@ bool open_and_lock_tables(THD *thd, TABLE_LIST *tables) break; if (!need_reopen) DBUG_RETURN(-1); - close_tables_for_reopen(thd, tables); + close_tables_for_reopen(thd, &tables); } if (mysql_handle_derived(thd->lex, &mysql_derived_prepare) || (thd->fill_derived_tables() && @@ -3310,18 +3297,24 @@ int lock_tables(THD *thd, TABLE_LIST *tables, uint count, bool *need_reopen) SYNOPSIS close_tables_for_reopen() - thd Thread context - tables List of tables which we were trying to open and lock + thd in Thread context + tables in/out List of tables which we were trying to open and lock */ -void close_tables_for_reopen(THD *thd, TABLE_LIST *tables) +void close_tables_for_reopen(THD *thd, TABLE_LIST **tables) { + /* + If table list consists only from tables from prelocking set, table list + for new attempt should be empty, so we have to update list's root pointer. + */ + if (thd->lex->first_not_own_table() == *tables) + *tables= 0; thd->lex->chop_off_not_own_tables(); sp_remove_not_own_routines(thd->lex); - for (TABLE_LIST *tmp= tables; tmp; tmp= tmp->next_global) - if (tmp->table && !tmp->table->s->tmp_table) - tmp->table= 0; + for (TABLE_LIST *tmp= *tables; tmp; tmp= tmp->next_global) + tmp->table= 0; + mark_used_tables_as_free_for_reuse(thd, thd->temporary_tables); close_thread_tables(thd); } @@ -4437,7 +4430,6 @@ mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2, { Field_iterator_table_ref it_1, it_2; Natural_join_column *nj_col_1, *nj_col_2; - const char *field_name_1; Query_arena *arena, backup; bool add_columns= TRUE; bool result= TRUE; @@ -4470,6 +4462,7 @@ mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2, { bool is_created_1; bool found= FALSE; + const char *field_name_1; if (!(nj_col_1= it_1.get_or_create_column_ref(&is_created_1))) goto err; field_name_1= nj_col_1->name(); @@ -4670,7 +4663,6 @@ store_natural_using_join_columns(THD *thd, TABLE_LIST *natural_using_join, { Field_iterator_table_ref it_1, it_2; Natural_join_column *nj_col_1, *nj_col_2; - bool is_created; Query_arena *arena, backup; bool result= TRUE; List<Natural_join_column> *non_join_columns; diff --git a/sql/sql_binlog.cc b/sql/sql_binlog.cc index cc0e9714d85..0939ad66cd0 100644 --- a/sql/sql_binlog.cc +++ b/sql/sql_binlog.cc @@ -58,7 +58,7 @@ void mysql_client_binlog_statement(THD* thd) const char *error= 0; char *buf= (char *) my_malloc(event_len, MYF(MY_WME)); - Log_event *ev; + Log_event *ev = 0; int res; /* diff --git a/sql/sql_cache.h b/sql/sql_cache.h index b7531696150..29d314d3c44 100644 --- a/sql/sql_cache.h +++ b/sql/sql_cache.h @@ -69,6 +69,7 @@ class Query_cache; struct Query_cache_block_table { + Query_cache_block_table() {} /* Remove gcc warning */ TABLE_COUNTER_TYPE n; // numbr in table (from 0) Query_cache_block_table *next, *prev; Query_cache_table *parent; @@ -78,6 +79,7 @@ struct Query_cache_block_table struct Query_cache_block { + Query_cache_block() {} /* Remove gcc warning */ enum block_type {FREE, QUERY, RESULT, RES_CONT, RES_BEG, RES_INCOMPLETE, TABLE, INCOMPLETE}; @@ -143,6 +145,7 @@ struct Query_cache_query struct Query_cache_table { + Query_cache_table() {} /* Remove gcc warning */ char *tbl; uint32 key_len; uint8 table_type; @@ -171,6 +174,7 @@ struct Query_cache_table struct Query_cache_result { + Query_cache_result() {} /* Remove gcc warning */ Query_cache_block *query; inline gptr data() @@ -197,6 +201,7 @@ extern "C" void query_cache_invalidate_by_MyISAM_filename(const char* filename); struct Query_cache_memory_bin { + Query_cache_memory_bin() {} /* Remove gcc warning */ #ifndef DBUG_OFF ulong size; #endif @@ -215,8 +220,7 @@ struct Query_cache_memory_bin struct Query_cache_memory_bin_step { -public: - Query_cache_memory_bin_step() {} + Query_cache_memory_bin_step() {} /* Remove gcc warning */ ulong size; ulong increment; uint idx; diff --git a/sql/sql_class.cc b/sql/sql_class.cc index e68bcb9e281..d391584a3be 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -329,6 +329,7 @@ void THD::init(void) bzero((char*) warn_count, sizeof(warn_count)); total_warn_count= 0; update_charset(); + reset_current_stmt_binlog_row_based(); bzero((char *) &status_var, sizeof(status_var)); } @@ -988,10 +989,9 @@ bool select_send::send_data(List<Item> &items) thd->sent_row_count++; if (!thd->vio_ok()) DBUG_RETURN(0); - if (thd->net.report_error) - protocol->remove_last_row(); - else + if (!thd->net.report_error) DBUG_RETURN(protocol->write()); + protocol->remove_last_row(); DBUG_RETURN(1); } @@ -2026,12 +2026,12 @@ void THD::reset_sub_statement_state(Sub_statement_state *backup, INSERT INTO t1 VALUES (1), (foo()), (2); */ - if (binlog_row_based) + if (current_stmt_binlog_row_based) binlog_flush_pending_rows_event(false); #endif /* HAVE_ROW_BASED_REPLICATION */ if ((!lex->requires_prelocking() || is_update_query(lex->sql_command)) && - !binlog_row_based) + !current_stmt_binlog_row_based) options&= ~OPTION_BIN_LOG; /* Disable result sets */ client_capabilities &= ~CLIENT_MULTI_RESULTS; @@ -2394,7 +2394,7 @@ int THD::binlog_write_row(TABLE* table, bool is_trans, MY_BITMAP const* cols, my_size_t colcnt, byte const *record) { - DBUG_ASSERT(binlog_row_based && mysql_bin_log.is_open()); + DBUG_ASSERT(current_stmt_binlog_row_based && mysql_bin_log.is_open()); /* Pack records into format for transfer. We are allocating more @@ -2441,7 +2441,7 @@ int THD::binlog_update_row(TABLE* table, bool is_trans, const byte *before_record, const byte *after_record) { - DBUG_ASSERT(binlog_row_based && mysql_bin_log.is_open()); + DBUG_ASSERT(current_stmt_binlog_row_based && mysql_bin_log.is_open()); bool error= 0; my_size_t const before_maxlen = max_row_length(table, before_record); @@ -2489,7 +2489,7 @@ int THD::binlog_delete_row(TABLE* table, bool is_trans, MY_BITMAP const* cols, my_size_t colcnt, byte const *record) { - DBUG_ASSERT(binlog_row_based && mysql_bin_log.is_open()); + DBUG_ASSERT(current_stmt_binlog_row_based && mysql_bin_log.is_open()); /* Pack records into format for transfer. We are allocating more @@ -2520,7 +2520,7 @@ int THD::binlog_delete_row(TABLE* table, bool is_trans, int THD::binlog_flush_pending_rows_event(bool stmt_end) { DBUG_ENTER("THD::binlog_flush_pending_rows_event"); - if (!binlog_row_based || !mysql_bin_log.is_open()) + if (!current_stmt_binlog_row_based || !mysql_bin_log.is_open()) DBUG_RETURN(0); /* @@ -2561,8 +2561,8 @@ void THD::binlog_delete_pending_rows_event() /* Member function that will log query, either row-based or - statement-based depending on the value of the 'binlog_row_based' - variable and the value of the 'qtype' flag. + statement-based depending on the value of the 'current_stmt_binlog_row_based' + the value of the 'qtype' flag. This function should be called after the all calls to ha_*_row() functions have been issued, but before tables are unlocked and @@ -2586,11 +2586,11 @@ int THD::binlog_query(THD::enum_binlog_query_type qtype, moving back and forth between using RBR for replication of system tables and not using it. - Make sure to change in check_table_binlog_row_based() according + Make sure to change in check_table_current_stmt_binlog_row_based according to how you treat this. */ case THD::ROW_QUERY_TYPE: - if (binlog_row_based) + if (current_stmt_binlog_row_based) DBUG_RETURN(binlog_flush_pending_rows_event(true)); /* Otherwise, we fall through */ case THD::STMT_QUERY_TYPE: diff --git a/sql/sql_class.h b/sql/sql_class.h index 00440449be8..267faba49f8 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -248,13 +248,15 @@ struct system_variables #endif /* HAVE_REPLICATION */ my_bool innodb_table_locks; my_bool innodb_support_xa; - ulong ndb_autoincrement_prefetch_sz; my_bool ndb_force_send; my_bool ndb_use_exact_count; my_bool ndb_use_transactions; my_bool ndb_index_stat_enable; + ulong ndb_autoincrement_prefetch_sz; ulong ndb_index_stat_cache_entries; ulong ndb_index_stat_update_freq; + ulong binlog_format; // binlog format for this thd (see enum_binlog_format) + my_bool old_alter_table; my_bool old_passwords; @@ -629,6 +631,7 @@ void xid_cache_delete(XID_STATE *xid_state); class Security_context { public: + Security_context() {} /* Remove gcc warning */ /* host - host of the client user - user of the client, set to NULL until the user has been read from @@ -1123,6 +1126,8 @@ public: char scramble[SCRAMBLE_LENGTH+1]; bool slave_thread, one_shot_set; + /* tells if current statement should binlog row-based(1) or stmt-based(0) */ + bool current_stmt_binlog_row_based; bool locked, some_tables_deleted; bool last_cuted_field; bool no_errors, password, is_fatal_error; @@ -1377,6 +1382,15 @@ public: void restore_sub_statement_state(Sub_statement_state *backup); void set_n_backup_active_arena(Query_arena *set, Query_arena *backup); void restore_active_arena(Query_arena *set, Query_arena *backup); + inline void set_current_stmt_binlog_row_based_if_mixed() + { + if (variables.binlog_format == BINLOG_FORMAT_MIXED) + current_stmt_binlog_row_based= 1; + } + inline void reset_current_stmt_binlog_row_based() + { + current_stmt_binlog_row_based= test(variables.binlog_format == BINLOG_FORMAT_ROW); + } }; @@ -1467,6 +1481,7 @@ public: class select_result_interceptor: public select_result { public: + select_result_interceptor() {} /* Remove gcc warning */ uint field_count(List<Item> &fields) const { return 0; } bool send_fields(List<Item> &fields, uint flag) { return FALSE; } }; @@ -1757,6 +1772,7 @@ class Table_ident :public Sql_alloc class user_var_entry { public: + user_var_entry() {} /* Remove gcc warning */ LEX_STRING name; char *value; ulong length; diff --git a/sql/sql_db.cc b/sql/sql_db.cc index 885643cf899..3d035359b6f 100644 --- a/sql/sql_db.cc +++ b/sql/sql_db.cc @@ -1226,17 +1226,21 @@ err: bool mysql_change_db(THD *thd, const char *name, bool no_access_check) { int length, db_length; - char *dbname=my_strdup((char*) name,MYF(MY_WME)); + char *dbname= thd->slave_thread ? (char *) name : + my_strdup((char *) name, MYF(MY_WME)); char path[FN_REFLEN]; HA_CREATE_INFO create; bool system_db= 0; #ifndef NO_EMBEDDED_ACCESS_CHECKS ulong db_access; Security_context *sctx= thd->security_ctx; + LINT_INIT(db_access); #endif DBUG_ENTER("mysql_change_db"); DBUG_PRINT("enter",("name: '%s'",name)); + LINT_INIT(db_length); + /* dbname can only be NULL if malloc failed */ if (!dbname || !(db_length= strlen(dbname))) { @@ -1246,7 +1250,8 @@ bool mysql_change_db(THD *thd, const char *name, bool no_access_check) system_db= 1; goto end; } - x_free(dbname); /* purecov: inspected */ + if (!(thd->slave_thread)) + x_free(dbname); /* purecov: inspected */ my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0)); /* purecov: inspected */ DBUG_RETURN(1); /* purecov: inspected */ @@ -1254,7 +1259,8 @@ bool mysql_change_db(THD *thd, const char *name, bool no_access_check) if (check_db_name(dbname)) { my_error(ER_WRONG_DB_NAME, MYF(0), dbname); - x_free(dbname); + if (!(thd->slave_thread)) + my_free(dbname, MYF(0)); DBUG_RETURN(1); } DBUG_PRINT("info",("Use database: %s", dbname)); @@ -1284,7 +1290,8 @@ bool mysql_change_db(THD *thd, const char *name, bool no_access_check) dbname); general_log_print(thd, COM_INIT_DB, ER(ER_DBACCESS_DENIED_ERROR), sctx->priv_user, sctx->priv_host, dbname); - my_free(dbname,MYF(0)); + if (!(thd->slave_thread)) + my_free(dbname,MYF(0)); DBUG_RETURN(1); } } @@ -1295,7 +1302,8 @@ bool mysql_change_db(THD *thd, const char *name, bool no_access_check) if (my_access(path,F_OK)) { my_error(ER_BAD_DB_ERROR, MYF(0), dbname); - my_free(dbname,MYF(0)); + if (!(thd->slave_thread)) + my_free(dbname,MYF(0)); DBUG_RETURN(1); } end: @@ -1304,7 +1312,7 @@ end: if (dbname && dbname[0] == 0) { if (!(thd->slave_thread)) - x_free(dbname); + my_free(dbname, MYF(0)); thd->db= NULL; thd->db_length= 0; } diff --git a/sql/sql_delete.cc b/sql/sql_delete.cc index c9cb1ccd5c2..34947e35b17 100644 --- a/sql/sql_delete.cc +++ b/sql/sql_delete.cc @@ -962,7 +962,7 @@ end: { /* TRUNCATE must always be statement-based binlogged (not row-based) so - we don't test binlog_row_based. + we don't test current_stmt_binlog_row_based. */ thd->clear_error(); thd->binlog_query(THD::STMT_QUERY_TYPE, diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index 6655491ca57..bd7be110b88 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2411,7 +2411,7 @@ void select_insert::send_error(uint errcode,const char *err) thd->binlog_query(THD::ROW_QUERY_TYPE, thd->query, thd->query_length, table->file->has_transactions(), FALSE); } - if (!binlog_row_based && !table->s->tmp_table) + if (!thd->current_stmt_binlog_row_based && !table->s->tmp_table) thd->options|=OPTION_STATUS_NO_TRANS_UPDATE; } if (info.copied || info.deleted || info.updated) @@ -2556,7 +2556,7 @@ select_create::binlog_show_create_table() on rollback, we clear the OPTION_STATUS_NO_TRANS_UPDATE bit of thd->options. */ - DBUG_ASSERT(binlog_row_based && !create_table_written); + DBUG_ASSERT(thd->current_stmt_binlog_row_based && !create_table_written); thd->options&= ~OPTION_STATUS_NO_TRANS_UPDATE; char buf[2048]; @@ -2582,7 +2582,7 @@ void select_create::store_values(List<Item> &values) Before writing the first row, we write the CREATE TABLE statement to the binlog. */ - if (binlog_row_based && !create_table_written) + if (thd->current_stmt_binlog_row_based && !create_table_written) { binlog_show_create_table(); create_table_written= TRUE; @@ -2611,7 +2611,7 @@ bool select_create::send_eof() If no rows where written to the binary log, we write the CREATE TABLE statement to the binlog. */ - if (binlog_row_based && !create_table_written) + if (thd->current_stmt_binlog_row_based && !create_table_written) { binlog_show_create_table(); create_table_written= TRUE; diff --git a/sql/sql_lex.h b/sql/sql_lex.h index bf4bf272f4d..08167f8b6d2 100644 --- a/sql/sql_lex.h +++ b/sql/sql_lex.h @@ -27,7 +27,7 @@ class sp_instr; class sp_pcontext; class st_alter_tablespace; class partition_info; -class event_timed; +class Event_timed; #ifdef MYSQL_SERVER /* @@ -932,7 +932,7 @@ typedef struct st_lex st_sp_chistics sp_chistics; - event_timed *et; + Event_timed *et; bool et_compile_phase; bool only_view; /* used for SHOW CREATE TABLE/VIEW */ diff --git a/sql/sql_load.cc b/sql/sql_load.cc index 1d6442ba7d6..30d83370255 100644 --- a/sql/sql_load.cc +++ b/sql/sql_load.cc @@ -426,7 +426,7 @@ bool mysql_load(THD *thd,sql_exchange *ex,TABLE_LIST *table_list, version for the binary log to mark that table maps are invalid after this point. */ - if (binlog_row_based) + if (thd->current_stmt_binlog_row_based) thd->binlog_flush_pending_rows_event(true); else #endif @@ -491,7 +491,7 @@ bool mysql_load(THD *thd,sql_exchange *ex,TABLE_LIST *table_list, version for the binary log to mark that table maps are invalid after this point. */ - if (binlog_row_based) + if (thd->current_stmt_binlog_row_based) thd->binlog_flush_pending_rows_event(true); else #endif @@ -948,7 +948,7 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs, if (get_it_from_net) cache.read_function = _my_b_net_read; - if (!binlog_row_based && mysql_bin_log.is_open()) + if (mysql_bin_log.is_open()) cache.pre_read = cache.pre_close = (IO_CACHE_CALLBACK) log_loaded_block; #endif diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc index b84eb1cfcb8..4ee47a574b1 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.cc @@ -2111,6 +2111,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd, void log_slow_statement(THD *thd) { + DBUG_ENTER("log_slow_statement"); time_t start_of_query; /* @@ -2142,6 +2143,7 @@ void log_slow_statement(THD *thd) slow_log_print(thd, thd->query, thd->query_length, start_of_query); } } + DBUG_VOID_RETURN; } @@ -3715,7 +3717,7 @@ end_with_restore_list: } if (!strip_sp(db) || check_db_name(db)) { - my_error(ER_WRONG_DB_NAME, MYF(0), lex->name); + my_error(ER_WRONG_DB_NAME, MYF(0), db); break; } /* @@ -3727,8 +3729,8 @@ end_with_restore_list: */ #ifdef HAVE_REPLICATION if (thd->slave_thread && - (!rpl_filter->db_ok(lex->name) || - !rpl_filter->db_ok_with_wild_table(lex->name))) + (!rpl_filter->db_ok(db) || + !rpl_filter->db_ok_with_wild_table(db))) { my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); break; @@ -4972,7 +4974,9 @@ end_with_restore_list: break; } default: +#ifndef EMBEDDED_LIBRARY DBUG_ASSERT(0); /* Impossible */ +#endif send_ok(thd); break; } @@ -4990,6 +4994,7 @@ end_with_restore_list: */ if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION) reset_one_shot_variables(thd); + thd->reset_current_stmt_binlog_row_based(); /* The return value for ROW_COUNT() is "implementation dependent" if the @@ -5916,10 +5921,7 @@ bool add_field_to_list(THD *thd, char *field_name, enum_field_types type, */ char buf[32]; my_snprintf(buf, sizeof(buf), "TIMESTAMP(%s)", length); - push_warning_printf(thd,MYSQL_ERROR::WARN_LEVEL_WARN, - ER_WARN_DEPRECATED_SYNTAX, - ER(ER_WARN_DEPRECATED_SYNTAX), - buf, "TIMESTAMP"); + WARN_DEPRECATED(thd, "5.2", buf, "'TIMESTAMP'"); } if (!(new_field= new create_field()) || @@ -6149,10 +6151,11 @@ TABLE_LIST *st_select_lex::add_table_to_list(THD *thd, /* table_list.next points to the last inserted TABLE_LIST->next_local' element + We don't use the offsetof() macro here to avoid warnings from gcc */ - previous_table_ref= (TABLE_LIST*) (table_list.next - - offsetof(TABLE_LIST, next_local)); - DBUG_ASSERT(previous_table_ref); + previous_table_ref= (TABLE_LIST*) ((char*) table_list.next - + ((char*) &(ptr->next_local) - + (char*) ptr)); /* Set next_name_resolution_table of the previous table reference to point to the current table reference. In effect the list diff --git a/sql/sql_partition.cc b/sql/sql_partition.cc index 71fbbcd2426..c98f8f915b9 100644 --- a/sql/sql_partition.cc +++ b/sql/sql_partition.cc @@ -15,10 +15,10 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* - This file was introduced as a container for general functionality related + This file is a container for general functionality related to partitioning introduced in MySQL version 5.1. It contains functionality - used by all handlers that support partitioning, which in the first version - is the partitioning handler itself and the NDB handler. + used by all handlers that support partitioning, such as + the partitioning handler itself and the NDB handler. The first version was written by Mikael Ronstrom. @@ -26,7 +26,7 @@ partitioning and composite partitioning (hereafter called subpartitioning) where each RANGE/LIST partitioning is HASH partitioned. The hash function can either be supplied by the user or by only a list of fields (also - called KEY partitioning, where the MySQL server will use an internal + called KEY partitioning), where the MySQL server will use an internal hash function. There are quite a few defaults that can be used as well. */ @@ -181,59 +181,6 @@ bool is_name_in_list(char *name, } -/* - A support function to check partition names for duplication in a - partitioned table - - SYNOPSIS - are_partitions_in_table() - new_part_info New partition info - old_part_info Old partition info - - RETURN VALUES - TRUE Duplicate names found - FALSE Duplicate names not found - - DESCRIPTION - Can handle that the new and old parts are the same in which case it - checks that the list of names in the partitions doesn't contain any - duplicated names. -*/ - -char *are_partitions_in_table(partition_info *new_part_info, - partition_info *old_part_info) -{ - uint no_new_parts= new_part_info->partitions.elements; - uint no_old_parts= old_part_info->partitions.elements; - uint new_count, old_count; - List_iterator<partition_element> new_parts_it(new_part_info->partitions); - bool is_same_part_info= (new_part_info == old_part_info); - DBUG_ENTER("are_partitions_in_table"); - DBUG_PRINT("enter", ("%u", no_new_parts)); - - new_count= 0; - do - { - List_iterator<partition_element> old_parts_it(old_part_info->partitions); - char *new_name= (new_parts_it++)->partition_name; - DBUG_PRINT("info", ("%s", new_name)); - new_count++; - old_count= 0; - do - { - char *old_name= (old_parts_it++)->partition_name; - old_count++; - if (is_same_part_info && old_count == new_count) - break; - if (!(my_strcasecmp(system_charset_info, old_name, new_name))) - { - DBUG_PRINT("info", ("old_name = %s, not ok", old_name)); - DBUG_RETURN(old_name); - } - } while (old_count < no_old_parts); - } while (new_count < no_new_parts); - DBUG_RETURN(NULL); -} /* Set-up defaults for partitions. @@ -262,7 +209,7 @@ bool partition_default_handling(TABLE *table, partition_info *part_info, DBUG_RETURN(TRUE); } } - else if (is_sub_partitioned(part_info) && + else if (part_info->is_sub_partitioned() && part_info->use_default_no_subpartitions) { uint no_parts; @@ -274,8 +221,8 @@ bool partition_default_handling(TABLE *table, partition_info *part_info, part_info->no_subparts= no_parts / part_info->no_parts; DBUG_ASSERT((no_parts % part_info->no_parts) == 0); } - set_up_defaults_for_partitioning(part_info, table->file, - (ulonglong)0, (uint)0); + part_info->set_up_defaults_for_partitioning(table->file, + (ulonglong)0, (uint)0); DBUG_RETURN(FALSE); } @@ -660,244 +607,9 @@ end: } -/* - Create a memory area where default partition names are stored and fill it - up with the names. - - SYNOPSIS - create_default_partition_names() - no_parts Number of partitions - start_no Starting partition number - subpart Is it subpartitions - RETURN VALUE - A pointer to the memory area of the default partition names - DESCRIPTION - A support routine for the partition code where default values are - generated. - The external routine needing this code is check_partition_info -*/ -#define MAX_PART_NAME_SIZE 8 - -static char *create_default_partition_names(uint no_parts, uint start_no, - bool is_subpart) -{ - char *ptr= sql_calloc(no_parts*MAX_PART_NAME_SIZE); - char *move_ptr= ptr; - uint i= 0; - DBUG_ENTER("create_default_partition_names"); - - if (likely(ptr != 0)) - { - do - { - if (is_subpart) - my_sprintf(move_ptr, (move_ptr,"sp%u", (start_no + i))); - else - my_sprintf(move_ptr, (move_ptr,"p%u", (start_no + i))); - move_ptr+=MAX_PART_NAME_SIZE; - } while (++i < no_parts); - } - else - { - mem_alloc_error(no_parts*MAX_PART_NAME_SIZE); - } - DBUG_RETURN(ptr); -} - - -/* - Set up all the default partitions not set-up by the user in the SQL - statement. Also perform a number of checks that the user hasn't tried - to use default values where no defaults exists. - - SYNOPSIS - set_up_default_partitions() - part_info The reference to all partition information - file A reference to a handler of the table - max_rows Maximum number of rows stored in the table - start_no Starting partition number - - RETURN VALUE - TRUE Error, attempted default values not possible - FALSE Ok, default partitions set-up - - DESCRIPTION - The routine uses the underlying handler of the partitioning to define - the default number of partitions. For some handlers this requires - knowledge of the maximum number of rows to be stored in the table. - This routine only accepts HASH and KEY partitioning and thus there is - no subpartitioning if this routine is successful. - The external routine needing this code is check_partition_info -*/ - -static bool set_up_default_partitions(partition_info *part_info, - handler *file, ulonglong max_rows, - uint start_no) -{ - uint no_parts, i; - char *default_name; - bool result= TRUE; - DBUG_ENTER("set_up_default_partitions"); - - if (part_info->part_type != HASH_PARTITION) - { - const char *error_string; - if (part_info->part_type == RANGE_PARTITION) - error_string= partition_keywords[PKW_RANGE].str; - else - error_string= partition_keywords[PKW_LIST].str; - my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), error_string); - goto end; - } - if (part_info->no_parts == 0) - part_info->no_parts= file->get_default_no_partitions(max_rows); - no_parts= part_info->no_parts; - if (unlikely(no_parts > MAX_PARTITIONS)) - { - my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0)); - goto end; - } - if (unlikely((!(default_name= create_default_partition_names(no_parts, - start_no, - FALSE))))) - goto end; - i= 0; - do - { - partition_element *part_elem= new partition_element(); - if (likely(part_elem != 0 && - (!part_info->partitions.push_back(part_elem)))) - { - part_elem->engine_type= part_info->default_engine_type; - part_elem->partition_name= default_name; - default_name+=MAX_PART_NAME_SIZE; - } - else - { - mem_alloc_error(sizeof(partition_element)); - goto end; - } - } while (++i < no_parts); - result= FALSE; -end: - DBUG_RETURN(result); -} - - -/* - Set up all the default subpartitions not set-up by the user in the SQL - statement. Also perform a number of checks that the default partitioning - becomes an allowed partitioning scheme. - - SYNOPSIS - set_up_default_subpartitions() - part_info The reference to all partition information - file A reference to a handler of the table - max_rows Maximum number of rows stored in the table - - RETURN VALUE - TRUE Error, attempted default values not possible - FALSE Ok, default partitions set-up - - DESCRIPTION - The routine uses the underlying handler of the partitioning to define - the default number of partitions. For some handlers this requires - knowledge of the maximum number of rows to be stored in the table. - This routine is only called for RANGE or LIST partitioning and those - need to be specified so only subpartitions are specified. - The external routine needing this code is check_partition_info -*/ - -static bool set_up_default_subpartitions(partition_info *part_info, - handler *file, ulonglong max_rows) -{ - uint i, j, no_parts, no_subparts; - char *default_name, *name_ptr; - bool result= TRUE; - partition_element *part_elem; - List_iterator<partition_element> part_it(part_info->partitions); - DBUG_ENTER("set_up_default_subpartitions"); - - if (part_info->no_subparts == 0) - part_info->no_subparts= file->get_default_no_partitions(max_rows); - no_parts= part_info->no_parts; - no_subparts= part_info->no_subparts; - if (unlikely((no_parts * no_subparts) > MAX_PARTITIONS)) - { - my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0)); - goto end; - } - if (unlikely((!(default_name= - create_default_partition_names(no_subparts, (uint)0, TRUE))))) - goto end; - i= 0; - do - { - part_elem= part_it++; - j= 0; - name_ptr= default_name; - do - { - partition_element *subpart_elem= new partition_element(); - if (likely(subpart_elem != 0 && - (!part_elem->subpartitions.push_back(subpart_elem)))) - { - subpart_elem->engine_type= part_info->default_engine_type; - subpart_elem->partition_name= name_ptr; - name_ptr+= MAX_PART_NAME_SIZE; - } - else - { - mem_alloc_error(sizeof(partition_element)); - goto end; - } - } while (++j < no_subparts); - } while (++i < no_parts); - result= FALSE; -end: - DBUG_RETURN(result); -} - - -/* - Support routine for check_partition_info - - SYNOPSIS - set_up_defaults_for_partitioning() - part_info The reference to all partition information - file A reference to a handler of the table - max_rows Maximum number of rows stored in the table - start_no Starting partition number - - RETURN VALUE - TRUE Error, attempted default values not possible - FALSE Ok, default partitions set-up - - DESCRIPTION - Set up defaults for partition or subpartition (cannot set-up for both, - this will return an error. -*/ - -bool set_up_defaults_for_partitioning(partition_info *part_info, - handler *file, - ulonglong max_rows, uint start_no) -{ - DBUG_ENTER("set_up_defaults_for_partitioning"); - - if (!part_info->default_partitions_setup) - { - part_info->default_partitions_setup= TRUE; - if (part_info->use_default_partitions) - DBUG_RETURN(set_up_default_partitions(part_info, file, max_rows, - start_no)); - if (is_sub_partitioned(part_info) && part_info->use_default_subpartitions) - DBUG_RETURN(set_up_default_subpartitions(part_info, file, max_rows)); - } - DBUG_RETURN(FALSE); -} /* @@ -967,7 +679,7 @@ bool check_partition_info(partition_info *part_info,handlerton **eng_type, char *same_name; DBUG_ENTER("check_partition_info"); - if (unlikely(is_sub_partitioned(part_info) && + if (unlikely(part_info->is_sub_partitioned() && (!(part_info->part_type == RANGE_PARTITION || part_info->part_type == LIST_PARTITION)))) { @@ -975,17 +687,17 @@ bool check_partition_info(partition_info *part_info,handlerton **eng_type, my_error(ER_SUBPARTITION_ERROR, MYF(0)); goto end; } - if (unlikely(set_up_defaults_for_partitioning(part_info, file, - max_rows, (uint)0))) + if (unlikely(part_info->set_up_defaults_for_partitioning(file, + max_rows, + (uint)0))) goto end; - tot_partitions= get_tot_partitions(part_info); + tot_partitions= part_info->get_tot_partitions(); if (unlikely(tot_partitions > MAX_PARTITIONS)) { my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0)); goto end; } - if (((same_name= are_partitions_in_table(part_info, - part_info)))) + if ((same_name= part_info->has_unique_names())) { my_error(ER_SAME_NAME_PARTITION, MYF(0), same_name); goto end; @@ -1001,7 +713,7 @@ bool check_partition_info(partition_info *part_info,handlerton **eng_type, do { partition_element *part_elem= part_it++; - if (!is_sub_partitioned(part_info)) + if (!part_info->is_sub_partitioned()) { if (part_elem->engine_type == NULL) part_elem->engine_type= part_info->default_engine_type; @@ -1194,7 +906,7 @@ static bool create_full_part_field_array(TABLE *table, bool result= FALSE; DBUG_ENTER("create_full_part_field_array"); - if (!is_sub_partitioned(part_info)) + if (!part_info->is_sub_partitioned()) { part_info->full_part_field_array= part_info->part_field_array; part_info->no_full_part_fields= part_info->no_part_fields; @@ -1702,6 +1414,7 @@ static bool set_up_partition_bitmap(THD *thd, partition_info *part_info) DBUG_RETURN(TRUE); } bitmap_init(&part_info->used_partitions, bitmap_buf, bitmap_bytes*8, FALSE); + bitmap_set_all(&part_info->used_partitions); DBUG_RETURN(FALSE); } @@ -1751,7 +1464,7 @@ static void set_up_partition_key_maps(TABLE *table, part_info->all_fields_in_PF.set_bit(i); if (some_fields) part_info->some_fields_in_PF.set_bit(i); - if (is_sub_partitioned(part_info)) + if (part_info->is_sub_partitioned()) { check_fields_in_PF(part_info->part_field_array, &all_fields, &some_fields); @@ -1789,7 +1502,7 @@ static void set_up_partition_func_pointers(partition_info *part_info) { DBUG_ENTER("set_up_partition_func_pointers"); - if (is_sub_partitioned(part_info)) + if (part_info->is_sub_partitioned()) { if (part_info->part_type == RANGE_PARTITION) { @@ -2011,7 +1724,7 @@ bool fix_partition_func(THD *thd, const char* name, TABLE *table, DBUG_RETURN(TRUE); } } - if (is_sub_partitioned(part_info)) + if (part_info->is_sub_partitioned()) { DBUG_ASSERT(part_info->subpart_type == HASH_PARTITION); /* @@ -2442,7 +2155,7 @@ char *generate_partition_syntax(partition_info *part_info, err+= add_int(fptr, part_info->no_parts); err+= add_space(fptr); } - if (is_sub_partitioned(part_info)) + if (part_info->is_sub_partitioned()) { err+= add_subpartition_by(fptr); /* Must be hash partitioning for subpartitioning */ @@ -2528,9 +2241,9 @@ char *generate_partition_syntax(partition_info *part_info, err+= add_string(fptr, part_elem->partition_name); err+= add_space(fptr); err+= add_partition_values(fptr, part_info, part_elem); - if (!is_sub_partitioned(part_info)) + if (!part_info->is_sub_partitioned()) err+= add_partition_options(fptr, part_elem); - if (is_sub_partitioned(part_info) && + if (part_info->is_sub_partitioned() && (write_all || (!part_info->use_default_subpartitions))) { err+= add_space(fptr); @@ -2630,6 +2343,29 @@ bool partition_key_modified(TABLE *table, List<Item> &fields) /* + A function to handle correct handling of NULL values in partition + functions. + SYNOPSIS + part_val_int() + item_expr The item expression to evaluate + RETURN VALUES + The value of the partition function, LONGLONG_MIN if any null value + in function +*/ + +static +inline +longlong +part_val_int(Item *item_expr) +{ + longlong value= item_expr->val_int(); + if (item_expr->null_value) + value= LONGLONG_MIN; + return value; +} + + +/* The next set of functions are used to calculate the partition identity. A handler sets up a variable that corresponds to one of these functions to be able to quickly call it whenever the partition id needs to calculated @@ -2725,7 +2461,7 @@ static uint32 get_part_id_hash(uint no_parts, longlong *func_value) { DBUG_ENTER("get_part_id_hash"); - *func_value= part_expr->val_int(); + *func_value= part_val_int(part_expr); longlong int_hash_id= *func_value % no_parts; DBUG_RETURN(int_hash_id < 0 ? -int_hash_id : int_hash_id); } @@ -2754,7 +2490,7 @@ static uint32 get_part_id_linear_hash(partition_info *part_info, { DBUG_ENTER("get_part_id_linear_hash"); - *func_value= part_expr->val_int(); + *func_value= part_val_int(part_expr); DBUG_RETURN(get_part_id_from_linear_hash(*func_value, part_info->linear_hash_mask, no_parts)); @@ -2892,7 +2628,7 @@ int get_partition_id_list(partition_info *part_info, longlong list_value; int min_list_index= 0; int max_list_index= part_info->no_list_values - 1; - longlong part_func_value= part_info->part_expr->val_int(); + longlong part_func_value= part_val_int(part_info->part_expr); DBUG_ENTER("get_partition_id_list"); *func_value= part_func_value; @@ -2968,7 +2704,7 @@ uint32 get_list_array_idx_for_endpoint(partition_info *part_info, longlong list_value; uint min_list_index= 0, max_list_index= part_info->no_list_values - 1; /* Get the partitioning function value for the endpoint */ - longlong part_func_value= part_info->part_expr->val_int(); + longlong part_func_value= part_val_int(part_info->part_expr); while (max_list_index >= min_list_index) { list_index= (max_list_index + min_list_index) >> 1; @@ -3002,7 +2738,7 @@ int get_partition_id_range(partition_info *part_info, uint min_part_id= 0; uint max_part_id= max_partition; uint loc_part_id; - longlong part_func_value= part_info->part_expr->val_int(); + longlong part_func_value= part_val_int(part_info->part_expr); DBUG_ENTER("get_partition_id_int_range"); while (max_part_id > min_part_id) @@ -3077,7 +2813,7 @@ uint32 get_partition_id_range_for_endpoint(partition_info *part_info, uint max_partition= part_info->no_parts - 1; uint min_part_id= 0, max_part_id= max_partition, loc_part_id; /* Get the partitioning function value for the endpoint */ - longlong part_func_value= part_info->part_expr->val_int(); + longlong part_func_value= part_val_int(part_info->part_expr); while (max_part_id > min_part_id) { loc_part_id= (max_part_id + min_part_id + 1) >> 1; @@ -3680,7 +3416,7 @@ void get_partition_set(const TABLE *table, byte *buf, const uint index, const key_range *key_spec, part_id_range *part_spec) { partition_info *part_info= table->part_info; - uint no_parts= get_tot_partitions(part_info); + uint no_parts= part_info->get_tot_partitions(); uint i, part_id; uint sub_part= no_parts; uint32 part_part= no_parts; @@ -3720,7 +3456,7 @@ void get_partition_set(const TABLE *table, byte *buf, const uint index, prune_partition_set(table, part_spec); DBUG_VOID_RETURN; } - else if (is_sub_partitioned(part_info)) + else if (part_info->is_sub_partitioned()) { if (part_info->all_fields_in_SPF.is_set(index)) sub_part= get_sub_part_id_from_key(table, buf, key_info, key_spec); @@ -3766,7 +3502,7 @@ void get_partition_set(const TABLE *table, byte *buf, const uint index, prune_partition_set(table, part_spec); DBUG_VOID_RETURN; } - else if (is_sub_partitioned(part_info)) + else if (part_info->is_sub_partitioned()) { if (check_part_func_bound(part_info->subpart_field_array)) sub_part= get_sub_part_id_from_key(table, buf, key_info, key_spec); @@ -3894,11 +3630,13 @@ bool mysql_unpack_partition(THD *thd, const uchar *part_buf, Item *thd_free_list= thd->free_list; bool result= TRUE; partition_info *part_info; + CHARSET_INFO *old_character_set_client= thd->variables.character_set_client; LEX *old_lex= thd->lex; LEX lex; DBUG_ENTER("mysql_unpack_partition"); thd->lex= &lex; + thd->variables.character_set_client= system_charset_info; lex_start(thd, part_buf, part_info_len); /* We need to use the current SELECT_LEX since I need to keep the @@ -4024,6 +3762,7 @@ bool mysql_unpack_partition(THD *thd, const uchar *part_buf, end: thd->free_list= thd_free_list; thd->lex= old_lex; + thd->variables.character_set_client= old_character_set_client; DBUG_RETURN(result); } @@ -4187,7 +3926,7 @@ static bool check_native_partitioned(HA_CREATE_INFO *create_info,bool *ret_val, do { partition_element *part_elem= part_it++; - if (is_sub_partitioned(part_info) && + if (part_info->is_sub_partitioned() && part_elem->subpartitions.elements) { uint no_subparts= part_elem->subpartitions.elements; @@ -4299,7 +4038,7 @@ uint prep_alter_part_table(THD *thd, TABLE *table, ALTER_INFO *alter_info, is freed by setting version to 0. table->s->version= 0 forces a flush of the table object in close_thread_tables(). */ - uint flags; + uint flags= 0; table->s->version= 0L; if (alter_info->flags == ALTER_TABLE_REORG) { @@ -4348,7 +4087,10 @@ uint prep_alter_part_table(THD *thd, TABLE *table, ALTER_INFO *alter_info, my_error(ER_PARTITION_FUNCTION_FAILURE, MYF(0)); DBUG_RETURN(1); } - *fast_alter_partition= flags ^ HA_PARTITION_FUNCTION_SUPPORTED; + *fast_alter_partition= + ((flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE)) != 0); + DBUG_PRINT("info", ("*fast_alter_partition: %d flags: 0x%x", + *fast_alter_partition, flags)); if (alter_info->flags & ALTER_ADD_PARTITION) { /* @@ -4377,7 +4119,7 @@ uint prep_alter_part_table(THD *thd, TABLE *table, ALTER_INFO *alter_info, my_error(ER_ADD_PARTITION_NO_NEW_PARTITION, MYF(0)); DBUG_RETURN(TRUE); } - if (is_sub_partitioned(tab_part_info)) + if (tab_part_info->is_sub_partitioned()) { if (alt_part_info->no_subparts == 0) alt_part_info->no_subparts= tab_part_info->no_subparts; @@ -4395,10 +4137,9 @@ uint prep_alter_part_table(THD *thd, TABLE *table, ALTER_INFO *alter_info, DBUG_RETURN(TRUE); } alt_part_info->part_type= tab_part_info->part_type; - if (set_up_defaults_for_partitioning(alt_part_info, - table->file, - ULL(0), - tab_part_info->no_parts)) + if (alt_part_info->set_up_defaults_for_partitioning(table->file, + ULL(0), + tab_part_info->no_parts)) { DBUG_RETURN(TRUE); } @@ -4949,7 +4690,6 @@ the generated partition syntax in a correct manner. DBUG_ASSERT(FALSE); } *partition_changed= TRUE; - create_info->db_type= &partition_hton; thd->lex->part_info= tab_part_info; if (alter_info->flags == ALTER_ADD_PARTITION || alter_info->flags == ALTER_REORGANIZE_PARTITION) @@ -5606,7 +5346,7 @@ void make_used_partitions_str(partition_info *part_info, String *parts_str) uint partition_id= 0; List_iterator<partition_element> it(part_info->partitions); - if (is_sub_partitioned(part_info)) + if (part_info->is_sub_partitioned()) { partition_element *head_pe; while ((head_pe= it++)) @@ -6065,7 +5805,7 @@ static uint32 get_next_partition_via_walking(PARTITION_ITERATOR *part_iter) field->store(part_iter->field_vals.start, FALSE); part_iter->field_vals.start++; longlong dummy; - if (is_sub_partitioned(part_iter->part_info) && + if (part_iter->part_info->is_sub_partitioned() && !part_iter->part_info->get_part_partition_id(part_iter->part_info, &part_id, &dummy) || !part_iter->part_info->get_partition_id(part_iter->part_info, diff --git a/sql/sql_partition.h b/sql/sql_partition.h new file mode 100644 index 00000000000..4982b1fcf1f --- /dev/null +++ b/sql/sql_partition.h @@ -0,0 +1,190 @@ +/* Copyright (C) 2006 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 */ + +#ifdef __GNUC__ +#pragma interface /* gcc class implementation */ +#endif + +/* Flags for partition handlers */ +#define HA_CAN_PARTITION (1 << 0) /* Partition support */ +#define HA_CAN_UPDATE_PARTITION_KEY (1 << 1) +#define HA_CAN_PARTITION_UNIQUE (1 << 2) +#define HA_USE_AUTO_PARTITION (1 << 3) + +/*typedef struct { + ulonglong data_file_length; + ulonglong max_data_file_length; + ulonglong index_file_length; + ulonglong delete_length; + ha_rows records; + ulong mean_rec_length; + time_t create_time; + time_t check_time; + time_t update_time; + ulonglong check_sum; +} PARTITION_INFO; +*/ +typedef struct { + longlong list_value; + uint32 partition_id; +} LIST_PART_ENTRY; + +typedef struct { + uint32 start_part; + uint32 end_part; +} part_id_range; + +struct st_partition_iter; +#define NOT_A_PARTITION_ID ((uint32)-1) + +bool is_partition_in_list(char *part_name, List<char> list_part_names); +char *are_partitions_in_table(partition_info *new_part_info, + partition_info *old_part_info); +bool check_reorganise_list(partition_info *new_part_info, + partition_info *old_part_info, + List<char> list_part_names); +handler *get_ha_partition(partition_info *part_info); +int get_parts_for_update(const byte *old_data, byte *new_data, + const byte *rec0, partition_info *part_info, + uint32 *old_part_id, uint32 *new_part_id, + longlong *func_value); +int get_part_for_delete(const byte *buf, const byte *rec0, + partition_info *part_info, uint32 *part_id); +void prune_partition_set(const TABLE *table, part_id_range *part_spec); +bool check_partition_info(partition_info *part_info,handlerton **eng_type, + handler *file, ulonglong max_rows); +bool fix_partition_func(THD *thd, const char *name, TABLE *table, + bool create_table_ind); +char *generate_partition_syntax(partition_info *part_info, + uint *buf_length, bool use_sql_alloc, + bool write_all); +bool partition_key_modified(TABLE *table, List<Item> &fields); +void get_partition_set(const TABLE *table, byte *buf, const uint index, + const key_range *key_spec, + part_id_range *part_spec); +void get_full_part_id_from_key(const TABLE *table, byte *buf, + KEY *key_info, + const key_range *key_spec, + part_id_range *part_spec); +bool mysql_unpack_partition(THD *thd, const uchar *part_buf, + uint part_info_len, + uchar *part_state, uint part_state_len, + TABLE *table, bool is_create_table_ind, + handlerton *default_db_type); +void make_used_partitions_str(partition_info *part_info, String *parts_str); +uint32 get_list_array_idx_for_endpoint(partition_info *part_info, + bool left_endpoint, + bool include_endpoint); +uint32 get_partition_id_range_for_endpoint(partition_info *part_info, + bool left_endpoint, + bool include_endpoint); + +/* + A "Get next" function for partition iterator. + SYNOPSIS + partition_iter_func() + part_iter Partition iterator, you call only "iter.get_next(&iter)" + + RETURN + NOT_A_PARTITION_ID if there are no more partitions. + [sub]partition_id of the next partition +*/ + +typedef uint32 (*partition_iter_func)(st_partition_iter* part_iter); + + +/* + Partition set iterator. Used to enumerate a set of [sub]partitions + obtained in partition interval analysis (see get_partitions_in_range_iter). + + For the user, the only meaningful field is get_next, which may be used as + follows: + part_iterator.get_next(&part_iterator); + + Initialization is done by any of the following calls: + - get_partitions_in_range_iter-type function call + - init_single_partition_iterator() + - init_all_partitions_iterator() + Cleanup is not needed. +*/ + +typedef struct st_partition_iter +{ + partition_iter_func get_next; + + struct st_part_num_range + { + uint32 start; + uint32 end; + }; + + struct st_field_value_range + { + longlong start; + longlong end; + }; + + union + { + struct st_part_num_range part_nums; + struct st_field_value_range field_vals; + }; + partition_info *part_info; +} PARTITION_ITERATOR; + + +/* + Get an iterator for set of partitions that match given field-space interval + + SYNOPSIS + get_partitions_in_range_iter() + part_info Partitioning info + is_subpart + min_val Left edge, field value in opt_range_key format. + max_val Right edge, field value in opt_range_key format. + flags Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE, + NO_MAX_RANGE. + part_iter Iterator structure to be initialized + + DESCRIPTION + Functions with this signature are used to perform "Partitioning Interval + Analysis". This analysis is applicable for any type of [sub]partitioning + by some function of a single fieldX. The idea is as follows: + Given an interval "const1 <=? fieldX <=? const2", find a set of partitions + that may contain records with value of fieldX within the given interval. + + The min_val, max_val and flags parameters specify the interval. + The set of partitions is returned by initializing an iterator in *part_iter + + NOTES + There are currently two functions of this type: + - get_part_iter_for_interval_via_walking + - get_part_iter_for_interval_via_mapping + + RETURN + 0 - No matching partitions, iterator not initialized + 1 - Some partitions would match, iterator intialized for traversing them + -1 - All partitions would match, iterator not initialized +*/ + +typedef int (*get_partitions_in_range_iter)(partition_info *part_info, + bool is_subpart, + char *min_val, char *max_val, + uint flags, + PARTITION_ITERATOR *part_iter); + +#include "partition_info.h" + diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index 2046596c428..ad99d81d7b4 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -681,7 +681,7 @@ void plugin_load(void) if (simple_open_n_lock_tables(new_thd, &tables)) { DBUG_PRINT("error",("Can't open plugin table")); - sql_print_error("Can't open the mysql.plugin table. Please run the mysql_install_db script to create it."); + sql_print_error("Can't open the mysql.plugin table. Please run the mysql_upgrade script to create it."); goto end; } table= tables.table; diff --git a/sql/sql_prepare.cc b/sql/sql_prepare.cc index 1b9cca9d84f..a66b2bdb9b6 100644 --- a/sql/sql_prepare.cc +++ b/sql/sql_prepare.cc @@ -1142,7 +1142,7 @@ static int mysql_test_update(Prepared_statement *stmt, break; if (!need_reopen) goto error; - close_tables_for_reopen(thd, table_list); + close_tables_for_reopen(thd, &table_list); } /* diff --git a/sql/sql_rename.cc b/sql/sql_rename.cc index 5f20442cc84..e3468b2b5cf 100644 --- a/sql/sql_rename.cc +++ b/sql/sql_rename.cc @@ -19,6 +19,7 @@ */ #include "mysql_priv.h" +#include "sql_trigger.h" static TABLE_LIST *rename_tables(THD *thd, TABLE_LIST *table_list, @@ -173,9 +174,30 @@ rename_tables(THD *thd, TABLE_LIST *table_list, bool skip_error) if (table_type == DB_TYPE_UNKNOWN) my_error(ER_FILE_NOT_FOUND, MYF(0), name, my_errno); else - rc= mysql_rename_table(ha_resolve_by_legacy_type(thd, table_type), - ren_table->db, old_alias, - new_table->db, new_alias); + { + if (!(rc= mysql_rename_table(ha_resolve_by_legacy_type(thd, + table_type), + ren_table->db, old_alias, + new_table->db, new_alias))) + { + if ((rc= Table_triggers_list::change_table_name(thd, ren_table->db, + old_alias, + new_table->db, + new_alias))) + { + /* + We've succeeded in renaming table's .frm and in updating + corresponding handler data, but have failed to update table's + triggers appropriately. So let us revert operations on .frm + and handler's data and report about failure to rename table. + */ + (void) mysql_rename_table(ha_resolve_by_legacy_type(thd, + table_type), + new_table->db, new_alias, + ren_table->db, old_alias); + } + } + } break; } case FRMTYPE_VIEW: diff --git a/sql/sql_repl.cc b/sql/sql_repl.cc index bf9a6078a8f..743a0a6b565 100644 --- a/sql/sql_repl.cc +++ b/sql/sql_repl.cc @@ -1576,6 +1576,8 @@ int log_loaded_block(IO_CACHE* file) if (!(block_len = (char*) file->read_end - (char*) buffer)) return 0; lf_info = (LOAD_FILE_INFO*) file->arg; + if (lf_info->thd->current_stmt_binlog_row_based) + return 0; if (lf_info->last_pos_in_file != HA_POS_ERROR && lf_info->last_pos_in_file >= file->pos_in_file) return 0; diff --git a/sql/sql_select.h b/sql/sql_select.h index 4f93a4aa996..459d2ff89a8 100644 --- a/sql/sql_select.h +++ b/sql/sql_select.h @@ -104,6 +104,7 @@ typedef int (*Read_record_func)(struct st_join_table *tab); Next_select_func setup_end_select_func(JOIN *join); typedef struct st_join_table { + st_join_table() {} /* Remove gcc warning */ TABLE *table; KEYUSE *keyuse; /* pointer to first used key */ SQL_SELECT *select; @@ -175,7 +176,9 @@ typedef struct st_rollup class JOIN :public Sql_alloc { - public: + JOIN(const JOIN &rhs); /* not implemented */ + JOIN& operator=(const JOIN &rhs); /* not implemented */ +public: JOIN_TAB *join_tab,**best_ref; JOIN_TAB **map2table; // mapping between table indexes and JOIN_TABs JOIN_TAB *join_tab_save; // saved join_tab for subquery reexecution @@ -287,13 +290,6 @@ class JOIN :public Sql_alloc init(thd_arg, fields_arg, select_options_arg, result_arg); } - JOIN(JOIN &join) - :fields_list(join.fields_list) - { - init(join.thd, join.fields_list, join.select_options, - join.result); - } - void init(THD *thd_arg, List<Item> &fields_arg, ulonglong select_options_arg, select_result *result_arg) { diff --git a/sql/sql_show.cc b/sql/sql_show.cc index cc2bec73ccf..13f880ef228 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -247,7 +247,7 @@ static struct show_privileges_st sys_privileges[]= {"Create user", "Server Admin", "To create new users"}, {"Delete", "Tables", "To delete existing rows"}, {"Drop", "Databases,Tables", "To drop databases, tables, and views"}, - {"Event","Server Admin","Creation, alteration, deletion and execution of events."}, + {"Event","Server Admin","To create, alter, drop and execute events"}, {"Execute", "Functions,Procedures", "To execute stored routines"}, {"File", "File access on server", "To read and write files on the server"}, {"Grant option", "Databases,Tables,Functions,Procedures", "To give to other users those privileges you possess"}, @@ -513,12 +513,15 @@ mysqld_show_create(THD *thd, TABLE_LIST *table_list) { if (!table_list->view || thd->net.last_errno != ER_VIEW_INVALID) DBUG_RETURN(TRUE); + /* Clear all messages with 'error' level status and issue a warning with 'warning' level status in case of invalid view and last error is ER_VIEW_INVALID */ mysql_reset_errors(thd, true); + thd->clear_error(); + push_warning_printf(thd,MYSQL_ERROR::WARN_LEVEL_WARN, ER_VIEW_INVALID, ER(ER_VIEW_INVALID), @@ -1654,7 +1657,7 @@ static int show_var_cmp(const void *var1, const void *var2) */ static void shrink_var_array(DYNAMIC_ARRAY *array) { - int a,b; + uint a,b; SHOW_VAR *all= dynamic_element(array, 0, SHOW_VAR *); for (a= b= 0; b < array->elements; b++) @@ -3775,7 +3778,7 @@ static int get_schema_partitions_record(THD *thd, struct st_table_list *tables, table->field[9]->set_notnull(); } - if (is_sub_partitioned(part_info)) + if (part_info->is_sub_partitioned()) { /* Subpartition method */ if (part_info->list_of_subpart_fields) @@ -3933,14 +3936,14 @@ fill_events_copy_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table) const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS; CHARSET_INFO *scs= system_charset_info; TIME time; - event_timed et; + Event_timed et; DBUG_ENTER("fill_events_copy_to_schema_tab"); restore_record(sch_table, s->default_values); if (et.load_from_row(thd->mem_root, event_table)) { - my_error(ER_EVENT_CANNOT_LOAD_FROM_TABLE, MYF(0)); + my_error(ER_CANNOT_LOAD_FROM_TABLE, MYF(0)); DBUG_RETURN(1); } @@ -3954,7 +3957,7 @@ fill_events_copy_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table) sch_table->field[3]->store(et.definer.str, et.definer.length, scs); sch_table->field[4]->store(et.body.str, et.body.length, scs); - // [9] is SQL_MODE + /* [9] is SQL_MODE */ { byte *sql_mode_str; ulong sql_mode_len=0; @@ -3969,39 +3972,38 @@ fill_events_copy_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table) String show_str; //type sch_table->field[5]->store(STRING_WITH_LEN("RECURRING"), scs); - //execute_at + /* execute_at */ sch_table->field[6]->set_null(); - //interval_value + /* interval_value */ //interval_type if (event_reconstruct_interval_expression(&show_str, et.interval, et.expression)) DBUG_RETURN(1); + sch_table->field[7]->set_notnull(); sch_table->field[7]->store(show_str.c_ptr(), show_str.length(), scs); LEX_STRING *ival= &interval_type_to_name[et.interval]; sch_table->field[8]->set_notnull(); sch_table->field[8]->store(ival->str, ival->length, scs); - //starts & ends + + //starts & ends sch_table->field[10]->set_notnull(); sch_table->field[10]->store_time(&et.starts, MYSQL_TIMESTAMP_DATETIME); - sch_table->field[11]->set_notnull(); - sch_table->field[11]->store_time(&et.ends, MYSQL_TIMESTAMP_DATETIME); + + if (!et.ends_null) + { + sch_table->field[11]->set_notnull(); + sch_table->field[11]->store_time(&et.ends, MYSQL_TIMESTAMP_DATETIME); + } } else { //type sch_table->field[5]->store(STRING_WITH_LEN("ONE TIME"), scs); - //execute_at + sch_table->field[6]->set_notnull(); sch_table->field[6]->store_time(&et.execute_at, MYSQL_TIMESTAMP_DATETIME); - //interval - sch_table->field[7]->set_null(); - //interval_type - sch_table->field[8]->set_null(); - //starts & ends - sch_table->field[10]->set_null(); - sch_table->field[11]->set_null(); } //status diff --git a/sql/sql_table.cc b/sql/sql_table.cc index 2737e9448f9..757321b5ccf 100644 --- a/sql/sql_table.cc +++ b/sql/sql_table.cc @@ -565,7 +565,7 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, String built_query; DBUG_ENTER("mysql_rm_table_part2"); - if (binlog_row_based && !dont_log_query) + if (thd->current_stmt_binlog_row_based && !dont_log_query) { built_query.set_charset(system_charset_info); if (if_exists) @@ -612,7 +612,7 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, being built. The string always end in a comma and the comma will be chopped off before being written to the binary log. */ - if (binlog_row_based && !dont_log_query) + if (thd->current_stmt_binlog_row_based && !dont_log_query) { ++non_temp_tables_count; /* @@ -722,7 +722,7 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, query_cache_invalidate3(thd, tables, 0); if (!dont_log_query) { - if (!binlog_row_based || + if (!thd->current_stmt_binlog_row_based || non_temp_tables_count > 0 && !tmp_table_deleted) { /* @@ -734,7 +734,7 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, */ write_bin_log(thd, !error, thd->query, thd->query_length); } - else if (binlog_row_based && + else if (thd->current_stmt_binlog_row_based && non_temp_tables_count > 0 && tmp_table_deleted) { @@ -1127,6 +1127,12 @@ static int mysql_prepare_table(THD *thd, HA_CREATE_INFO *create_info, { CHARSET_INFO *save_cs; + /* + Initialize length from its original value (number of characters), + which was set in the parser. This is necessary if we're + executing a prepared statement for the second time. + */ + sql_field->length= sql_field->char_length; if (!sql_field->charset) sql_field->charset= create_info->default_table_charset; /* @@ -1311,7 +1317,7 @@ static int mysql_prepare_table(THD *thd, HA_CREATE_INFO *create_info, sql_field->charset= (dup_field->charset ? dup_field->charset : create_info->default_table_charset); - sql_field->length= dup_field->chars_length; + sql_field->length= dup_field->char_length; sql_field->pack_length= dup_field->pack_length; sql_field->key_length= dup_field->key_length; sql_field->create_length_to_internal_length(); @@ -1742,7 +1748,9 @@ static int mysql_prepare_table(THD *thd, HA_CREATE_INFO *create_info, } if (length > file->max_key_part_length() && key->type != Key::FULLTEXT) { - length=file->max_key_part_length(); + length= file->max_key_part_length(); + /* Align key length to multibyte char boundary */ + length-= length % sql_field->charset->mbmaxlen; if (key->type == Key::MULTIPLE) { /* not a critical problem */ @@ -2248,8 +2256,8 @@ bool mysql_create_table_internal(THD *thd, Otherwise, the statement shall be binlogged. */ if (!internal_tmp_table && - (!binlog_row_based || - (binlog_row_based && + (!thd->current_stmt_binlog_row_based || + (thd->current_stmt_binlog_row_based && !(create_info->options & HA_LEX_CREATE_TMP_TABLE)))) write_bin_log(thd, TRUE, thd->query, thd->query_length); error= FALSE; @@ -3475,7 +3483,7 @@ bool mysql_create_like_table(THD* thd, TABLE_LIST* table, /* We have to write the query before we unlock the tables. */ - if (binlog_row_based) + if (thd->current_stmt_binlog_row_based) { /* Since temporary tables are not replicated under row-based @@ -4029,6 +4037,13 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name, close_cached_table(thd, table); if (mysql_rename_table(old_db_type,db,table_name,new_db,new_alias)) error= -1; + else if (Table_triggers_list::change_table_name(thd, db, table_name, + new_db, new_alias)) + { + VOID(mysql_rename_table(old_db_type, new_db, new_alias, db, + table_name)); + error= -1; + } } VOID(pthread_mutex_unlock(&LOCK_open)); } @@ -4861,7 +4876,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name, goto err; } /* We don't replicate alter table statement on temporary tables */ - if (!binlog_row_based) + if (!thd->current_stmt_binlog_row_based) write_bin_log(thd, TRUE, thd->query, thd->query_length); goto end_temporary; } @@ -4931,7 +4946,11 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name, VOID(quick_rm_table(new_db_type,new_db,tmp_name)); } else if (mysql_rename_table(new_db_type,new_db,tmp_name,new_db, - new_alias)) + new_alias) || + (new_name != table_name || new_db != db) && // we also do rename + Table_triggers_list::change_table_name(thd, db, table_name, + new_db, new_alias)) + { // Try to get everything back error=1; VOID(quick_rm_table(new_db_type,new_db,new_alias)); @@ -5031,7 +5050,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name, thd->query, thd->query_length, db, table_name); - DBUG_ASSERT(!(mysql_bin_log.is_open() && binlog_row_based && + DBUG_ASSERT(!(mysql_bin_log.is_open() && thd->current_stmt_binlog_row_based && (create_info->options & HA_LEX_CREATE_TMP_TABLE))); write_bin_log(thd, TRUE, thd->query, thd->query_length); /* diff --git a/sql/sql_trigger.cc b/sql/sql_trigger.cc index 0198dba780d..e33dc52df8f 100644 --- a/sql/sql_trigger.cc +++ b/sql/sql_trigger.cc @@ -65,7 +65,6 @@ File_option sql_modes_parameters= */ static const int TRG_NUM_REQUIRED_PARAMETERS= 4; -static const int TRG_MAX_VERSIONS= 3; /* Structure representing contents of .TRN file which are used to support @@ -318,8 +317,7 @@ bool Table_triggers_list::create_trigger(THD *thd, TABLE_LIST *tables, { LEX *lex= thd->lex; TABLE *table= tables->table; - char file_buff[FN_REFLEN], trigname_buff[FN_REFLEN], - trigname_path[FN_REFLEN]; + char file_buff[FN_REFLEN], trigname_buff[FN_REFLEN]; LEX_STRING file, trigname_file; LEX_STRING *trg_def, *name; ulonglong *trg_sql_mode; @@ -472,12 +470,11 @@ bool Table_triggers_list::create_trigger(THD *thd, TABLE_LIST *tables, definer_host->str, NullS) - trg_definer->str; if (!sql_create_definition_file(NULL, &file, &triggers_file_type, - (gptr)this, triggers_file_parameters, - TRG_MAX_VERSIONS)) + (gptr)this, triggers_file_parameters, 0)) return 0; err_with_cleanup: - my_delete(trigname_path, MYF(MY_WME)); + my_delete(trigname_buff, MYF(MY_WME)); return 1; } @@ -497,7 +494,8 @@ err_with_cleanup: True - error */ -static bool rm_trigger_file(char *path, char *db, char *table_name) +static bool rm_trigger_file(char *path, const char *db, + const char *table_name) { build_table_filename(path, FN_REFLEN-1, db, table_name, triggers_file_ext); return my_delete(path, MYF(MY_WME)); @@ -519,7 +517,8 @@ static bool rm_trigger_file(char *path, char *db, char *table_name) True - error */ -static bool rm_trigname_file(char *path, char *db, char *trigger_name) +static bool rm_trigname_file(char *path, const char *db, + const char *trigger_name) { build_table_filename(path, FN_REFLEN-1, db, trigger_name, trigname_file_ext); return my_delete(path, MYF(MY_WME)); @@ -527,6 +526,35 @@ static bool rm_trigname_file(char *path, char *db, char *trigger_name) /* + Helper function that saves .TRG file for Table_triggers_list object. + + SYNOPSIS + save_trigger_file() + triggers Table_triggers_list object for which file should be saved + db Name of database for subject table + table_name Name of subject table + + RETURN VALUE + FALSE Success + TRUE Error +*/ + +static bool save_trigger_file(Table_triggers_list *triggers, const char *db, + const char *table_name) +{ + char file_buff[FN_REFLEN]; + LEX_STRING file; + + file.length= build_table_filename(file_buff, FN_REFLEN-1, db, table_name, + triggers_file_ext); + file.str= file_buff; + return sql_create_definition_file(NULL, &file, &triggers_file_type, + (gptr)triggers, triggers_file_parameters, + 0); +} + + +/* Drop trigger for table. SYNOPSIS @@ -579,16 +607,7 @@ bool Table_triggers_list::drop_trigger(THD *thd, TABLE_LIST *tables) } else { - char file_buff[FN_REFLEN]; - LEX_STRING file; - - file.length= build_table_filename(file_buff, FN_REFLEN-1, - tables->db, tables->table_name, - triggers_file_ext); - file.str= file_buff; - if (sql_create_definition_file(NULL, &file, &triggers_file_type, - (gptr)this, triggers_file_parameters, - TRG_MAX_VERSIONS)) + if (save_trigger_file(this, tables->db, tables->table_name)) return 1; } @@ -827,12 +846,12 @@ bool Table_triggers_list::check_n_load(THD *thd, const char *db, if (!names_only && triggers->prepare_record1_accessors(table)) DBUG_RETURN(1); - char *trg_name_buff; List_iterator_fast<ulonglong> itm(triggers->definition_modes_list); List_iterator_fast<LEX_STRING> it_definer(triggers->definers_list); LEX *old_lex= thd->lex, lex; sp_rcontext *save_spcont= thd->spcont; ulong save_sql_mode= thd->variables.sql_mode; + LEX_STRING *on_table_name; thd->lex= &lex; @@ -898,6 +917,21 @@ bool Table_triggers_list::check_n_load(THD *thd, const char *db, &table->mem_root)) goto err_with_lex_cleanup; + if (!(on_table_name= (LEX_STRING*) alloc_root(&table->mem_root, + sizeof(LEX_STRING)))) + goto err_with_lex_cleanup; + *on_table_name= lex.ident; + if (triggers->on_table_names_list.push_back(on_table_name, &table->mem_root)) + goto err_with_lex_cleanup; + + /* + Let us check that we correctly update trigger definitions when we + rename tables with triggers. + */ + DBUG_ASSERT(!my_strcasecmp(table_alias_charset, lex.query_tables->db, db) && + !my_strcasecmp(table_alias_charset, lex.query_tables->table_name, + table_name)); + if (names_only) { lex_end(&lex); @@ -1063,7 +1097,7 @@ static TABLE_LIST *add_table_for_trigger(THD *thd, sp_name *trig) lex->query_tables= 0; lex->query_tables_last= &lex->query_tables; DBUG_RETURN(sp_add_to_query_tables(thd, lex, trig->m_db.str, - trigname.trigger_table.str, TL_WRITE)); + trigname.trigger_table.str, TL_IGNORE)); } @@ -1133,6 +1167,218 @@ end: } +/* + Update .TRG file after renaming triggers' subject table + (change name of table in triggers' definitions). + + SYNOPSIS + change_table_name_in_triggers() + thd Thread context + db_name Database of subject table + old_table_name Old subject table's name + new_table_name New subject table's name + + RETURN VALUE + FALSE Success + TRUE Failure +*/ + +bool +Table_triggers_list::change_table_name_in_triggers(THD *thd, + const char *db_name, + LEX_STRING *old_table_name, + LEX_STRING *new_table_name) +{ + char path_buff[FN_REFLEN]; + LEX_STRING *def, *on_table_name, new_def; + ulonglong *sql_mode; + ulong save_sql_mode= thd->variables.sql_mode; + List_iterator_fast<LEX_STRING> it_def(definitions_list); + List_iterator_fast<LEX_STRING> it_on_table_name(on_table_names_list); + List_iterator_fast<ulonglong> it_mode(definition_modes_list); + uint on_q_table_name_len, before_on_len; + String buff; + + DBUG_ASSERT(definitions_list.elements == on_table_names_list.elements && + definitions_list.elements == definition_modes_list.elements); + + while ((def= it_def++)) + { + on_table_name= it_on_table_name++; + thd->variables.sql_mode= *(it_mode++); + + /* Construct CREATE TRIGGER statement with new table name. */ + buff.length(0); + before_on_len= on_table_name->str - def->str; + buff.append(def->str, before_on_len); + buff.append(STRING_WITH_LEN("ON ")); + append_identifier(thd, &buff, new_table_name->str, new_table_name->length); + on_q_table_name_len= buff.length() - before_on_len; + buff.append(on_table_name->str + on_table_name->length, + def->length - (before_on_len + on_table_name->length)); + /* + It is OK to allocate some memory on table's MEM_ROOT since this + table instance will be thrown out at the end of rename anyway. + */ + new_def.str= memdup_root(&table->mem_root, buff.ptr(), buff.length()); + new_def.length= buff.length(); + on_table_name->str= new_def.str + before_on_len; + on_table_name->length= on_q_table_name_len; + *def= new_def; + } + + thd->variables.sql_mode= save_sql_mode; + + if (thd->is_fatal_error) + return TRUE; /* OOM */ + + if (save_trigger_file(this, db_name, new_table_name->str)) + return TRUE; + if (rm_trigger_file(path_buff, db_name, old_table_name->str)) + { + (void) rm_trigger_file(path_buff, db_name, new_table_name->str); + return TRUE; + } + return FALSE; +} + + +/* + Iterate though Table_triggers_list::names_list list and update .TRN files + after renaming triggers' subject table. + + SYNOPSIS + change_table_name_in_trignames() + db_name Database of subject table + new_table_name New subject table's name + stopper Pointer to Table_triggers_list::names_list at + which we should stop updating. + + RETURN VALUE + 0 Success + non-0 Failure, pointer to Table_triggers_list::names_list element + for which update failed. +*/ + +LEX_STRING* +Table_triggers_list::change_table_name_in_trignames(const char *db_name, + LEX_STRING *new_table_name, + LEX_STRING *stopper) +{ + char trigname_buff[FN_REFLEN]; + struct st_trigname trigname; + LEX_STRING trigname_file; + LEX_STRING *trigger; + List_iterator_fast<LEX_STRING> it_name(names_list); + + while ((trigger= it_name++) != stopper) + { + trigname_file.length= build_table_filename(trigname_buff, FN_REFLEN-1, + db_name, trigger->str, + trigname_file_ext); + trigname_file.str= trigname_buff; + + trigname.trigger_table= *new_table_name; + + if (sql_create_definition_file(NULL, &trigname_file, &trigname_file_type, + (gptr)&trigname, trigname_file_parameters, + 0)) + return trigger; + } + + return 0; +} + + +/* + Update .TRG and .TRN files after renaming triggers' subject table. + + SYNOPSIS + change_table_name() + thd Thread context + db Old database of subject table + old_table Old name of subject table + new_db New database for subject table + new_table New name of subject table + + NOTE + This method tries to leave trigger related files in consistent state, + i.e. it either will complete successfully, or will fail leaving files + in their initial state. + + RETURN VALUE + FALSE Success + TRUE Error +*/ + +bool Table_triggers_list::change_table_name(THD *thd, const char *db, + const char *old_table, + const char *new_db, + const char *new_table) +{ + TABLE table; + bool result= 0; + LEX_STRING *err_trigname; + DBUG_ENTER("change_table_name"); + + bzero(&table, sizeof(table)); + init_alloc_root(&table.mem_root, 8192, 0); + + safe_mutex_assert_owner(&LOCK_open); + + if (Table_triggers_list::check_n_load(thd, db, old_table, &table, TRUE)) + { + result= 1; + goto end; + } + if (table.triggers) + { + LEX_STRING_WITH_INIT old_table_name(old_table, strlen(old_table)); + LEX_STRING_WITH_INIT new_table_name(new_table, strlen(new_table)); + /* + Since triggers should be in the same schema as their subject tables + moving table with them between two schemas raises too many questions. + (E.g. what should happen if in new schema we already have trigger + with same name ?). + */ + if (my_strcasecmp(table_alias_charset, db, new_db)) + { + my_error(ER_TRG_IN_WRONG_SCHEMA, MYF(0)); + result= 1; + goto end; + } + if (table.triggers->change_table_name_in_triggers(thd, db, + &old_table_name, + &new_table_name)) + { + result= 1; + goto end; + } + if ((err_trigname= table.triggers->change_table_name_in_trignames( + db, &new_table_name, 0))) + { + /* + If we were unable to update one of .TRN files properly we will + revert all changes that we have done and report about error. + We assume that we will be able to undo our changes without errors + (we can't do much if there will be an error anyway). + */ + (void) table.triggers->change_table_name_in_trignames(db, + &old_table_name, + err_trigname); + (void) table.triggers->change_table_name_in_triggers(thd, db, + &new_table_name, + &old_table_name); + result= 1; + goto end; + } + } +end: + delete table.triggers; + free_root(&table.mem_root, MYF(0)); + DBUG_RETURN(result); +} + bool Table_triggers_list::process_triggers(THD *thd, trg_event_type event, trg_action_time_type time_type, diff --git a/sql/sql_trigger.h b/sql/sql_trigger.h index 8992de63b37..b67c22e0588 100644 --- a/sql/sql_trigger.h +++ b/sql/sql_trigger.h @@ -47,6 +47,11 @@ class Table_triggers_list: public Sql_alloc */ List<LEX_STRING> names_list; /* + List of "ON table_name" parts in trigger definitions, used for + updating trigger definitions during RENAME TABLE. + */ + List<LEX_STRING> on_table_names_list; + /* Key representing triggers for this table in set of all stored routines used by statement. TODO: We won't need this member once triggers namespace will be @@ -97,7 +102,10 @@ public: static bool check_n_load(THD *thd, const char *db, const char *table_name, TABLE *table, bool names_only); static bool drop_all_triggers(THD *thd, char *db, char *table_name); - + static bool change_table_name(THD *thd, const char *db, + const char *old_table, + const char *new_db, + const char *new_table); bool has_delete_triggers() { return (bodies[TRG_EVENT_DELETE][TRG_ACTION_BEFORE] || @@ -117,6 +125,13 @@ public: private: bool prepare_record1_accessors(TABLE *table); + LEX_STRING* change_table_name_in_trignames(const char *db_name, + LEX_STRING *new_table_name, + LEX_STRING *stopper); + bool change_table_name_in_triggers(THD *thd, + const char *db_name, + LEX_STRING *old_table_name, + LEX_STRING *new_table_name); }; extern const LEX_STRING trg_action_time_type_names[]; diff --git a/sql/sql_udf.cc b/sql/sql_udf.cc index 77bfba5ba28..69c5388f776 100644 --- a/sql/sql_udf.cc +++ b/sql/sql_udf.cc @@ -146,7 +146,7 @@ void udf_init() if (simple_open_n_lock_tables(new_thd, &tables)) { DBUG_PRINT("error",("Can't open udf table")); - sql_print_error("Can't open the mysql.func table. Please run the mysql_install_db script to create it."); + sql_print_error("Can't open the mysql.func table. Please run the mysql_upgrade script to create it."); goto end; } @@ -284,6 +284,10 @@ static void del_udf(udf_func *udf) void free_udf(udf_func *udf) { DBUG_ENTER("free_udf"); + + if (!initialized) + DBUG_VOID_RETURN; + rw_wrlock(&THR_LOCK_udf); if (!--udf->usage_count) { @@ -308,6 +312,9 @@ udf_func *find_udf(const char *name,uint length,bool mark_used) udf_func *udf=0; DBUG_ENTER("find_udf"); + if (!initialized) + DBUG_RETURN(NULL); + /* TODO: This should be changed to reader locks someday! */ if (mark_used) rw_wrlock(&THR_LOCK_udf); /* Called during fix_fields */ diff --git a/sql/sql_update.cc b/sql/sql_update.cc index b1abf2c0777..b19d6504b2e 100644 --- a/sql/sql_update.cc +++ b/sql/sql_update.cc @@ -158,7 +158,7 @@ int mysql_update(THD *thd, break; if (!need_reopen) DBUG_RETURN(1); - close_tables_for_reopen(thd, table_list); + close_tables_for_reopen(thd, &table_list); } if (mysql_handle_derived(thd->lex, &mysql_derived_prepare) || @@ -958,7 +958,7 @@ reopen_tables: for (TABLE_LIST *tbl= table_list; tbl; tbl= tbl->next_global) tbl->cleanup_items(); - close_tables_for_reopen(thd, table_list); + close_tables_for_reopen(thd, &table_list); goto reopen_tables; } diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy index 2c7f17a7a99..a744d941a4b 100644 --- a/sql/sql_yacc.yy +++ b/sql/sql_yacc.yy @@ -48,12 +48,7 @@ const LEX_STRING null_lex_str={0,0}; #define yyoverflow(A,B,C,D,E,F) {ulong val= *(F); if (my_yyoverflow((B), (D), &val)) { yyerror((char*) (A)); return 2; } else { *(F)= (YYSIZE_T)val; }} -#define WARN_DEPRECATED(A,B) \ - push_warning_printf(((THD *)yythd), MYSQL_ERROR::WARN_LEVEL_WARN, \ - ER_WARN_DEPRECATED_SYNTAX, \ - ER(ER_WARN_DEPRECATED_SYNTAX), (A), (B)); - -#define YYERROR_UNLESS(A) \ +#define YYERROR_UNLESS(A) \ if (!(A)) \ { \ yyerror(ER(ER_SYNTAX_ERROR)); \ @@ -1343,7 +1338,7 @@ create: lex->create_info.options= $3; - if (!(lex->et= new event_timed())) // implicitly calls event_timed::init() + if (!(lex->et= new Event_timed())) // implicitly calls Event_timed::init() YYABORT; /* @@ -1419,6 +1414,8 @@ ev_schedule_time: EVERY_SYM expr interval break; case EVEX_BAD_PARAMS: my_error(ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG, MYF(0)); + case EVEX_MICROSECOND_UNSUP: + my_error(ER_NOT_SUPPORTED_YET, MYF(0), "MICROSECOND"); YYABORT; break; } @@ -1474,6 +1471,9 @@ opt_ev_status: /* empty */ { $$= 0; } ; ev_starts: /* empty */ + { + Lex->et->init_starts(YYTHD, new Item_func_now_local()); + } | STARTS_SYM expr { LEX *lex= Lex; @@ -1679,6 +1679,16 @@ create_function_tail: LEX *lex= Lex; sp_head *sp; + /* + First check if AGGREGATE was used, in that case it's a + syntax error. + */ + if (lex->udf.type == UDFTYPE_AGGREGATE) + { + my_error(ER_SP_NO_AGGREGATE, MYF(0)); + YYABORT; + } + if (lex->sphead) { my_error(ER_SP_NO_RECURSIVE_CREATE, MYF(0), "FUNCTION"); @@ -3474,7 +3484,7 @@ part_func: uint expr_len= (uint)($4 - $2) - 1; lex->part_info->list_of_part_fields= FALSE; lex->part_info->part_expr= $3; - lex->part_info->part_func_string= $2+1; + lex->part_info->part_func_string= (char* ) sql_memdup($2+1, expr_len); lex->part_info->part_func_len= expr_len; } ; @@ -3486,7 +3496,7 @@ sub_part_func: uint expr_len= (uint)($4 - $2) - 1; lex->part_info->list_of_subpart_fields= FALSE; lex->part_info->subpart_expr= $3; - lex->part_info->subpart_func_string= $2+1; + lex->part_info->subpart_func_string= (char* ) sql_memdup($2+1, expr_len); lex->part_info->subpart_func_len= expr_len; } ; @@ -3994,6 +4004,13 @@ create_table_options: create_table_option: ENGINE_SYM opt_equal storage_engines { Lex->create_info.db_type= $3; Lex->create_info.used_fields|= HA_CREATE_USED_ENGINE; } + | TYPE_SYM opt_equal storage_engines + { + Lex->create_info.db_type= $3; + WARN_DEPRECATED(yythd, "5.2", "TYPE=storage_engine", + "'ENGINE=storage_engine'"); + Lex->create_info.used_fields|= HA_CREATE_USED_ENGINE; + } | MAX_ROWS opt_equal ulonglong_num { Lex->create_info.max_rows= $3; Lex->create_info.used_fields|= HA_CREATE_USED_MAX_ROWS;} | MIN_ROWS opt_equal ulonglong_num { Lex->create_info.min_rows= $3; Lex->create_info.used_fields|= HA_CREATE_USED_MIN_ROWS;} | AVG_ROW_LENGTH opt_equal ulong_num { Lex->create_info.avg_row_length=$3; Lex->create_info.used_fields|= HA_CREATE_USED_AVG_ROW_LENGTH;} @@ -4807,7 +4824,7 @@ alter: */ { LEX *lex=Lex; - event_timed *et; + Event_timed *et; if (lex->et) { @@ -4820,7 +4837,7 @@ alter: } lex->spname= 0;//defensive programming - if (!(et= new event_timed()))// implicitly calls event_timed::init() + if (!(et= new Event_timed()))// implicitly calls Event_timed::init() YYABORT; lex->et = et; @@ -4896,7 +4913,7 @@ opt_ev_rename_to: /* empty */ { $$= 0;} { LEX *lex=Lex; lex->spname= $3; //use lex's spname to hold the new name - //the original name is in the event_timed object + //the original name is in the Event_timed object $$= 1; } ; @@ -5350,11 +5367,8 @@ restore: RESTORE_SYM table_or_tables { Lex->sql_command = SQLCOM_RESTORE_TABLE; - push_warning_printf(((THD *)yythd), MYSQL_ERROR::WARN_LEVEL_WARN, - ER_WARN_DEPRECATED_STATEMENT, - ER(ER_WARN_DEPRECATED_STATEMENT), - "RESTORE TABLE", "5.2", - "mysqldump, mysql, MySQL Administrator"); + WARN_DEPRECATED(yythd, "5.2", "RESTORE TABLE", + "MySQL Administrator (mysqldump, mysql)"); } table_list FROM TEXT_STRING_sys { @@ -5365,11 +5379,8 @@ backup: BACKUP_SYM table_or_tables { Lex->sql_command = SQLCOM_BACKUP_TABLE; - push_warning_printf(((THD *)yythd), MYSQL_ERROR::WARN_LEVEL_WARN, - ER_WARN_DEPRECATED_STATEMENT, - ER(ER_WARN_DEPRECATED_STATEMENT), - "BACKUP TABLE", "5.2", - "mysqldump, mysql, MySQL Administrator"); + WARN_DEPRECATED(yythd, "5.2", "BACKUP TABLE", + "MySQL Administrator (mysqldump, mysql)"); } table_list TO_SYM TEXT_STRING_sys { @@ -7719,7 +7730,7 @@ drop: YYABORT; } - if (!(lex->et= new event_timed())) + if (!(lex->et= new Event_timed())) YYABORT; if (!lex->et_compile_phase) @@ -8212,7 +8223,7 @@ show_param: { LEX *lex=Lex; lex->sql_command= SQLCOM_SHOW_STORAGE_ENGINES; - WARN_DEPRECATED("SHOW TABLE TYPES", "SHOW [STORAGE] ENGINES"); + WARN_DEPRECATED(yythd, "5.2", "SHOW TABLE TYPES", "'SHOW [STORAGE] ENGINES'"); } | opt_storage ENGINES_SYM { @@ -8248,7 +8259,7 @@ show_param: lex->option_type= $1; if (prepare_schema_table(YYTHD, lex, 0, SCH_STATUS)) YYABORT; - } + } | INNOBASE_SYM STATUS_SYM { LEX *lex= Lex; @@ -8259,19 +8270,19 @@ show_param: my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), "InnoDB"); YYABORT; } - WARN_DEPRECATED("SHOW INNODB STATUS", "SHOW ENGINE INNODB STATUS"); + WARN_DEPRECATED(yythd, "5.2", "SHOW INNODB STATUS", "'SHOW ENGINE INNODB STATUS'"); } | MUTEX_SYM STATUS_SYM { LEX *lex= Lex; - lex->sql_command = SQLCOM_SHOW_ENGINE_MUTEX; + lex->sql_command = SQLCOM_SHOW_ENGINE_MUTEX; if (!(lex->create_info.db_type= ha_resolve_by_legacy_type(YYTHD, DB_TYPE_INNODB))) { my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), "InnoDB"); YYABORT; } - WARN_DEPRECATED("SHOW MUTEX STATUS", "SHOW ENGINE INNODB MUTEX"); + WARN_DEPRECATED(yythd, "5.2", "SHOW MUTEX STATUS", "'SHOW ENGINE INNODB MUTEX'"); } | opt_full PROCESSLIST_SYM { Lex->sql_command= SQLCOM_SHOW_PROCESSLIST;} @@ -8310,7 +8321,7 @@ show_param: my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), "BerkeleyDB"); YYABORT; } - WARN_DEPRECATED("SHOW BDB LOGS", "SHOW ENGINE BDB LOGS"); + WARN_DEPRECATED(yythd, "5.2", "SHOW BDB LOGS", "'SHOW ENGINE BDB LOGS'"); } | LOGS_SYM { @@ -8322,7 +8333,7 @@ show_param: my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), "BerkeleyDB"); YYABORT; } - WARN_DEPRECATED("SHOW LOGS", "SHOW ENGINE BDB LOGS"); + WARN_DEPRECATED(yythd, "5.2", "SHOW LOGS", "'SHOW ENGINE BDB LOGS'"); } | GRANTS { @@ -8443,7 +8454,7 @@ show_param: { Lex->sql_command = SQLCOM_SHOW_CREATE_EVENT; Lex->spname= $3; - Lex->et= new event_timed(); + Lex->et= new Event_timed(); if (!Lex->et) YYABORT; Lex->et->init_definer(YYTHD); @@ -8676,11 +8687,8 @@ load: LOAD DATA_SYM LOAD TABLE_SYM table_ident FROM MASTER_SYM { LEX *lex=Lex; - push_warning_printf(((THD *)yythd), MYSQL_ERROR::WARN_LEVEL_WARN, - ER_WARN_DEPRECATED_STATEMENT, - ER(ER_WARN_DEPRECATED_STATEMENT), - "LOAD TABLE FROM MASTER", "5.2", - "mysqldump, mysql, MySQL Administrator"); + WARN_DEPRECATED(yythd, "5.2", "LOAD TABLE FROM MASTER", + "MySQL Administrator (mysqldump, mysql)"); if (lex->sphead) { my_error(ER_SP_BADSTATEMENT, MYF(0), "LOAD TABLE"); @@ -10919,7 +10927,7 @@ view_check_option: trigger_tail: TRIGGER_SYM remember_name sp_name trg_action_time trg_event - ON table_ident FOR_SYM EACH_SYM ROW_SYM + ON remember_name table_ident remember_end FOR_SYM EACH_SYM ROW_SYM { LEX *lex= Lex; sp_head *sp; @@ -10936,6 +10944,8 @@ trigger_tail: sp->init(lex); lex->trigger_definition_begin= $2; + lex->ident.str= $7; + lex->ident.length= $9 - $7; sp->m_type= TYPE_ENUM_TRIGGER; lex->sphead= sp; @@ -10963,7 +10973,7 @@ trigger_tail: sp->init_strings(YYTHD, lex, $3); /* Restore flag if it was cleared above */ - YYTHD->client_capabilities |= $<ulong_num>11; + YYTHD->client_capabilities |= $<ulong_num>13; sp->restore_thd_mem_root(YYTHD); if (sp->is_not_allowed_in_function("trigger")) @@ -10973,15 +10983,11 @@ trigger_tail: We have to do it after parsing trigger body, because some of sp_proc_stmt alternatives are not saving/restoring LEX, so lex->query_tables can be wiped out. - - QQ: What are other consequences of this? - - QQ: Could we loosen lock type in certain cases ? */ - if (!lex->select_lex.add_table_to_list(YYTHD, $7, + if (!lex->select_lex.add_table_to_list(YYTHD, $8, (LEX_STRING*) 0, TL_OPTION_UPDATING, - TL_WRITE)) + TL_IGNORE)) YYABORT; } ; diff --git a/sql/table.cc b/sql/table.cc index 7c266243d29..d6a715ae1b4 100644 --- a/sql/table.cc +++ b/sql/table.cc @@ -130,6 +130,24 @@ TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key, share->version= refresh_version; share->flush_version= flush_version; +#ifdef HAVE_ROW_BASED_REPLICATION + /* + This constant is used to mark that no table map version has been + assigned. No arithmetic is done on the value: it will be + overwritten with a value taken from MYSQL_BIN_LOG. + */ + share->table_map_version= ~(ulonglong)0; + + /* + Since alloc_table_share() can be called without any locking (for + example, ha_create_table... functions), we do not assign a table + map id here. Instead we assign a value that is not used + elsewhere, and then assign a table map id inside open_table() + under the protection of the LOCK_open mutex. + */ + share->table_map_id= ULONG_MAX; +#endif + memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root)); pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST); pthread_cond_init(&share->cond, NULL); @@ -180,6 +198,15 @@ void init_tmp_table_share(TABLE_SHARE *share, const char *key, share->path.length= share->normalized_path.length= strlen(path); share->frm_version= FRM_VER_TRUE_VARCHAR; +#ifdef HAVE_ROW_BASED_REPLICATION + /* + Temporary tables are not replicated, but we set up these fields + anyway to be able to catch errors. + */ + share->table_map_version= ~(ulonglong)0; + share->table_map_id= ULONG_MAX; +#endif + DBUG_VOID_RETURN; } @@ -371,6 +398,7 @@ err_not_open: share->error= error; open_table_error(share, error, (share->open_errno= my_errno), 0); } + DBUG_RETURN(error); } @@ -1503,24 +1531,6 @@ int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, *root_ptr= old_root; thd->status_var.opened_tables++; -#ifdef HAVE_REPLICATION - - /* - This constant is used to mark that no table map version has been - assigned. No arithmetic is done on the value: it will be - overwritten with a value taken from MYSQL_BIN_LOG. - */ - share->table_map_version= ~(ulonglong)0; - - /* - Since openfrm() can be called without any locking (for example, - ha_create_table... functions), we do not assign a table map id - here. Instead we assign a value that is not used elsewhere, and - then assign a table map id inside open_table() under the - protection of the LOCK_open mutex. - */ - share->table_map_id= ULONG_MAX; -#endif DBUG_RETURN (0); @@ -3326,8 +3336,15 @@ const char *Natural_join_column::db_name() if (view_field) return table_ref->view_db.str; + /* + Test that TABLE_LIST::db is the same as st_table_share::db to + ensure consistency. An exception are I_S schema tables, which + are inconsistent in this respect. + */ DBUG_ASSERT(!strcmp(table_ref->db, - table_ref->table->s->db.str)); + table_ref->table->s->db.str) || + (table_ref->schema_table && + table_ref->table->s->db.str[0] == 0)); return table_ref->db; } @@ -3529,7 +3546,15 @@ const char *Field_iterator_table_ref::db_name() else if (table_ref->is_natural_join) return natural_join_it.column_ref()->db_name(); - DBUG_ASSERT(!strcmp(table_ref->db, table_ref->table->s->db.str)); + /* + Test that TABLE_LIST::db is the same as st_table_share::db to + ensure consistency. An exception are I_S schema tables, which + are inconsistent in this respect. + */ + DBUG_ASSERT(!strcmp(table_ref->db, table_ref->table->s->db.str) || + (table_ref->schema_table && + table_ref->table->s->db.str[0] == 0)); + return table_ref->db; } diff --git a/sql/table.h b/sql/table.h index d1009ade09b..2bde68e5919 100644 --- a/sql/table.h +++ b/sql/table.h @@ -216,6 +216,8 @@ typedef struct st_table_share /* Information for one open table */ struct st_table { + st_table() {} /* Remove gcc warning */ + TABLE_SHARE *s; handler *file; #ifdef NOT_YET @@ -490,6 +492,7 @@ public: typedef struct st_table_list { + st_table_list() {} /* Remove gcc warning */ /* List of tables local to a subquery (used by SQL_LIST). Considers views as leaves (unlike 'next_leaf' below). Created at parse time @@ -722,6 +725,7 @@ class Item; class Field_iterator: public Sql_alloc { public: + Field_iterator() {} /* Remove gcc warning */ virtual ~Field_iterator() {} virtual void set(TABLE_LIST *)= 0; virtual void next()= 0; diff --git a/sql/tztime.cc b/sql/tztime.cc index 96eb31449da..94c1eb8ac63 100644 --- a/sql/tztime.cc +++ b/sql/tztime.cc @@ -973,6 +973,7 @@ static const String tz_SYSTEM_name("SYSTEM", 6, &my_charset_latin1); class Time_zone_system : public Time_zone { public: + Time_zone_system() {} /* Remove gcc warning */ virtual my_time_t TIME_to_gmt_sec(const TIME *t, my_bool *in_dst_time_gap) const; virtual void gmt_sec_to_TIME(TIME *tmp, my_time_t t) const; @@ -1066,6 +1067,7 @@ Time_zone_system::get_name() const class Time_zone_utc : public Time_zone { public: + Time_zone_utc() {} /* Remove gcc warning */ virtual my_time_t TIME_to_gmt_sec(const TIME *t, my_bool *in_dst_time_gap) const; virtual void gmt_sec_to_TIME(TIME *tmp, my_time_t t) const; diff --git a/sql/tztime.h b/sql/tztime.h index 2d574eadf18..42e50988e52 100644 --- a/sql/tztime.h +++ b/sql/tztime.h @@ -30,6 +30,7 @@ class Time_zone: public Sql_alloc { public: + Time_zone() {} /* Remove gcc warning */ /* Converts local time in broken down TIME representation to my_time_t (UTC seconds since Epoch) represenation. diff --git a/sql/udf_example.cc b/sql/udf_example.cc index a186b4fbf6c..35833e63fab 100644 --- a/sql/udf_example.cc +++ b/sql/udf_example.cc @@ -144,6 +144,7 @@ char *metaphon(UDF_INIT *initid, UDF_ARGS *args, char *result, my_bool myfunc_double_init(UDF_INIT *, UDF_ARGS *args, char *message); double myfunc_double(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error); +my_bool myfunc_int_init(UDF_INIT *initid, UDF_ARGS *args, char *message); longlong myfunc_int(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error); my_bool sequence_init(UDF_INIT *initid, UDF_ARGS *args, char *message); @@ -597,6 +598,14 @@ longlong myfunc_int(UDF_INIT *initid, UDF_ARGS *args, char *is_null, return val; } +/* + At least one of _init/_deinit is needed unless the server is started + with --allow_suspicious_udfs. +*/ +my_bool myfunc_int_init(UDF_INIT *initid, UDF_ARGS *args, char *message) +{ + return 0; +} /* Simple example of how to get a sequences starting from the first argument |