~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2004 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
17
#include <drizzled/server_includes.h>
1 by brian
clean slate
18
#include "rpl_rli.h"
19
#include "rpl_mi.h"
20
#include "rpl_filter.h"
21
#include "rpl_utility.h"
22
#include "rpl_record.h"
212.5.38 by Monty Taylor
Moved my_dir (and removed references to a lot of places)
23
#include <mysys/my_dir.h>
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
24
#include <drizzled/drizzled_error_messages.h>
1 by brian
clean slate
25
398.1.5 by Monty Taylor
Removed C++ includes and std namespace from global.h.
26
#include <algorithm>
27
212.5.3 by Monty Taylor
Moved base64.h to mysys.
28
#include <mysys/base64.h>
212.5.18 by Monty Taylor
Moved m_ctype, m_string and my_bitmap. Removed t_ctype.
29
#include <mysys/my_bitmap.h>
1 by brian
clean slate
30
340 by Monty Taylor
Got everything using sql_print_*.
31
#include <libdrizzle/gettext.h>
383.1.44 by Monty Taylor
Renamed drizzle.h to libdrizzle.h.
32
#include <libdrizzle/libdrizzle.h>
340 by Monty Taylor
Got everything using sql_print_*.
33
383.1.12 by Brian Aker
Much closer toward UTF8 being around all the time...
34
#define log_cs	&my_charset_utf8_general_ci
1 by brian
clean slate
35
36
#define FLAGSTR(V,F) ((V)&(F)?#F" ":"")
37
38
39
/*
40
  Size of buffer for printing a double in format %.<PREC>g
41
42
  optional '-' + optional zero + '.'  + PREC digits + 'e' + sign +
43
  exponent digits + '\0'
44
*/
45
#define FMT_G_BUFSIZE(PREC) (3 + (PREC) + 5 + 1)
46
47
48
static const char *HA_ERR(int i)
49
{
50
  switch (i) {
51
  case HA_ERR_KEY_NOT_FOUND: return "HA_ERR_KEY_NOT_FOUND";
52
  case HA_ERR_FOUND_DUPP_KEY: return "HA_ERR_FOUND_DUPP_KEY";
53
  case HA_ERR_RECORD_CHANGED: return "HA_ERR_RECORD_CHANGED";
54
  case HA_ERR_WRONG_INDEX: return "HA_ERR_WRONG_INDEX";
55
  case HA_ERR_CRASHED: return "HA_ERR_CRASHED";
56
  case HA_ERR_WRONG_IN_RECORD: return "HA_ERR_WRONG_IN_RECORD";
57
  case HA_ERR_OUT_OF_MEM: return "HA_ERR_OUT_OF_MEM";
58
  case HA_ERR_NOT_A_TABLE: return "HA_ERR_NOT_A_TABLE";
59
  case HA_ERR_WRONG_COMMAND: return "HA_ERR_WRONG_COMMAND";
60
  case HA_ERR_OLD_FILE: return "HA_ERR_OLD_FILE";
61
  case HA_ERR_NO_ACTIVE_RECORD: return "HA_ERR_NO_ACTIVE_RECORD";
62
  case HA_ERR_RECORD_DELETED: return "HA_ERR_RECORD_DELETED";
63
  case HA_ERR_RECORD_FILE_FULL: return "HA_ERR_RECORD_FILE_FULL";
64
  case HA_ERR_INDEX_FILE_FULL: return "HA_ERR_INDEX_FILE_FULL";
65
  case HA_ERR_END_OF_FILE: return "HA_ERR_END_OF_FILE";
66
  case HA_ERR_UNSUPPORTED: return "HA_ERR_UNSUPPORTED";
67
  case HA_ERR_TO_BIG_ROW: return "HA_ERR_TO_BIG_ROW";
68
  case HA_WRONG_CREATE_OPTION: return "HA_WRONG_CREATE_OPTION";
69
  case HA_ERR_FOUND_DUPP_UNIQUE: return "HA_ERR_FOUND_DUPP_UNIQUE";
70
  case HA_ERR_UNKNOWN_CHARSET: return "HA_ERR_UNKNOWN_CHARSET";
71
  case HA_ERR_WRONG_MRG_TABLE_DEF: return "HA_ERR_WRONG_MRG_TABLE_DEF";
72
  case HA_ERR_CRASHED_ON_REPAIR: return "HA_ERR_CRASHED_ON_REPAIR";
73
  case HA_ERR_CRASHED_ON_USAGE: return "HA_ERR_CRASHED_ON_USAGE";
74
  case HA_ERR_LOCK_WAIT_TIMEOUT: return "HA_ERR_LOCK_WAIT_TIMEOUT";
75
  case HA_ERR_LOCK_TABLE_FULL: return "HA_ERR_LOCK_TABLE_FULL";
76
  case HA_ERR_READ_ONLY_TRANSACTION: return "HA_ERR_READ_ONLY_TRANSACTION";
77
  case HA_ERR_LOCK_DEADLOCK: return "HA_ERR_LOCK_DEADLOCK";
78
  case HA_ERR_CANNOT_ADD_FOREIGN: return "HA_ERR_CANNOT_ADD_FOREIGN";
79
  case HA_ERR_NO_REFERENCED_ROW: return "HA_ERR_NO_REFERENCED_ROW";
80
  case HA_ERR_ROW_IS_REFERENCED: return "HA_ERR_ROW_IS_REFERENCED";
81
  case HA_ERR_NO_SAVEPOINT: return "HA_ERR_NO_SAVEPOINT";
82
  case HA_ERR_NON_UNIQUE_BLOCK_SIZE: return "HA_ERR_NON_UNIQUE_BLOCK_SIZE";
83
  case HA_ERR_NO_SUCH_TABLE: return "HA_ERR_NO_SUCH_TABLE";
84
  case HA_ERR_TABLE_EXIST: return "HA_ERR_TABLE_EXIST";
85
  case HA_ERR_NO_CONNECTION: return "HA_ERR_NO_CONNECTION";
86
  case HA_ERR_NULL_IN_SPATIAL: return "HA_ERR_NULL_IN_SPATIAL";
87
  case HA_ERR_TABLE_DEF_CHANGED: return "HA_ERR_TABLE_DEF_CHANGED";
88
  case HA_ERR_NO_PARTITION_FOUND: return "HA_ERR_NO_PARTITION_FOUND";
89
  case HA_ERR_RBR_LOGGING_FAILED: return "HA_ERR_RBR_LOGGING_FAILED";
90
  case HA_ERR_DROP_INDEX_FK: return "HA_ERR_DROP_INDEX_FK";
91
  case HA_ERR_FOREIGN_DUPLICATE_KEY: return "HA_ERR_FOREIGN_DUPLICATE_KEY";
92
  case HA_ERR_TABLE_NEEDS_UPGRADE: return "HA_ERR_TABLE_NEEDS_UPGRADE";
93
  case HA_ERR_TABLE_READONLY: return "HA_ERR_TABLE_READONLY";
94
  case HA_ERR_AUTOINC_READ_FAILED: return "HA_ERR_AUTOINC_READ_FAILED";
95
  case HA_ERR_AUTOINC_ERANGE: return "HA_ERR_AUTOINC_ERANGE";
96
  case HA_ERR_GENERIC: return "HA_ERR_GENERIC";
97
  case HA_ERR_RECORD_IS_THE_SAME: return "HA_ERR_RECORD_IS_THE_SAME";
98
  case HA_ERR_LOGGING_IMPOSSIBLE: return "HA_ERR_LOGGING_IMPOSSIBLE";
99
  case HA_ERR_CORRUPT_EVENT: return "HA_ERR_CORRUPT_EVENT";
100
  case HA_ERR_ROWS_EVENT_APPLY : return "HA_ERR_ROWS_EVENT_APPLY";
101
  }
102
  return 0;
103
}
104
105
/**
106
   Error reporting facility for Rows_log_event::do_apply_event
107
108
   @param level     error, warning or info
109
   @param ha_error  HA_ERR_ code
110
   @param rli       pointer to the active Relay_log_info instance
111
   @param thd       pointer to the slave thread's thd
112
   @param table     pointer to the event's table object
113
   @param type      the type of the event
114
   @param log_name  the master binlog file name
115
   @param pos       the master binlog file pos (the next after the event)
116
117
*/
118
static void inline slave_rows_error_report(enum loglevel level, int ha_error,
119
                                           Relay_log_info const *rli, THD *thd,
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
120
                                           Table *table, const char * type,
1 by brian
clean slate
121
                                           const char *log_name, ulong pos)
122
{
123
  const char *handler_error= HA_ERR(ha_error);
124
  char buff[MAX_SLAVE_ERRMSG], *slider;
125
  const char *buff_end= buff + sizeof(buff);
482 by Brian Aker
Remove uint.
126
  uint32_t len;
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
127
  List_iterator_fast<DRIZZLE_ERROR> it(thd->warn_list);
128
  DRIZZLE_ERROR *err;
1 by brian
clean slate
129
  buff[0]= 0;
130
131
  for (err= it++, slider= buff; err && slider < buff_end - 1;
132
       slider += len, err= it++)
133
  {
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
134
    len= snprintf(slider, buff_end - slider,
398.1.7 by Monty Taylor
Marked some new translations.
135
                  _(" %s, Error_code: %d;"), err->msg, err->code);
1 by brian
clean slate
136
  }
137
  
138
  rli->report(level, thd->is_error()? thd->main_da.sql_errno() : 0,
398.1.7 by Monty Taylor
Marked some new translations.
139
              _("Could not execute %s event on table %s.%s;"
140
                "%s handler error %s; "
141
                "the event's master log %s, end_log_pos %lu"),
1 by brian
clean slate
142
              type, table->s->db.str,
143
              table->s->table_name.str,
144
              buff,
398.1.7 by Monty Taylor
Marked some new translations.
145
              handler_error == NULL? _("<unknown>") : handler_error,
1 by brian
clean slate
146
              log_name, pos);
147
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
148
1 by brian
clean slate
149
150
/*
151
  Cache that will automatically be written to a dedicated file on
152
  destruction.
153
154
  DESCRIPTION
155
156
 */
157
class Write_on_release_cache
158
{
159
public:
160
  enum flag
161
  {
162
    FLUSH_F
163
  };
164
165
  typedef unsigned short flag_set;
166
167
  /*
168
    Constructor.
169
170
    SYNOPSIS
171
      Write_on_release_cache
172
      cache  Pointer to cache to use
173
      file   File to write cache to upon destruction
174
      flags  Flags for the cache
175
176
    DESCRIPTION
177
178
      Class used to guarantee copy of cache to file before exiting the
179
      current block.  On successful copy of the cache, the cache will
180
      be reinited as a WRITE_CACHE.
181
182
      Currently, a pointer to the cache is provided in the
183
      constructor, but it would be possible to create a subclass
184
      holding the IO_CACHE itself.
185
   */
186
  Write_on_release_cache(IO_CACHE *cache, FILE *file, flag_set flags = 0)
187
    : m_cache(cache), m_file(file), m_flags(flags)
188
  {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
189
    reinit_io_cache(m_cache, WRITE_CACHE, 0L, false, true);
1 by brian
clean slate
190
  }
191
192
  ~Write_on_release_cache()
193
  {
194
    copy_event_cache_to_file_and_reinit(m_cache, m_file);
195
    if (m_flags | FLUSH_F)
196
      fflush(m_file);
197
  }
198
199
  /*
200
    Return a pointer to the internal IO_CACHE.
201
202
    SYNOPSIS
203
      operator&()
204
205
    DESCRIPTION
206
207
      Function to return a pointer to the internal cache, so that the
208
      object can be treated as a IO_CACHE and used with the my_b_*
209
      IO_CACHE functions
210
211
    RETURN VALUE
212
      A pointer to the internal IO_CACHE.
213
   */
214
  IO_CACHE *operator&()
215
  {
216
    return m_cache;
217
  }
218
219
private:
220
  // Hidden, to prevent usage.
221
  Write_on_release_cache(Write_on_release_cache const&);
222
223
  IO_CACHE *m_cache;
224
  FILE *m_file;
225
  flag_set m_flags;
226
};
227
482 by Brian Aker
Remove uint.
228
uint32_t debug_not_change_ts_if_art_event= 1; // bug#29309 simulation
1 by brian
clean slate
229
230
/*
231
  pretty_print_str()
232
*/
233
234
static void clear_all_errors(THD *thd, Relay_log_info *rli)
235
{
236
  thd->is_slave_error = 0;
237
  thd->clear_error();
238
  rli->clear_error();
239
}
240
241
242
/**
243
  Ignore error code specified on command line.
244
*/
245
246
inline int ignored_error_code(int err_code)
247
{
248
  return ((err_code == ER_SLAVE_IGNORED_TABLE) ||
249
          (use_slave_mask && bitmap_is_set(&slave_error_mask, err_code)));
250
}
251
252
253
/*
254
  pretty_print_str()
255
*/
256
257
static char *pretty_print_str(char *packet, const char *str, int len)
258
{
259
  const char *end= str + len;
260
  char *pos= packet;
261
  *pos++= '\'';
262
  while (str < end)
263
  {
264
    char c;
265
    switch ((c=*str++)) {
266
    case '\n': *pos++= '\\'; *pos++= 'n'; break;
267
    case '\r': *pos++= '\\'; *pos++= 'r'; break;
268
    case '\\': *pos++= '\\'; *pos++= '\\'; break;
269
    case '\b': *pos++= '\\'; *pos++= 'b'; break;
270
    case '\t': *pos++= '\\'; *pos++= 't'; break;
271
    case '\'': *pos++= '\\'; *pos++= '\''; break;
272
    case 0   : *pos++= '\\'; *pos++= '0'; break;
273
    default:
274
      *pos++= c;
275
      break;
276
    }
277
  }
278
  *pos++= '\'';
279
  return pos;
280
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
281
1 by brian
clean slate
282
283
/**
284
  Creates a temporary name for load data infile:.
285
286
  @param buf		      Store new filename here
287
  @param file_id	      File_id (part of file name)
288
  @param event_server_id     Event_id (part of file name)
289
  @param ext		      Extension for file name
290
291
  @return
292
    Pointer to start of extension
293
*/
294
482 by Brian Aker
Remove uint.
295
static char *slave_load_file_stem(char *buf, uint32_t file_id,
1 by brian
clean slate
296
                                  int event_server_id, const char *ext)
297
{
298
  char *res;
299
  fn_format(buf,"SQL_LOAD-",slave_load_tmpdir, "", MY_UNPACK_FILENAME);
300
  to_unix_path(buf);
301
376 by Brian Aker
strend remove
302
  buf= strchr(buf, '\0');
303
  buf= int10_to_str(::server_id, buf, 10);
1 by brian
clean slate
304
  *buf++ = '-';
376 by Brian Aker
strend remove
305
  buf= int10_to_str(event_server_id, buf, 10);
1 by brian
clean slate
306
  *buf++ = '-';
307
  res= int10_to_str(file_id, buf, 10);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
308
  my_stpcpy(res, ext);                             // Add extension last
1 by brian
clean slate
309
  return res;                                   // Pointer to extension
310
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
311
1 by brian
clean slate
312
313
/**
314
  Delete all temporary files used for SQL_LOAD.
315
*/
316
317
static void cleanup_load_tmpdir()
318
{
319
  MY_DIR *dirp;
320
  FILEINFO *file;
482 by Brian Aker
Remove uint.
321
  uint32_t i;
1 by brian
clean slate
322
  char fname[FN_REFLEN], prefbuf[31], *p;
323
324
  if (!(dirp=my_dir(slave_load_tmpdir,MYF(MY_WME))))
325
    return;
326
327
  /* 
328
     When we are deleting temporary files, we should only remove
329
     the files associated with the server id of our server.
330
     We don't use event_server_id here because since we've disabled
331
     direct binlogging of Create_file/Append_file/Exec_load events
332
     we cannot meet Start_log event in the middle of events from one 
333
     LOAD DATA.
334
  */
335
  p= strmake(prefbuf, STRING_WITH_LEN("SQL_LOAD-"));
336
  p= int10_to_str(::server_id, p, 10);
337
  *(p++)= '-';
338
  *p= 0;
339
340
  for (i=0 ; i < (uint)dirp->number_off_files; i++)
341
  {
342
    file=dirp->dir_entry+i;
343
    if (is_prefix(file->name, prefbuf))
344
    {
345
      fn_format(fname,file->name,slave_load_tmpdir,"",MY_UNPACK_FILENAME);
346
      my_delete(fname, MYF(0));
347
    }
348
  }
349
350
  my_dirend(dirp);
351
}
352
353
354
/*
355
  write_str()
356
*/
357
482 by Brian Aker
Remove uint.
358
static bool write_str(IO_CACHE *file, const char *str, uint32_t length)
1 by brian
clean slate
359
{
481 by Brian Aker
Remove all of uchar.
360
  unsigned char tmp[1];
361
  tmp[0]= (unsigned char) length;
1 by brian
clean slate
362
  return (my_b_safe_write(file, tmp, sizeof(tmp)) ||
481 by Brian Aker
Remove all of uchar.
363
	  my_b_safe_write(file, (unsigned char*) str, length));
1 by brian
clean slate
364
}
365
366
367
/*
368
  read_str()
369
*/
370
371
static inline int read_str(const char **buf, const char *buf_end,
206 by Brian Aker
Removed final uint dead types.
372
                           const char **str, uint8_t *len)
1 by brian
clean slate
373
{
481 by Brian Aker
Remove all of uchar.
374
  if (*buf + ((uint) (unsigned char) **buf) >= buf_end)
1 by brian
clean slate
375
    return 1;
206 by Brian Aker
Removed final uint dead types.
376
  *len= (uint8_t) **buf;
1 by brian
clean slate
377
  *str= (*buf)+1;
378
  (*buf)+= (uint) *len+1;
379
  return 0;
380
}
381
382
383
/**
384
  Transforms a string into "" or its expression in 0x... form.
385
*/
386
482 by Brian Aker
Remove uint.
387
char *str_to_hex(char *to, const char *from, uint32_t len)
1 by brian
clean slate
388
{
389
  if (len)
390
  {
391
    *to++= '0';
392
    *to++= 'x';
393
    to= octet2hex(to, from, len);
394
  }
395
  else
411.1.1 by Brian Aker
Work on removing GNU specific calls.
396
    to= my_stpcpy(to, "\"\"");
1 by brian
clean slate
397
  return to;                               // pointer to end 0 of 'to'
398
}
399
400
401
/**
402
  Append a version of the 'from' string suitable for use in a query to
403
  the 'to' string.  To generate a correct escaping, the character set
404
  information in 'csinfo' is used.
405
*/
406
407
int
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
408
append_query_string(const CHARSET_INFO * const csinfo,
1 by brian
clean slate
409
                    String const *from, String *to)
410
{
411
  char *beg, *ptr;
205 by Brian Aker
uint32 -> uin32_t
412
  uint32_t const orig_len= to->length();
1 by brian
clean slate
413
  if (to->reserve(orig_len + from->length()*2+3))
414
    return 1;
415
416
  beg= to->c_ptr_quick() + to->length();
417
  ptr= beg;
418
  if (csinfo->escape_with_backslash_is_dangerous)
419
    ptr= str_to_hex(ptr, from->ptr(), from->length());
420
  else
421
  {
422
    *ptr++= '\'';
383.1.38 by Monty Taylor
Reworked drizzle_escape_string.
423
    ptr+= drizzle_escape_string(ptr, from->ptr(), from->length());
1 by brian
clean slate
424
    *ptr++='\'';
425
  }
426
  to->length(orig_len + ptr - beg);
427
  return 0;
428
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
429
1 by brian
clean slate
430
431
/**************************************************************************
432
	Log_event methods (= the parent class of all events)
433
**************************************************************************/
434
435
/**
436
  @return
437
  returns the human readable name of the event's type
438
*/
439
440
const char* Log_event::get_type_str(Log_event_type type)
441
{
442
  switch(type) {
443
  case START_EVENT_V3:  return "Start_v3";
444
  case STOP_EVENT:   return "Stop";
445
  case QUERY_EVENT:  return "Query";
446
  case ROTATE_EVENT: return "Rotate";
447
  case INTVAR_EVENT: return "Intvar";
448
  case LOAD_EVENT:   return "Load";
449
  case NEW_LOAD_EVENT:   return "New_load";
450
  case SLAVE_EVENT:  return "Slave";
451
  case CREATE_FILE_EVENT: return "Create_file";
452
  case APPEND_BLOCK_EVENT: return "Append_block";
453
  case DELETE_FILE_EVENT: return "Delete_file";
454
  case EXEC_LOAD_EVENT: return "Exec_load";
455
  case RAND_EVENT: return "RAND";
456
  case XID_EVENT: return "Xid";
457
  case USER_VAR_EVENT: return "User var";
458
  case FORMAT_DESCRIPTION_EVENT: return "Format_desc";
459
  case TABLE_MAP_EVENT: return "Table_map";
460
  case PRE_GA_WRITE_ROWS_EVENT: return "Write_rows_event_old";
461
  case PRE_GA_UPDATE_ROWS_EVENT: return "Update_rows_event_old";
462
  case PRE_GA_DELETE_ROWS_EVENT: return "Delete_rows_event_old";
463
  case WRITE_ROWS_EVENT: return "Write_rows";
464
  case UPDATE_ROWS_EVENT: return "Update_rows";
465
  case DELETE_ROWS_EVENT: return "Delete_rows";
466
  case BEGIN_LOAD_QUERY_EVENT: return "Begin_load_query";
467
  case EXECUTE_LOAD_QUERY_EVENT: return "Execute_load_query";
468
  case INCIDENT_EVENT: return "Incident";
469
  default: return "Unknown";				/* impossible */
470
  }
471
}
472
473
const char* Log_event::get_type_str()
474
{
475
  return get_type_str(get_type_code());
476
}
477
478
479
/*
480
  Log_event::Log_event()
481
*/
482
206 by Brian Aker
Removed final uint dead types.
483
Log_event::Log_event(THD* thd_arg, uint16_t flags_arg, bool using_trans)
1 by brian
clean slate
484
  :log_pos(0), temp_buf(0), exec_time(0), flags(flags_arg), thd(thd_arg)
485
{
486
  server_id=	thd->server_id;
487
  when=		thd->start_time;
488
  cache_stmt=	using_trans;
489
}
490
491
492
/**
493
  This minimal constructor is for when you are not even sure that there
494
  is a valid THD. For example in the server when we are shutting down or
495
  flushing logs after receiving a SIGHUP (then we must write a Rotate to
496
  the binlog but we have no THD, so we need this minimal constructor).
497
*/
498
499
Log_event::Log_event()
500
  :temp_buf(0), exec_time(0), flags(0), cache_stmt(0),
501
   thd(0)
502
{
503
  server_id=	::server_id;
504
  /*
505
    We can't call my_time() here as this would cause a call before
506
    my_init() is called
507
  */
508
  when=		0;
509
  log_pos=	0;
510
}
511
512
513
/*
514
  Log_event::Log_event()
515
*/
516
517
Log_event::Log_event(const char* buf,
518
                     const Format_description_log_event* description_event)
519
  :temp_buf(0), cache_stmt(0)
520
{
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
521
  thd= 0;
522
  when= uint4korr(buf);
523
  server_id= uint4korr(buf + SERVER_ID_OFFSET);
1 by brian
clean slate
524
  data_written= uint4korr(buf + EVENT_LEN_OFFSET);
525
  if (description_event->binlog_version==1)
526
  {
527
    log_pos= 0;
528
    flags= 0;
529
    return;
530
  }
531
  /* 4.0 or newer */
532
  log_pos= uint4korr(buf + LOG_POS_OFFSET);
533
  /*
534
    If the log is 4.0 (so here it can only be a 4.0 relay log read by
535
    the SQL thread or a 4.0 master binlog read by the I/O thread),
536
    log_pos is the beginning of the event: we transform it into the end
537
    of the event, which is more useful.
538
    But how do you know that the log is 4.0: you know it if
539
    description_event is version 3 *and* you are not reading a
540
    Format_desc (remember that mysqlbinlog starts by assuming that 5.0
541
    logs are in 4.0 format, until it finds a Format_desc).
542
  */
543
  if (description_event->binlog_version==3 &&
544
      buf[EVENT_TYPE_OFFSET]<FORMAT_DESCRIPTION_EVENT && log_pos)
545
  {
546
      /*
547
        If log_pos=0, don't change it. log_pos==0 is a marker to mean
548
        "don't change rli->group_master_log_pos" (see
549
        inc_group_relay_log_pos()). As it is unreal log_pos, adding the
550
        event len's is nonsense. For example, a fake Rotate event should
551
        not have its log_pos (which is 0) changed or it will modify
552
        Exec_master_log_pos in SHOW SLAVE STATUS, displaying a nonsense
553
        value of (a non-zero offset which does not exist in the master's
554
        binlog, so which will cause problems if the user uses this value
555
        in CHANGE MASTER).
556
      */
557
    log_pos+= data_written; /* purecov: inspected */
558
  }
559
560
  flags= uint2korr(buf + FLAGS_OFFSET);
561
  if ((buf[EVENT_TYPE_OFFSET] == FORMAT_DESCRIPTION_EVENT) ||
562
      (buf[EVENT_TYPE_OFFSET] == ROTATE_EVENT))
563
  {
564
    /*
565
      These events always have a header which stops here (i.e. their
566
      header is FROZEN).
567
    */
568
    /*
569
      Initialization to zero of all other Log_event members as they're
570
      not specified. Currently there are no such members; in the future
571
      there will be an event UID (but Format_description and Rotate
572
      don't need this UID, as they are not propagated through
573
      --log-slave-updates (remember the UID is used to not play a query
574
      twice when you have two masters which are slaves of a 3rd master).
575
      Then we are done.
576
    */
577
    return;
578
  }
579
  /* otherwise, go on with reading the header from buf (nothing now) */
580
}
581
582
583
int Log_event::do_update_pos(Relay_log_info *rli)
584
{
585
  /*
586
    rli is null when (as far as I (Guilhem) know) the caller is
587
    Load_log_event::do_apply_event *and* that one is called from
588
    Execute_load_log_event::do_apply_event.  In this case, we don't
589
    do anything here ; Execute_load_log_event::do_apply_event will
590
    call Log_event::do_apply_event again later with the proper rli.
591
    Strictly speaking, if we were sure that rli is null only in the
592
    case discussed above, 'if (rli)' is useless here.  But as we are
593
    not 100% sure, keep it for now.
594
595
    Matz: I don't think we will need this check with this refactoring.
596
  */
597
  if (rli)
598
  {
599
    /*
600
      bug#29309 simulation: resetting the flag to force
601
      wrong behaviour of artificial event to update
602
      rli->last_master_timestamp for only one time -
603
      the first FLUSH LOGS in the test.
604
    */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
605
    if (debug_not_change_ts_if_art_event == 1
606
        && is_artificial_event())
607
      debug_not_change_ts_if_art_event= 0;
1 by brian
clean slate
608
    rli->stmt_done(log_pos, 
609
                   is_artificial_event() &&
610
                   debug_not_change_ts_if_art_event > 0 ? 0 : when);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
611
    if (debug_not_change_ts_if_art_event == 0)
612
      debug_not_change_ts_if_art_event= 2;
1 by brian
clean slate
613
  }
614
  return 0;                                   // Cannot fail currently
615
}
616
617
618
Log_event::enum_skip_reason
619
Log_event::do_shall_skip(Relay_log_info *rli)
620
{
621
  if ((server_id == ::server_id && !rli->replicate_same_server_id) || (rli->slave_skip_counter == 1 && rli->is_in_group()))
622
    return EVENT_SKIP_IGNORE;
623
  else if (rli->slave_skip_counter > 0)
624
    return EVENT_SKIP_COUNT;
625
  else
626
    return EVENT_SKIP_NOT;
627
}
628
629
630
/*
631
  Log_event::pack_info()
632
*/
633
634
void Log_event::pack_info(Protocol *protocol)
635
{
636
  protocol->store("", &my_charset_bin);
637
}
638
639
640
/**
641
  init_show_field_list() prepares the column names and types for the
642
  output of SHOW BINLOG EVENTS; it is used only by SHOW BINLOG
643
  EVENTS.
644
*/
645
646
void Log_event::init_show_field_list(List<Item>* field_list)
647
{
648
  field_list->push_back(new Item_empty_string("Log_name", 20));
649
  field_list->push_back(new Item_return_int("Pos", MY_INT32_NUM_DECIMAL_DIGITS,
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
650
					    DRIZZLE_TYPE_LONGLONG));
1 by brian
clean slate
651
  field_list->push_back(new Item_empty_string("Event_type", 20));
652
  field_list->push_back(new Item_return_int("Server_id", 10,
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
653
					    DRIZZLE_TYPE_LONG));
1 by brian
clean slate
654
  field_list->push_back(new Item_return_int("End_log_pos",
655
                                            MY_INT32_NUM_DECIMAL_DIGITS,
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
656
					    DRIZZLE_TYPE_LONGLONG));
1 by brian
clean slate
657
  field_list->push_back(new Item_empty_string("Info", 20));
658
}
659
660
/*
661
  Log_event::write()
662
*/
663
664
bool Log_event::write_header(IO_CACHE* file, ulong event_data_length)
665
{
481 by Brian Aker
Remove all of uchar.
666
  unsigned char header[LOG_EVENT_HEADER_LEN];
1 by brian
clean slate
667
  ulong now;
668
669
  /* Store number of bytes that will be written by this event */
670
  data_written= event_data_length + sizeof(header);
671
672
  /*
673
    log_pos != 0 if this is relay-log event. In this case we should not
674
    change the position
675
  */
676
677
  if (is_artificial_event())
678
  {
679
    /*
680
      We should not do any cleanup on slave when reading this. We
681
      mark this by setting log_pos to 0.  Start_log_event_v3() will
682
      detect this on reading and set artificial_event=1 for the event.
683
    */
684
    log_pos= 0;
685
  }
686
  else  if (!log_pos)
687
  {
688
    /*
689
      Calculate position of end of event
690
691
      Note that with a SEQ_READ_APPEND cache, my_b_tell() does not
692
      work well.  So this will give slightly wrong positions for the
693
      Format_desc/Rotate/Stop events which the slave writes to its
694
      relay log. For example, the initial Format_desc will have
695
      end_log_pos=91 instead of 95. Because after writing the first 4
696
      bytes of the relay log, my_b_tell() still reports 0. Because
697
      my_b_append() does not update the counter which my_b_tell()
698
      later uses (one should probably use my_b_append_tell() to work
699
      around this).  To get right positions even when writing to the
700
      relay log, we use the (new) my_b_safe_tell().
701
702
      Note that this raises a question on the correctness of all these
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
703
      assert(my_b_tell()=rli->event_relay_log_pos).
1 by brian
clean slate
704
705
      If in a transaction, the log_pos which we calculate below is not
706
      very good (because then my_b_safe_tell() returns start position
707
      of the BEGIN, so it's like the statement was at the BEGIN's
708
      place), but it's not a very serious problem (as the slave, when
709
      it is in a transaction, does not take those end_log_pos into
710
      account (as it calls inc_event_relay_log_pos()). To be fixed
711
      later, so that it looks less strange. But not bug.
712
    */
713
714
    log_pos= my_b_safe_tell(file)+data_written;
715
  }
716
717
  now= (ulong) get_time();                              // Query start time
718
719
  /*
720
    Header will be of size LOG_EVENT_HEADER_LEN for all events, except for
721
    FORMAT_DESCRIPTION_EVENT and ROTATE_EVENT, where it will be
722
    LOG_EVENT_MINIMAL_HEADER_LEN (remember these 2 have a frozen header,
723
    because we read them before knowing the format).
724
  */
725
726
  int4store(header, now);              // timestamp
727
  header[EVENT_TYPE_OFFSET]= get_type_code();
728
  int4store(header+ SERVER_ID_OFFSET, server_id);
729
  int4store(header+ EVENT_LEN_OFFSET, data_written);
730
  int4store(header+ LOG_POS_OFFSET, log_pos);
731
  int2store(header+ FLAGS_OFFSET, flags);
732
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
733
  return(my_b_safe_write(file, header, sizeof(header)) != 0);
1 by brian
clean slate
734
}
735
736
737
/**
738
  This needn't be format-tolerant, because we only read
739
  LOG_EVENT_MINIMAL_HEADER_LEN (we just want to read the event's length).
740
*/
741
742
int Log_event::read_log_event(IO_CACHE* file, String* packet,
743
			      pthread_mutex_t* log_lock)
744
{
745
  ulong data_len;
746
  int result=0;
747
  char buf[LOG_EVENT_MINIMAL_HEADER_LEN];
748
749
  if (log_lock)
750
    pthread_mutex_lock(log_lock);
481 by Brian Aker
Remove all of uchar.
751
  if (my_b_read(file, (unsigned char*) buf, sizeof(buf)))
1 by brian
clean slate
752
  {
753
    /*
754
      If the read hits eof, we must report it as eof so the caller
755
      will know it can go into cond_wait to be woken up on the next
756
      update to the log.
757
    */
758
    if (!file->error)
759
      result= LOG_READ_EOF;
760
    else
761
      result= (file->error > 0 ? LOG_READ_TRUNC : LOG_READ_IO);
762
    goto end;
763
  }
764
  data_len= uint4korr(buf + EVENT_LEN_OFFSET);
765
  if (data_len < LOG_EVENT_MINIMAL_HEADER_LEN ||
766
      data_len > current_thd->variables.max_allowed_packet)
767
  {
768
    result= ((data_len < LOG_EVENT_MINIMAL_HEADER_LEN) ? LOG_READ_BOGUS :
769
	     LOG_READ_TOO_LARGE);
770
    goto end;
771
  }
772
773
  /* Append the log event header to packet */
774
  if (packet->append(buf, sizeof(buf)))
775
  {
776
    /* Failed to allocate packet */
777
    result= LOG_READ_MEM;
778
    goto end;
779
  }
780
  data_len-= LOG_EVENT_MINIMAL_HEADER_LEN;
781
  if (data_len)
782
  {
783
    /* Append rest of event, read directly from file into packet */
784
    if (packet->append(file, data_len))
785
    {
786
      /*
787
        Fatal error occured when appending rest of the event
788
        to packet, possible failures:
789
	1. EOF occured when reading from file, it's really an error
790
           as data_len is >=0 there's supposed to be more bytes available.
791
           file->error will have been set to number of bytes left to read
792
        2. Read was interrupted, file->error would normally be set to -1
793
        3. Failed to allocate memory for packet, my_errno
794
           will be ENOMEM(file->error shuold be 0, but since the
795
           memory allocation occurs before the call to read it might
796
           be uninitialized)
797
      */
798
      result= (my_errno == ENOMEM ? LOG_READ_MEM :
799
               (file->error >= 0 ? LOG_READ_TRUNC: LOG_READ_IO));
800
      /* Implicit goto end; */
801
    }
802
  }
803
804
end:
805
  if (log_lock)
806
    pthread_mutex_unlock(log_lock);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
807
  return(result);
1 by brian
clean slate
808
}
809
810
#define UNLOCK_MUTEX if (log_lock) pthread_mutex_unlock(log_lock);
811
#define LOCK_MUTEX if (log_lock) pthread_mutex_lock(log_lock);
812
813
/**
814
  @note
815
    Allocates memory;  The caller is responsible for clean-up.
816
*/
817
Log_event* Log_event::read_log_event(IO_CACHE* file,
818
				     pthread_mutex_t* log_lock,
819
                                     const Format_description_log_event
820
                                     *description_event)
821
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
822
  assert(description_event != 0);
1 by brian
clean slate
823
  char head[LOG_EVENT_MINIMAL_HEADER_LEN];
824
  /*
825
    First we only want to read at most LOG_EVENT_MINIMAL_HEADER_LEN, just to
826
    check the event for sanity and to know its length; no need to really parse
827
    it. We say "at most" because this could be a 3.23 master, which has header
828
    of 13 bytes, whereas LOG_EVENT_MINIMAL_HEADER_LEN is 19 bytes (it's
829
    "minimal" over the set {MySQL >=4.0}).
830
  */
482 by Brian Aker
Remove uint.
831
  uint32_t header_size= cmin(description_event->common_header_len,
1 by brian
clean slate
832
                        LOG_EVENT_MINIMAL_HEADER_LEN);
833
834
  LOCK_MUTEX;
481 by Brian Aker
Remove all of uchar.
835
  if (my_b_read(file, (unsigned char *) head, header_size))
1 by brian
clean slate
836
  {
837
    UNLOCK_MUTEX;
838
    /*
839
      No error here; it could be that we are at the file's end. However
840
      if the next my_b_read() fails (below), it will be an error as we
841
      were able to read the first bytes.
842
    */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
843
    return(0);
1 by brian
clean slate
844
  }
482 by Brian Aker
Remove uint.
845
  uint32_t data_len = uint4korr(head + EVENT_LEN_OFFSET);
1 by brian
clean slate
846
  char *buf= 0;
847
  const char *error= 0;
848
  Log_event *res=  0;
849
#ifndef max_allowed_packet
850
  THD *thd=current_thd;
482 by Brian Aker
Remove uint.
851
  uint32_t max_allowed_packet= thd ? thd->variables.max_allowed_packet : ~(ulong)0;
1 by brian
clean slate
852
#endif
853
854
  if (data_len > max_allowed_packet)
855
  {
856
    error = "Event too big";
857
    goto err;
858
  }
859
860
  if (data_len < header_size)
861
  {
862
    error = "Event too small";
863
    goto err;
864
  }
865
866
  // some events use the extra byte to null-terminate strings
867
  if (!(buf = (char*) my_malloc(data_len+1, MYF(MY_WME))))
868
  {
869
    error = "Out of memory";
870
    goto err;
871
  }
872
  buf[data_len] = 0;
873
  memcpy(buf, head, header_size);
481 by Brian Aker
Remove all of uchar.
874
  if (my_b_read(file, (unsigned char*) buf + header_size, data_len - header_size))
1 by brian
clean slate
875
  {
876
    error = "read error";
877
    goto err;
878
  }
879
  if ((res= read_log_event(buf, data_len, &error, description_event)))
880
    res->register_temp_buf(buf);
881
882
err:
883
  UNLOCK_MUTEX;
884
  if (!res)
885
  {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
886
    assert(error != 0);
340 by Monty Taylor
Got everything using sql_print_*.
887
    sql_print_error(_("Error in Log_event::read_log_event(): "
888
                    "'%s', data_len: %d, event_type: %d"),
1 by brian
clean slate
889
		    error,data_len,head[EVENT_TYPE_OFFSET]);
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
890
    free(buf);
1 by brian
clean slate
891
    /*
892
      The SQL slave thread will check if file->error<0 to know
893
      if there was an I/O error. Even if there is no "low-level" I/O errors
894
      with 'file', any of the high-level above errors is worrying
895
      enough to stop the SQL thread now ; as we are skipping the current event,
896
      going on with reading and successfully executing other events can
897
      only corrupt the slave's databases. So stop.
898
    */
899
    file->error= -1;
900
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
901
  return(res);
1 by brian
clean slate
902
}
903
904
905
/**
906
  Binlog format tolerance is in (buf, event_len, description_event)
907
  constructors.
908
*/
909
482 by Brian Aker
Remove uint.
910
Log_event* Log_event::read_log_event(const char* buf, uint32_t event_len,
1 by brian
clean slate
911
				     const char **error,
912
                                     const Format_description_log_event *description_event)
913
{
914
  Log_event* ev;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
915
  assert(description_event != 0);
1 by brian
clean slate
916
917
  /* Check the integrity */
918
  if (event_len < EVENT_LEN_OFFSET ||
919
      buf[EVENT_TYPE_OFFSET] >= ENUM_END_EVENT ||
920
      (uint) event_len != uint4korr(buf+EVENT_LEN_OFFSET))
921
  {
922
    *error="Sanity check failed";		// Needed to free buffer
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
923
    return(NULL); // general sanity check - will fail on a partial read
1 by brian
clean slate
924
  }
925
482 by Brian Aker
Remove uint.
926
  uint32_t event_type= buf[EVENT_TYPE_OFFSET];
1 by brian
clean slate
927
  if (event_type > description_event->number_of_event_types &&
928
      event_type != FORMAT_DESCRIPTION_EVENT)
929
  {
930
    /*
931
      It is unsafe to use the description_event if its post_header_len
932
      array does not include the event type.
933
    */
934
    ev= NULL;
935
  }
936
  else
937
  {
938
    /*
939
      In some previuos versions (see comment in
940
      Format_description_log_event::Format_description_log_event(char*,...)),
941
      event types were assigned different id numbers than in the
942
      present version. In order to replicate from such versions to the
943
      present version, we must map those event type id's to our event
944
      type id's.  The mapping is done with the event_type_permutation
945
      array, which was set up when the Format_description_log_event
946
      was read.
947
    */
948
    if (description_event->event_type_permutation)
949
      event_type= description_event->event_type_permutation[event_type];
950
951
    switch(event_type) {
952
    case QUERY_EVENT:
953
      ev  = new Query_log_event(buf, event_len, description_event, QUERY_EVENT);
954
      break;
955
    case LOAD_EVENT:
956
      ev = new Load_log_event(buf, event_len, description_event);
957
      break;
958
    case NEW_LOAD_EVENT:
959
      ev = new Load_log_event(buf, event_len, description_event);
960
      break;
961
    case ROTATE_EVENT:
962
      ev = new Rotate_log_event(buf, event_len, description_event);
963
      break;
964
    case CREATE_FILE_EVENT:
965
      ev = new Create_file_log_event(buf, event_len, description_event);
966
      break;
967
    case APPEND_BLOCK_EVENT:
968
      ev = new Append_block_log_event(buf, event_len, description_event);
969
      break;
970
    case DELETE_FILE_EVENT:
971
      ev = new Delete_file_log_event(buf, event_len, description_event);
972
      break;
973
    case EXEC_LOAD_EVENT:
974
      ev = new Execute_load_log_event(buf, event_len, description_event);
975
      break;
976
    case START_EVENT_V3: /* this is sent only by MySQL <=4.x */
977
      ev = new Start_log_event_v3(buf, description_event);
978
      break;
979
    case STOP_EVENT:
980
      ev = new Stop_log_event(buf, description_event);
981
      break;
982
    case INTVAR_EVENT:
983
      ev = new Intvar_log_event(buf, description_event);
984
      break;
985
    case XID_EVENT:
986
      ev = new Xid_log_event(buf, description_event);
987
      break;
988
    case RAND_EVENT:
989
      ev = new Rand_log_event(buf, description_event);
990
      break;
991
    case USER_VAR_EVENT:
992
      ev = new User_var_log_event(buf, description_event);
993
      break;
994
    case FORMAT_DESCRIPTION_EVENT:
995
      ev = new Format_description_log_event(buf, event_len, description_event);
996
      break;
997
    case WRITE_ROWS_EVENT:
998
      ev = new Write_rows_log_event(buf, event_len, description_event);
999
      break;
1000
    case UPDATE_ROWS_EVENT:
1001
      ev = new Update_rows_log_event(buf, event_len, description_event);
1002
      break;
1003
    case DELETE_ROWS_EVENT:
1004
      ev = new Delete_rows_log_event(buf, event_len, description_event);
1005
      break;
1006
    case TABLE_MAP_EVENT:
1007
      ev = new Table_map_log_event(buf, event_len, description_event);
1008
      break;
1009
    case BEGIN_LOAD_QUERY_EVENT:
1010
      ev = new Begin_load_query_log_event(buf, event_len, description_event);
1011
      break;
1012
    case EXECUTE_LOAD_QUERY_EVENT:
1013
      ev= new Execute_load_query_log_event(buf, event_len, description_event);
1014
      break;
1015
    case INCIDENT_EVENT:
1016
      ev = new Incident_log_event(buf, event_len, description_event);
1017
      break;
1018
    default:
1019
      ev= NULL;
1020
      break;
1021
    }
1022
  }
1023
1024
  /*
1025
    is_valid() are small event-specific sanity tests which are
1026
    important; for example there are some my_malloc() in constructors
1027
    (e.g. Query_log_event::Query_log_event(char*...)); when these
1028
    my_malloc() fail we can't return an error out of the constructor
1029
    (because constructor is "void") ; so instead we leave the pointer we
1030
    wanted to allocate (e.g. 'query') to 0 and we test it in is_valid().
1031
    Same for Format_description_log_event, member 'post_header_len'.
1032
  */
1033
  if (!ev || !ev->is_valid())
1034
  {
1035
    delete ev;
1036
    *error= "Found invalid event in binary log";
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1037
    return(0);
1 by brian
clean slate
1038
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1039
  return(ev);  
1 by brian
clean slate
1040
}
1041
1042
inline Log_event::enum_skip_reason
1043
Log_event::continue_group(Relay_log_info *rli)
1044
{
1045
  if (rli->slave_skip_counter == 1)
1046
    return Log_event::EVENT_SKIP_IGNORE;
1047
  return Log_event::do_shall_skip(rli);
1048
}
1049
1050
/**************************************************************************
1051
	Query_log_event methods
1052
**************************************************************************/
1053
1054
/**
1055
  This (which is used only for SHOW BINLOG EVENTS) could be updated to
1056
  print SET @@session_var=. But this is not urgent, as SHOW BINLOG EVENTS is
1057
  only an information, it does not produce suitable queries to replay (for
1058
  example it does not print LOAD DATA INFILE).
1059
  @todo
1060
    show the catalog ??
1061
*/
1062
1063
void Query_log_event::pack_info(Protocol *protocol)
1064
{
1065
  // TODO: show the catalog ??
1066
  char *buf, *pos;
1067
  if (!(buf= (char*) my_malloc(9 + db_len + q_len, MYF(MY_WME))))
1068
    return;
1069
  pos= buf;
1070
  if (!(flags & LOG_EVENT_SUPPRESS_USE_F)
1071
      && db && db_len)
1072
  {
411.1.1 by Brian Aker
Work on removing GNU specific calls.
1073
    pos= my_stpcpy(buf, "use `");
1 by brian
clean slate
1074
    memcpy(pos, db, db_len);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
1075
    pos= my_stpcpy(pos+db_len, "`; ");
1 by brian
clean slate
1076
  }
1077
  if (query && q_len)
1078
  {
1079
    memcpy(pos, query, q_len);
1080
    pos+= q_len;
1081
  }
1082
  protocol->store(buf, pos-buf, &my_charset_bin);
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
1083
  free(buf);
1 by brian
clean slate
1084
}
1085
1086
1087
/**
1088
  Utility function for the next method (Query_log_event::write()) .
1089
*/
1090
static void write_str_with_code_and_len(char **dst, const char *src,
482 by Brian Aker
Remove uint.
1091
                                        int len, uint32_t code)
1 by brian
clean slate
1092
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1093
  assert(src);
1 by brian
clean slate
1094
  *((*dst)++)= code;
481 by Brian Aker
Remove all of uchar.
1095
  *((*dst)++)= (unsigned char) len;
212.6.3 by Mats Kindahl
Removing deprecated functions from code and replacing them with C99 equivalents:
1096
  memcpy(*dst, src, len);
1 by brian
clean slate
1097
  (*dst)+= len;
1098
}
1099
1100
1101
/**
1102
  Query_log_event::write().
1103
1104
  @note
1105
    In this event we have to modify the header to have the correct
1106
    EVENT_LEN_OFFSET as we don't yet know how many status variables we
1107
    will print!
1108
*/
1109
1110
bool Query_log_event::write(IO_CACHE* file)
1111
{
1112
  /**
1113
    @todo if catalog can be of length FN_REFLEN==512, then we are not
1114
    replicating it correctly, since the length is stored in a byte
1115
    /sven
1116
  */
481 by Brian Aker
Remove all of uchar.
1117
  unsigned char buf[QUERY_HEADER_LEN+
1 by brian
clean slate
1118
            1+4+           // code of flags2 and flags2
1119
            1+8+           // code of sql_mode and sql_mode
1120
            1+1+FN_REFLEN+ // code of catalog and catalog length and catalog
1121
            1+4+           // code of autoinc and the 2 autoinc variables
1122
            1+6+           // code of charset and charset
1123
            1+1+MAX_TIME_ZONE_NAME_LENGTH+ // code of tz and tz length and tz name
1124
            1+2+           // code of lc_time_names and lc_time_names_number
1125
            1+2            // code of charset_database and charset_database_number
1126
            ], *start, *start_of_status;
1127
  ulong event_length;
1128
1129
  if (!query)
1130
    return 1;                                   // Something wrong with event
1131
1132
  /*
1133
    We want to store the thread id:
1134
    (- as an information for the user when he reads the binlog)
1135
    - if the query uses temporary table: for the slave SQL thread to know to
1136
    which master connection the temp table belongs.
1137
    Now imagine we (write()) are called by the slave SQL thread (we are
1138
    logging a query executed by this thread; the slave runs with
1139
    --log-slave-updates). Then this query will be logged with
1140
    thread_id=the_thread_id_of_the_SQL_thread. Imagine that 2 temp tables of
1141
    the same name were created simultaneously on the master (in the master
1142
    binlog you have
1143
    CREATE TEMPORARY TABLE t; (thread 1)
1144
    CREATE TEMPORARY TABLE t; (thread 2)
1145
    ...)
1146
    then in the slave's binlog there will be
1147
    CREATE TEMPORARY TABLE t; (thread_id_of_the_slave_SQL_thread)
1148
    CREATE TEMPORARY TABLE t; (thread_id_of_the_slave_SQL_thread)
1149
    which is bad (same thread id!).
1150
1151
    To avoid this, we log the thread's thread id EXCEPT for the SQL
1152
    slave thread for which we log the original (master's) thread id.
1153
    Now this moves the bug: what happens if the thread id on the
1154
    master was 10 and when the slave replicates the query, a
1155
    connection number 10 is opened by a normal client on the slave,
1156
    and updates a temp table of the same name? We get a problem
1157
    again. To avoid this, in the handling of temp tables (sql_base.cc)
1158
    we use thread_id AND server_id.  TODO when this is merged into
1159
    4.1: in 4.1, slave_proxy_id has been renamed to pseudo_thread_id
1160
    and is a session variable: that's to make mysqlbinlog work with
1161
    temp tables. We probably need to introduce
1162
1163
    SET PSEUDO_SERVER_ID
1164
    for mysqlbinlog in 4.1. mysqlbinlog would print:
1165
    SET PSEUDO_SERVER_ID=
1166
    SET PSEUDO_THREAD_ID=
1167
    for each query using temp tables.
1168
  */
1169
  int4store(buf + Q_THREAD_ID_OFFSET, slave_proxy_id);
1170
  int4store(buf + Q_EXEC_TIME_OFFSET, exec_time);
1171
  buf[Q_DB_LEN_OFFSET] = (char) db_len;
1172
  int2store(buf + Q_ERR_CODE_OFFSET, error_code);
1173
1174
  /*
1175
    You MUST always write status vars in increasing order of code. This
1176
    guarantees that a slightly older slave will be able to parse those he
1177
    knows.
1178
  */
1179
  start_of_status= start= buf+QUERY_HEADER_LEN;
1180
  if (flags2_inited)
1181
  {
1182
    *start++= Q_FLAGS2_CODE;
1183
    int4store(start, flags2);
1184
    start+= 4;
1185
  }
1186
  if (sql_mode_inited)
1187
  {
1188
    *start++= Q_SQL_MODE_CODE;
151 by Brian Aker
Ulonglong to uint64_t
1189
    int8store(start, (uint64_t)sql_mode);
1 by brian
clean slate
1190
    start+= 8;
1191
  }
1192
  if (catalog_len) // i.e. this var is inited (false for 4.0 events)
1193
  {
1194
    write_str_with_code_and_len((char **)(&start),
1195
                                catalog, catalog_len, Q_CATALOG_NZ_CODE);
1196
    /*
1197
      In 5.0.x where x<4 masters we used to store the end zero here. This was
1198
      a waste of one byte so we don't do it in x>=4 masters. We change code to
1199
      Q_CATALOG_NZ_CODE, because re-using the old code would make x<4 slaves
1200
      of this x>=4 master segfault (expecting a zero when there is
1201
      none). Remaining compatibility problems are: the older slave will not
1202
      find the catalog; but it is will not crash, and it's not an issue
1203
      that it does not find the catalog as catalogs were not used in these
1204
      older MySQL versions (we store it in binlog and read it from relay log
1205
      but do nothing useful with it). What is an issue is that the older slave
1206
      will stop processing the Q_* blocks (and jumps to the db/query) as soon
1207
      as it sees unknown Q_CATALOG_NZ_CODE; so it will not be able to read
1208
      Q_AUTO_INCREMENT*, Q_CHARSET and so replication will fail silently in
1209
      various ways. Documented that you should not mix alpha/beta versions if
1210
      they are not exactly the same version, with example of 5.0.3->5.0.2 and
1211
      5.0.4->5.0.3. If replication is from older to new, the new will
1212
      recognize Q_CATALOG_CODE and have no problem.
1213
    */
1214
  }
1215
  if (auto_increment_increment != 1 || auto_increment_offset != 1)
1216
  {
1217
    *start++= Q_AUTO_INCREMENT;
1218
    int2store(start, auto_increment_increment);
1219
    int2store(start+2, auto_increment_offset);
1220
    start+= 4;
1221
  }
1222
  if (charset_inited)
1223
  {
1224
    *start++= Q_CHARSET_CODE;
1225
    memcpy(start, charset, 6);
1226
    start+= 6;
1227
  }
1228
  if (time_zone_len)
1229
  {
1230
    /* In the TZ sys table, column Name is of length 64 so this should be ok */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1231
    assert(time_zone_len <= MAX_TIME_ZONE_NAME_LENGTH);
1 by brian
clean slate
1232
    *start++= Q_TIME_ZONE_CODE;
1233
    *start++= time_zone_len;
1234
    memcpy(start, time_zone_str, time_zone_len);
1235
    start+= time_zone_len;
1236
  }
1237
  if (lc_time_names_number)
1238
  {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1239
    assert(lc_time_names_number <= 0xFFFF);
1 by brian
clean slate
1240
    *start++= Q_LC_TIME_NAMES_CODE;
1241
    int2store(start, lc_time_names_number);
1242
    start+= 2;
1243
  }
1244
  if (charset_database_number)
1245
  {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1246
    assert(charset_database_number <= 0xFFFF);
1 by brian
clean slate
1247
    *start++= Q_CHARSET_DATABASE_CODE;
1248
    int2store(start, charset_database_number);
1249
    start+= 2;
1250
  }
1251
  /*
1252
    Here there could be code like
1253
    if (command-line-option-which-says-"log_this_variable" && inited)
1254
    {
1255
    *start++= Q_THIS_VARIABLE_CODE;
1256
    int4store(start, this_variable);
1257
    start+= 4;
1258
    }
1259
  */
1260
  
1261
  /* Store length of status variables */
1262
  status_vars_len= (uint) (start-start_of_status);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1263
  assert(status_vars_len <= MAX_SIZE_LOG_EVENT_STATUS);
1 by brian
clean slate
1264
  int2store(buf + Q_STATUS_VARS_LEN_OFFSET, status_vars_len);
1265
1266
  /*
1267
    Calculate length of whole event
1268
    The "1" below is the \0 in the db's length
1269
  */
1270
  event_length= (uint) (start-buf) + get_post_header_size_for_derived() + db_len + 1 + q_len;
1271
1272
  return (write_header(file, event_length) ||
481 by Brian Aker
Remove all of uchar.
1273
          my_b_safe_write(file, (unsigned char*) buf, QUERY_HEADER_LEN) ||
1 by brian
clean slate
1274
          write_post_header_for_derived(file) ||
481 by Brian Aker
Remove all of uchar.
1275
          my_b_safe_write(file, (unsigned char*) start_of_status,
1 by brian
clean slate
1276
                          (uint) (start-start_of_status)) ||
481 by Brian Aker
Remove all of uchar.
1277
          my_b_safe_write(file, (db) ? (unsigned char*) db : (unsigned char*)"", db_len + 1) ||
1278
          my_b_safe_write(file, (unsigned char*) query, q_len)) ? 1 : 0;
1 by brian
clean slate
1279
}
1280
1281
/**
1282
  The simplest constructor that could possibly work.  This is used for
1283
  creating static objects that have a special meaning and are invisible
1284
  to the log.  
1285
*/
1286
Query_log_event::Query_log_event()
1287
  :Log_event(), data_buf(0)
1288
{
1289
}
1290
1291
1292
/*
1293
  SYNOPSIS
1294
    Query_log_event::Query_log_event()
1295
      thd_arg           - thread handle
1296
      query_arg         - array of char representing the query
1297
      query_length      - size of the  `query_arg' array
1298
      using_trans       - there is a modified transactional table
1299
      suppress_use      - suppress the generation of 'USE' statements
1300
      killed_status_arg - an optional with default to THD::KILLED_NO_VALUE
1301
                          if the value is different from the default, the arg
1302
                          is set to the current thd->killed value.
1303
                          A caller might need to masquerade thd->killed with
1304
                          THD::NOT_KILLED.
1305
  DESCRIPTION
1306
  Creates an event for binlogging
1307
  The value for local `killed_status' can be supplied by caller.
1308
*/
1309
Query_log_event::Query_log_event(THD* thd_arg, const char* query_arg,
1310
				 ulong query_length, bool using_trans,
1311
				 bool suppress_use,
1312
                                 THD::killed_state killed_status_arg)
1313
  :Log_event(thd_arg,
1314
             (thd_arg->thread_specific_used ? LOG_EVENT_THREAD_SPECIFIC_F :
1315
              0) |
1316
             (suppress_use ? LOG_EVENT_SUPPRESS_USE_F : 0),
1317
	     using_trans),
1318
   data_buf(0), query(query_arg), catalog(thd_arg->catalog),
205 by Brian Aker
uint32 -> uin32_t
1319
   db(thd_arg->db), q_len((uint32_t) query_length),
1 by brian
clean slate
1320
   thread_id(thd_arg->thread_id),
1321
   /* save the original thread id; we already know the server id */
1322
   slave_proxy_id(thd_arg->variables.pseudo_thread_id),
1323
   flags2_inited(1), sql_mode_inited(1), charset_inited(1),
1324
   sql_mode(0),
1325
   auto_increment_increment(thd_arg->variables.auto_increment_increment),
1326
   auto_increment_offset(thd_arg->variables.auto_increment_offset),
1327
   lc_time_names_number(thd_arg->variables.lc_time_names->number),
1328
   charset_database_number(0)
1329
{
1330
  time_t end_time;
1331
1332
  if (killed_status_arg == THD::KILLED_NO_VALUE)
1333
    killed_status_arg= thd_arg->killed;
135 by Brian Aker
Random cleanup. Dead partition tests, pass operator in sql_plugin, mtr based
1334
1 by brian
clean slate
1335
  error_code=
1336
    (killed_status_arg == THD::NOT_KILLED) ?
1337
    (thd_arg->is_error() ? thd_arg->main_da.sql_errno() : 0) :
135 by Brian Aker
Random cleanup. Dead partition tests, pass operator in sql_plugin, mtr based
1338
    (thd_arg->killed_errno());
1 by brian
clean slate
1339
  
1340
  time(&end_time);
1341
  exec_time = (ulong) (end_time  - thd_arg->start_time);
1342
  /**
1343
    @todo this means that if we have no catalog, then it is replicated
1344
    as an existing catalog of length zero. is that safe? /sven
1345
  */
205 by Brian Aker
uint32 -> uin32_t
1346
  catalog_len = (catalog) ? (uint32_t) strlen(catalog) : 0;
1 by brian
clean slate
1347
  /* status_vars_len is set just before writing the event */
205 by Brian Aker
uint32 -> uin32_t
1348
  db_len = (db) ? (uint32_t) strlen(db) : 0;
1 by brian
clean slate
1349
  if (thd_arg->variables.collation_database != thd_arg->db_charset)
1350
    charset_database_number= thd_arg->variables.collation_database->number;
1351
  
1352
  /*
1353
    If we don't use flags2 for anything else than options contained in
1354
    thd_arg->options, it would be more efficient to flags2=thd_arg->options
1355
    (OPTIONS_WRITTEN_TO_BIN_LOG would be used only at reading time).
1356
    But it's likely that we don't want to use 32 bits for 3 bits; in the future
1357
    we will probably want to reclaim the 29 bits. So we need the &.
1358
  */
205 by Brian Aker
uint32 -> uin32_t
1359
  flags2= (uint32_t) (thd_arg->options & OPTIONS_WRITTEN_TO_BIN_LOG);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1360
  assert(thd_arg->variables.character_set_client->number < 256*256);
1361
  assert(thd_arg->variables.collation_connection->number < 256*256);
1362
  assert(thd_arg->variables.collation_server->number < 256*256);
1363
  assert(thd_arg->variables.character_set_client->mbminlen == 1);
1 by brian
clean slate
1364
  int2store(charset, thd_arg->variables.character_set_client->number);
1365
  int2store(charset+2, thd_arg->variables.collation_connection->number);
1366
  int2store(charset+4, thd_arg->variables.collation_server->number);
1367
  if (thd_arg->time_zone_used)
1368
  {
1369
    /*
1370
      Note that our event becomes dependent on the Time_zone object
1371
      representing the time zone. Fortunately such objects are never deleted
1372
      or changed during mysqld's lifetime.
1373
    */
1374
    time_zone_len= thd_arg->variables.time_zone->get_name()->length();
1375
    time_zone_str= thd_arg->variables.time_zone->get_name()->ptr();
1376
  }
1377
  else
1378
    time_zone_len= 0;
1379
}
1380
1381
1382
/* 2 utility functions for the next method */
1383
1384
/**
1385
   Read a string with length from memory.
1386
1387
   This function reads the string-with-length stored at
1388
   <code>src</code> and extract the length into <code>*len</code> and
1389
   a pointer to the start of the string into <code>*dst</code>. The
1390
   string can then be copied using <code>memcpy()</code> with the
1391
   number of bytes given in <code>*len</code>.
1392
1393
   @param src Pointer to variable holding a pointer to the memory to
1394
              read the string from.
1395
   @param dst Pointer to variable holding a pointer where the actual
1396
              string starts. Starting from this position, the string
1397
              can be copied using @c memcpy().
1398
   @param len Pointer to variable where the length will be stored.
1399
   @param end One-past-the-end of the memory where the string is
1400
              stored.
1401
1402
   @return    Zero if the entire string can be copied successfully,
1403
              @c UINT_MAX if the length could not be read from memory
1404
              (that is, if <code>*src >= end</code>), otherwise the
1405
              number of bytes that are missing to read the full
1406
              string, which happends <code>*dst + *len >= end</code>.
1407
*/
1408
static int
1409
get_str_len_and_pointer(const Log_event::Byte **src,
1410
                        const char **dst,
482 by Brian Aker
Remove uint.
1411
                        uint32_t *len,
1 by brian
clean slate
1412
                        const Log_event::Byte *end)
1413
{
1414
  if (*src >= end)
1415
    return -1;       // Will be UINT_MAX in two-complement arithmetics
482 by Brian Aker
Remove uint.
1416
  uint32_t length= **src;
1 by brian
clean slate
1417
  if (length > 0)
1418
  {
1419
    if (*src + length >= end)
1420
      return *src + length - end + 1;       // Number of bytes missing
1421
    *dst= (char *)*src + 1;                    // Will be copied later
1422
  }
1423
  *len= length;
1424
  *src+= length + 1;
1425
  return 0;
1426
}
1427
1428
static void copy_str_and_move(const char **src, 
1429
                              Log_event::Byte **dst, 
482 by Brian Aker
Remove uint.
1430
                              uint32_t len)
1 by brian
clean slate
1431
{
1432
  memcpy(*dst, *src, len);
1433
  *src= (const char *)*dst;
1434
  (*dst)+= len;
1435
  *(*dst)++= 0;
1436
}
1437
1438
1439
/**
1440
   Macro to check that there is enough space to read from memory.
1441
1442
   @param PTR Pointer to memory
1443
   @param END End of memory
1444
   @param CNT Number of bytes that should be read.
1445
 */
1446
#define CHECK_SPACE(PTR,END,CNT)                      \
1447
  do {                                                \
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
1448
    assert((PTR) + (CNT) <= (END));                   \
1 by brian
clean slate
1449
    if ((PTR) + (CNT) > (END)) {                      \
1450
      query= 0;                                       \
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
1451
      return;                                         \
1 by brian
clean slate
1452
    }                                                 \
1453
  } while (0)
1454
1455
1456
/**
1457
  This is used by the SQL slave thread to prepare the event before execution.
1458
*/
482 by Brian Aker
Remove uint.
1459
Query_log_event::Query_log_event(const char* buf, uint32_t event_len,
1 by brian
clean slate
1460
                                 const Format_description_log_event
1461
                                 *description_event,
1462
                                 Log_event_type event_type)
461 by Monty Taylor
Removed NullS. bu-bye.
1463
  :Log_event(buf, description_event), data_buf(0), query(NULL),
1464
   db(NULL), catalog_len(0), status_vars_len(0),
1 by brian
clean slate
1465
   flags2_inited(0), sql_mode_inited(0), charset_inited(0),
1466
   auto_increment_increment(1), auto_increment_offset(1),
1467
   time_zone_len(0), lc_time_names_number(0), charset_database_number(0)
1468
{
287.3.8 by Monty Taylor
Oy. Replaced max and min macros with std::max and std::min so that we get
1469
  uint32_t data_len;
205 by Brian Aker
uint32 -> uin32_t
1470
  uint32_t tmp;
206 by Brian Aker
Removed final uint dead types.
1471
  uint8_t common_header_len, post_header_len;
1 by brian
clean slate
1472
  Log_event::Byte *start;
1473
  const Log_event::Byte *end;
1474
  bool catalog_nz= 1;
1475
1476
  common_header_len= description_event->common_header_len;
1477
  post_header_len= description_event->post_header_len[event_type-1];
1478
  
1479
  /*
1480
    We test if the event's length is sensible, and if so we compute data_len.
1481
    We cannot rely on QUERY_HEADER_LEN here as it would not be format-tolerant.
1482
    We use QUERY_HEADER_MINIMAL_LEN which is the same for 3.23, 4.0 & 5.0.
1483
  */
1484
  if (event_len < (uint)(common_header_len + post_header_len))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1485
    return;				
1 by brian
clean slate
1486
  data_len = event_len - (common_header_len + post_header_len);
1487
  buf+= common_header_len;
1488
  
1489
  slave_proxy_id= thread_id = uint4korr(buf + Q_THREAD_ID_OFFSET);
1490
  exec_time = uint4korr(buf + Q_EXEC_TIME_OFFSET);
1491
  db_len = (uint)buf[Q_DB_LEN_OFFSET]; // TODO: add a check of all *_len vars
1492
  error_code = uint2korr(buf + Q_ERR_CODE_OFFSET);
1493
1494
  /*
1495
    5.0 format starts here.
1496
    Depending on the format, we may or not have affected/warnings etc
1497
    The remnent post-header to be parsed has length:
1498
  */
1499
  tmp= post_header_len - QUERY_HEADER_MINIMAL_LEN; 
1500
  if (tmp)
1501
  {
1502
    status_vars_len= uint2korr(buf + Q_STATUS_VARS_LEN_OFFSET);
1503
    /*
1504
      Check if status variable length is corrupt and will lead to very
1505
      wrong data. We could be even more strict and require data_len to
1506
      be even bigger, but this will suffice to catch most corruption
1507
      errors that can lead to a crash.
1508
    */
398.1.4 by Monty Taylor
Renamed max/min.
1509
    if (status_vars_len > cmin(data_len, (uint32_t)MAX_SIZE_LOG_EVENT_STATUS))
1 by brian
clean slate
1510
    {
1511
      query= 0;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1512
      return;
1 by brian
clean slate
1513
    }
1514
    data_len-= status_vars_len;
1515
    tmp-= 2;
1516
  }
1517
  /*
1518
    We have parsed everything we know in the post header for QUERY_EVENT,
1519
    the rest of post header is either comes from older version MySQL or
1520
    dedicated to derived events (e.g. Execute_load_query...)
1521
  */
1522
1523
  /* variable-part: the status vars; only in MySQL 5.0  */
1524
  
1525
  start= (Log_event::Byte*) (buf+post_header_len);
1526
  end= (const Log_event::Byte*) (start+status_vars_len);
1527
  for (const Log_event::Byte* pos= start; pos < end;)
1528
  {
1529
    switch (*pos++) {
1530
    case Q_FLAGS2_CODE:
1531
      CHECK_SPACE(pos, end, 4);
1532
      flags2_inited= 1;
1533
      flags2= uint4korr(pos);
1534
      pos+= 4;
1535
      break;
1536
    case Q_SQL_MODE_CODE:
1537
    {
1538
      CHECK_SPACE(pos, end, 8);
1539
      sql_mode_inited= 1;
151 by Brian Aker
Ulonglong to uint64_t
1540
      sql_mode= (ulong) uint8korr(pos); // QQ: Fix when sql_mode is uint64_t
1 by brian
clean slate
1541
      pos+= 8;
1542
      break;
1543
    }
1544
    case Q_CATALOG_NZ_CODE:
1545
      if (get_str_len_and_pointer(&pos, &catalog, &catalog_len, end))
1546
      {
1547
        query= 0;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1548
        return;
1 by brian
clean slate
1549
      }
1550
      break;
1551
    case Q_AUTO_INCREMENT:
1552
      CHECK_SPACE(pos, end, 4);
1553
      auto_increment_increment= uint2korr(pos);
1554
      auto_increment_offset=    uint2korr(pos+2);
1555
      pos+= 4;
1556
      break;
1557
    case Q_TIME_ZONE_CODE:
1558
    {
1559
      if (get_str_len_and_pointer(&pos, &time_zone_str, &time_zone_len, end))
1560
      {
1561
        query= 0;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1562
        return;
1 by brian
clean slate
1563
      }
1564
      break;
1565
    }
1566
    case Q_CATALOG_CODE: /* for 5.0.x where 0<=x<=3 masters */
1567
      CHECK_SPACE(pos, end, 1);
1568
      if ((catalog_len= *pos))
1569
        catalog= (char*) pos+1;                           // Will be copied later
1570
      CHECK_SPACE(pos, end, catalog_len + 2);
1571
      pos+= catalog_len+2; // leap over end 0
1572
      catalog_nz= 0; // catalog has end 0 in event
1573
      break;
1574
    case Q_LC_TIME_NAMES_CODE:
1575
      CHECK_SPACE(pos, end, 2);
1576
      lc_time_names_number= uint2korr(pos);
1577
      pos+= 2;
1578
      break;
1579
    case Q_CHARSET_DATABASE_CODE:
1580
      CHECK_SPACE(pos, end, 2);
1581
      charset_database_number= uint2korr(pos);
1582
      pos+= 2;
1583
      break;
1584
    default:
1585
      /* That's why you must write status vars in growing order of code */
481 by Brian Aker
Remove all of uchar.
1586
      pos= (const unsigned char*) end;                         // Break loop
1 by brian
clean slate
1587
    }
1588
  }
1589
  
1590
  if (!(start= data_buf = (Log_event::Byte*) my_malloc(catalog_len + 1 +
1591
                                             time_zone_len + 1 +
1592
                                             data_len + 1,
1593
                                             MYF(MY_WME))))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1594
      return;
1 by brian
clean slate
1595
  if (catalog_len)                                  // If catalog is given
1596
  {
1597
    /**
1598
      @todo we should clean up and do only copy_str_and_move; it
1599
      works for both cases.  Then we can remove the catalog_nz
1600
      flag. /sven
1601
    */
1602
    if (likely(catalog_nz)) // true except if event comes from 5.0.0|1|2|3.
1603
      copy_str_and_move(&catalog, &start, catalog_len);
1604
    else
1605
    {
1606
      memcpy(start, catalog, catalog_len+1); // copy end 0
1607
      catalog= (const char *)start;
1608
      start+= catalog_len+1;
1609
    }
1610
  }
1611
  if (time_zone_len)
1612
    copy_str_and_move(&time_zone_str, &start, time_zone_len);
1613
1614
  /**
1615
    if time_zone_len or catalog_len are 0, then time_zone and catalog
1616
    are uninitialized at this point.  shouldn't they point to the
1617
    zero-length null-terminated strings we allocated space for in the
1618
    my_alloc call above? /sven
1619
  */
1620
1621
  /* A 2nd variable part; this is common to all versions */ 
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1622
  memcpy(start, end, data_len);          // Copy db and query
1 by brian
clean slate
1623
  start[data_len]= '\0';              // End query with \0 (For safetly)
1624
  db= (char *)start;
1625
  query= (char *)(start + db_len + 1);
1626
  q_len= data_len - db_len -1;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1627
  return;
1 by brian
clean slate
1628
}
1629
1630
1631
/*
1632
  Query_log_event::do_apply_event()
1633
*/
1634
int Query_log_event::do_apply_event(Relay_log_info const *rli)
1635
{
1636
  return do_apply_event(rli, query, q_len);
1637
}
1638
1639
1640
/**
1641
  @todo
1642
  Compare the values of "affected rows" around here. Something
1643
  like:
1644
  @code
205 by Brian Aker
uint32 -> uin32_t
1645
     if ((uint32_t) affected_in_event != (uint32_t) affected_on_slave)
1 by brian
clean slate
1646
     {
1647
     sql_print_error("Slave: did not get the expected number of affected \
1648
     rows running query from master - expected %d, got %d (this numbers \
1649
     should have matched modulo 4294967296).", 0, ...);
1650
     thd->query_error = 1;
1651
     }
1652
  @endcode
1653
  We may also want an option to tell the slave to ignore "affected"
1654
  mismatch. This mismatch could be implemented with a new ER_ code, and
1655
  to ignore it you would use --slave-skip-errors...
1656
*/
1657
int Query_log_event::do_apply_event(Relay_log_info const *rli,
205 by Brian Aker
uint32 -> uin32_t
1658
                                      const char *query_arg, uint32_t q_len_arg)
1 by brian
clean slate
1659
{
1660
  LEX_STRING new_db;
1661
  int expected_error,actual_error= 0;
1662
  /*
1663
    Colleagues: please never free(thd->catalog) in MySQL. This would
1664
    lead to bugs as here thd->catalog is a part of an alloced block,
1665
    not an entire alloced block (see
1666
    Query_log_event::do_apply_event()). Same for thd->db.  Thank
1667
    you.
1668
  */
1669
  thd->catalog= catalog_len ? (char *) catalog : (char *)"";
1670
  new_db.length= db_len;
1671
  new_db.str= (char *) rpl_filter->get_rewrite_db(db, &new_db.length);
1672
  thd->set_db(new_db.str, new_db.length);       /* allocates a copy of 'db' */
1673
  thd->variables.auto_increment_increment= auto_increment_increment;
1674
  thd->variables.auto_increment_offset=    auto_increment_offset;
1675
1676
  /*
1677
    InnoDB internally stores the master log position it has executed so far,
1678
    i.e. the position just after the COMMIT event.
1679
    When InnoDB will want to store, the positions in rli won't have
1680
    been updated yet, so group_master_log_* will point to old BEGIN
1681
    and event_master_log* will point to the beginning of current COMMIT.
1682
    But log_pos of the COMMIT Query event is what we want, i.e. the pos of the
1683
    END of the current log event (COMMIT). We save it in rli so that InnoDB can
1684
    access it.
1685
  */
1686
  const_cast<Relay_log_info*>(rli)->future_group_master_log_pos= log_pos;
1687
1688
  clear_all_errors(thd, const_cast<Relay_log_info*>(rli));
1689
  const_cast<Relay_log_info*>(rli)->clear_tables_to_lock();
1690
1691
  /*
1692
    Note:   We do not need to execute reset_one_shot_variables() if this
1693
            db_ok() test fails.
1694
    Reason: The db stored in binlog events is the same for SET and for
1695
            its companion query.  If the SET is ignored because of
1696
            db_ok(), the companion query will also be ignored, and if
1697
            the companion query is ignored in the db_ok() test of
1698
            ::do_apply_event(), then the companion SET also have so
1699
            we don't need to reset_one_shot_variables().
1700
  */
1701
  if (rpl_filter->db_ok(thd->db))
1702
  {
1703
    thd->set_time((time_t)when);
1704
    thd->query_length= q_len_arg;
1705
    thd->query= (char*)query_arg;
398.1.6 by Monty Taylor
Removed __alpha__ references.
1706
    pthread_mutex_lock(&LOCK_thread_count);
1 by brian
clean slate
1707
    thd->query_id = next_query_id();
398.1.6 by Monty Taylor
Removed __alpha__ references.
1708
    pthread_mutex_unlock(&LOCK_thread_count);
1 by brian
clean slate
1709
    thd->variables.pseudo_thread_id= thread_id;		// for temp tables
1710
1711
    if (ignored_error_code((expected_error= error_code)) ||
1712
	!check_expected_error(thd,rli,expected_error))
1713
    {
1714
      if (flags2_inited)
1715
        /*
1716
          all bits of thd->options which are 1 in OPTIONS_WRITTEN_TO_BIN_LOG
1717
          must take their value from flags2.
1718
        */
1719
        thd->options= flags2|(thd->options & ~OPTIONS_WRITTEN_TO_BIN_LOG);
1720
      if (time_zone_len)
1721
      {
1722
        String tmp(time_zone_str, time_zone_len, &my_charset_bin);
1723
        if (!(thd->variables.time_zone= my_tz_find(thd, &tmp)))
1724
        {
1725
          my_error(ER_UNKNOWN_TIME_ZONE, MYF(0), tmp.c_ptr());
1726
          thd->variables.time_zone= global_system_variables.time_zone;
1727
          goto compare_errors;
1728
        }
1729
      }
1730
      if (lc_time_names_number)
1731
      {
1732
        if (!(thd->variables.lc_time_names=
1733
              my_locale_by_number(lc_time_names_number)))
1734
        {
1735
          my_printf_error(ER_UNKNOWN_ERROR,
1736
                      "Unknown locale: '%d'", MYF(0), lc_time_names_number);
1737
          thd->variables.lc_time_names= &my_locale_en_US;
1738
          goto compare_errors;
1739
        }
1740
      }
1741
      else
1742
        thd->variables.lc_time_names= &my_locale_en_US;
1743
      if (charset_database_number)
1744
      {
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1745
        const CHARSET_INFO *cs;
1 by brian
clean slate
1746
        if (!(cs= get_charset(charset_database_number, MYF(0))))
1747
        {
1748
          char buf[20];
1749
          int10_to_str((int) charset_database_number, buf, -10);
1750
          my_error(ER_UNKNOWN_COLLATION, MYF(0), buf);
1751
          goto compare_errors;
1752
        }
1753
        thd->variables.collation_database= cs;
1754
      }
1755
      else
1756
        thd->variables.collation_database= thd->db_charset;
1757
      
1758
      /* Execute the query (note that we bypass dispatch_command()) */
1759
      const char* found_semicolon= NULL;
1760
      mysql_parse(thd, thd->query, thd->query_length, &found_semicolon);
1761
      log_slow_statement(thd);
1762
    }
1763
    else
1764
    {
1765
      /*
1766
        The query got a really bad error on the master (thread killed etc),
1767
        which could be inconsistent. Parse it to test the table names: if the
1768
        replicate-*-do|ignore-table rules say "this query must be ignored" then
1769
        we exit gracefully; otherwise we warn about the bad error and tell DBA
1770
        to check/fix it.
1771
      */
1772
      if (mysql_test_parse_for_slave(thd, thd->query, thd->query_length))
1773
        clear_all_errors(thd, const_cast<Relay_log_info*>(rli)); /* Can ignore query */
1774
      else
1775
      {
398.1.7 by Monty Taylor
Marked some new translations.
1776
        rli->report(ERROR_LEVEL, expected_error,
1777
                    _("Query partially completed on the master "
1778
                      "(error on master: %d) and was aborted. There is a "
1779
                      "chance that your master is inconsistent at this "
1780
                      "point. If you are sure that your master is ok, run "
1781
                      "this query manually on the slave and then restart the "
1782
                      "slave with SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; "
1783
                      "START SLAVE; . Query: '%s'"),
1784
                    expected_error, thd->query);
1 by brian
clean slate
1785
        thd->is_slave_error= 1;
1786
      }
1787
      goto end;
1788
    }
1789
1790
compare_errors:
1791
1792
     /*
1793
      If we expected a non-zero error code, and we don't get the same error
1794
      code, and none of them should be ignored.
1795
    */
1796
    actual_error= thd->is_error() ? thd->main_da.sql_errno() : 0;
1797
    if ((expected_error != actual_error) &&
398.1.7 by Monty Taylor
Marked some new translations.
1798
        expected_error &&
1799
        !ignored_error_code(actual_error) &&
1800
        !ignored_error_code(expected_error))
1 by brian
clean slate
1801
    {
1802
      rli->report(ERROR_LEVEL, 0,
398.1.7 by Monty Taylor
Marked some new translations.
1803
                  _("Query caused differenxt errors on master and slave.\n"
1804
                    "Error on master: '%s' (%d), Error on slave: '%s' (%d).\n"
1805
                    "Default database: '%s'. Query: '%s'"),
1806
                  ER_SAFE(expected_error),
1807
                  expected_error,
1808
                  actual_error ? thd->main_da.message() : _("no error"),
1809
                  actual_error,
1810
                  print_slave_db_safe(db), query_arg);
1 by brian
clean slate
1811
      thd->is_slave_error= 1;
1812
    }
1813
    /*
1814
      If we get the same error code as expected, or they should be ignored. 
1815
    */
1816
    else if (expected_error == actual_error ||
1817
 	     ignored_error_code(actual_error))
1818
    {
1819
      clear_all_errors(thd, const_cast<Relay_log_info*>(rli));
1820
      thd->killed= THD::NOT_KILLED;
1821
    }
1822
    /*
1823
      Other cases: mostly we expected no error and get one.
1824
    */
1825
    else if (thd->is_slave_error || thd->is_fatal_error)
1826
    {
1827
      rli->report(ERROR_LEVEL, actual_error,
398.1.7 by Monty Taylor
Marked some new translations.
1828
                  _("Error '%s' on query. Default database: '%s'. Query: '%s'"),
1829
                  (actual_error ? thd->main_da.message() :
1830
                   _("unexpected success or fatal error")),
1 by brian
clean slate
1831
                      print_slave_db_safe(thd->db), query_arg);
1832
      thd->is_slave_error= 1;
1833
    }
1834
1835
    /*
1836
      TODO: compare the values of "affected rows" around here. Something
1837
      like:
205 by Brian Aker
uint32 -> uin32_t
1838
      if ((uint32_t) affected_in_event != (uint32_t) affected_on_slave)
1 by brian
clean slate
1839
      {
1840
      sql_print_error("Slave: did not get the expected number of affected \
1841
      rows running query from master - expected %d, got %d (this numbers \
1842
      should have matched modulo 4294967296).", 0, ...);
1843
      thd->is_slave_error = 1;
1844
      }
1845
      We may also want an option to tell the slave to ignore "affected"
1846
      mismatch. This mismatch could be implemented with a new ER_ code, and
1847
      to ignore it you would use --slave-skip-errors...
1848
1849
      To do the comparison we need to know the value of "affected" which the
1850
      above mysql_parse() computed. And we need to know the value of
1851
      "affected" in the master's binlog. Both will be implemented later. The
1852
      important thing is that we now have the format ready to log the values
1853
      of "affected" in the binlog. So we can release 5.0.0 before effectively
1854
      logging "affected" and effectively comparing it.
1855
    */
1856
  } /* End of if (db_ok(... */
1857
1858
end:
398.1.6 by Monty Taylor
Removed __alpha__ references.
1859
  pthread_mutex_lock(&LOCK_thread_count);
1 by brian
clean slate
1860
  /*
1861
    Probably we have set thd->query, thd->db, thd->catalog to point to places
1862
    in the data_buf of this event. Now the event is going to be deleted
1863
    probably, so data_buf will be freed, so the thd->... listed above will be
1864
    pointers to freed memory. 
1865
    So we must set them to 0, so that those bad pointers values are not later
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1866
    used. Note that "cleanup" queries like automatic DROP TEMPORARY Table
1 by brian
clean slate
1867
    don't suffer from these assignments to 0 as DROP TEMPORARY
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1868
    Table uses the db.table syntax.
1 by brian
clean slate
1869
  */
1870
  thd->catalog= 0;
1871
  thd->set_db(NULL, 0);                 /* will free the current database */
1872
  thd->query= 0;			// just to be sure
1873
  thd->query_length= 0;
398.1.6 by Monty Taylor
Removed __alpha__ references.
1874
  pthread_mutex_unlock(&LOCK_thread_count);
1 by brian
clean slate
1875
  close_thread_tables(thd);      
1876
  /*
1877
    As a disk space optimization, future masters will not log an event for
1878
    LAST_INSERT_ID() if that function returned 0 (and thus they will be able
1879
    to replace the THD::stmt_depends_on_first_successful_insert_id_in_prev_stmt
1880
    variable by (THD->first_successful_insert_id_in_prev_stmt > 0) ; with the
1881
    resetting below we are ready to support that.
1882
  */
1883
  thd->first_successful_insert_id_in_prev_stmt_for_binlog= 0;
1884
  thd->first_successful_insert_id_in_prev_stmt= 0;
1885
  thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
1886
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1887
  return thd->is_slave_error;
1888
}
1889
1890
int Query_log_event::do_update_pos(Relay_log_info *rli)
1891
{
1892
  /*
1893
    Note that we will not increment group* positions if we are just
1894
    after a SET ONE_SHOT, because SET ONE_SHOT should not be separated
1895
    from its following updating query.
1896
  */
1897
  if (thd->one_shot_set)
1898
  {
1899
    rli->inc_event_relay_log_pos();
1900
    return 0;
1901
  }
1902
  else
1903
    return Log_event::do_update_pos(rli);
1904
}
1905
1906
1907
Log_event::enum_skip_reason
1908
Query_log_event::do_shall_skip(Relay_log_info *rli)
1909
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1910
  assert(query && q_len > 0);
1 by brian
clean slate
1911
1912
  if (rli->slave_skip_counter > 0)
1913
  {
1914
    if (strcmp("BEGIN", query) == 0)
1915
    {
1916
      thd->options|= OPTION_BEGIN;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1917
      return(Log_event::continue_group(rli));
1 by brian
clean slate
1918
    }
1919
1920
    if (strcmp("COMMIT", query) == 0 || strcmp("ROLLBACK", query) == 0)
1921
    {
1922
      thd->options&= ~OPTION_BEGIN;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1923
      return(Log_event::EVENT_SKIP_COUNT);
1 by brian
clean slate
1924
    }
1925
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1926
  return(Log_event::do_shall_skip(rli));
1 by brian
clean slate
1927
}
1928
1929
1930
/**************************************************************************
1931
	Start_log_event_v3 methods
1932
**************************************************************************/
1933
1934
Start_log_event_v3::Start_log_event_v3()
1935
  :Log_event(), created(0), binlog_version(BINLOG_VERSION),
1936
   artificial_event(0), dont_set_created(0)
1937
{
1938
  memcpy(server_version, ::server_version, ST_SERVER_VER_LEN);
1939
}
1940
1941
/*
1942
  Start_log_event_v3::pack_info()
1943
*/
1944
1945
void Start_log_event_v3::pack_info(Protocol *protocol)
1946
{
1947
  char buf[12 + ST_SERVER_VER_LEN + 14 + 22], *pos;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
1948
  pos= my_stpcpy(buf, "Server ver: ");
1949
  pos= my_stpcpy(pos, server_version);
1950
  pos= my_stpcpy(pos, ", Binlog ver: ");
1 by brian
clean slate
1951
  pos= int10_to_str(binlog_version, pos, 10);
1952
  protocol->store(buf, (uint) (pos-buf), &my_charset_bin);
1953
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
1954
1 by brian
clean slate
1955
1956
/*
1957
  Start_log_event_v3::Start_log_event_v3()
1958
*/
1959
1960
Start_log_event_v3::Start_log_event_v3(const char* buf,
1961
                                       const Format_description_log_event
1962
                                       *description_event)
1963
  :Log_event(buf, description_event)
1964
{
1965
  buf+= description_event->common_header_len;
1966
  binlog_version= uint2korr(buf+ST_BINLOG_VER_OFFSET);
1967
  memcpy(server_version, buf+ST_SERVER_VER_OFFSET,
1968
	 ST_SERVER_VER_LEN);
1969
  // prevent overrun if log is corrupted on disk
1970
  server_version[ST_SERVER_VER_LEN-1]= 0;
1971
  created= uint4korr(buf+ST_CREATED_OFFSET);
1972
  /* We use log_pos to mark if this was an artificial event or not */
1973
  artificial_event= (log_pos == 0);
1974
  dont_set_created= 1;
1975
}
1976
1977
1978
/*
1979
  Start_log_event_v3::write()
1980
*/
1981
1982
bool Start_log_event_v3::write(IO_CACHE* file)
1983
{
1984
  char buff[START_V3_HEADER_LEN];
1985
  int2store(buff + ST_BINLOG_VER_OFFSET,binlog_version);
1986
  memcpy(buff + ST_SERVER_VER_OFFSET,server_version,ST_SERVER_VER_LEN);
1987
  if (!dont_set_created)
1988
    created= when= get_time();
1989
  int4store(buff + ST_CREATED_OFFSET,created);
1990
  return (write_header(file, sizeof(buff)) ||
481 by Brian Aker
Remove all of uchar.
1991
          my_b_safe_write(file, (unsigned char*) buff, sizeof(buff)));
1 by brian
clean slate
1992
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
1993
1 by brian
clean slate
1994
1995
/**
1996
  Start_log_event_v3::do_apply_event() .
1997
  The master started
1998
1999
    IMPLEMENTATION
2000
    - To handle the case where the master died without having time to write
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2001
    DROP TEMPORARY Table, DO RELEASE_LOCK (prepared statements' deletion is
1 by brian
clean slate
2002
    TODO), we clean up all temporary tables that we got, if we are sure we
2003
    can (see below).
2004
2005
  @todo
2006
    - Remove all active user locks.
2007
    Guilhem 2003-06: this is true but not urgent: the worst it can cause is
2008
    the use of a bit of memory for a user lock which will not be used
2009
    anymore. If the user lock is later used, the old one will be released. In
2010
    other words, no deadlock problem.
2011
*/
2012
2013
int Start_log_event_v3::do_apply_event(Relay_log_info const *rli)
2014
{
2015
  switch (binlog_version)
2016
  {
2017
  case 3:
2018
  case 4:
2019
    /*
2020
      This can either be 4.x (then a Start_log_event_v3 is only at master
2021
      startup so we are sure the master has restarted and cleared his temp
2022
      tables; the event always has 'created'>0) or 5.0 (then we have to test
2023
      'created').
2024
    */
2025
    if (created)
2026
    {
2027
      close_temporary_tables(thd);
2028
      cleanup_load_tmpdir();
2029
    }
2030
    break;
2031
2032
    /*
2033
       Now the older formats; in that case load_tmpdir is cleaned up by the I/O
2034
       thread.
2035
    */
2036
  case 1:
2037
    if (strncmp(rli->relay_log.description_event_for_exec->server_version,
2038
                "3.23.57",7) >= 0 && created)
2039
    {
2040
      /*
2041
        Can distinguish, based on the value of 'created': this event was
2042
        generated at master startup.
2043
      */
2044
      close_temporary_tables(thd);
2045
    }
2046
    /*
2047
      Otherwise, can't distinguish a Start_log_event generated at
2048
      master startup and one generated by master FLUSH LOGS, so cannot
2049
      be sure temp tables have to be dropped. So do nothing.
2050
    */
2051
    break;
2052
  default:
2053
    /* this case is impossible */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2054
    return(1);
1 by brian
clean slate
2055
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2056
  return(0);
1 by brian
clean slate
2057
}
2058
2059
/***************************************************************************
2060
       Format_description_log_event methods
2061
****************************************************************************/
2062
2063
/**
2064
  Format_description_log_event 1st ctor.
2065
2066
    Ctor. Can be used to create the event to write to the binary log (when the
2067
    server starts or when FLUSH LOGS), or to create artificial events to parse
2068
    binlogs from MySQL 3.23 or 4.x.
2069
    When in a client, only the 2nd use is possible.
2070
2071
  @param binlog_version         the binlog version for which we want to build
2072
                                an event. Can be 1 (=MySQL 3.23), 3 (=4.0.x
2073
                                x>=2 and 4.1) or 4 (MySQL 5.0). Note that the
2074
                                old 4.0 (binlog version 2) is not supported;
2075
                                it should not be used for replication with
2076
                                5.0.
2077
*/
2078
2079
Format_description_log_event::
206 by Brian Aker
Removed final uint dead types.
2080
Format_description_log_event(uint8_t binlog_ver, const char* server_ver)
1 by brian
clean slate
2081
  :Start_log_event_v3(), event_type_permutation(0)
2082
{
2083
  binlog_version= binlog_ver;
2084
  switch (binlog_ver) {
2085
  case 4: /* MySQL 5.0 */
2086
    memcpy(server_version, ::server_version, ST_SERVER_VER_LEN);
2087
    common_header_len= LOG_EVENT_HEADER_LEN;
2088
    number_of_event_types= LOG_EVENT_TYPES;
2089
    /* we'll catch my_malloc() error in is_valid() */
206 by Brian Aker
Removed final uint dead types.
2090
    post_header_len=(uint8_t*) my_malloc(number_of_event_types*sizeof(uint8_t),
1 by brian
clean slate
2091
                                       MYF(MY_ZEROFILL));
2092
    /*
2093
      This long list of assignments is not beautiful, but I see no way to
2094
      make it nicer, as the right members are #defines, not array members, so
2095
      it's impossible to write a loop.
2096
    */
2097
    if (post_header_len)
2098
    {
2099
      post_header_len[START_EVENT_V3-1]= START_V3_HEADER_LEN;
2100
      post_header_len[QUERY_EVENT-1]= QUERY_HEADER_LEN;
2101
      post_header_len[ROTATE_EVENT-1]= ROTATE_HEADER_LEN;
2102
      post_header_len[LOAD_EVENT-1]= LOAD_HEADER_LEN;
2103
      post_header_len[CREATE_FILE_EVENT-1]= CREATE_FILE_HEADER_LEN;
2104
      post_header_len[APPEND_BLOCK_EVENT-1]= APPEND_BLOCK_HEADER_LEN;
2105
      post_header_len[EXEC_LOAD_EVENT-1]= EXEC_LOAD_HEADER_LEN;
2106
      post_header_len[DELETE_FILE_EVENT-1]= DELETE_FILE_HEADER_LEN;
2107
      post_header_len[NEW_LOAD_EVENT-1]= post_header_len[LOAD_EVENT-1];
2108
      post_header_len[FORMAT_DESCRIPTION_EVENT-1]= FORMAT_DESCRIPTION_HEADER_LEN;
2109
      post_header_len[TABLE_MAP_EVENT-1]=    TABLE_MAP_HEADER_LEN;
2110
      post_header_len[WRITE_ROWS_EVENT-1]=   ROWS_HEADER_LEN;
2111
      post_header_len[UPDATE_ROWS_EVENT-1]=  ROWS_HEADER_LEN;
2112
      post_header_len[DELETE_ROWS_EVENT-1]=  ROWS_HEADER_LEN;
2113
      post_header_len[BEGIN_LOAD_QUERY_EVENT-1]= post_header_len[APPEND_BLOCK_EVENT-1];
2114
      post_header_len[EXECUTE_LOAD_QUERY_EVENT-1]= EXECUTE_LOAD_QUERY_HEADER_LEN;
2115
      post_header_len[INCIDENT_EVENT-1]= INCIDENT_HEADER_LEN;
2116
      post_header_len[HEARTBEAT_LOG_EVENT-1]= 0;
2117
    }
2118
    break;
2119
2120
  case 1: /* 3.23 */
2121
  case 3: /* 4.0.x x>=2 */
2122
    /*
2123
      We build an artificial (i.e. not sent by the master) event, which
2124
      describes what those old master versions send.
2125
    */
2126
    if (binlog_ver==1)
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2127
      my_stpcpy(server_version, server_ver ? server_ver : "3.23");
1 by brian
clean slate
2128
    else
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2129
      my_stpcpy(server_version, server_ver ? server_ver : "4.0");
1 by brian
clean slate
2130
    common_header_len= binlog_ver==1 ? OLD_HEADER_LEN :
2131
      LOG_EVENT_MINIMAL_HEADER_LEN;
2132
    /*
2133
      The first new event in binlog version 4 is Format_desc. So any event type
2134
      after that does not exist in older versions. We use the events known by
2135
      version 3, even if version 1 had only a subset of them (this is not a
2136
      problem: it uses a few bytes for nothing but unifies code; it does not
2137
      make the slave detect less corruptions).
2138
    */
2139
    number_of_event_types= FORMAT_DESCRIPTION_EVENT - 1;
206 by Brian Aker
Removed final uint dead types.
2140
    post_header_len=(uint8_t*) my_malloc(number_of_event_types*sizeof(uint8_t),
1 by brian
clean slate
2141
                                       MYF(0));
2142
    if (post_header_len)
2143
    {
2144
      post_header_len[START_EVENT_V3-1]= START_V3_HEADER_LEN;
2145
      post_header_len[QUERY_EVENT-1]= QUERY_HEADER_MINIMAL_LEN;
2146
      post_header_len[STOP_EVENT-1]= 0;
2147
      post_header_len[ROTATE_EVENT-1]= (binlog_ver==1) ? 0 : ROTATE_HEADER_LEN;
2148
      post_header_len[INTVAR_EVENT-1]= 0;
2149
      post_header_len[LOAD_EVENT-1]= LOAD_HEADER_LEN;
2150
      post_header_len[SLAVE_EVENT-1]= 0;
2151
      post_header_len[CREATE_FILE_EVENT-1]= CREATE_FILE_HEADER_LEN;
2152
      post_header_len[APPEND_BLOCK_EVENT-1]= APPEND_BLOCK_HEADER_LEN;
2153
      post_header_len[EXEC_LOAD_EVENT-1]= EXEC_LOAD_HEADER_LEN;
2154
      post_header_len[DELETE_FILE_EVENT-1]= DELETE_FILE_HEADER_LEN;
2155
      post_header_len[NEW_LOAD_EVENT-1]= post_header_len[LOAD_EVENT-1];
2156
      post_header_len[RAND_EVENT-1]= 0;
2157
      post_header_len[USER_VAR_EVENT-1]= 0;
2158
    }
2159
    break;
2160
  default: /* Includes binlog version 2 i.e. 4.0.x x<=1 */
2161
    post_header_len= 0; /* will make is_valid() fail */
2162
    break;
2163
  }
2164
  calc_server_version_split();
2165
}
2166
2167
2168
/**
2169
  The problem with this constructor is that the fixed header may have a
2170
  length different from this version, but we don't know this length as we
2171
  have not read the Format_description_log_event which says it, yet. This
2172
  length is in the post-header of the event, but we don't know where the
2173
  post-header starts.
2174
2175
  So this type of event HAS to:
2176
  - either have the header's length at the beginning (in the header, at a
2177
  fixed position which will never be changed), not in the post-header. That
2178
  would make the header be "shifted" compared to other events.
2179
  - or have a header of size LOG_EVENT_MINIMAL_HEADER_LEN (19), in all future
2180
  versions, so that we know for sure.
2181
2182
  I (Guilhem) chose the 2nd solution. Rotate has the same constraint (because
2183
  it is sent before Format_description_log_event).
2184
*/
2185
2186
Format_description_log_event::
2187
Format_description_log_event(const char* buf,
482 by Brian Aker
Remove uint.
2188
                             uint32_t event_len,
1 by brian
clean slate
2189
                             const
2190
                             Format_description_log_event*
2191
                             description_event)
2192
  :Start_log_event_v3(buf, description_event), event_type_permutation(0)
2193
{
2194
  buf+= LOG_EVENT_MINIMAL_HEADER_LEN;
2195
  if ((common_header_len=buf[ST_COMMON_HEADER_LEN_OFFSET]) < OLD_HEADER_LEN)
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2196
    return; /* sanity check */
1 by brian
clean slate
2197
  number_of_event_types=
2198
    event_len-(LOG_EVENT_MINIMAL_HEADER_LEN+ST_COMMON_HEADER_LEN_OFFSET+1);
2199
  /* If alloc fails, we'll detect it in is_valid() */
481 by Brian Aker
Remove all of uchar.
2200
  post_header_len= (uint8_t*) my_memdup((unsigned char*)buf+ST_COMMON_HEADER_LEN_OFFSET+1,
1 by brian
clean slate
2201
                                      number_of_event_types*
2202
                                      sizeof(*post_header_len), MYF(0));
2203
  calc_server_version_split();
2204
2205
  /*
2206
    In some previous versions, the events were given other event type
2207
    id numbers than in the present version. When replicating from such
2208
    a version, we therefore set up an array that maps those id numbers
2209
    to the id numbers of the present server.
2210
2211
    If post_header_len is null, it means malloc failed, and is_valid
2212
    will fail, so there is no need to do anything.
2213
2214
    The trees in which events have wrong id's are:
2215
2216
    mysql-5.1-wl1012.old mysql-5.1-wl2325-5.0-drop6p13-alpha
2217
    mysql-5.1-wl2325-5.0-drop6 mysql-5.1-wl2325-5.0
2218
    mysql-5.1-wl2325-no-dd
2219
2220
    (this was found by grepping for two lines in sequence where the
2221
    first matches "FORMAT_DESCRIPTION_EVENT," and the second matches
2222
    "TABLE_MAP_EVENT," in log_event.h in all trees)
2223
2224
    In these trees, the following server_versions existed since
2225
    TABLE_MAP_EVENT was introduced:
2226
2227
    5.1.1-a_drop5p3   5.1.1-a_drop5p4        5.1.1-alpha
2228
    5.1.2-a_drop5p10  5.1.2-a_drop5p11       5.1.2-a_drop5p12
2229
    5.1.2-a_drop5p13  5.1.2-a_drop5p14       5.1.2-a_drop5p15
2230
    5.1.2-a_drop5p16  5.1.2-a_drop5p16b      5.1.2-a_drop5p16c
2231
    5.1.2-a_drop5p17  5.1.2-a_drop5p4        5.1.2-a_drop5p5
2232
    5.1.2-a_drop5p6   5.1.2-a_drop5p7        5.1.2-a_drop5p8
2233
    5.1.2-a_drop5p9   5.1.3-a_drop5p17       5.1.3-a_drop5p17b
2234
    5.1.3-a_drop5p17c 5.1.4-a_drop5p18       5.1.4-a_drop5p19
2235
    5.1.4-a_drop5p20  5.1.4-a_drop6p0        5.1.4-a_drop6p1
2236
    5.1.4-a_drop6p2   5.1.5-a_drop5p20       5.2.0-a_drop6p3
2237
    5.2.0-a_drop6p4   5.2.0-a_drop6p5        5.2.0-a_drop6p6
2238
    5.2.1-a_drop6p10  5.2.1-a_drop6p11       5.2.1-a_drop6p12
2239
    5.2.1-a_drop6p6   5.2.1-a_drop6p7        5.2.1-a_drop6p8
2240
    5.2.2-a_drop6p13  5.2.2-a_drop6p13-alpha 5.2.2-a_drop6p13b
2241
    5.2.2-a_drop6p13c
2242
2243
    (this was found by grepping for "mysql," in all historical
2244
    versions of configure.in in the trees listed above).
2245
2246
    There are 5.1.1-alpha versions that use the new event id's, so we
2247
    do not test that version string.  So replication from 5.1.1-alpha
2248
    with the other event id's to a new version does not work.
2249
    Moreover, we can safely ignore the part after drop[56].  This
2250
    allows us to simplify the big list above to the following regexes:
2251
2252
    5\.1\.[1-5]-a_drop5.*
2253
    5\.1\.4-a_drop6.*
2254
    5\.2\.[0-2]-a_drop6.*
2255
2256
    This is what we test for in the 'if' below.
2257
  */
2258
  if (post_header_len &&
2259
      server_version[0] == '5' && server_version[1] == '.' &&
2260
      server_version[3] == '.' &&
2261
      strncmp(server_version + 5, "-a_drop", 7) == 0 &&
2262
      ((server_version[2] == '1' &&
2263
        server_version[4] >= '1' && server_version[4] <= '5' &&
2264
        server_version[12] == '5') ||
2265
       (server_version[2] == '1' &&
2266
        server_version[4] == '4' &&
2267
        server_version[12] == '6') ||
2268
       (server_version[2] == '2' &&
2269
        server_version[4] >= '0' && server_version[4] <= '2' &&
2270
        server_version[12] == '6')))
2271
  {
2272
    if (number_of_event_types != 22)
2273
    {
2274
      /* this makes is_valid() return false. */
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
2275
      free(post_header_len);
1 by brian
clean slate
2276
      post_header_len= NULL;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2277
      return;
1 by brian
clean slate
2278
    }
206 by Brian Aker
Removed final uint dead types.
2279
    static const uint8_t perm[23]=
1 by brian
clean slate
2280
      {
2281
        UNKNOWN_EVENT, START_EVENT_V3, QUERY_EVENT, STOP_EVENT, ROTATE_EVENT,
2282
        INTVAR_EVENT, LOAD_EVENT, SLAVE_EVENT, CREATE_FILE_EVENT,
2283
        APPEND_BLOCK_EVENT, EXEC_LOAD_EVENT, DELETE_FILE_EVENT,
2284
        NEW_LOAD_EVENT,
2285
        RAND_EVENT, USER_VAR_EVENT,
2286
        FORMAT_DESCRIPTION_EVENT,
2287
        TABLE_MAP_EVENT,
2288
        PRE_GA_WRITE_ROWS_EVENT,
2289
        PRE_GA_UPDATE_ROWS_EVENT,
2290
        PRE_GA_DELETE_ROWS_EVENT,
2291
        XID_EVENT,
2292
        BEGIN_LOAD_QUERY_EVENT,
2293
        EXECUTE_LOAD_QUERY_EVENT,
2294
      };
2295
    event_type_permutation= perm;
2296
    /*
2297
      Since we use (permuted) event id's to index the post_header_len
2298
      array, we need to permute the post_header_len array too.
2299
    */
206 by Brian Aker
Removed final uint dead types.
2300
    uint8_t post_header_len_temp[23];
1 by brian
clean slate
2301
    for (int i= 1; i < 23; i++)
2302
      post_header_len_temp[perm[i] - 1]= post_header_len[i - 1];
2303
    for (int i= 0; i < 22; i++)
2304
      post_header_len[i] = post_header_len_temp[i];
2305
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2306
  return;
1 by brian
clean slate
2307
}
2308
2309
bool Format_description_log_event::write(IO_CACHE* file)
2310
{
2311
  /*
2312
    We don't call Start_log_event_v3::write() because this would make 2
2313
    my_b_safe_write().
2314
  */
481 by Brian Aker
Remove all of uchar.
2315
  unsigned char buff[FORMAT_DESCRIPTION_HEADER_LEN];
1 by brian
clean slate
2316
  int2store(buff + ST_BINLOG_VER_OFFSET,binlog_version);
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
2317
  memcpy(buff + ST_SERVER_VER_OFFSET,server_version,ST_SERVER_VER_LEN);
1 by brian
clean slate
2318
  if (!dont_set_created)
2319
    created= when= get_time();
2320
  int4store(buff + ST_CREATED_OFFSET,created);
2321
  buff[ST_COMMON_HEADER_LEN_OFFSET]= LOG_EVENT_HEADER_LEN;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
2322
  memcpy(buff+ST_COMMON_HEADER_LEN_OFFSET+1, post_header_len,
1 by brian
clean slate
2323
         LOG_EVENT_TYPES);
2324
  return (write_header(file, sizeof(buff)) ||
2325
          my_b_safe_write(file, buff, sizeof(buff)));
2326
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
2327
2328
1 by brian
clean slate
2329
int Format_description_log_event::do_apply_event(Relay_log_info const *rli)
2330
{
2331
  /*
2332
    As a transaction NEVER spans on 2 or more binlogs:
2333
    if we have an active transaction at this point, the master died
2334
    while writing the transaction to the binary log, i.e. while
2335
    flushing the binlog cache to the binlog. XA guarantees that master has
2336
    rolled back. So we roll back.
2337
    Note: this event could be sent by the master to inform us of the
2338
    format of its binlog; in other words maybe it is not at its
2339
    original place when it comes to us; we'll know this by checking
2340
    log_pos ("artificial" events have log_pos == 0).
2341
  */
2342
  if (!artificial_event && created && thd->transaction.all.ha_list)
2343
  {
2344
    /* This is not an error (XA is safe), just an information */
2345
    rli->report(INFORMATION_LEVEL, 0,
398.1.7 by Monty Taylor
Marked some new translations.
2346
                _("Rolling back unfinished transaction (no COMMIT "
2347
                  "or ROLLBACK in relay log). A probable cause is that "
2348
                  "the master died while writing the transaction to "
2349
                  "its binary log, thus rolled back too."));
1 by brian
clean slate
2350
    const_cast<Relay_log_info*>(rli)->cleanup_context(thd, 1);
2351
  }
2352
  /*
2353
    If this event comes from ourselves, there is no cleaning task to
2354
    perform, we don't call Start_log_event_v3::do_apply_event()
2355
    (this was just to update the log's description event).
2356
  */
205 by Brian Aker
uint32 -> uin32_t
2357
  if (server_id != (uint32_t) ::server_id)
1 by brian
clean slate
2358
  {
2359
    /*
2360
      If the event was not requested by the slave i.e. the master sent
2361
      it while the slave asked for a position >4, the event will make
2362
      rli->group_master_log_pos advance. Say that the slave asked for
2363
      position 1000, and the Format_desc event's end is 96. Then in
2364
      the beginning of replication rli->group_master_log_pos will be
2365
      0, then 96, then jump to first really asked event (which is
2366
      >96). So this is ok.
2367
    */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2368
    return(Start_log_event_v3::do_apply_event(rli));
1 by brian
clean slate
2369
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2370
  return(0);
1 by brian
clean slate
2371
}
2372
2373
int Format_description_log_event::do_update_pos(Relay_log_info *rli)
2374
{
2375
  /* save the information describing this binlog */
2376
  delete rli->relay_log.description_event_for_exec;
2377
  rli->relay_log.description_event_for_exec= this;
2378
205 by Brian Aker
uint32 -> uin32_t
2379
  if (server_id == (uint32_t) ::server_id)
1 by brian
clean slate
2380
  {
2381
    /*
2382
      We only increase the relay log position if we are skipping
2383
      events and do not touch any group_* variables, nor flush the
2384
      relay log info.  If there is a crash, we will have to re-skip
2385
      the events again, but that is a minor issue.
2386
2387
      If we do not skip stepping the group log position (and the
2388
      server id was changed when restarting the server), it might well
2389
      be that we start executing at a position that is invalid, e.g.,
2390
      at a Rows_log_event or a Query_log_event preceeded by a
2391
      Intvar_log_event instead of starting at a Table_map_log_event or
2392
      the Intvar_log_event respectively.
2393
     */
2394
    rli->inc_event_relay_log_pos();
2395
    return 0;
2396
  }
2397
  else
2398
  {
2399
    return Log_event::do_update_pos(rli);
2400
  }
2401
}
2402
2403
Log_event::enum_skip_reason
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
2404
Format_description_log_event::do_shall_skip(Relay_log_info *rli __attribute__((unused)))
1 by brian
clean slate
2405
{
2406
  return Log_event::EVENT_SKIP_NOT;
2407
}
2408
2409
2410
/**
2411
   Splits the event's 'server_version' string into three numeric pieces stored
2412
   into 'server_version_split':
2413
   X.Y.Zabc (X,Y,Z numbers, a not a digit) -> {X,Y,Z}
2414
   X.Yabc -> {X,Y,0}
2415
   Xabc -> {X,0,0}
2416
   'server_version_split' is then used for lookups to find if the server which
2417
   created this event has some known bug.
2418
*/
2419
void Format_description_log_event::calc_server_version_split()
2420
{
2421
  char *p= server_version, *r;
2422
  ulong number;
482 by Brian Aker
Remove uint.
2423
  for (uint32_t i= 0; i<=2; i++)
1 by brian
clean slate
2424
  {
2425
    number= strtoul(p, &r, 10);
481 by Brian Aker
Remove all of uchar.
2426
    server_version_split[i]= (unsigned char)number;
2427
    assert(number < 256); // fit in unsigned char
1 by brian
clean slate
2428
    p= r;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2429
    assert(!((i == 0) && (*r != '.'))); // should be true in practice
1 by brian
clean slate
2430
    if (*r == '.')
2431
      p++; // skip the dot
2432
  }
2433
}
2434
2435
2436
  /**************************************************************************
2437
        Load_log_event methods
2438
   General note about Load_log_event: the binlogging of LOAD DATA INFILE is
2439
   going to be changed in 5.0 (or maybe in 5.1; not decided yet).
2440
   However, the 5.0 slave could still have to read such events (from a 4.x
2441
   master), convert them (which just means maybe expand the header, when 5.0
2442
   servers have a UID in events) (remember that whatever is after the header
2443
   will be like in 4.x, as this event's format is not modified in 5.0 as we
2444
   will use new types of events to log the new LOAD DATA INFILE features).
2445
   To be able to read/convert, we just need to not assume that the common
2446
   header is of length LOG_EVENT_HEADER_LEN (we must use the description
2447
   event).
2448
   Note that I (Guilhem) manually tested replication of a big LOAD DATA INFILE
2449
   between 3.23 and 5.0, and between 4.0 and 5.0, and it works fine (and the
2450
   positions displayed in SHOW SLAVE STATUS then are fine too).
2451
  **************************************************************************/
2452
2453
/*
2454
  Load_log_event::pack_info()
2455
*/
2456
482 by Brian Aker
Remove uint.
2457
uint32_t Load_log_event::get_query_buffer_length()
1 by brian
clean slate
2458
{
2459
  return
2460
    5 + db_len + 3 +                        // "use DB; "
2461
    18 + fname_len + 2 +                    // "LOAD DATA INFILE 'file''"
2462
    7 +					    // LOCAL
2463
    9 +                                     // " REPLACE or IGNORE "
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2464
    13 + table_name_len*2 +                 // "INTO Table `table`"
1 by brian
clean slate
2465
    21 + sql_ex.field_term_len*4 + 2 +      // " FIELDS TERMINATED BY 'str'"
2466
    23 + sql_ex.enclosed_len*4 + 2 +        // " OPTIONALLY ENCLOSED BY 'str'"
2467
    12 + sql_ex.escaped_len*4 + 2 +         // " ESCAPED BY 'str'"
2468
    21 + sql_ex.line_term_len*4 + 2 +       // " LINES TERMINATED BY 'str'"
2469
    19 + sql_ex.line_start_len*4 + 2 +      // " LINES STARTING BY 'str'"
2470
    15 + 22 +                               // " IGNORE xxx  LINES"
2471
    3 + (num_fields-1)*2 + field_block_len; // " (field1, field2, ...)"
2472
}
2473
2474
2475
void Load_log_event::print_query(bool need_db, char *buf,
2476
                                 char **end, char **fn_start, char **fn_end)
2477
{
2478
  char *pos= buf;
2479
2480
  if (need_db && db && db_len)
2481
  {
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2482
    pos= my_stpcpy(pos, "use `");
1 by brian
clean slate
2483
    memcpy(pos, db, db_len);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2484
    pos= my_stpcpy(pos+db_len, "`; ");
1 by brian
clean slate
2485
  }
2486
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2487
  pos= my_stpcpy(pos, "LOAD DATA ");
1 by brian
clean slate
2488
2489
  if (fn_start)
2490
    *fn_start= pos;
2491
2492
  if (check_fname_outside_temp_buf())
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2493
    pos= my_stpcpy(pos, "LOCAL ");
2494
  pos= my_stpcpy(pos, "INFILE '");
1 by brian
clean slate
2495
  memcpy(pos, fname, fname_len);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2496
  pos= my_stpcpy(pos+fname_len, "' ");
1 by brian
clean slate
2497
2498
  if (sql_ex.opt_flags & REPLACE_FLAG)
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2499
    pos= my_stpcpy(pos, " REPLACE ");
1 by brian
clean slate
2500
  else if (sql_ex.opt_flags & IGNORE_FLAG)
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2501
    pos= my_stpcpy(pos, " IGNORE ");
1 by brian
clean slate
2502
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2503
  pos= my_stpcpy(pos ,"INTO");
1 by brian
clean slate
2504
2505
  if (fn_end)
2506
    *fn_end= pos;
2507
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2508
  pos= my_stpcpy(pos ," Table `");
1 by brian
clean slate
2509
  memcpy(pos, table_name, table_name_len);
2510
  pos+= table_name_len;
2511
2512
  /* We have to create all optinal fields as the default is not empty */
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2513
  pos= my_stpcpy(pos, "` FIELDS TERMINATED BY ");
1 by brian
clean slate
2514
  pos= pretty_print_str(pos, sql_ex.field_term, sql_ex.field_term_len);
2515
  if (sql_ex.opt_flags & OPT_ENCLOSED_FLAG)
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2516
    pos= my_stpcpy(pos, " OPTIONALLY ");
2517
  pos= my_stpcpy(pos, " ENCLOSED BY ");
1 by brian
clean slate
2518
  pos= pretty_print_str(pos, sql_ex.enclosed, sql_ex.enclosed_len);
2519
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2520
  pos= my_stpcpy(pos, " ESCAPED BY ");
1 by brian
clean slate
2521
  pos= pretty_print_str(pos, sql_ex.escaped, sql_ex.escaped_len);
2522
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2523
  pos= my_stpcpy(pos, " LINES TERMINATED BY ");
1 by brian
clean slate
2524
  pos= pretty_print_str(pos, sql_ex.line_term, sql_ex.line_term_len);
2525
  if (sql_ex.line_start_len)
2526
  {
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2527
    pos= my_stpcpy(pos, " STARTING BY ");
1 by brian
clean slate
2528
    pos= pretty_print_str(pos, sql_ex.line_start, sql_ex.line_start_len);
2529
  }
2530
2531
  if ((long) skip_lines > 0)
2532
  {
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2533
    pos= my_stpcpy(pos, " IGNORE ");
152 by Brian Aker
longlong replacement
2534
    pos= int64_t10_to_str((int64_t) skip_lines, pos, 10);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2535
    pos= my_stpcpy(pos," LINES ");    
1 by brian
clean slate
2536
  }
2537
2538
  if (num_fields)
2539
  {
482 by Brian Aker
Remove uint.
2540
    uint32_t i;
1 by brian
clean slate
2541
    const char *field= fields;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
2542
    pos= my_stpcpy(pos, " (");
1 by brian
clean slate
2543
    for (i = 0; i < num_fields; i++)
2544
    {
2545
      if (i)
2546
      {
2547
        *pos++= ' ';
2548
        *pos++= ',';
2549
      }
2550
      memcpy(pos, field, field_lens[i]);
2551
      pos+=   field_lens[i];
2552
      field+= field_lens[i]  + 1;
2553
    }
2554
    *pos++= ')';
2555
  }
2556
2557
  *end= pos;
2558
}
2559
2560
2561
void Load_log_event::pack_info(Protocol *protocol)
2562
{
2563
  char *buf, *end;
2564
2565
  if (!(buf= (char*) my_malloc(get_query_buffer_length(), MYF(MY_WME))))
2566
    return;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2567
  print_query(true, buf, &end, 0, 0);
1 by brian
clean slate
2568
  protocol->store(buf, end-buf, &my_charset_bin);
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
2569
  free(buf);
1 by brian
clean slate
2570
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
2571
1 by brian
clean slate
2572
2573
/*
2574
  Load_log_event::write_data_header()
2575
*/
2576
2577
bool Load_log_event::write_data_header(IO_CACHE* file)
2578
{
2579
  char buf[LOAD_HEADER_LEN];
2580
  int4store(buf + L_THREAD_ID_OFFSET, slave_proxy_id);
2581
  int4store(buf + L_EXEC_TIME_OFFSET, exec_time);
2582
  int4store(buf + L_SKIP_LINES_OFFSET, skip_lines);
2583
  buf[L_TBL_LEN_OFFSET] = (char)table_name_len;
2584
  buf[L_DB_LEN_OFFSET] = (char)db_len;
2585
  int4store(buf + L_NUM_FIELDS_OFFSET, num_fields);
481 by Brian Aker
Remove all of uchar.
2586
  return my_b_safe_write(file, (unsigned char*)buf, LOAD_HEADER_LEN) != 0;
1 by brian
clean slate
2587
}
2588
2589
2590
/*
2591
  Load_log_event::write_data_body()
2592
*/
2593
2594
bool Load_log_event::write_data_body(IO_CACHE* file)
2595
{
2596
  if (sql_ex.write_data(file))
2597
    return 1;
2598
  if (num_fields && fields && field_lens)
2599
  {
481 by Brian Aker
Remove all of uchar.
2600
    if (my_b_safe_write(file, (unsigned char*)field_lens, num_fields) ||
2601
	my_b_safe_write(file, (unsigned char*)fields, field_block_len))
1 by brian
clean slate
2602
      return 1;
2603
  }
481 by Brian Aker
Remove all of uchar.
2604
  return (my_b_safe_write(file, (unsigned char*)table_name, table_name_len + 1) ||
2605
	  my_b_safe_write(file, (unsigned char*)db, db_len + 1) ||
2606
	  my_b_safe_write(file, (unsigned char*)fname, fname_len));
1 by brian
clean slate
2607
}
2608
2609
2610
/*
2611
  Load_log_event::Load_log_event()
2612
*/
2613
2614
Load_log_event::Load_log_event(THD *thd_arg, sql_exchange *ex,
2615
			       const char *db_arg, const char *table_name_arg,
2616
			       List<Item> &fields_arg,
2617
			       enum enum_duplicates handle_dup,
2618
			       bool ignore, bool using_trans)
2619
  :Log_event(thd_arg,
2620
             thd_arg->thread_specific_used ? LOG_EVENT_THREAD_SPECIFIC_F : 0,
2621
             using_trans),
2622
   thread_id(thd_arg->thread_id),
2623
   slave_proxy_id(thd_arg->variables.pseudo_thread_id),
2624
   num_fields(0),fields(0),
2625
   field_lens(0),field_block_len(0),
2626
   table_name(table_name_arg ? table_name_arg : ""),
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2627
   db(db_arg), fname(ex->file_name), local_fname(false)
1 by brian
clean slate
2628
{
2629
  time_t end_time;
2630
  time(&end_time);
2631
  exec_time = (ulong) (end_time  - thd_arg->start_time);
2632
  /* db can never be a zero pointer in 4.0 */
205 by Brian Aker
uint32 -> uin32_t
2633
  db_len = (uint32_t) strlen(db);
2634
  table_name_len = (uint32_t) strlen(table_name);
1 by brian
clean slate
2635
  fname_len = (fname) ? (uint) strlen(fname) : 0;
2636
  sql_ex.field_term = (char*) ex->field_term->ptr();
206 by Brian Aker
Removed final uint dead types.
2637
  sql_ex.field_term_len = (uint8_t) ex->field_term->length();
1 by brian
clean slate
2638
  sql_ex.enclosed = (char*) ex->enclosed->ptr();
206 by Brian Aker
Removed final uint dead types.
2639
  sql_ex.enclosed_len = (uint8_t) ex->enclosed->length();
1 by brian
clean slate
2640
  sql_ex.line_term = (char*) ex->line_term->ptr();
206 by Brian Aker
Removed final uint dead types.
2641
  sql_ex.line_term_len = (uint8_t) ex->line_term->length();
1 by brian
clean slate
2642
  sql_ex.line_start = (char*) ex->line_start->ptr();
206 by Brian Aker
Removed final uint dead types.
2643
  sql_ex.line_start_len = (uint8_t) ex->line_start->length();
1 by brian
clean slate
2644
  sql_ex.escaped = (char*) ex->escaped->ptr();
206 by Brian Aker
Removed final uint dead types.
2645
  sql_ex.escaped_len = (uint8_t) ex->escaped->length();
1 by brian
clean slate
2646
  sql_ex.opt_flags = 0;
2647
  sql_ex.cached_new_format = -1;
2648
    
2649
  if (ex->dumpfile)
2650
    sql_ex.opt_flags|= DUMPFILE_FLAG;
2651
  if (ex->opt_enclosed)
2652
    sql_ex.opt_flags|= OPT_ENCLOSED_FLAG;
2653
2654
  sql_ex.empty_flags= 0;
2655
2656
  switch (handle_dup) {
2657
  case DUP_REPLACE:
2658
    sql_ex.opt_flags|= REPLACE_FLAG;
2659
    break;
2660
  case DUP_UPDATE:				// Impossible here
2661
  case DUP_ERROR:
2662
    break;	
2663
  }
2664
  if (ignore)
2665
    sql_ex.opt_flags|= IGNORE_FLAG;
2666
2667
  if (!ex->field_term->length())
2668
    sql_ex.empty_flags |= FIELD_TERM_EMPTY;
2669
  if (!ex->enclosed->length())
2670
    sql_ex.empty_flags |= ENCLOSED_EMPTY;
2671
  if (!ex->line_term->length())
2672
    sql_ex.empty_flags |= LINE_TERM_EMPTY;
2673
  if (!ex->line_start->length())
2674
    sql_ex.empty_flags |= LINE_START_EMPTY;
2675
  if (!ex->escaped->length())
2676
    sql_ex.empty_flags |= ESCAPED_EMPTY;
2677
    
2678
  skip_lines = ex->skip_lines;
2679
2680
  List_iterator<Item> li(fields_arg);
2681
  field_lens_buf.length(0);
2682
  fields_buf.length(0);
2683
  Item* item;
2684
  while ((item = li++))
2685
  {
2686
    num_fields++;
481 by Brian Aker
Remove all of uchar.
2687
    unsigned char len = (unsigned char) strlen(item->name);
1 by brian
clean slate
2688
    field_block_len += len + 1;
2689
    fields_buf.append(item->name, len + 1);
2690
    field_lens_buf.append((char*)&len, 1);
2691
  }
2692
481 by Brian Aker
Remove all of uchar.
2693
  field_lens = (const unsigned char*)field_lens_buf.ptr();
1 by brian
clean slate
2694
  fields = fields_buf.ptr();
2695
}
2696
2697
2698
/**
2699
  @note
2700
    The caller must do buf[event_len] = 0 before he starts using the
2701
    constructed event.
2702
*/
482 by Brian Aker
Remove uint.
2703
Load_log_event::Load_log_event(const char *buf, uint32_t event_len,
1 by brian
clean slate
2704
                               const Format_description_log_event *description_event)
2705
  :Log_event(buf, description_event), num_fields(0), fields(0),
2706
   field_lens(0),field_block_len(0),
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2707
   table_name(0), db(0), fname(0), local_fname(false)
1 by brian
clean slate
2708
{
2709
  /*
2710
    I (Guilhem) manually tested replication of LOAD DATA INFILE for 3.23->5.0,
2711
    4.0->5.0 and 5.0->5.0 and it works.
2712
  */
2713
  if (event_len)
2714
    copy_log_event(buf, event_len,
2715
                   ((buf[EVENT_TYPE_OFFSET] == LOAD_EVENT) ?
2716
                    LOAD_HEADER_LEN + 
2717
                    description_event->common_header_len :
2718
                    LOAD_HEADER_LEN + LOG_EVENT_HEADER_LEN),
2719
                   description_event);
2720
  /* otherwise it's a derived class, will call copy_log_event() itself */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2721
  return;
1 by brian
clean slate
2722
}
2723
2724
2725
/*
2726
  Load_log_event::copy_log_event()
2727
*/
2728
2729
int Load_log_event::copy_log_event(const char *buf, ulong event_len,
2730
                                   int body_offset,
2731
                                   const Format_description_log_event *description_event)
2732
{
482 by Brian Aker
Remove uint.
2733
  uint32_t data_len;
1 by brian
clean slate
2734
  char* buf_end = (char*)buf + event_len;
2735
  /* this is the beginning of the post-header */
2736
  const char* data_head = buf + description_event->common_header_len;
2737
  slave_proxy_id= thread_id= uint4korr(data_head + L_THREAD_ID_OFFSET);
2738
  exec_time = uint4korr(data_head + L_EXEC_TIME_OFFSET);
2739
  skip_lines = uint4korr(data_head + L_SKIP_LINES_OFFSET);
2740
  table_name_len = (uint)data_head[L_TBL_LEN_OFFSET];
2741
  db_len = (uint)data_head[L_DB_LEN_OFFSET];
2742
  num_fields = uint4korr(data_head + L_NUM_FIELDS_OFFSET);
2743
	  
2744
  if ((int) event_len < body_offset)
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2745
    return(1);
1 by brian
clean slate
2746
  /*
2747
    Sql_ex.init() on success returns the pointer to the first byte after
2748
    the sql_ex structure, which is the start of field lengths array.
2749
  */
481 by Brian Aker
Remove all of uchar.
2750
  if (!(field_lens= (unsigned char*)sql_ex.init((char*)buf + body_offset,
1 by brian
clean slate
2751
                                        buf_end,
2752
                                        buf[EVENT_TYPE_OFFSET] != LOAD_EVENT)))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2753
    return(1);
1 by brian
clean slate
2754
  
2755
  data_len = event_len - body_offset;
2756
  if (num_fields > data_len) // simple sanity check against corruption
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2757
    return(1);
482 by Brian Aker
Remove uint.
2758
  for (uint32_t i = 0; i < num_fields; i++)
1 by brian
clean slate
2759
    field_block_len += (uint)field_lens[i] + 1;
2760
2761
  fields = (char*)field_lens + num_fields;
2762
  table_name  = fields + field_block_len;
2763
  db = table_name + table_name_len + 1;
2764
  fname = db + db_len + 1;
2765
  fname_len = strlen(fname);
2766
  // null termination is accomplished by the caller doing buf[event_len]=0
2767
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2768
  return(0);
1 by brian
clean slate
2769
}
2770
2771
2772
/**
2773
  Load_log_event::set_fields()
2774
2775
  @note
2776
    This function can not use the member variable 
2777
    for the database, since LOAD DATA INFILE on the slave
2778
    can be for a different database than the current one.
2779
    This is the reason for the affected_db argument to this method.
2780
*/
2781
2782
void Load_log_event::set_fields(const char* affected_db, 
2783
				List<Item> &field_list,
2784
                                Name_resolution_context *context)
2785
{
482 by Brian Aker
Remove uint.
2786
  uint32_t i;
1 by brian
clean slate
2787
  const char* field = fields;
2788
  for (i= 0; i < num_fields; i++)
2789
  {
2790
    field_list.push_back(new Item_field(context,
2791
                                        affected_db, table_name, field));
2792
    field+= field_lens[i]  + 1;
2793
  }
2794
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
2795
2796
1 by brian
clean slate
2797
/**
2798
  Does the data loading job when executing a LOAD DATA on the slave.
2799
2800
  @param net
2801
  @param rli
2802
  @param use_rli_only_for_errors     If set to 1, rli is provided to
2803
                                     Load_log_event::exec_event only for this
2804
                                     function to have RPL_LOG_NAME and
2805
                                     rli->last_slave_error, both being used by
2806
                                     error reports. rli's position advancing
2807
                                     is skipped (done by the caller which is
2808
                                     Execute_load_log_event::exec_event).
2809
                                     If set to 0, rli is provided for full use,
2810
                                     i.e. for error reports and position
2811
                                     advancing.
2812
2813
  @todo
2814
    fix this; this can be done by testing rules in
2815
    Create_file_log_event::exec_event() and then discarding Append_block and
2816
    al.
2817
  @todo
2818
    this is a bug - this needs to be moved to the I/O thread
2819
2820
  @retval
2821
    0           Success
2822
  @retval
2823
    1           Failure
2824
*/
2825
2826
int Load_log_event::do_apply_event(NET* net, Relay_log_info const *rli,
2827
                                   bool use_rli_only_for_errors)
2828
{
2829
  LEX_STRING new_db;
2830
  new_db.length= db_len;
2831
  new_db.str= (char *) rpl_filter->get_rewrite_db(db, &new_db.length);
2832
  thd->set_db(new_db.str, new_db.length);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2833
  assert(thd->query == 0);
1 by brian
clean slate
2834
  thd->query_length= 0;                         // Should not be needed
2835
  thd->is_slave_error= 0;
2836
  clear_all_errors(thd, const_cast<Relay_log_info*>(rli));
2837
2838
  /* see Query_log_event::do_apply_event() and BUG#13360 */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2839
  assert(!rli->m_table_map.count());
1 by brian
clean slate
2840
  /*
2841
    Usually lex_start() is called by mysql_parse(), but we need it here
2842
    as the present method does not call mysql_parse().
2843
  */
2844
  lex_start(thd);
2845
  mysql_reset_thd_for_next_command(thd);
2846
2847
  if (!use_rli_only_for_errors)
2848
  {
2849
    /*
2850
      Saved for InnoDB, see comment in
2851
      Query_log_event::do_apply_event()
2852
    */
2853
    const_cast<Relay_log_info*>(rli)->future_group_master_log_pos= log_pos;
2854
  }
2855
 
2856
   /*
2857
    We test replicate_*_db rules. Note that we have already prepared
2858
    the file to load, even if we are going to ignore and delete it
2859
    now. So it is possible that we did a lot of disk writes for
2860
    nothing. In other words, a big LOAD DATA INFILE on the master will
2861
    still consume a lot of space on the slave (space in the relay log
2862
    + space of temp files: twice the space of the file to load...)
2863
    even if it will finally be ignored.  TODO: fix this; this can be
2864
    done by testing rules in Create_file_log_event::do_apply_event()
2865
    and then discarding Append_block and al. Another way is do the
2866
    filtering in the I/O thread (more efficient: no disk writes at
2867
    all).
2868
2869
2870
    Note:   We do not need to execute reset_one_shot_variables() if this
2871
            db_ok() test fails.
2872
    Reason: The db stored in binlog events is the same for SET and for
2873
            its companion query.  If the SET is ignored because of
2874
            db_ok(), the companion query will also be ignored, and if
2875
            the companion query is ignored in the db_ok() test of
2876
            ::do_apply_event(), then the companion SET also have so
2877
            we don't need to reset_one_shot_variables().
2878
  */
2879
  if (rpl_filter->db_ok(thd->db))
2880
  {
2881
    thd->set_time((time_t)when);
398.1.6 by Monty Taylor
Removed __alpha__ references.
2882
    pthread_mutex_lock(&LOCK_thread_count);
1 by brian
clean slate
2883
    thd->query_id = next_query_id();
398.1.6 by Monty Taylor
Removed __alpha__ references.
2884
    pthread_mutex_unlock(&LOCK_thread_count);
1 by brian
clean slate
2885
    /*
2886
      Initing thd->row_count is not necessary in theory as this variable has no
2887
      influence in the case of the slave SQL thread (it is used to generate a
2888
      "data truncated" warning but which is absorbed and never gets to the
2889
      error log); still we init it to avoid a Valgrind message.
2890
    */
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
2891
    drizzle_reset_errors(thd, 0);
1 by brian
clean slate
2892
327.2.4 by Brian Aker
Refactoring table.h
2893
    TableList tables;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
2894
    memset(&tables, 0, sizeof(tables));
1 by brian
clean slate
2895
    tables.db= thd->strmake(thd->db, thd->db_length);
2896
    tables.alias = tables.table_name = (char*) table_name;
2897
    tables.lock_type = TL_WRITE;
2898
    tables.updating= 1;
2899
2900
    // the table will be opened in mysql_load    
2901
    if (rpl_filter->is_on() && !rpl_filter->tables_ok(thd->db, &tables))
2902
    {
2903
      // TODO: this is a bug - this needs to be moved to the I/O thread
2904
      if (net)
2905
        skip_load_data_infile(net);
2906
    }
2907
    else
2908
    {
2909
      char llbuff[22];
2910
      char *end;
2911
      enum enum_duplicates handle_dup;
2912
      bool ignore= 0;
2913
      char *load_data_query;
2914
2915
      /*
2916
        Forge LOAD DATA INFILE query which will be used in SHOW PROCESS LIST
2917
        and written to slave's binlog if binlogging is on.
2918
      */
2919
      if (!(load_data_query= (char *)thd->alloc(get_query_buffer_length() + 1)))
2920
      {
2921
        /*
2922
          This will set thd->fatal_error in case of OOM. So we surely will notice
2923
          that something is wrong.
2924
        */
2925
        goto error;
2926
      }
2927
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2928
      print_query(false, load_data_query, &end, (char **)&thd->lex->fname_start,
1 by brian
clean slate
2929
                  (char **)&thd->lex->fname_end);
2930
      *end= 0;
2931
      thd->query_length= end - load_data_query;
2932
      thd->query= load_data_query;
2933
2934
      if (sql_ex.opt_flags & REPLACE_FLAG)
2935
      {
2936
	handle_dup= DUP_REPLACE;
2937
      }
2938
      else if (sql_ex.opt_flags & IGNORE_FLAG)
2939
      {
2940
        ignore= 1;
2941
        handle_dup= DUP_ERROR;
2942
      }
2943
      else
2944
      {
2945
        /*
2946
	  When replication is running fine, if it was DUP_ERROR on the
2947
          master then we could choose IGNORE here, because if DUP_ERROR
2948
          suceeded on master, and data is identical on the master and slave,
2949
          then there should be no uniqueness errors on slave, so IGNORE is
2950
          the same as DUP_ERROR. But in the unlikely case of uniqueness errors
2951
          (because the data on the master and slave happen to be different
2952
	  (user error or bug), we want LOAD DATA to print an error message on
2953
	  the slave to discover the problem.
2954
2955
          If reading from net (a 3.23 master), mysql_load() will change this
2956
          to IGNORE.
2957
        */
2958
        handle_dup= DUP_ERROR;
2959
      }
2960
      /*
2961
        We need to set thd->lex->sql_command and thd->lex->duplicates
2962
        since InnoDB tests these variables to decide if this is a LOAD
2963
        DATA ... REPLACE INTO ... statement even though mysql_parse()
2964
        is not called.  This is not needed in 5.0 since there the LOAD
2965
        DATA ... statement is replicated using mysql_parse(), which
2966
        sets the thd->lex fields correctly.
2967
      */
2968
      thd->lex->sql_command= SQLCOM_LOAD;
2969
      thd->lex->duplicates= handle_dup;
2970
2971
      sql_exchange ex((char*)fname, sql_ex.opt_flags & DUMPFILE_FLAG);
2972
      String field_term(sql_ex.field_term,sql_ex.field_term_len,log_cs);
2973
      String enclosed(sql_ex.enclosed,sql_ex.enclosed_len,log_cs);
2974
      String line_term(sql_ex.line_term,sql_ex.line_term_len,log_cs);
2975
      String line_start(sql_ex.line_start,sql_ex.line_start_len,log_cs);
2976
      String escaped(sql_ex.escaped,sql_ex.escaped_len, log_cs);
2977
      ex.field_term= &field_term;
2978
      ex.enclosed= &enclosed;
2979
      ex.line_term= &line_term;
2980
      ex.line_start= &line_start;
2981
      ex.escaped= &escaped;
2982
2983
      ex.opt_enclosed = (sql_ex.opt_flags & OPT_ENCLOSED_FLAG);
2984
      if (sql_ex.empty_flags & FIELD_TERM_EMPTY)
2985
	ex.field_term->length(0);
2986
2987
      ex.skip_lines = skip_lines;
2988
      List<Item> field_list;
2989
      thd->lex->select_lex.context.resolve_in_table_list_only(&tables);
2990
      set_fields(tables.db, field_list, &thd->lex->select_lex.context);
2991
      thd->variables.pseudo_thread_id= thread_id;
2992
      if (net)
2993
      {
2994
	// mysql_load will use thd->net to read the file
2995
	thd->net.vio = net->vio;
2996
	/*
2997
	  Make sure the client does not get confused about the packet sequence
2998
	*/
2999
	thd->net.pkt_nr = net->pkt_nr;
3000
      }
3001
      /*
3002
        It is safe to use tmp_list twice because we are not going to
3003
        update it inside mysql_load().
3004
      */
3005
      List<Item> tmp_list;
3006
      if (mysql_load(thd, &ex, &tables, field_list, tmp_list, tmp_list,
3007
                     handle_dup, ignore, net != 0))
3008
        thd->is_slave_error= 1;
3009
      if (thd->cuted_fields)
3010
      {
3011
	/* log_pos is the position of the LOAD event in the master log */
340 by Monty Taylor
Got everything using sql_print_*.
3012
        sql_print_warning(_("Slave: load data infile on table '%s' at "
1 by brian
clean slate
3013
                          "log position %s in log '%s' produced %ld "
340 by Monty Taylor
Got everything using sql_print_*.
3014
                          "warning(s). Default database: '%s'"),
1 by brian
clean slate
3015
                          (char*) table_name,
3016
                          llstr(log_pos,llbuff), RPL_LOG_NAME, 
3017
                          (ulong) thd->cuted_fields,
3018
                          print_slave_db_safe(thd->db));
3019
      }
3020
      if (net)
3021
        net->pkt_nr= thd->net.pkt_nr;
3022
    }
3023
  }
3024
  else
3025
  {
3026
    /*
3027
      We will just ask the master to send us /dev/null if we do not
3028
      want to load the data.
3029
      TODO: this a bug - needs to be done in I/O thread
3030
    */
3031
    if (net)
3032
      skip_load_data_infile(net);
3033
  }
3034
3035
error:
3036
  thd->net.vio = 0; 
3037
  const char *remember_db= thd->db;
398.1.6 by Monty Taylor
Removed __alpha__ references.
3038
  pthread_mutex_lock(&LOCK_thread_count);
1 by brian
clean slate
3039
  thd->catalog= 0;
3040
  thd->set_db(NULL, 0);                   /* will free the current database */
3041
  thd->query= 0;
3042
  thd->query_length= 0;
398.1.6 by Monty Taylor
Removed __alpha__ references.
3043
  pthread_mutex_unlock(&LOCK_thread_count);
1 by brian
clean slate
3044
  close_thread_tables(thd);
3045
3046
  if (thd->is_slave_error)
3047
  {
3048
    /* this err/sql_errno code is copy-paste from net_send_error() */
3049
    const char *err;
3050
    int sql_errno;
3051
    if (thd->is_error())
3052
    {
3053
      err= thd->main_da.message();
3054
      sql_errno= thd->main_da.sql_errno();
3055
    }
3056
    else
3057
    {
3058
      sql_errno=ER_UNKNOWN_ERROR;
398.1.7 by Monty Taylor
Marked some new translations.
3059
      err=ER(sql_errno);
1 by brian
clean slate
3060
    }
398.1.7 by Monty Taylor
Marked some new translations.
3061
    rli->report(ERROR_LEVEL, sql_errno,
3062
                _("Error '%s' running LOAD DATA INFILE on table '%s'. "
3063
                  "Default database: '%s'"),
3064
                err, (char*)table_name, print_slave_db_safe(remember_db));
1 by brian
clean slate
3065
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
3066
    return 1;
3067
  }
3068
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
3069
3070
  if (thd->is_fatal_error)
3071
  {
3072
    char buf[256];
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
3073
    snprintf(buf, sizeof(buf),
398.1.7 by Monty Taylor
Marked some new translations.
3074
             _("Running LOAD DATA INFILE on table '%-.64s'."
3075
               " Default database: '%-.64s'"),
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
3076
             (char*)table_name,
3077
             print_slave_db_safe(remember_db));
1 by brian
clean slate
3078
3079
    rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR,
3080
                ER(ER_SLAVE_FATAL_ERROR), buf);
3081
    return 1;
3082
  }
3083
398.1.7 by Monty Taylor
Marked some new translations.
3084
  return ( use_rli_only_for_errors ? 0 : Log_event::do_apply_event(rli) );
1 by brian
clean slate
3085
}
3086
3087
3088
/**************************************************************************
3089
  Rotate_log_event methods
3090
**************************************************************************/
3091
3092
/*
3093
  Rotate_log_event::pack_info()
3094
*/
3095
3096
void Rotate_log_event::pack_info(Protocol *protocol)
3097
{
3098
  char buf1[256], buf[22];
3099
  String tmp(buf1, sizeof(buf1), log_cs);
3100
  tmp.length(0);
3101
  tmp.append(new_log_ident, ident_len);
3102
  tmp.append(STRING_WITH_LEN(";pos="));
3103
  tmp.append(llstr(pos,buf));
3104
  protocol->store(tmp.ptr(), tmp.length(), &my_charset_bin);
3105
}
3106
3107
3108
/*
3109
  Rotate_log_event::Rotate_log_event() (2 constructors)
3110
*/
3111
3112
3113
Rotate_log_event::Rotate_log_event(const char* new_log_ident_arg,
482 by Brian Aker
Remove uint.
3114
                                   uint32_t ident_len_arg, uint64_t pos_arg,
3115
                                   uint32_t flags_arg)
1 by brian
clean slate
3116
  :Log_event(), new_log_ident(new_log_ident_arg),
3117
   pos(pos_arg),ident_len(ident_len_arg ? ident_len_arg :
3118
                          (uint) strlen(new_log_ident_arg)), flags(flags_arg)
3119
{
3120
  if (flags & DUP_NAME)
3121
    new_log_ident= my_strndup(new_log_ident_arg, ident_len, MYF(MY_WME));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3122
  return;
1 by brian
clean slate
3123
}
3124
3125
482 by Brian Aker
Remove uint.
3126
Rotate_log_event::Rotate_log_event(const char* buf, uint32_t event_len,
1 by brian
clean slate
3127
                                   const Format_description_log_event* description_event)
3128
  :Log_event(buf, description_event) ,new_log_ident(0), flags(DUP_NAME)
3129
{
3130
  // The caller will ensure that event_len is what we have at EVENT_LEN_OFFSET
206 by Brian Aker
Removed final uint dead types.
3131
  uint8_t header_size= description_event->common_header_len;
3132
  uint8_t post_header_len= description_event->post_header_len[ROTATE_EVENT-1];
482 by Brian Aker
Remove uint.
3133
  uint32_t ident_offset;
1 by brian
clean slate
3134
  if (event_len < header_size)
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3135
    return;
1 by brian
clean slate
3136
  buf += header_size;
3137
  pos = post_header_len ? uint8korr(buf + R_POS_OFFSET) : 4;
3138
  ident_len = (uint)(event_len -
3139
                     (header_size+post_header_len)); 
3140
  ident_offset = post_header_len; 
3141
  set_if_smaller(ident_len,FN_REFLEN-1);
3142
  new_log_ident= my_strndup(buf + ident_offset, (uint) ident_len, MYF(MY_WME));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3143
  return;
1 by brian
clean slate
3144
}
3145
3146
3147
/*
3148
  Rotate_log_event::write()
3149
*/
3150
3151
bool Rotate_log_event::write(IO_CACHE* file)
3152
{
3153
  char buf[ROTATE_HEADER_LEN];
3154
  int8store(buf + R_POS_OFFSET, pos);
3155
  return (write_header(file, ROTATE_HEADER_LEN + ident_len) ||
481 by Brian Aker
Remove all of uchar.
3156
          my_b_safe_write(file, (unsigned char*)buf, ROTATE_HEADER_LEN) ||
3157
          my_b_safe_write(file, (unsigned char*)new_log_ident, (uint) ident_len));
1 by brian
clean slate
3158
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
3159
1 by brian
clean slate
3160
3161
/*
3162
  Got a rotate log event from the master.
3163
3164
  This is mainly used so that we can later figure out the logname and
3165
  position for the master.
3166
3167
  We can't rotate the slave's BINlog as this will cause infinitive rotations
3168
  in a A -> B -> A setup.
3169
  The NOTES below is a wrong comment which will disappear when 4.1 is merged.
3170
3171
  @retval
3172
    0	ok
3173
*/
3174
int Rotate_log_event::do_update_pos(Relay_log_info *rli)
3175
{
3176
  pthread_mutex_lock(&rli->data_lock);
3177
  rli->event_relay_log_pos= my_b_tell(rli->cur_log);
3178
  /*
3179
    If we are in a transaction or in a group: the only normal case is
3180
    when the I/O thread was copying a big transaction, then it was
3181
    stopped and restarted: we have this in the relay log:
3182
3183
    BEGIN
3184
    ...
3185
    ROTATE (a fake one)
3186
    ...
3187
    COMMIT or ROLLBACK
3188
3189
    In that case, we don't want to touch the coordinates which
3190
    correspond to the beginning of the transaction.  Starting from
3191
    5.0.0, there also are some rotates from the slave itself, in the
3192
    relay log, which shall not change the group positions.
3193
  */
3194
  if ((server_id != ::server_id || rli->replicate_same_server_id) &&
3195
      !rli->is_in_group())
3196
  {
490 by Brian Aker
More effort around master.info (and relay.info)
3197
    rli->group_master_log_name.assign(new_log_ident, ident_len+1);
1 by brian
clean slate
3198
    rli->notify_group_master_log_name_update();
3199
    rli->group_master_log_pos= pos;
490 by Brian Aker
More effort around master.info (and relay.info)
3200
    rli->group_relay_log_name.assign(rli->event_relay_log_name);
1 by brian
clean slate
3201
    rli->notify_group_relay_log_name_update();
3202
    rli->group_relay_log_pos= rli->event_relay_log_pos;
3203
    /*
3204
      Reset thd->options and sql_mode etc, because this could be the signal of
3205
      a master's downgrade from 5.0 to 4.0.
3206
      However, no need to reset description_event_for_exec: indeed, if the next
3207
      master is 5.0 (even 5.0.1) we will soon get a Format_desc; if the next
3208
      master is 4.0 then the events are in the slave's format (conversion).
3209
    */
3210
    set_slave_thread_options(thd);
3211
    thd->variables.auto_increment_increment=
3212
      thd->variables.auto_increment_offset= 1;
3213
  }
3214
  pthread_mutex_unlock(&rli->data_lock);
3215
  pthread_cond_broadcast(&rli->data_cond);
3216
  flush_relay_log_info(rli);
3217
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3218
  return(0);
1 by brian
clean slate
3219
}
3220
3221
3222
Log_event::enum_skip_reason
3223
Rotate_log_event::do_shall_skip(Relay_log_info *rli)
3224
{
3225
  enum_skip_reason reason= Log_event::do_shall_skip(rli);
3226
3227
  switch (reason) {
3228
  case Log_event::EVENT_SKIP_NOT:
3229
  case Log_event::EVENT_SKIP_COUNT:
3230
    return Log_event::EVENT_SKIP_NOT;
3231
3232
  case Log_event::EVENT_SKIP_IGNORE:
3233
    return Log_event::EVENT_SKIP_IGNORE;
3234
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3235
  assert(0);
1 by brian
clean slate
3236
  return Log_event::EVENT_SKIP_NOT;             // To keep compiler happy
3237
}
3238
3239
3240
/**************************************************************************
3241
	Intvar_log_event methods
3242
**************************************************************************/
3243
3244
/*
3245
  Intvar_log_event::pack_info()
3246
*/
3247
3248
void Intvar_log_event::pack_info(Protocol *protocol)
3249
{
3250
  char buf[256], *pos;
3251
  pos= strmake(buf, get_var_type_name(), sizeof(buf)-23);
3252
  *pos++= '=';
152 by Brian Aker
longlong replacement
3253
  pos= int64_t10_to_str(val, pos, -10);
1 by brian
clean slate
3254
  protocol->store(buf, (uint) (pos-buf), &my_charset_bin);
3255
}
3256
3257
3258
/*
3259
  Intvar_log_event::Intvar_log_event()
3260
*/
3261
3262
Intvar_log_event::Intvar_log_event(const char* buf,
3263
                                   const Format_description_log_event* description_event)
3264
  :Log_event(buf, description_event)
3265
{
3266
  buf+= description_event->common_header_len;
3267
  type= buf[I_TYPE_OFFSET];
3268
  val= uint8korr(buf+I_VAL_OFFSET);
3269
}
3270
3271
3272
/*
3273
  Intvar_log_event::get_var_type_name()
3274
*/
3275
3276
const char* Intvar_log_event::get_var_type_name()
3277
{
3278
  switch(type) {
3279
  case LAST_INSERT_ID_EVENT: return "LAST_INSERT_ID";
3280
  case INSERT_ID_EVENT: return "INSERT_ID";
3281
  default: /* impossible */ return "UNKNOWN";
3282
  }
3283
}
3284
3285
3286
/*
3287
  Intvar_log_event::write()
3288
*/
3289
3290
bool Intvar_log_event::write(IO_CACHE* file)
3291
{
481 by Brian Aker
Remove all of uchar.
3292
  unsigned char buf[9];
3293
  buf[I_TYPE_OFFSET]= (unsigned char) type;
1 by brian
clean slate
3294
  int8store(buf + I_VAL_OFFSET, val);
3295
  return (write_header(file, sizeof(buf)) ||
3296
          my_b_safe_write(file, buf, sizeof(buf)));
3297
}
3298
3299
3300
/*
3301
  Intvar_log_event::print()
3302
*/
3303
3304
/*
3305
  Intvar_log_event::do_apply_event()
3306
*/
3307
3308
int Intvar_log_event::do_apply_event(Relay_log_info const *rli)
3309
{
3310
  /*
3311
    We are now in a statement until the associated query log event has
3312
    been processed.
3313
   */
3314
  const_cast<Relay_log_info*>(rli)->set_flag(Relay_log_info::IN_STMT);
3315
3316
  switch (type) {
3317
  case LAST_INSERT_ID_EVENT:
3318
    thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1;
3319
    thd->first_successful_insert_id_in_prev_stmt= val;
3320
    break;
3321
  case INSERT_ID_EVENT:
3322
    thd->force_one_auto_inc_interval(val);
3323
    break;
3324
  }
3325
  return 0;
3326
}
3327
3328
int Intvar_log_event::do_update_pos(Relay_log_info *rli)
3329
{
3330
  rli->inc_event_relay_log_pos();
3331
  return 0;
3332
}
3333
3334
3335
Log_event::enum_skip_reason
3336
Intvar_log_event::do_shall_skip(Relay_log_info *rli)
3337
{
3338
  /*
3339
    It is a common error to set the slave skip counter to 1 instead of
3340
    2 when recovering from an insert which used a auto increment,
3341
    rand, or user var.  Therefore, if the slave skip counter is 1, we
3342
    just say that this event should be skipped by ignoring it, meaning
3343
    that we do not change the value of the slave skip counter since it
3344
    will be decreased by the following insert event.
3345
  */
3346
  return continue_group(rli);
3347
}
3348
3349
3350
/**************************************************************************
3351
  Rand_log_event methods
3352
**************************************************************************/
3353
3354
void Rand_log_event::pack_info(Protocol *protocol)
3355
{
3356
  char buf1[256], *pos;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3357
  pos= my_stpcpy(buf1,"rand_seed1=");
1 by brian
clean slate
3358
  pos= int10_to_str((long) seed1, pos, 10);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3359
  pos= my_stpcpy(pos, ",rand_seed2=");
1 by brian
clean slate
3360
  pos= int10_to_str((long) seed2, pos, 10);
3361
  protocol->store(buf1, (uint) (pos-buf1), &my_charset_bin);
3362
}
3363
3364
3365
Rand_log_event::Rand_log_event(const char* buf,
3366
                               const Format_description_log_event* description_event)
3367
  :Log_event(buf, description_event)
3368
{
3369
  buf+= description_event->common_header_len;
3370
  seed1= uint8korr(buf+RAND_SEED1_OFFSET);
3371
  seed2= uint8korr(buf+RAND_SEED2_OFFSET);
3372
}
3373
3374
3375
bool Rand_log_event::write(IO_CACHE* file)
3376
{
481 by Brian Aker
Remove all of uchar.
3377
  unsigned char buf[16];
1 by brian
clean slate
3378
  int8store(buf + RAND_SEED1_OFFSET, seed1);
3379
  int8store(buf + RAND_SEED2_OFFSET, seed2);
3380
  return (write_header(file, sizeof(buf)) ||
3381
          my_b_safe_write(file, buf, sizeof(buf)));
3382
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
3383
3384
1 by brian
clean slate
3385
int Rand_log_event::do_apply_event(Relay_log_info const *rli)
3386
{
3387
  /*
3388
    We are now in a statement until the associated query log event has
3389
    been processed.
3390
   */
3391
  const_cast<Relay_log_info*>(rli)->set_flag(Relay_log_info::IN_STMT);
3392
3393
  thd->rand.seed1= (ulong) seed1;
3394
  thd->rand.seed2= (ulong) seed2;
3395
  return 0;
3396
}
3397
3398
int Rand_log_event::do_update_pos(Relay_log_info *rli)
3399
{
3400
  rli->inc_event_relay_log_pos();
3401
  return 0;
3402
}
3403
3404
3405
Log_event::enum_skip_reason
3406
Rand_log_event::do_shall_skip(Relay_log_info *rli)
3407
{
3408
  /*
3409
    It is a common error to set the slave skip counter to 1 instead of
3410
    2 when recovering from an insert which used a auto increment,
3411
    rand, or user var.  Therefore, if the slave skip counter is 1, we
3412
    just say that this event should be skipped by ignoring it, meaning
3413
    that we do not change the value of the slave skip counter since it
3414
    will be decreased by the following insert event.
3415
  */
3416
  return continue_group(rli);
3417
}
3418
3419
3420
/**************************************************************************
3421
  Xid_log_event methods
3422
**************************************************************************/
3423
3424
void Xid_log_event::pack_info(Protocol *protocol)
3425
{
3426
  char buf[128], *pos;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3427
  pos= my_stpcpy(buf, "COMMIT /* xid=");
152 by Brian Aker
longlong replacement
3428
  pos= int64_t10_to_str(xid, pos, 10);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3429
  pos= my_stpcpy(pos, " */");
1 by brian
clean slate
3430
  protocol->store(buf, (uint) (pos-buf), &my_charset_bin);
3431
}
3432
3433
/**
3434
  @note
3435
  It's ok not to use int8store here,
151 by Brian Aker
Ulonglong to uint64_t
3436
  as long as xid_t::set(uint64_t) and
1 by brian
clean slate
3437
  xid_t::get_my_xid doesn't do it either.
3438
  We don't care about actual values of xids as long as
3439
  identical numbers compare identically
3440
*/
3441
3442
Xid_log_event::
3443
Xid_log_event(const char* buf,
3444
              const Format_description_log_event *description_event)
3445
  :Log_event(buf, description_event)
3446
{
3447
  buf+= description_event->common_header_len;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
3448
  memcpy(&xid, buf, sizeof(xid));
1 by brian
clean slate
3449
}
3450
3451
3452
bool Xid_log_event::write(IO_CACHE* file)
3453
{
3454
  return write_header(file, sizeof(xid)) ||
481 by Brian Aker
Remove all of uchar.
3455
         my_b_safe_write(file, (unsigned char*) &xid, sizeof(xid));
1 by brian
clean slate
3456
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
3457
3458
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
3459
int Xid_log_event::do_apply_event(Relay_log_info const *rli __attribute__((unused)))
1 by brian
clean slate
3460
{
3461
  return end_trans(thd, COMMIT);
3462
}
3463
3464
Log_event::enum_skip_reason
3465
Xid_log_event::do_shall_skip(Relay_log_info *rli)
3466
{
3467
  if (rli->slave_skip_counter > 0) {
3468
    thd->options&= ~OPTION_BEGIN;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3469
    return(Log_event::EVENT_SKIP_COUNT);
1 by brian
clean slate
3470
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3471
  return(Log_event::do_shall_skip(rli));
1 by brian
clean slate
3472
}
3473
3474
3475
/**************************************************************************
3476
  User_var_log_event methods
3477
**************************************************************************/
3478
3479
void User_var_log_event::pack_info(Protocol* protocol)
3480
{
3481
  char *buf= 0;
482 by Brian Aker
Remove uint.
3482
  uint32_t val_offset= 4 + name_len;
3483
  uint32_t event_len= val_offset;
1 by brian
clean slate
3484
3485
  if (is_null)
3486
  {
3487
    if (!(buf= (char*) my_malloc(val_offset + 5, MYF(MY_WME))))
3488
      return;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3489
    my_stpcpy(buf + val_offset, "NULL");
1 by brian
clean slate
3490
    event_len= val_offset + 4;
3491
  }
3492
  else
3493
  {
3494
    switch (type) {
3495
    case REAL_RESULT:
3496
      double real_val;
3497
      float8get(real_val, val);
3498
      if (!(buf= (char*) my_malloc(val_offset + MY_GCVT_MAX_FIELD_WIDTH + 1,
3499
                                   MYF(MY_WME))))
3500
        return;
3501
      event_len+= my_gcvt(real_val, MY_GCVT_ARG_DOUBLE, MY_GCVT_MAX_FIELD_WIDTH,
3502
                          buf + val_offset, NULL);
3503
      break;
3504
    case INT_RESULT:
3505
      if (!(buf= (char*) my_malloc(val_offset + 22, MYF(MY_WME))))
3506
        return;
152 by Brian Aker
longlong replacement
3507
      event_len= int64_t10_to_str(uint8korr(val), buf + val_offset,-10)-buf;
1 by brian
clean slate
3508
      break;
3509
    case DECIMAL_RESULT:
3510
    {
3511
      if (!(buf= (char*) my_malloc(val_offset + DECIMAL_MAX_STR_LENGTH,
3512
                                   MYF(MY_WME))))
3513
        return;
3514
      String str(buf+val_offset, DECIMAL_MAX_STR_LENGTH, &my_charset_bin);
3515
      my_decimal dec;
481 by Brian Aker
Remove all of uchar.
3516
      binary2my_decimal(E_DEC_FATAL_ERROR, (unsigned char*) (val+2), &dec, val[0],
1 by brian
clean slate
3517
                        val[1]);
3518
      my_decimal2string(E_DEC_FATAL_ERROR, &dec, 0, 0, 0, &str);
3519
      event_len= str.length() + val_offset;
3520
      break;
3521
    } 
3522
    case STRING_RESULT:
3523
      /* 15 is for 'COLLATE' and other chars */
3524
      buf= (char*) my_malloc(event_len+val_len*2+1+2*MY_CS_NAME_SIZE+15,
3525
                             MYF(MY_WME));
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
3526
      const CHARSET_INFO *cs;
1 by brian
clean slate
3527
      if (!buf)
3528
        return;
3529
      if (!(cs= get_charset(charset_number, MYF(0))))
3530
      {
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3531
        my_stpcpy(buf+val_offset, "???");
1 by brian
clean slate
3532
        event_len+= 3;
3533
      }
3534
      else
3535
      {
461 by Monty Taylor
Removed NullS. bu-bye.
3536
        char *p= strxmov(buf + val_offset, "_", cs->csname, " ", NULL);
1 by brian
clean slate
3537
        p= str_to_hex(p, val, val_len);
461 by Monty Taylor
Removed NullS. bu-bye.
3538
        p= strxmov(p, " COLLATE ", cs->name, NULL);
1 by brian
clean slate
3539
        event_len= p-buf;
3540
      }
3541
      break;
3542
    case ROW_RESULT:
3543
    default:
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3544
      assert(1);
1 by brian
clean slate
3545
      return;
3546
    }
3547
  }
3548
  buf[0]= '@';
3549
  buf[1]= '`';
3550
  memcpy(buf+2, name, name_len);
3551
  buf[2+name_len]= '`';
3552
  buf[3+name_len]= '=';
3553
  protocol->store(buf, event_len, &my_charset_bin);
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
3554
  free(buf);
1 by brian
clean slate
3555
}
3556
3557
3558
User_var_log_event::
3559
User_var_log_event(const char* buf,
3560
                   const Format_description_log_event* description_event)
3561
  :Log_event(buf, description_event)
3562
{
3563
  buf+= description_event->common_header_len;
3564
  name_len= uint4korr(buf);
3565
  name= (char *) buf + UV_NAME_LEN_SIZE;
3566
  buf+= UV_NAME_LEN_SIZE + name_len;
3567
  is_null= (bool) *buf;
3568
  if (is_null)
3569
  {
3570
    type= STRING_RESULT;
3571
    charset_number= my_charset_bin.number;
3572
    val_len= 0;
3573
    val= 0;  
3574
  }
3575
  else
3576
  {
3577
    type= (Item_result) buf[UV_VAL_IS_NULL];
3578
    charset_number= uint4korr(buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE);
3579
    val_len= uint4korr(buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE + 
3580
		       UV_CHARSET_NUMBER_SIZE);
3581
    val= (char *) (buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE +
3582
		   UV_CHARSET_NUMBER_SIZE + UV_VAL_LEN_SIZE);
3583
  }
3584
}
3585
3586
3587
bool User_var_log_event::write(IO_CACHE* file)
3588
{
3589
  char buf[UV_NAME_LEN_SIZE];
3590
  char buf1[UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE + 
3591
	    UV_CHARSET_NUMBER_SIZE + UV_VAL_LEN_SIZE];
481 by Brian Aker
Remove all of uchar.
3592
  unsigned char buf2[(8 > DECIMAL_MAX_FIELD_SIZE + 2) ? 8 : DECIMAL_MAX_FIELD_SIZE +2], *pos= buf2;
482 by Brian Aker
Remove uint.
3593
  uint32_t buf1_length;
1 by brian
clean slate
3594
  ulong event_length;
3595
3596
  int4store(buf, name_len);
3597
  
3598
  if ((buf1[0]= is_null))
3599
  {
3600
    buf1_length= 1;
3601
    val_len= 0;                                 // Length of 'pos'
3602
  }    
3603
  else
3604
  {
3605
    buf1[1]= type;
3606
    int4store(buf1 + 2, charset_number);
3607
3608
    switch (type) {
3609
    case REAL_RESULT:
3610
      float8store(buf2, *(double*) val);
3611
      break;
3612
    case INT_RESULT:
152 by Brian Aker
longlong replacement
3613
      int8store(buf2, *(int64_t*) val);
1 by brian
clean slate
3614
      break;
3615
    case DECIMAL_RESULT:
3616
    {
3617
      my_decimal *dec= (my_decimal *)val;
3618
      dec->fix_buffer_pointer();
3619
      buf2[0]= (char)(dec->intg + dec->frac);
3620
      buf2[1]= (char)dec->frac;
3621
      decimal2bin((decimal_t*)val, buf2+2, buf2[0], buf2[1]);
3622
      val_len= decimal_bin_size(buf2[0], buf2[1]) + 2;
3623
      break;
3624
    }
3625
    case STRING_RESULT:
481 by Brian Aker
Remove all of uchar.
3626
      pos= (unsigned char*) val;
1 by brian
clean slate
3627
      break;
3628
    case ROW_RESULT:
3629
    default:
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3630
      assert(1);
1 by brian
clean slate
3631
      return 0;
3632
    }
3633
    int4store(buf1 + 2 + UV_CHARSET_NUMBER_SIZE, val_len);
3634
    buf1_length= 10;
3635
  }
3636
3637
  /* Length of the whole event */
3638
  event_length= sizeof(buf)+ name_len + buf1_length + val_len;
3639
3640
  return (write_header(file, event_length) ||
481 by Brian Aker
Remove all of uchar.
3641
          my_b_safe_write(file, (unsigned char*) buf, sizeof(buf))   ||
3642
	  my_b_safe_write(file, (unsigned char*) name, name_len)     ||
3643
	  my_b_safe_write(file, (unsigned char*) buf1, buf1_length) ||
1 by brian
clean slate
3644
	  my_b_safe_write(file, pos, val_len));
3645
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
3646
1 by brian
clean slate
3647
3648
3649
/*
3650
  User_var_log_event::do_apply_event()
3651
*/
3652
3653
int User_var_log_event::do_apply_event(Relay_log_info const *rli)
3654
{
3655
  Item *it= 0;
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
3656
  const CHARSET_INFO *charset;
1 by brian
clean slate
3657
  if (!(charset= get_charset(charset_number, MYF(MY_WME))))
3658
    return 1;
3659
  LEX_STRING user_var_name;
3660
  user_var_name.str= name;
3661
  user_var_name.length= name_len;
3662
  double real_val;
152 by Brian Aker
longlong replacement
3663
  int64_t int_val;
1 by brian
clean slate
3664
3665
  /*
3666
    We are now in a statement until the associated query log event has
3667
    been processed.
3668
   */
3669
  const_cast<Relay_log_info*>(rli)->set_flag(Relay_log_info::IN_STMT);
3670
3671
  if (is_null)
3672
  {
3673
    it= new Item_null();
3674
  }
3675
  else
3676
  {
3677
    switch (type) {
3678
    case REAL_RESULT:
3679
      float8get(real_val, val);
3680
      it= new Item_float(real_val, 0);
3681
      val= (char*) &real_val;		// Pointer to value in native format
3682
      val_len= 8;
3683
      break;
3684
    case INT_RESULT:
152 by Brian Aker
longlong replacement
3685
      int_val= (int64_t) uint8korr(val);
1 by brian
clean slate
3686
      it= new Item_int(int_val);
3687
      val= (char*) &int_val;		// Pointer to value in native format
3688
      val_len= 8;
3689
      break;
3690
    case DECIMAL_RESULT:
3691
    {
481 by Brian Aker
Remove all of uchar.
3692
      Item_decimal *dec= new Item_decimal((unsigned char*) val+2, val[0], val[1]);
1 by brian
clean slate
3693
      it= dec;
3694
      val= (char *)dec->val_decimal(NULL);
3695
      val_len= sizeof(my_decimal);
3696
      break;
3697
    }
3698
    case STRING_RESULT:
3699
      it= new Item_string(val, val_len, charset);
3700
      break;
3701
    case ROW_RESULT:
3702
    default:
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3703
      assert(1);
1 by brian
clean slate
3704
      return 0;
3705
    }
3706
  }
3707
  Item_func_set_user_var e(user_var_name, it);
3708
  /*
3709
    Item_func_set_user_var can't substitute something else on its place =>
3710
    0 can be passed as last argument (reference on item)
3711
  */
3712
  e.fix_fields(thd, 0);
3713
  /*
3714
    A variable can just be considered as a table with
3715
    a single record and with a single column. Thus, like
3716
    a column value, it could always have IMPLICIT derivation.
3717
   */
3718
  e.update_hash(val, val_len, type, charset, DERIVATION_IMPLICIT, 0);
3719
  free_root(thd->mem_root,0);
3720
3721
  return 0;
3722
}
3723
3724
int User_var_log_event::do_update_pos(Relay_log_info *rli)
3725
{
3726
  rli->inc_event_relay_log_pos();
3727
  return 0;
3728
}
3729
3730
Log_event::enum_skip_reason
3731
User_var_log_event::do_shall_skip(Relay_log_info *rli)
3732
{
3733
  /*
3734
    It is a common error to set the slave skip counter to 1 instead
3735
    of 2 when recovering from an insert which used a auto increment,
3736
    rand, or user var.  Therefore, if the slave skip counter is 1, we
3737
    just say that this event should be skipped by ignoring it, meaning
3738
    that we do not change the value of the slave skip counter since it
3739
    will be decreased by the following insert event.
3740
  */
3741
  return continue_group(rli);
3742
}
3743
3744
3745
/**************************************************************************
3746
  Slave_log_event methods
3747
**************************************************************************/
3748
3749
void Slave_log_event::pack_info(Protocol *protocol)
3750
{
3751
  char buf[256+HOSTNAME_LENGTH], *pos;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3752
  pos= my_stpcpy(buf, "host=");
490 by Brian Aker
More effort around master.info (and relay.info)
3753
  pos= my_stpncpy(pos, master_host.c_str(), HOSTNAME_LENGTH);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3754
  pos= my_stpcpy(pos, ",port=");
1 by brian
clean slate
3755
  pos= int10_to_str((long) master_port, pos, 10);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3756
  pos= my_stpcpy(pos, ",log=");
490 by Brian Aker
More effort around master.info (and relay.info)
3757
  pos= my_stpcpy(pos, master_log.c_str());
411.1.1 by Brian Aker
Work on removing GNU specific calls.
3758
  pos= my_stpcpy(pos, ",pos=");
152 by Brian Aker
longlong replacement
3759
  pos= int64_t10_to_str(master_pos, pos, 10);
1 by brian
clean slate
3760
  protocol->store(buf, pos-buf, &my_charset_bin);
3761
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
3762
3763
1 by brian
clean slate
3764
/**
3765
  @todo
3766
  re-write this better without holding both locks at the same time
3767
*/
3768
Slave_log_event::Slave_log_event(THD* thd_arg,
3769
				 Relay_log_info* rli)
3770
  :Log_event(thd_arg, 0, 0) , mem_pool(0), master_host(0)
3771
{
3772
  if (!rli->inited)				// QQ When can this happen ?
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3773
    return;
1 by brian
clean slate
3774
3775
  Master_info* mi = rli->mi;
3776
  // TODO: re-write this better without holding both locks at the same time
3777
  pthread_mutex_lock(&mi->data_lock);
3778
  pthread_mutex_lock(&rli->data_lock);
3779
  // on OOM, just do not initialize the structure and print the error
3780
  if ((mem_pool = (char*)my_malloc(get_data_size() + 1,
3781
				   MYF(MY_WME))))
3782
  {
490 by Brian Aker
More effort around master.info (and relay.info)
3783
    master_host.assign(mi->getHostname());
3784
    master_log.assign(rli->group_master_log_name);
3785
    master_port = mi->getPort();
1 by brian
clean slate
3786
    master_pos = rli->group_master_log_pos;
3787
  }
3788
  else
340 by Monty Taylor
Got everything using sql_print_*.
3789
    sql_print_error(_("Out of memory while recording slave event"));
1 by brian
clean slate
3790
  pthread_mutex_unlock(&rli->data_lock);
3791
  pthread_mutex_unlock(&mi->data_lock);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3792
  return;
1 by brian
clean slate
3793
}
3794
3795
3796
Slave_log_event::~Slave_log_event()
3797
{
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
3798
  free(mem_pool);
1 by brian
clean slate
3799
}
3800
3801
3802
int Slave_log_event::get_data_size()
3803
{
490 by Brian Aker
More effort around master.info (and relay.info)
3804
  return master_host.length() + master_log.length() + 1 + SL_MASTER_HOST_OFFSET;
1 by brian
clean slate
3805
}
3806
3807
3808
bool Slave_log_event::write(IO_CACHE* file)
3809
{
3810
  ulong event_length= get_data_size();
3811
  int8store(mem_pool + SL_MASTER_POS_OFFSET, master_pos);
3812
  int2store(mem_pool + SL_MASTER_PORT_OFFSET, master_port);
3813
  // log and host are already there
3814
3815
  return (write_header(file, event_length) ||
481 by Brian Aker
Remove all of uchar.
3816
          my_b_safe_write(file, (unsigned char*) mem_pool, event_length));
1 by brian
clean slate
3817
}
3818
3819
490 by Brian Aker
More effort around master.info (and relay.info)
3820
void Slave_log_event::init_from_mem_pool()
1 by brian
clean slate
3821
{
3822
  master_pos = uint8korr(mem_pool + SL_MASTER_POS_OFFSET);
3823
  master_port = uint2korr(mem_pool + SL_MASTER_PORT_OFFSET);
490 by Brian Aker
More effort around master.info (and relay.info)
3824
#ifdef FIXME
3825
  /* Assign these correctly */
3826
  master_host.assign(mem_pool + SL_MASTER_HOST_OFFSET);
3827
  master_log.assign();
3828
#endif
1 by brian
clean slate
3829
}
3830
3831
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
3832
int Slave_log_event::do_apply_event(Relay_log_info const *rli __attribute__((unused)))
1 by brian
clean slate
3833
{
3834
  if (mysql_bin_log.is_open())
3835
    mysql_bin_log.write(this);
3836
  return 0;
3837
}
3838
3839
3840
/**************************************************************************
3841
	Stop_log_event methods
3842
**************************************************************************/
3843
3844
/*
3845
  The master stopped.  We used to clean up all temporary tables but
3846
  this is useless as, as the master has shut down properly, it has
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3847
  written all DROP TEMPORARY Table (prepared statements' deletion is
1 by brian
clean slate
3848
  TODO only when we binlog prep stmts).  We used to clean up
3849
  slave_load_tmpdir, but this is useless as it has been cleared at the
3850
  end of LOAD DATA INFILE.  So we have nothing to do here.  The place
3851
  were we must do this cleaning is in
3852
  Start_log_event_v3::do_apply_event(), not here. Because if we come
3853
  here, the master was sane.
3854
*/
3855
int Stop_log_event::do_update_pos(Relay_log_info *rli)
3856
{
3857
  /*
3858
    We do not want to update master_log pos because we get a rotate event
3859
    before stop, so by now group_master_log_name is set to the next log.
3860
    If we updated it, we will have incorrect master coordinates and this
3861
    could give false triggers in MASTER_POS_WAIT() that we have reached
3862
    the target position when in fact we have not.
3863
  */
3864
  if (thd->options & OPTION_BEGIN)
3865
    rli->inc_event_relay_log_pos();
3866
  else
3867
  {
3868
    rli->inc_group_relay_log_pos(0);
3869
    flush_relay_log_info(rli);
3870
  }
3871
  return 0;
3872
}
3873
3874
3875
/**************************************************************************
3876
	Create_file_log_event methods
3877
**************************************************************************/
3878
3879
/*
3880
  Create_file_log_event ctor
3881
*/
3882
3883
Create_file_log_event::
3884
Create_file_log_event(THD* thd_arg, sql_exchange* ex,
3885
		      const char* db_arg, const char* table_name_arg,
3886
		      List<Item>& fields_arg, enum enum_duplicates handle_dup,
3887
                      bool ignore,
482 by Brian Aker
Remove uint.
3888
		      unsigned char* block_arg, uint32_t block_len_arg, bool using_trans)
1 by brian
clean slate
3889
  :Load_log_event(thd_arg,ex,db_arg,table_name_arg,fields_arg,handle_dup, ignore,
3890
		  using_trans),
3891
   fake_base(0), block(block_arg), event_buf(0), block_len(block_len_arg),
3892
   file_id(thd_arg->file_id = mysql_bin_log.next_file_id())
3893
{
3894
  sql_ex.force_new_format();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3895
  return;
1 by brian
clean slate
3896
}
3897
3898
3899
/*
3900
  Create_file_log_event::write_data_body()
3901
*/
3902
3903
bool Create_file_log_event::write_data_body(IO_CACHE* file)
3904
{
3905
  bool res;
3906
  if ((res= Load_log_event::write_data_body(file)) || fake_base)
3907
    return res;
481 by Brian Aker
Remove all of uchar.
3908
  return (my_b_safe_write(file, (unsigned char*) "", 1) ||
3909
          my_b_safe_write(file, (unsigned char*) block, block_len));
1 by brian
clean slate
3910
}
3911
3912
3913
/*
3914
  Create_file_log_event::write_data_header()
3915
*/
3916
3917
bool Create_file_log_event::write_data_header(IO_CACHE* file)
3918
{
3919
  bool res;
481 by Brian Aker
Remove all of uchar.
3920
  unsigned char buf[CREATE_FILE_HEADER_LEN];
1 by brian
clean slate
3921
  if ((res= Load_log_event::write_data_header(file)) || fake_base)
3922
    return res;
3923
  int4store(buf + CF_FILE_ID_OFFSET, file_id);
3924
  return my_b_safe_write(file, buf, CREATE_FILE_HEADER_LEN) != 0;
3925
}
3926
3927
3928
/*
3929
  Create_file_log_event::write_base()
3930
*/
3931
3932
bool Create_file_log_event::write_base(IO_CACHE* file)
3933
{
3934
  bool res;
3935
  fake_base= 1;                                 // pretend we are Load event
3936
  res= write(file);
3937
  fake_base= 0;
3938
  return res;
3939
}
3940
3941
/*
3942
  Create_file_log_event ctor
3943
*/
3944
482 by Brian Aker
Remove uint.
3945
Create_file_log_event::Create_file_log_event(const char* buf, uint32_t len,
1 by brian
clean slate
3946
                                             const Format_description_log_event* description_event)
3947
  :Load_log_event(buf,0,description_event),fake_base(0),block(0),inited_from_old(0)
3948
{
482 by Brian Aker
Remove uint.
3949
  uint32_t block_offset;
3950
  uint32_t header_len= description_event->common_header_len;
206 by Brian Aker
Removed final uint dead types.
3951
  uint8_t load_header_len= description_event->post_header_len[LOAD_EVENT-1];
3952
  uint8_t create_file_header_len= description_event->post_header_len[CREATE_FILE_EVENT-1];
1 by brian
clean slate
3953
  if (!(event_buf= (char*) my_memdup(buf, len, MYF(MY_WME))) ||
3954
      copy_log_event(event_buf,len,
3955
                     ((buf[EVENT_TYPE_OFFSET] == LOAD_EVENT) ?
3956
                      load_header_len + header_len :
3957
                      (fake_base ? (header_len+load_header_len) :
3958
                       (header_len+load_header_len) +
3959
                       create_file_header_len)),
3960
                     description_event))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3961
    return;
1 by brian
clean slate
3962
  if (description_event->binlog_version!=1)
3963
  {
3964
    file_id= uint4korr(buf + 
3965
                       header_len +
3966
		       load_header_len + CF_FILE_ID_OFFSET);
3967
    /*
3968
      Note that it's ok to use get_data_size() below, because it is computed
3969
      with values we have already read from this event (because we called
3970
      copy_log_event()); we are not using slave's format info to decode
3971
      master's format, we are really using master's format info.
3972
      Anyway, both formats should be identical (except the common_header_len)
3973
      as these Load events are not changed between 4.0 and 5.0 (as logging of
3974
      LOAD DATA INFILE does not use Load_log_event in 5.0).
3975
3976
      The + 1 is for \0 terminating fname  
3977
    */
3978
    block_offset= (description_event->common_header_len +
3979
                   Load_log_event::get_data_size() +
3980
                   create_file_header_len + 1);
3981
    if (len < block_offset)
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3982
      return;
481 by Brian Aker
Remove all of uchar.
3983
    block = (unsigned char*)buf + block_offset;
1 by brian
clean slate
3984
    block_len = len - block_offset;
3985
  }
3986
  else
3987
  {
3988
    sql_ex.force_new_format();
3989
    inited_from_old = 1;
3990
  }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3991
  return;
1 by brian
clean slate
3992
}
3993
3994
3995
/*
3996
  Create_file_log_event::pack_info()
3997
*/
3998
3999
void Create_file_log_event::pack_info(Protocol *protocol)
4000
{
4001
  char buf[NAME_LEN*2 + 30 + 21*2], *pos;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4002
  pos= my_stpcpy(buf, "db=");
1 by brian
clean slate
4003
  memcpy(pos, db, db_len);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4004
  pos= my_stpcpy(pos + db_len, ";table=");
1 by brian
clean slate
4005
  memcpy(pos, table_name, table_name_len);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4006
  pos= my_stpcpy(pos + table_name_len, ";file_id=");
1 by brian
clean slate
4007
  pos= int10_to_str((long) file_id, pos, 10);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4008
  pos= my_stpcpy(pos, ";block_len=");
1 by brian
clean slate
4009
  pos= int10_to_str((long) block_len, pos, 10);
4010
  protocol->store(buf, (uint) (pos-buf), &my_charset_bin);
4011
}
4012
4013
4014
/*
4015
  Create_file_log_event::do_apply_event()
4016
*/
4017
4018
int Create_file_log_event::do_apply_event(Relay_log_info const *rli)
4019
{
4020
  char proc_info[17+FN_REFLEN+10], *fname_buf;
4021
  char *ext;
4022
  int fd = -1;
4023
  IO_CACHE file;
4024
  int error = 1;
4025
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
4026
  memset(&file, 0, sizeof(file));
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4027
  fname_buf= my_stpcpy(proc_info, "Making temp file ");
1 by brian
clean slate
4028
  ext= slave_load_file_stem(fname_buf, file_id, server_id, ".info");
322.2.5 by Mats Kindahl
Replaced use of thd_proc_info() macro with calls to
4029
  thd->set_proc_info(proc_info);
1 by brian
clean slate
4030
  my_delete(fname_buf, MYF(0)); // old copy may exist already
4031
  if ((fd= my_create(fname_buf, CREATE_MODE,
499.1.3 by Monty Taylor
Removed O_NOFOLLOW
4032
		     O_WRONLY | O_EXCL,
1 by brian
clean slate
4033
		     MYF(MY_WME))) < 0 ||
4034
      init_io_cache(&file, fd, IO_SIZE, WRITE_CACHE, (my_off_t)0, 0,
4035
		    MYF(MY_WME|MY_NABP)))
4036
  {
4037
    rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4038
                _("Error in Create_file event: could not open file '%s'"),
1 by brian
clean slate
4039
                fname_buf);
4040
    goto err;
4041
  }
4042
  
4043
  // a trick to avoid allocating another buffer
4044
  fname= fname_buf;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4045
  fname_len= (uint) (my_stpcpy(ext, ".data") - fname);
1 by brian
clean slate
4046
  if (write_base(&file))
4047
  {
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4048
    my_stpcpy(ext, ".info"); // to have it right in the error message
1 by brian
clean slate
4049
    rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4050
                _("Error in Create_file event: could not write to file '%s'"),
1 by brian
clean slate
4051
                fname_buf);
4052
    goto err;
4053
  }
4054
  end_io_cache(&file);
4055
  my_close(fd, MYF(0));
398.1.7 by Monty Taylor
Marked some new translations.
4056
1 by brian
clean slate
4057
  // fname_buf now already has .data, not .info, because we did our trick
4058
  my_delete(fname_buf, MYF(0)); // old copy may exist already
4059
  if ((fd= my_create(fname_buf, CREATE_MODE,
499.1.3 by Monty Taylor
Removed O_NOFOLLOW
4060
                     O_WRONLY | O_EXCL,
398.1.7 by Monty Taylor
Marked some new translations.
4061
                     MYF(MY_WME))) < 0)
1 by brian
clean slate
4062
  {
4063
    rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4064
                _("Error in Create_file event: could not open file '%s'"),
1 by brian
clean slate
4065
                fname_buf);
4066
    goto err;
4067
  }
481 by Brian Aker
Remove all of uchar.
4068
  if (my_write(fd, (unsigned char*) block, block_len, MYF(MY_WME+MY_NABP)))
1 by brian
clean slate
4069
  {
4070
    rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4071
                _("Error in Create_file event: write to '%s' failed"),
1 by brian
clean slate
4072
                fname_buf);
4073
    goto err;
4074
  }
4075
  error=0;					// Everything is ok
4076
4077
err:
4078
  if (error)
4079
    end_io_cache(&file);
4080
  if (fd >= 0)
4081
    my_close(fd, MYF(0));
322.2.5 by Mats Kindahl
Replaced use of thd_proc_info() macro with calls to
4082
  thd->set_proc_info(0);
1 by brian
clean slate
4083
  return error == 0;
4084
}
4085
4086
4087
/**************************************************************************
4088
	Append_block_log_event methods
4089
**************************************************************************/
4090
4091
/*
4092
  Append_block_log_event ctor
4093
*/
4094
4095
Append_block_log_event::Append_block_log_event(THD *thd_arg,
4096
                                               const char *db_arg,
481 by Brian Aker
Remove all of uchar.
4097
					       unsigned char *block_arg,
482 by Brian Aker
Remove uint.
4098
					       uint32_t block_len_arg,
1 by brian
clean slate
4099
					       bool using_trans)
4100
  :Log_event(thd_arg,0, using_trans), block(block_arg),
4101
   block_len(block_len_arg), file_id(thd_arg->file_id), db(db_arg)
4102
{
4103
}
4104
4105
4106
/*
4107
  Append_block_log_event ctor
4108
*/
4109
482 by Brian Aker
Remove uint.
4110
Append_block_log_event::Append_block_log_event(const char* buf, uint32_t len,
1 by brian
clean slate
4111
                                               const Format_description_log_event* description_event)
4112
  :Log_event(buf, description_event),block(0)
4113
{
206 by Brian Aker
Removed final uint dead types.
4114
  uint8_t common_header_len= description_event->common_header_len; 
4115
  uint8_t append_block_header_len=
1 by brian
clean slate
4116
    description_event->post_header_len[APPEND_BLOCK_EVENT-1];
482 by Brian Aker
Remove uint.
4117
  uint32_t total_header_len= common_header_len+append_block_header_len;
1 by brian
clean slate
4118
  if (len < total_header_len)
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4119
    return;
1 by brian
clean slate
4120
  file_id= uint4korr(buf + common_header_len + AB_FILE_ID_OFFSET);
481 by Brian Aker
Remove all of uchar.
4121
  block= (unsigned char*)buf + total_header_len;
1 by brian
clean slate
4122
  block_len= len - total_header_len;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4123
  return;
1 by brian
clean slate
4124
}
4125
4126
4127
/*
4128
  Append_block_log_event::write()
4129
*/
4130
4131
bool Append_block_log_event::write(IO_CACHE* file)
4132
{
481 by Brian Aker
Remove all of uchar.
4133
  unsigned char buf[APPEND_BLOCK_HEADER_LEN];
1 by brian
clean slate
4134
  int4store(buf + AB_FILE_ID_OFFSET, file_id);
4135
  return (write_header(file, APPEND_BLOCK_HEADER_LEN + block_len) ||
4136
          my_b_safe_write(file, buf, APPEND_BLOCK_HEADER_LEN) ||
481 by Brian Aker
Remove all of uchar.
4137
	  my_b_safe_write(file, (unsigned char*) block, block_len));
1 by brian
clean slate
4138
}
4139
4140
4141
/*
4142
  Append_block_log_event::pack_info()
4143
*/
4144
4145
void Append_block_log_event::pack_info(Protocol *protocol)
4146
{
4147
  char buf[256];
482 by Brian Aker
Remove uint.
4148
  uint32_t length;
171.1.1 by Patrick Galbraith
Dar, I forgot to commit this earlier.
4149
  length= (uint) sprintf(buf, ";file_id=%u;block_len=%u", file_id,
4150
			     block_len);
1 by brian
clean slate
4151
  protocol->store(buf, length, &my_charset_bin);
4152
}
4153
4154
4155
/*
4156
  Append_block_log_event::get_create_or_append()
4157
*/
4158
4159
int Append_block_log_event::get_create_or_append() const
4160
{
4161
  return 0; /* append to the file, fail if not exists */
4162
}
4163
4164
/*
4165
  Append_block_log_event::do_apply_event()
4166
*/
4167
4168
int Append_block_log_event::do_apply_event(Relay_log_info const *rli)
4169
{
4170
  char proc_info[17+FN_REFLEN+10], *fname= proc_info+17;
4171
  int fd;
4172
  int error = 1;
4173
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4174
  fname= my_stpcpy(proc_info, "Making temp file ");
1 by brian
clean slate
4175
  slave_load_file_stem(fname, file_id, server_id, ".data");
322.2.5 by Mats Kindahl
Replaced use of thd_proc_info() macro with calls to
4176
  thd->set_proc_info(proc_info);
1 by brian
clean slate
4177
  if (get_create_or_append())
4178
  {
4179
    my_delete(fname, MYF(0)); // old copy may exist already
4180
    if ((fd= my_create(fname, CREATE_MODE,
499.1.3 by Monty Taylor
Removed O_NOFOLLOW
4181
		       O_WRONLY | O_EXCL,
1 by brian
clean slate
4182
		       MYF(MY_WME))) < 0)
4183
    {
4184
      rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4185
                  _("Error in %s event: could not create file '%s'"),
1 by brian
clean slate
4186
                  get_type_str(), fname);
4187
      goto err;
4188
    }
4189
  }
499.1.3 by Monty Taylor
Removed O_NOFOLLOW
4190
  else if ((fd = my_open(fname, O_WRONLY | O_APPEND,
1 by brian
clean slate
4191
                         MYF(MY_WME))) < 0)
4192
  {
4193
    rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4194
                _("Error in %s event: could not open file '%s'"),
1 by brian
clean slate
4195
                get_type_str(), fname);
4196
    goto err;
4197
  }
481 by Brian Aker
Remove all of uchar.
4198
  if (my_write(fd, (unsigned char*) block, block_len, MYF(MY_WME+MY_NABP)))
1 by brian
clean slate
4199
  {
4200
    rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4201
                _("Error in %s event: write to '%s' failed"),
1 by brian
clean slate
4202
                get_type_str(), fname);
4203
    goto err;
4204
  }
4205
  error=0;
4206
4207
err:
4208
  if (fd >= 0)
4209
    my_close(fd, MYF(0));
322.2.5 by Mats Kindahl
Replaced use of thd_proc_info() macro with calls to
4210
  thd->set_proc_info(0);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4211
  return(error);
1 by brian
clean slate
4212
}
4213
4214
4215
/**************************************************************************
4216
	Delete_file_log_event methods
4217
**************************************************************************/
4218
4219
/*
4220
  Delete_file_log_event ctor
4221
*/
4222
4223
Delete_file_log_event::Delete_file_log_event(THD *thd_arg, const char* db_arg,
4224
					     bool using_trans)
4225
  :Log_event(thd_arg, 0, using_trans), file_id(thd_arg->file_id), db(db_arg)
4226
{
4227
}
4228
4229
/*
4230
  Delete_file_log_event ctor
4231
*/
4232
482 by Brian Aker
Remove uint.
4233
Delete_file_log_event::Delete_file_log_event(const char* buf, uint32_t len,
1 by brian
clean slate
4234
                                             const Format_description_log_event* description_event)
4235
  :Log_event(buf, description_event),file_id(0)
4236
{
206 by Brian Aker
Removed final uint dead types.
4237
  uint8_t common_header_len= description_event->common_header_len;
4238
  uint8_t delete_file_header_len= description_event->post_header_len[DELETE_FILE_EVENT-1];
1 by brian
clean slate
4239
  if (len < (uint)(common_header_len + delete_file_header_len))
4240
    return;
4241
  file_id= uint4korr(buf + common_header_len + DF_FILE_ID_OFFSET);
4242
}
4243
4244
4245
/*
4246
  Delete_file_log_event::write()
4247
*/
4248
4249
bool Delete_file_log_event::write(IO_CACHE* file)
4250
{
481 by Brian Aker
Remove all of uchar.
4251
 unsigned char buf[DELETE_FILE_HEADER_LEN];
1 by brian
clean slate
4252
 int4store(buf + DF_FILE_ID_OFFSET, file_id);
4253
 return (write_header(file, sizeof(buf)) ||
4254
         my_b_safe_write(file, buf, sizeof(buf)));
4255
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
4256
1 by brian
clean slate
4257
4258
/*
4259
  Delete_file_log_event::pack_info()
4260
*/
4261
4262
void Delete_file_log_event::pack_info(Protocol *protocol)
4263
{
4264
  char buf[64];
482 by Brian Aker
Remove uint.
4265
  uint32_t length;
171.1.1 by Patrick Galbraith
Dar, I forgot to commit this earlier.
4266
  length= (uint) sprintf(buf, ";file_id=%u", (uint) file_id);
205 by Brian Aker
uint32 -> uin32_t
4267
  protocol->store(buf, (int32_t) length, &my_charset_bin);
1 by brian
clean slate
4268
}
4269
4270
/*
4271
  Delete_file_log_event::do_apply_event()
4272
*/
4273
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
4274
int Delete_file_log_event::do_apply_event(Relay_log_info const *rli __attribute__((unused)))
1 by brian
clean slate
4275
{
4276
  char fname[FN_REFLEN+10];
4277
  char *ext= slave_load_file_stem(fname, file_id, server_id, ".data");
4278
  (void) my_delete(fname, MYF(MY_WME));
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4279
  my_stpcpy(ext, ".info");
1 by brian
clean slate
4280
  (void) my_delete(fname, MYF(MY_WME));
4281
  return 0;
4282
}
4283
4284
4285
/**************************************************************************
4286
	Execute_load_log_event methods
4287
**************************************************************************/
4288
4289
/*
4290
  Execute_load_log_event ctor
4291
*/
4292
4293
Execute_load_log_event::Execute_load_log_event(THD *thd_arg,
4294
                                               const char* db_arg,
4295
					       bool using_trans)
4296
  :Log_event(thd_arg, 0, using_trans), file_id(thd_arg->file_id), db(db_arg)
4297
{
4298
}
4299
  
4300
4301
/*
4302
  Execute_load_log_event ctor
4303
*/
4304
482 by Brian Aker
Remove uint.
4305
Execute_load_log_event::Execute_load_log_event(const char* buf, uint32_t len,
1 by brian
clean slate
4306
                                               const Format_description_log_event* description_event)
4307
  :Log_event(buf, description_event), file_id(0)
4308
{
206 by Brian Aker
Removed final uint dead types.
4309
  uint8_t common_header_len= description_event->common_header_len;
4310
  uint8_t exec_load_header_len= description_event->post_header_len[EXEC_LOAD_EVENT-1];
1 by brian
clean slate
4311
  if (len < (uint)(common_header_len+exec_load_header_len))
4312
    return;
4313
  file_id= uint4korr(buf + common_header_len + EL_FILE_ID_OFFSET);
4314
}
4315
4316
4317
/*
4318
  Execute_load_log_event::write()
4319
*/
4320
4321
bool Execute_load_log_event::write(IO_CACHE* file)
4322
{
481 by Brian Aker
Remove all of uchar.
4323
  unsigned char buf[EXEC_LOAD_HEADER_LEN];
1 by brian
clean slate
4324
  int4store(buf + EL_FILE_ID_OFFSET, file_id);
4325
  return (write_header(file, sizeof(buf)) || 
4326
          my_b_safe_write(file, buf, sizeof(buf)));
4327
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
4328
1 by brian
clean slate
4329
4330
/*
4331
  Execute_load_log_event::pack_info()
4332
*/
4333
4334
void Execute_load_log_event::pack_info(Protocol *protocol)
4335
{
4336
  char buf[64];
482 by Brian Aker
Remove uint.
4337
  uint32_t length;
171.1.1 by Patrick Galbraith
Dar, I forgot to commit this earlier.
4338
  length= (uint) sprintf(buf, ";file_id=%u", (uint) file_id);
205 by Brian Aker
uint32 -> uin32_t
4339
  protocol->store(buf, (int32_t) length, &my_charset_bin);
1 by brian
clean slate
4340
}
4341
4342
4343
/*
4344
  Execute_load_log_event::do_apply_event()
4345
*/
4346
4347
int Execute_load_log_event::do_apply_event(Relay_log_info const *rli)
4348
{
4349
  char fname[FN_REFLEN+10];
4350
  char *ext;
4351
  int fd;
4352
  int error= 1;
4353
  IO_CACHE file;
4354
  Load_log_event *lev= 0;
4355
4356
  ext= slave_load_file_stem(fname, file_id, server_id, ".info");
499.1.3 by Monty Taylor
Removed O_NOFOLLOW
4357
  if ((fd = my_open(fname, O_RDONLY,
1 by brian
clean slate
4358
                    MYF(MY_WME))) < 0 ||
4359
      init_io_cache(&file, fd, IO_SIZE, READ_CACHE, (my_off_t)0, 0,
4360
		    MYF(MY_WME|MY_NABP)))
4361
  {
4362
    rli->report(ERROR_LEVEL, my_errno,
398.1.7 by Monty Taylor
Marked some new translations.
4363
                _("Error in Exec_load event: could not open file '%s'"),
1 by brian
clean slate
4364
                fname);
4365
    goto err;
4366
  }
4367
  if (!(lev = (Load_log_event*)Log_event::read_log_event(&file,
4368
                                                         (pthread_mutex_t*)0,
4369
                                                         rli->relay_log.description_event_for_exec)) ||
4370
      lev->get_type_code() != NEW_LOAD_EVENT)
4371
  {
398.1.7 by Monty Taylor
Marked some new translations.
4372
    rli->report(ERROR_LEVEL, 0,
4373
                _("Error in Exec_load event: "
4374
                  "file '%s' appears corrupted"),
4375
                fname);
1 by brian
clean slate
4376
    goto err;
4377
  }
4378
4379
  lev->thd = thd;
4380
  /*
4381
    lev->do_apply_event should use rli only for errors i.e. should
4382
    not advance rli's position.
4383
4384
    lev->do_apply_event is the place where the table is loaded (it
4385
    calls mysql_load()).
4386
  */
4387
4388
  const_cast<Relay_log_info*>(rli)->future_group_master_log_pos= log_pos;
4389
  if (lev->do_apply_event(0,rli,1)) 
4390
  {
4391
    /*
4392
      We want to indicate the name of the file that could not be loaded
4393
      (SQL_LOADxxx).
4394
      But as we are here we are sure the error is in rli->last_slave_error and
4395
      rli->last_slave_errno (example of error: duplicate entry for key), so we
4396
      don't want to overwrite it with the filename.
4397
      What we want instead is add the filename to the current error message.
4398
    */
4399
    char *tmp= my_strdup(rli->last_error().message, MYF(MY_WME));
4400
    if (tmp)
4401
    {
4402
      rli->report(ERROR_LEVEL, rli->last_error().number,
398.1.7 by Monty Taylor
Marked some new translations.
4403
                  _("%s. Failed executing load from '%s'"),
4404
                  tmp, fname);
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
4405
      free(tmp);
1 by brian
clean slate
4406
    }
4407
    goto err;
4408
  }
4409
  /*
4410
    We have an open file descriptor to the .info file; we need to close it
4411
    or Windows will refuse to delete the file in my_delete().
4412
  */
4413
  if (fd >= 0)
4414
  {
4415
    my_close(fd, MYF(0));
4416
    end_io_cache(&file);
4417
    fd= -1;
4418
  }
4419
  (void) my_delete(fname, MYF(MY_WME));
4420
  memcpy(ext, ".data", 6);
4421
  (void) my_delete(fname, MYF(MY_WME));
4422
  error = 0;
4423
4424
err:
4425
  delete lev;
4426
  if (fd >= 0)
4427
  {
4428
    my_close(fd, MYF(0));
4429
    end_io_cache(&file);
4430
  }
4431
  return error;
4432
}
4433
4434
4435
/**************************************************************************
4436
	Begin_load_query_log_event methods
4437
**************************************************************************/
4438
4439
Begin_load_query_log_event::
481 by Brian Aker
Remove all of uchar.
4440
Begin_load_query_log_event(THD* thd_arg, const char* db_arg, unsigned char* block_arg,
482 by Brian Aker
Remove uint.
4441
                           uint32_t block_len_arg, bool using_trans)
1 by brian
clean slate
4442
  :Append_block_log_event(thd_arg, db_arg, block_arg, block_len_arg,
4443
                          using_trans)
4444
{
4445
   file_id= thd_arg->file_id= mysql_bin_log.next_file_id();
4446
}
4447
4448
4449
Begin_load_query_log_event::
482 by Brian Aker
Remove uint.
4450
Begin_load_query_log_event(const char* buf, uint32_t len,
1 by brian
clean slate
4451
                           const Format_description_log_event* desc_event)
4452
  :Append_block_log_event(buf, len, desc_event)
4453
{
4454
}
4455
4456
4457
int Begin_load_query_log_event::get_create_or_append() const
4458
{
4459
  return 1; /* create the file */
4460
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
4461
4462
1 by brian
clean slate
4463
Log_event::enum_skip_reason
4464
Begin_load_query_log_event::do_shall_skip(Relay_log_info *rli)
4465
{
4466
  /*
4467
    If the slave skip counter is 1, then we should not start executing
4468
    on the next event.
4469
  */
4470
  return continue_group(rli);
4471
}
4472
4473
4474
/**************************************************************************
4475
	Execute_load_query_log_event methods
4476
**************************************************************************/
4477
4478
4479
Execute_load_query_log_event::
4480
Execute_load_query_log_event(THD *thd_arg, const char* query_arg,
482 by Brian Aker
Remove uint.
4481
                             ulong query_length_arg, uint32_t fn_pos_start_arg,
4482
                             uint32_t fn_pos_end_arg,
1 by brian
clean slate
4483
                             enum_load_dup_handling dup_handling_arg,
4484
                             bool using_trans, bool suppress_use,
4485
                             THD::killed_state killed_err_arg):
4486
  Query_log_event(thd_arg, query_arg, query_length_arg, using_trans,
4487
                  suppress_use, killed_err_arg),
4488
  file_id(thd_arg->file_id), fn_pos_start(fn_pos_start_arg),
4489
  fn_pos_end(fn_pos_end_arg), dup_handling(dup_handling_arg)
4490
{
4491
}
4492
4493
4494
Execute_load_query_log_event::
482 by Brian Aker
Remove uint.
4495
Execute_load_query_log_event(const char* buf, uint32_t event_len,
1 by brian
clean slate
4496
                             const Format_description_log_event* desc_event):
4497
  Query_log_event(buf, event_len, desc_event, EXECUTE_LOAD_QUERY_EVENT),
4498
  file_id(0), fn_pos_start(0), fn_pos_end(0)
4499
{
4500
  if (!Query_log_event::is_valid())
4501
    return;
4502
4503
  buf+= desc_event->common_header_len;
4504
4505
  fn_pos_start= uint4korr(buf + ELQ_FN_POS_START_OFFSET);
4506
  fn_pos_end= uint4korr(buf + ELQ_FN_POS_END_OFFSET);
4507
  dup_handling= (enum_load_dup_handling)(*(buf + ELQ_DUP_HANDLING_OFFSET));
4508
4509
  if (fn_pos_start > q_len || fn_pos_end > q_len ||
4510
      dup_handling > LOAD_DUP_REPLACE)
4511
    return;
4512
4513
  file_id= uint4korr(buf + ELQ_FILE_ID_OFFSET);
4514
}
4515
4516
4517
ulong Execute_load_query_log_event::get_post_header_size_for_derived()
4518
{
4519
  return EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN;
4520
}
4521
4522
4523
bool
4524
Execute_load_query_log_event::write_post_header_for_derived(IO_CACHE* file)
4525
{
481 by Brian Aker
Remove all of uchar.
4526
  unsigned char buf[EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN];
1 by brian
clean slate
4527
  int4store(buf, file_id);
4528
  int4store(buf + 4, fn_pos_start);
4529
  int4store(buf + 4 + 4, fn_pos_end);
481 by Brian Aker
Remove all of uchar.
4530
  *(buf + 4 + 4 + 4)= (unsigned char) dup_handling;
1 by brian
clean slate
4531
  return my_b_safe_write(file, buf, EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN);
4532
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
4533
4534
1 by brian
clean slate
4535
void Execute_load_query_log_event::pack_info(Protocol *protocol)
4536
{
4537
  char *buf, *pos;
4538
  if (!(buf= (char*) my_malloc(9 + db_len + q_len + 10 + 21, MYF(MY_WME))))
4539
    return;
4540
  pos= buf;
4541
  if (db && db_len)
4542
  {
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4543
    pos= my_stpcpy(buf, "use `");
1 by brian
clean slate
4544
    memcpy(pos, db, db_len);
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4545
    pos= my_stpcpy(pos+db_len, "`; ");
1 by brian
clean slate
4546
  }
4547
  if (query && q_len)
4548
  {
4549
    memcpy(pos, query, q_len);
4550
    pos+= q_len;
4551
  }
411.1.1 by Brian Aker
Work on removing GNU specific calls.
4552
  pos= my_stpcpy(pos, " ;file_id=");
1 by brian
clean slate
4553
  pos= int10_to_str((long) file_id, pos, 10);
4554
  protocol->store(buf, pos-buf, &my_charset_bin);
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
4555
  free(buf);
1 by brian
clean slate
4556
}
4557
4558
4559
int
4560
Execute_load_query_log_event::do_apply_event(Relay_log_info const *rli)
4561
{
4562
  char *p;
4563
  char *buf;
4564
  char *fname;
4565
  char *fname_end;
4566
  int error;
4567
4568
  buf= (char*) my_malloc(q_len + 1 - (fn_pos_end - fn_pos_start) +
4569
                         (FN_REFLEN + 10) + 10 + 8 + 5, MYF(MY_WME));
4570
4571
  /* Replace filename and LOCAL keyword in query before executing it */
4572
  if (buf == NULL)
4573
  {
4574
    rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR,
398.1.7 by Monty Taylor
Marked some new translations.
4575
                ER(ER_SLAVE_FATAL_ERROR),
4576
                _("Not enough memory"));
1 by brian
clean slate
4577
    return 1;
4578
  }
4579
4580
  p= buf;
4581
  memcpy(p, query, fn_pos_start);
4582
  p+= fn_pos_start;
4583
  fname= (p= strmake(p, STRING_WITH_LEN(" INFILE \'")));
4584
  p= slave_load_file_stem(p, file_id, server_id, ".data");
376 by Brian Aker
strend remove
4585
  fname_end= p= strchr(p, '\0');                      // Safer than p=p+5
1 by brian
clean slate
4586
  *(p++)='\'';
4587
  switch (dup_handling) {
4588
  case LOAD_DUP_IGNORE:
4589
    p= strmake(p, STRING_WITH_LEN(" IGNORE"));
4590
    break;
4591
  case LOAD_DUP_REPLACE:
4592
    p= strmake(p, STRING_WITH_LEN(" REPLACE"));
4593
    break;
4594
  default:
4595
    /* Ordinary load data */
4596
    break;
4597
  }
4598
  p= strmake(p, STRING_WITH_LEN(" INTO"));
4599
  p= strmake(p, query+fn_pos_end, q_len-fn_pos_end);
4600
4601
  error= Query_log_event::do_apply_event(rli, buf, p-buf);
4602
4603
  /* Forging file name for deletion in same buffer */
4604
  *fname_end= 0;
4605
4606
  /*
4607
    If there was an error the slave is going to stop, leave the
4608
    file so that we can re-execute this event at START SLAVE.
4609
  */
4610
  if (!error)
4611
    (void) my_delete(fname, MYF(MY_WME));
4612
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
4613
  free(buf);
1 by brian
clean slate
4614
  return error;
4615
}
4616
4617
4618
/**************************************************************************
4619
	sql_ex_info methods
4620
**************************************************************************/
4621
4622
/*
4623
  sql_ex_info::write_data()
4624
*/
4625
4626
bool sql_ex_info::write_data(IO_CACHE* file)
4627
{
4628
  if (new_format())
4629
  {
4630
    return (write_str(file, field_term, (uint) field_term_len) ||
4631
	    write_str(file, enclosed,   (uint) enclosed_len) ||
4632
	    write_str(file, line_term,  (uint) line_term_len) ||
4633
	    write_str(file, line_start, (uint) line_start_len) ||
4634
	    write_str(file, escaped,    (uint) escaped_len) ||
481 by Brian Aker
Remove all of uchar.
4635
	    my_b_safe_write(file,(unsigned char*) &opt_flags,1));
1 by brian
clean slate
4636
  }
4637
  else
4638
  {
4639
    /**
4640
      @todo This is sensitive to field padding. We should write a
4641
      char[7], not an old_sql_ex. /sven
4642
    */
4643
    old_sql_ex old_ex;
4644
    old_ex.field_term= *field_term;
4645
    old_ex.enclosed=   *enclosed;
4646
    old_ex.line_term=  *line_term;
4647
    old_ex.line_start= *line_start;
4648
    old_ex.escaped=    *escaped;
4649
    old_ex.opt_flags=  opt_flags;
4650
    old_ex.empty_flags=empty_flags;
481 by Brian Aker
Remove all of uchar.
4651
    return my_b_safe_write(file, (unsigned char*) &old_ex, sizeof(old_ex)) != 0;
1 by brian
clean slate
4652
  }
4653
}
4654
4655
4656
/*
4657
  sql_ex_info::init()
4658
*/
4659
4660
const char *sql_ex_info::init(const char *buf, const char *buf_end,
4661
                              bool use_new_format)
4662
{
4663
  cached_new_format = use_new_format;
4664
  if (use_new_format)
4665
  {
4666
    empty_flags=0;
4667
    /*
4668
      The code below assumes that buf will not disappear from
4669
      under our feet during the lifetime of the event. This assumption
4670
      holds true in the slave thread if the log is in new format, but is not
4671
      the case when we have old format because we will be reusing net buffer
4672
      to read the actual file before we write out the Create_file event.
4673
    */
4674
    if (read_str(&buf, buf_end, &field_term, &field_term_len) ||
4675
        read_str(&buf, buf_end, &enclosed,   &enclosed_len) ||
4676
        read_str(&buf, buf_end, &line_term,  &line_term_len) ||
4677
        read_str(&buf, buf_end, &line_start, &line_start_len) ||
4678
        read_str(&buf, buf_end, &escaped,    &escaped_len))
4679
      return 0;
4680
    opt_flags = *buf++;
4681
  }
4682
  else
4683
  {
4684
    field_term_len= enclosed_len= line_term_len= line_start_len= escaped_len=1;
4685
    field_term = buf++;			// Use first byte in string
4686
    enclosed=	 buf++;
4687
    line_term=   buf++;
4688
    line_start=  buf++;
4689
    escaped=     buf++;
4690
    opt_flags =  *buf++;
4691
    empty_flags= *buf++;
4692
    if (empty_flags & FIELD_TERM_EMPTY)
4693
      field_term_len=0;
4694
    if (empty_flags & ENCLOSED_EMPTY)
4695
      enclosed_len=0;
4696
    if (empty_flags & LINE_TERM_EMPTY)
4697
      line_term_len=0;
4698
    if (empty_flags & LINE_START_EMPTY)
4699
      line_start_len=0;
4700
    if (empty_flags & ESCAPED_EMPTY)
4701
      escaped_len=0;
4702
  }
4703
  return buf;
4704
}
4705
4706
4707
/**************************************************************************
4708
	Rows_log_event member functions
4709
**************************************************************************/
4710
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4711
Rows_log_event::Rows_log_event(THD *thd_arg, Table *tbl_arg, ulong tid,
1 by brian
clean slate
4712
                               MY_BITMAP const *cols, bool is_transactional)
4713
  : Log_event(thd_arg, 0, is_transactional),
4714
    m_row_count(0),
4715
    m_table(tbl_arg),
4716
    m_table_id(tid),
4717
    m_width(tbl_arg ? tbl_arg->s->fields : 1),
4718
    m_rows_buf(0), m_rows_cur(0), m_rows_end(0), m_flags(0) 
4719
    , m_curr_row(NULL), m_curr_row_end(NULL), m_key(NULL)
4720
{
4721
  /*
4722
    We allow a special form of dummy event when the table, and cols
365.2.5 by Monty Taylor
More ~0 removal.
4723
    are null and the table id is UINT32_MAX.  This is a temporary
1 by brian
clean slate
4724
    solution, to be able to terminate a started statement in the
4725
    binary log: the extraneous events will be removed in the future.
4726
   */
365.2.5 by Monty Taylor
More ~0 removal.
4727
  assert((tbl_arg && tbl_arg->s && tid != UINT32_MAX) || (!tbl_arg && !cols && tid == UINT32_MAX));
1 by brian
clean slate
4728
4729
  if (thd_arg->options & OPTION_NO_FOREIGN_KEY_CHECKS)
4730
      set_flags(NO_FOREIGN_KEY_CHECKS_F);
4731
  if (thd_arg->options & OPTION_RELAXED_UNIQUE_CHECKS)
4732
      set_flags(RELAXED_UNIQUE_CHECKS_F);
4733
  /* if bitmap_init fails, caught in is_valid() */
4734
  if (likely(!bitmap_init(&m_cols,
4735
                          m_width <= sizeof(m_bitbuf)*8 ? m_bitbuf : NULL,
4736
                          m_width,
4737
                          false)))
4738
  {
4739
    /* Cols can be zero if this is a dummy binrows event */
4740
    if (likely(cols != NULL))
4741
    {
4742
      memcpy(m_cols.bitmap, cols->bitmap, no_bytes_in_map(cols));
4743
      create_last_word_mask(&m_cols);
4744
    }
4745
  }
4746
  else
4747
  {
4748
    // Needed because bitmap_init() does not set it to null on failure
4749
    m_cols.bitmap= 0;
4750
  }
4751
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
4752
1 by brian
clean slate
4753
482 by Brian Aker
Remove uint.
4754
Rows_log_event::Rows_log_event(const char *buf, uint32_t event_len,
1 by brian
clean slate
4755
                               Log_event_type event_type,
4756
                               const Format_description_log_event
4757
                               *description_event)
4758
  : Log_event(buf, description_event),
4759
    m_row_count(0),
4760
    m_table(NULL),
4761
    m_table_id(0), m_rows_buf(0), m_rows_cur(0), m_rows_end(0)
4762
    , m_curr_row(NULL), m_curr_row_end(NULL), m_key(NULL)
4763
{
206 by Brian Aker
Removed final uint dead types.
4764
  uint8_t const common_header_len= description_event->common_header_len;
4765
  uint8_t const post_header_len= description_event->post_header_len[event_type-1];
1 by brian
clean slate
4766
4767
  const char *post_start= buf + common_header_len;
4768
  post_start+= RW_MAPID_OFFSET;
4769
  if (post_header_len == 6)
4770
  {
4771
    /* Master is of an intermediate source tree before 5.1.4. Id is 4 bytes */
4772
    m_table_id= uint4korr(post_start);
4773
    post_start+= 4;
4774
  }
4775
  else
4776
  {
4777
    m_table_id= (ulong) uint6korr(post_start);
4778
    post_start+= RW_FLAGS_OFFSET;
4779
  }
4780
4781
  m_flags= uint2korr(post_start);
4782
481 by Brian Aker
Remove all of uchar.
4783
  unsigned char const *const var_start=
4784
    (const unsigned char *)buf + common_header_len + post_header_len;
4785
  unsigned char const *const ptr_width= var_start;
4786
  unsigned char *ptr_after_width= (unsigned char*) ptr_width;
1 by brian
clean slate
4787
  m_width = net_field_length(&ptr_after_width);
4788
  /* if bitmap_init fails, catched in is_valid() */
4789
  if (likely(!bitmap_init(&m_cols,
4790
                          m_width <= sizeof(m_bitbuf)*8 ? m_bitbuf : NULL,
4791
                          m_width,
4792
                          false)))
4793
  {
4794
    memcpy(m_cols.bitmap, ptr_after_width, (m_width + 7) / 8);
4795
    create_last_word_mask(&m_cols);
4796
    ptr_after_width+= (m_width + 7) / 8;
4797
  }
4798
  else
4799
  {
4800
    // Needed because bitmap_init() does not set it to null on failure
4801
    m_cols.bitmap= NULL;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4802
    return;
1 by brian
clean slate
4803
  }
4804
4805
  m_cols_ai.bitmap= m_cols.bitmap; /* See explanation in is_valid() */
4806
4807
  if (event_type == UPDATE_ROWS_EVENT)
4808
  {
4809
    /* if bitmap_init fails, caught in is_valid() */
4810
    if (likely(!bitmap_init(&m_cols_ai,
4811
                            m_width <= sizeof(m_bitbuf_ai)*8 ? m_bitbuf_ai : NULL,
4812
                            m_width,
4813
                            false)))
4814
    {
4815
      memcpy(m_cols_ai.bitmap, ptr_after_width, (m_width + 7) / 8);
4816
      create_last_word_mask(&m_cols_ai);
4817
      ptr_after_width+= (m_width + 7) / 8;
4818
    }
4819
    else
4820
    {
4821
      // Needed because bitmap_init() does not set it to null on failure
4822
      m_cols_ai.bitmap= 0;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4823
      return;
1 by brian
clean slate
4824
    }
4825
  }
4826
481 by Brian Aker
Remove all of uchar.
4827
  const unsigned char* const ptr_rows_data= (const unsigned char*) ptr_after_width;
4828
4829
  size_t const data_size= event_len - (ptr_rows_data - (const unsigned char *) buf);
4830
4831
  m_rows_buf= (unsigned char*) my_malloc(data_size, MYF(MY_WME));
1 by brian
clean slate
4832
  if (likely((bool)m_rows_buf))
4833
  {
4834
    m_curr_row= m_rows_buf;
4835
    m_rows_end= m_rows_buf + data_size;
4836
    m_rows_cur= m_rows_end;
4837
    memcpy(m_rows_buf, ptr_rows_data, data_size);
4838
  }
4839
  else
4840
    m_cols.bitmap= 0; // to not free it
4841
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4842
  return;
1 by brian
clean slate
4843
}
4844
4845
Rows_log_event::~Rows_log_event()
4846
{
4847
  if (m_cols.bitmap == m_bitbuf) // no my_malloc happened
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
4848
    m_cols.bitmap= 0; // so no free in bitmap_free
1 by brian
clean slate
4849
  bitmap_free(&m_cols); // To pair with bitmap_init().
481 by Brian Aker
Remove all of uchar.
4850
  free((unsigned char*)m_rows_buf);
1 by brian
clean slate
4851
}
4852
4853
int Rows_log_event::get_data_size()
4854
{
4855
  int const type_code= get_type_code();
4856
481 by Brian Aker
Remove all of uchar.
4857
  unsigned char buf[sizeof(m_width)+1];
4858
  unsigned char *end= net_store_length(buf, (m_width + 7) / 8);
1 by brian
clean slate
4859
4860
  int data_size= ROWS_HEADER_LEN;
4861
  data_size+= no_bytes_in_map(&m_cols);
4862
  data_size+= end - buf;
4863
4864
  if (type_code == UPDATE_ROWS_EVENT)
4865
    data_size+= no_bytes_in_map(&m_cols_ai);
4866
4867
  data_size+= (m_rows_cur - m_rows_buf);
4868
  return data_size; 
4869
}
4870
4871
481 by Brian Aker
Remove all of uchar.
4872
int Rows_log_event::do_add_row_data(unsigned char *row_data, size_t length)
1 by brian
clean slate
4873
{
4874
  /*
4875
    When the table has a primary key, we would probably want, by default, to
4876
    log only the primary key value instead of the entire "before image". This
4877
    would save binlog space. TODO
4878
  */
4879
4880
  /*
4881
    If length is zero, there is nothing to write, so we just
4882
    return. Note that this is not an optimization, since calling
4883
    realloc() with size 0 means free().
4884
   */
4885
  if (length == 0)
4886
  {
4887
    m_row_count++;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4888
    return(0);
1 by brian
clean slate
4889
  }
4890
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4891
  assert(m_rows_buf <= m_rows_cur);
133 by Brian Aker
Cleanup of warning/errors.
4892
  assert(!m_rows_buf || (m_rows_end && m_rows_buf <= m_rows_end));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4893
  assert(m_rows_cur <= m_rows_end);
1 by brian
clean slate
4894
4895
  /* The cast will always work since m_rows_cur <= m_rows_end */
4896
  if (static_cast<size_t>(m_rows_end - m_rows_cur) <= length)
4897
  {
4898
    size_t const block_size= 1024;
4899
    my_ptrdiff_t const cur_size= m_rows_cur - m_rows_buf;
4900
    my_ptrdiff_t const new_alloc= 
4901
        block_size * ((cur_size + length + block_size - 1) / block_size);
4902
481 by Brian Aker
Remove all of uchar.
4903
    unsigned char* const new_buf= (unsigned char*)my_realloc((unsigned char*)m_rows_buf, (uint) new_alloc,
1 by brian
clean slate
4904
                                           MYF(MY_ALLOW_ZERO_PTR|MY_WME));
4905
    if (unlikely(!new_buf))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4906
      return(HA_ERR_OUT_OF_MEM);
1 by brian
clean slate
4907
4908
    /* If the memory moved, we need to move the pointers */
4909
    if (new_buf != m_rows_buf)
4910
    {
4911
      m_rows_buf= new_buf;
4912
      m_rows_cur= m_rows_buf + cur_size;
4913
    }
4914
4915
    /*
4916
       The end pointer should always be changed to point to the end of
4917
       the allocated memory.
4918
    */
4919
    m_rows_end= m_rows_buf + new_alloc;
4920
  }
4921
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4922
  assert(m_rows_cur + length <= m_rows_end);
1 by brian
clean slate
4923
  memcpy(m_rows_cur, row_data, length);
4924
  m_rows_cur+= length;
4925
  m_row_count++;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4926
  return(0);
1 by brian
clean slate
4927
}
4928
4929
int Rows_log_event::do_apply_event(Relay_log_info const *rli)
4930
{
4931
  int error= 0;
4932
  /*
365.2.5 by Monty Taylor
More ~0 removal.
4933
    If m_table_id == UINT32_MAX, then we have a dummy event that does not
1 by brian
clean slate
4934
    contain any data.  In that case, we just remove all tables in the
4935
    tables_to_lock list, close the thread tables, and return with
4936
    success.
4937
   */
365.2.5 by Monty Taylor
More ~0 removal.
4938
  if (m_table_id == UINT32_MAX)
1 by brian
clean slate
4939
  {
4940
    /*
4941
       This one is supposed to be set: just an extra check so that
4942
       nothing strange has happened.
4943
     */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4944
    assert(get_flags(STMT_END_F));
1 by brian
clean slate
4945
4946
    const_cast<Relay_log_info*>(rli)->clear_tables_to_lock();
4947
    close_thread_tables(thd);
4948
    thd->clear_error();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4949
    return(0);
1 by brian
clean slate
4950
  }
4951
4952
  /*
4953
    'thd' has been set by exec_relay_log_event(), just before calling
4954
    do_apply_event(). We still check here to prevent future coding
4955
    errors.
4956
  */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4957
  assert(rli->sql_thd == thd);
1 by brian
clean slate
4958
4959
  /*
4960
    If there is no locks taken, this is the first binrow event seen
4961
    after the table map events.  We should then lock all the tables
4962
    used in the transaction and proceed with execution of the actual
4963
    event.
4964
  */
4965
  if (!thd->lock)
4966
  {
4967
    bool need_reopen= 1; /* To execute the first lap of the loop below */
4968
4969
    /*
4970
      lock_tables() reads the contents of thd->lex, so they must be
4971
      initialized. Contrary to in
4972
      Table_map_log_event::do_apply_event() we don't call
4973
      mysql_init_query() as that may reset the binlog format.
4974
    */
4975
    lex_start(thd);
4976
4977
    /*
4978
      There are a few flags that are replicated with each row event.
4979
      Make sure to set/clear them before executing the main body of
4980
      the event.
4981
    */
4982
    if (get_flags(NO_FOREIGN_KEY_CHECKS_F))
4983
        thd->options|= OPTION_NO_FOREIGN_KEY_CHECKS;
4984
    else
4985
        thd->options&= ~OPTION_NO_FOREIGN_KEY_CHECKS;
4986
4987
    if (get_flags(RELAXED_UNIQUE_CHECKS_F))
4988
        thd->options|= OPTION_RELAXED_UNIQUE_CHECKS;
4989
    else
4990
        thd->options&= ~OPTION_RELAXED_UNIQUE_CHECKS;
4991
    /* A small test to verify that objects have consistent types */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
4992
    assert(sizeof(thd->options) == sizeof(OPTION_RELAXED_UNIQUE_CHECKS));
1 by brian
clean slate
4993
4994
4995
    while ((error= lock_tables(thd, rli->tables_to_lock,
4996
                               rli->tables_to_lock_count, &need_reopen)))
4997
    {
4998
      if (!need_reopen)
4999
      {
5000
        if (thd->is_slave_error || thd->is_fatal_error)
5001
        {
5002
          /*
5003
            Error reporting borrowed from Query_log_event with many excessive
5004
            simplifications (we don't honour --slave-skip-errors)
5005
          */
482 by Brian Aker
Remove uint.
5006
          uint32_t actual_error= thd->main_da.sql_errno();
1 by brian
clean slate
5007
          rli->report(ERROR_LEVEL, actual_error,
398.1.7 by Monty Taylor
Marked some new translations.
5008
                      _("Error '%s' in %s event: when locking tables"),
5009
                      (actual_error
5010
                       ? thd->main_da.message()
5011
                       : _("unexpected success or fatal error")),
1 by brian
clean slate
5012
                      get_type_str());
5013
          thd->is_fatal_error= 1;
5014
        }
5015
        else
5016
        {
5017
          rli->report(ERROR_LEVEL, error,
398.1.7 by Monty Taylor
Marked some new translations.
5018
                      _("Error in %s event: when locking tables"),
1 by brian
clean slate
5019
                      get_type_str());
5020
        }
5021
        const_cast<Relay_log_info*>(rli)->clear_tables_to_lock();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5022
        return(error);
1 by brian
clean slate
5023
      }
5024
5025
      /*
5026
        So we need to reopen the tables.
5027
5028
        We need to flush the pending RBR event, since it keeps a
5029
        pointer to an open table.
5030
5031
        ALTERNATIVE SOLUTION (not implemented): Extract a pointer to
5032
        the pending RBR event and reset the table pointer after the
5033
        tables has been reopened.
5034
5035
        NOTE: For this new scheme there should be no pending event:
5036
        need to add code to assert that is the case.
5037
       */
5038
      thd->binlog_flush_pending_rows_event(false);
327.2.4 by Brian Aker
Refactoring table.h
5039
      TableList *tables= rli->tables_to_lock;
1 by brian
clean slate
5040
      close_tables_for_reopen(thd, &tables);
5041
482 by Brian Aker
Remove uint.
5042
      uint32_t tables_count= rli->tables_to_lock_count;
1 by brian
clean slate
5043
      if ((error= open_tables(thd, &tables, &tables_count, 0)))
5044
      {
5045
        if (thd->is_slave_error || thd->is_fatal_error)
5046
        {
5047
          /*
5048
            Error reporting borrowed from Query_log_event with many excessive
5049
            simplifications (we don't honour --slave-skip-errors)
5050
          */
482 by Brian Aker
Remove uint.
5051
          uint32_t actual_error= thd->main_da.sql_errno();
1 by brian
clean slate
5052
          rli->report(ERROR_LEVEL, actual_error,
398.1.7 by Monty Taylor
Marked some new translations.
5053
                      _("Error '%s' on reopening tables"),
5054
                      (actual_error
5055
                       ? thd->main_da.message()
5056
                       : _("unexpected success or fatal error")));
1 by brian
clean slate
5057
          thd->is_slave_error= 1;
5058
        }
5059
        const_cast<Relay_log_info*>(rli)->clear_tables_to_lock();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5060
        return(error);
1 by brian
clean slate
5061
      }
5062
    }
5063
5064
    /*
5065
      When the open and locking succeeded, we check all tables to
5066
      ensure that they still have the correct type.
5067
5068
      We can use a down cast here since we know that every table added
327.2.4 by Brian Aker
Refactoring table.h
5069
      to the tables_to_lock is a RPL_TableList.
1 by brian
clean slate
5070
    */
5071
5072
    {
327.2.4 by Brian Aker
Refactoring table.h
5073
      RPL_TableList *ptr= rli->tables_to_lock;
5074
      for ( ; ptr ; ptr= static_cast<RPL_TableList*>(ptr->next_global))
1 by brian
clean slate
5075
      {
5076
        if (ptr->m_tabledef.compatible_with(rli, ptr->table))
5077
        {
5078
          mysql_unlock_tables(thd, thd->lock);
5079
          thd->lock= 0;
5080
          thd->is_slave_error= 1;
5081
          const_cast<Relay_log_info*>(rli)->clear_tables_to_lock();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5082
          return(ERR_BAD_TABLE_DEF);
1 by brian
clean slate
5083
        }
5084
      }
5085
    }
5086
5087
    /*
5088
      ... and then we add all the tables to the table map and remove
5089
      them from tables to lock.
5090
5091
      We also invalidate the query cache for all the tables, since
5092
      they will now be changed.
5093
5094
      TODO [/Matz]: Maybe the query cache should not be invalidated
5095
      here? It might be that a table is not changed, even though it
5096
      was locked for the statement.  We do know that each
5097
      Rows_log_event contain at least one row, so after processing one
5098
      Rows_log_event, we can invalidate the query cache for the
5099
      associated table.
5100
     */
327.2.4 by Brian Aker
Refactoring table.h
5101
    for (TableList *ptr= rli->tables_to_lock ; ptr ; ptr= ptr->next_global)
1 by brian
clean slate
5102
    {
5103
      const_cast<Relay_log_info*>(rli)->m_table_map.set_table(ptr->table_id, ptr->table);
5104
    }
5105
  }
5106
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
5107
  Table* 
1 by brian
clean slate
5108
    table= 
5109
    m_table= const_cast<Relay_log_info*>(rli)->m_table_map.get_table(m_table_id);
5110
5111
  if (table)
5112
  {
5113
    /*
5114
      table == NULL means that this table should not be replicated
5115
      (this was set up by Table_map_log_event::do_apply_event()
5116
      which tested replicate-* rules).
5117
    */
5118
5119
    /*
5120
      It's not needed to set_time() but
5121
      1) it continues the property that "Time" in SHOW PROCESSLIST shows how
5122
      much slave is behind
5123
      2) it will be needed when we allow replication from a table with no
5124
      TIMESTAMP column to a table with one.
5125
      So we call set_time(), like in SBR. Presently it changes nothing.
5126
    */
5127
    thd->set_time((time_t)when);
5128
    /*
5129
      There are a few flags that are replicated with each row event.
5130
      Make sure to set/clear them before executing the main body of
5131
      the event.
5132
    */
5133
    if (get_flags(NO_FOREIGN_KEY_CHECKS_F))
5134
        thd->options|= OPTION_NO_FOREIGN_KEY_CHECKS;
5135
    else
5136
        thd->options&= ~OPTION_NO_FOREIGN_KEY_CHECKS;
5137
5138
    if (get_flags(RELAXED_UNIQUE_CHECKS_F))
5139
        thd->options|= OPTION_RELAXED_UNIQUE_CHECKS;
5140
    else
5141
        thd->options&= ~OPTION_RELAXED_UNIQUE_CHECKS;
5142
    
5143
    if (slave_allow_batching)
5144
      thd->options|= OPTION_ALLOW_BATCH;
5145
    else
5146
      thd->options&= ~OPTION_ALLOW_BATCH;
5147
    
5148
    /* A small test to verify that objects have consistent types */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5149
    assert(sizeof(thd->options) == sizeof(OPTION_RELAXED_UNIQUE_CHECKS));
1 by brian
clean slate
5150
5151
    /*
5152
      Now we are in a statement and will stay in a statement until we
5153
      see a STMT_END_F.
5154
5155
      We set this flag here, before actually applying any rows, in
5156
      case the SQL thread is stopped and we need to detect that we're
5157
      inside a statement and halting abruptly might cause problems
5158
      when restarting.
5159
     */
5160
    const_cast<Relay_log_info*>(rli)->set_flag(Relay_log_info::IN_STMT);
5161
5162
     if ( m_width == table->s->fields && bitmap_is_set_all(&m_cols))
5163
      set_flags(COMPLETE_ROWS_F);
5164
5165
    /* 
5166
      Set tables write and read sets.
5167
      
5168
      Read_set contains all slave columns (in case we are going to fetch
5169
      a complete record from slave)
5170
      
5171
      Write_set equals the m_cols bitmap sent from master but it can be 
5172
      longer if slave has extra columns. 
5173
     */ 
5174
5175
    bitmap_set_all(table->read_set);
5176
    bitmap_set_all(table->write_set);
5177
    if (!get_flags(COMPLETE_ROWS_F))
5178
      bitmap_intersect(table->write_set,&m_cols);
5179
5180
    this->slave_exec_mode= slave_exec_mode_options; // fix the mode
5181
5182
    // Do event specific preparations 
5183
    error= do_before_row_operations(rli);
5184
5185
    // row processing loop
5186
5187
    while (error == 0 && m_curr_row < m_rows_end)
5188
    {
5189
      /* in_use can have been set to NULL in close_tables_for_reopen */
5190
      THD* old_thd= table->in_use;
5191
      if (!table->in_use)
5192
        table->in_use= thd;
5193
5194
      error= do_exec_row(rli);
5195
5196
      table->in_use = old_thd;
5197
      switch (error)
5198
      {
5199
      case 0:
5200
	break;
5201
      /*
5202
        The following list of "idempotent" errors
5203
        means that an error from the list might happen
5204
        because of idempotent (more than once) 
5205
        applying of a binlog file.
5206
        Notice, that binlog has a  ddl operation its
5207
        second applying may cause
5208
5209
        case HA_ERR_TABLE_DEF_CHANGED:
5210
        case HA_ERR_CANNOT_ADD_FOREIGN:
5211
        
5212
        which are not included into to the list.
5213
      */
5214
      case HA_ERR_RECORD_CHANGED:
5215
      case HA_ERR_RECORD_DELETED:
5216
      case HA_ERR_KEY_NOT_FOUND:
5217
      case HA_ERR_END_OF_FILE:
5218
      case HA_ERR_FOUND_DUPP_KEY:
5219
      case HA_ERR_FOUND_DUPP_UNIQUE:
5220
      case HA_ERR_FOREIGN_DUPLICATE_KEY:
5221
      case HA_ERR_NO_REFERENCED_ROW:
5222
      case HA_ERR_ROW_IS_REFERENCED:
5223
        if (bit_is_set(slave_exec_mode, SLAVE_EXEC_MODE_IDEMPOTENT) == 1)
5224
        {
5225
          if (global_system_variables.log_warnings)
5226
            slave_rows_error_report(WARNING_LEVEL, error, rli, thd, table,
5227
                                    get_type_str(),
5228
                                    RPL_LOG_NAME, (ulong) log_pos);
5229
          error= 0;
5230
        }
5231
        break;
5232
        
5233
      default:
5234
	thd->is_slave_error= 1;
5235
	break;
5236
      }
5237
5238
      /*
5239
       If m_curr_row_end  was not set during event execution (e.g., because
5240
       of errors) we can't proceed to the next row. If the error is transient
5241
       (i.e., error==0 at this point) we must call unpack_current_row() to set 
5242
       m_curr_row_end.
5243
      */ 
5244
      if (!m_curr_row_end && !error)
5245
        unpack_current_row(rli, &m_cols);
5246
  
5247
      // at this moment m_curr_row_end should be set
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5248
      assert(error || m_curr_row_end != NULL); 
5249
      assert(error || m_curr_row < m_curr_row_end);
5250
      assert(error || m_curr_row_end <= m_rows_end);
1 by brian
clean slate
5251
  
5252
      m_curr_row= m_curr_row_end;
5253
 
5254
    } // row processing loop
5255
5256
    error= do_after_row_operations(rli, error);
5257
    if (!cache_stmt)
5258
    {
5259
      thd->options|= OPTION_KEEP_LOG;
5260
    }
5261
  } // if (table)
5262
5263
  /*
5264
    We need to delay this clear until here bacause unpack_current_row() uses
5265
    master-side table definitions stored in rli.
5266
  */
5267
  if (rli->tables_to_lock && get_flags(STMT_END_F))
5268
    const_cast<Relay_log_info*>(rli)->clear_tables_to_lock();
5269
  /* reset OPTION_ALLOW_BATCH as not affect later events */
5270
  thd->options&= ~OPTION_ALLOW_BATCH;
5271
  
5272
  if (error)
5273
  {                     /* error has occured during the transaction */
5274
    slave_rows_error_report(ERROR_LEVEL, error, rli, thd, table,
5275
                            get_type_str(), RPL_LOG_NAME, (ulong) log_pos);
5276
  }
5277
  if (error)
5278
  {
5279
    /*
5280
      If one day we honour --skip-slave-errors in row-based replication, and
5281
      the error should be skipped, then we would clear mappings, rollback,
5282
      close tables, but the slave SQL thread would not stop and then may
5283
      assume the mapping is still available, the tables are still open...
5284
      So then we should clear mappings/rollback/close here only if this is a
5285
      STMT_END_F.
5286
      For now we code, knowing that error is not skippable and so slave SQL
5287
      thread is certainly going to stop.
5288
      rollback at the caller along with sbr.
5289
    */
5290
    thd->reset_current_stmt_binlog_row_based();
5291
    const_cast<Relay_log_info*>(rli)->cleanup_context(thd, error);
5292
    thd->is_slave_error= 1;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5293
    return(error);
1 by brian
clean slate
5294
  }
5295
5296
  /*
5297
    This code would ideally be placed in do_update_pos() instead, but
5298
    since we have no access to table there, we do the setting of
5299
    last_event_start_time here instead.
5300
  */
5301
  if (table && (table->s->primary_key == MAX_KEY) &&
5302
      !cache_stmt && get_flags(STMT_END_F) == RLE_NO_FLAGS)
5303
  {
5304
    /*
5305
      ------------ Temporary fix until WL#2975 is implemented ---------
5306
5307
      This event is not the last one (no STMT_END_F). If we stop now
5308
      (in case of terminate_slave_thread()), how will we restart? We
5309
      have to restart from Table_map_log_event, but as this table is
5310
      not transactional, the rows already inserted will still be
5311
      present, and idempotency is not guaranteed (no PK) so we risk
5312
      that repeating leads to double insert. So we desperately try to
5313
      continue, hope we'll eventually leave this buggy situation (by
5314
      executing the final Rows_log_event). If we are in a hopeless
5315
      wait (reached end of last relay log and nothing gets appended
5316
      there), we timeout after one minute, and notify DBA about the
5317
      problem.  When WL#2975 is implemented, just remove the member
5318
      Relay_log_info::last_event_start_time and all its occurrences.
5319
    */
5320
    const_cast<Relay_log_info*>(rli)->last_event_start_time= my_time(0);
5321
  }
5322
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5323
  return(0);
1 by brian
clean slate
5324
}
5325
5326
Log_event::enum_skip_reason
5327
Rows_log_event::do_shall_skip(Relay_log_info *rli)
5328
{
5329
  /*
5330
    If the slave skip counter is 1 and this event does not end a
5331
    statement, then we should not start executing on the next event.
5332
    Otherwise, we defer the decision to the normal skipping logic.
5333
  */
5334
  if (rli->slave_skip_counter == 1 && !get_flags(STMT_END_F))
5335
    return Log_event::EVENT_SKIP_IGNORE;
5336
  else
5337
    return Log_event::do_shall_skip(rli);
5338
}
5339
5340
int
5341
Rows_log_event::do_update_pos(Relay_log_info *rli)
5342
{
5343
  int error= 0;
5344
5345
  if (get_flags(STMT_END_F))
5346
  {
5347
    /*
5348
      This is the end of a statement or transaction, so close (and
5349
      unlock) the tables we opened when processing the
5350
      Table_map_log_event starting the statement.
5351
5352
      OBSERVER.  This will clear *all* mappings, not only those that
5353
      are open for the table. There is not good handle for on-close
5354
      actions for tables.
5355
5356
      NOTE. Even if we have no table ('table' == 0) we still need to be
5357
      here, so that we increase the group relay log position. If we didn't, we
5358
      could have a group relay log position which lags behind "forever"
5359
      (assume the last master's transaction is ignored by the slave because of
5360
      replicate-ignore rules).
5361
    */
5362
    thd->binlog_flush_pending_rows_event(true);
5363
5364
    /*
5365
      If this event is not in a transaction, the call below will, if some
5366
      transactional storage engines are involved, commit the statement into
5367
      them and flush the pending event to binlog.
5368
      If this event is in a transaction, the call will do nothing, but a
5369
      Xid_log_event will come next which will, if some transactional engines
5370
      are involved, commit the transaction and flush the pending event to the
5371
      binlog.
5372
    */
5373
    error= ha_autocommit_or_rollback(thd, 0);
5374
5375
    /*
5376
      Now what if this is not a transactional engine? we still need to
5377
      flush the pending event to the binlog; we did it with
5378
      thd->binlog_flush_pending_rows_event(). Note that we imitate
5379
      what is done for real queries: a call to
5380
      ha_autocommit_or_rollback() (sometimes only if involves a
5381
      transactional engine), and a call to be sure to have the pending
5382
      event flushed.
5383
    */
5384
5385
    thd->reset_current_stmt_binlog_row_based();
5386
5387
    rli->cleanup_context(thd, 0);
5388
    if (error == 0)
5389
    {
5390
      /*
5391
        Indicate that a statement is finished.
5392
        Step the group log position if we are not in a transaction,
5393
        otherwise increase the event log position.
5394
       */
5395
      rli->stmt_done(log_pos, when);
5396
5397
      /*
5398
        Clear any errors pushed in thd->net.last_err* if for example "no key
5399
        found" (as this is allowed). This is a safety measure; apparently
5400
        those errors (e.g. when executing a Delete_rows_log_event of a
5401
        non-existing row, like in rpl_row_mystery22.test,
5402
        thd->net.last_error = "Can't find record in 't1'" and last_errno=1032)
5403
        do not become visible. We still prefer to wipe them out.
5404
      */
5405
      thd->clear_error();
5406
    }
5407
    else
5408
      rli->report(ERROR_LEVEL, error,
398.1.7 by Monty Taylor
Marked some new translations.
5409
                  _("Error in %s event: commit of row events failed, "
5410
                    "table `%s`.`%s`"),
1 by brian
clean slate
5411
                  get_type_str(), m_table->s->db.str,
5412
                  m_table->s->table_name.str);
5413
  }
5414
  else
5415
  {
5416
    rli->inc_event_relay_log_pos();
5417
  }
5418
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5419
  return(error);
1 by brian
clean slate
5420
}
5421
5422
bool Rows_log_event::write_data_header(IO_CACHE *file)
5423
{
481 by Brian Aker
Remove all of uchar.
5424
  unsigned char buf[ROWS_HEADER_LEN];	// No need to init the buffer
365.2.5 by Monty Taylor
More ~0 removal.
5425
  assert(m_table_id != UINT32_MAX);
151 by Brian Aker
Ulonglong to uint64_t
5426
  int6store(buf + RW_MAPID_OFFSET, (uint64_t)m_table_id);
1 by brian
clean slate
5427
  int2store(buf + RW_FLAGS_OFFSET, m_flags);
5428
  return (my_b_safe_write(file, buf, ROWS_HEADER_LEN));
5429
}
5430
5431
bool Rows_log_event::write_data_body(IO_CACHE*file)
5432
{
5433
  /*
5434
     Note that this should be the number of *bits*, not the number of
5435
     bytes.
5436
  */
481 by Brian Aker
Remove all of uchar.
5437
  unsigned char sbuf[sizeof(m_width)];
1 by brian
clean slate
5438
  my_ptrdiff_t const data_size= m_rows_cur - m_rows_buf;
5439
  bool res= false;
481 by Brian Aker
Remove all of uchar.
5440
  unsigned char *const sbuf_end= net_store_length(sbuf, (size_t) m_width);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5441
  assert(static_cast<size_t>(sbuf_end - sbuf) <= sizeof(sbuf));
1 by brian
clean slate
5442
5443
  res= res || my_b_safe_write(file, sbuf, (size_t) (sbuf_end - sbuf));
5444
481 by Brian Aker
Remove all of uchar.
5445
  res= res || my_b_safe_write(file, (unsigned char*) m_cols.bitmap,
1 by brian
clean slate
5446
                              no_bytes_in_map(&m_cols));
5447
  /*
5448
    TODO[refactor write]: Remove the "down cast" here (and elsewhere).
5449
   */
5450
  if (get_type_code() == UPDATE_ROWS_EVENT)
5451
  {
481 by Brian Aker
Remove all of uchar.
5452
    res= res || my_b_safe_write(file, (unsigned char*) m_cols_ai.bitmap,
1 by brian
clean slate
5453
                                no_bytes_in_map(&m_cols_ai));
5454
  }
5455
  res= res || my_b_safe_write(file, m_rows_buf, (size_t) data_size);
5456
5457
  return res;
5458
5459
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
5460
5461
1 by brian
clean slate
5462
void Rows_log_event::pack_info(Protocol *protocol)
5463
{
5464
  char buf[256];
5465
  char const *const flagstr=
5466
    get_flags(STMT_END_F) ? " flags: STMT_END_F" : "";
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
5467
  size_t bytes= snprintf(buf, sizeof(buf),
5468
                         "table_id: %lu%s", m_table_id, flagstr);
1 by brian
clean slate
5469
  protocol->store(buf, bytes, &my_charset_bin);
5470
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
5471
1 by brian
clean slate
5472
5473
/**************************************************************************
5474
	Table_map_log_event member functions and support functions
5475
**************************************************************************/
5476
5477
/**
5478
  @page How replication of field metadata works.
5479
  
5480
  When a table map is created, the master first calls 
5481
  Table_map_log_event::save_field_metadata() which calculates how many 
5482
  values will be in the field metadata. Only those fields that require the 
5483
  extra data are added. The method also loops through all of the fields in 
5484
  the table calling the method Field::save_field_metadata() which returns the
5485
  values for the field that will be saved in the metadata and replicated to
5486
  the slave. Once all fields have been processed, the table map is written to
5487
  the binlog adding the size of the field metadata and the field metadata to
5488
  the end of the body of the table map.
5489
5490
  When a table map is read on the slave, the field metadata is read from the 
5491
  table map and passed to the table_def class constructor which saves the 
5492
  field metadata from the table map into an array based on the type of the 
5493
  field. Field metadata values not present (those fields that do not use extra 
5494
  data) in the table map are initialized as zero (0). The array size is the 
5495
  same as the columns for the table on the slave.
5496
5497
  Additionally, values saved for field metadata on the master are saved as a 
481 by Brian Aker
Remove all of uchar.
5498
  string of bytes (unsigned char) in the binlog. A field may require 1 or more bytes
1 by brian
clean slate
5499
  to store the information. In cases where values require multiple bytes 
5500
  (e.g. values > 255), the endian-safe methods are used to properly encode 
5501
  the values on the master and decode them on the slave. When the field
5502
  metadata values are captured on the slave, they are stored in an array of
206 by Brian Aker
Removed final uint dead types.
5503
  type uint16_t. This allows the least number of casts to prevent casting bugs
1 by brian
clean slate
5504
  when the field metadata is used in comparisons of field attributes. When
5505
  the field metadata is used for calculating addresses in pointer math, the
205 by Brian Aker
uint32 -> uin32_t
5506
  type used is uint32_t. 
1 by brian
clean slate
5507
*/
5508
5509
/**
5510
  Save the field metadata based on the real_type of the field.
5511
  The metadata saved depends on the type of the field. Some fields
5512
  store a single byte for pack_length() while others store two bytes
5513
  for field_length (max length).
5514
  
5515
  @retval  0  Ok.
5516
5517
  @todo
5518
  We may want to consider changing the encoding of the information.
5519
  Currently, the code attempts to minimize the number of bytes written to 
5520
  the tablemap. There are at least two other alternatives; 1) using 
5521
  net_store_length() to store the data allowing it to choose the number of
5522
  bytes that are appropriate thereby making the code much easier to 
5523
  maintain (only 1 place to change the encoding), or 2) use a fixed number
5524
  of bytes for each field. The problem with option 1 is that net_store_length()
5525
  will use one byte if the value < 251, but 3 bytes if it is > 250. Thus,
5526
  for fields like CHAR which can be no larger than 255 characters, the method
5527
  will use 3 bytes when the value is > 250. Further, every value that is
5528
  encoded using 2 parts (e.g., pack_length, field_length) will be numerically
5529
  > 250 therefore will use 3 bytes for eah value. The problem with option 2
5530
  is less wasteful for space but does waste 1 byte for every field that does
5531
  not encode 2 parts. 
5532
*/
5533
int Table_map_log_event::save_field_metadata()
5534
{
5535
  int index= 0;
5536
  for (unsigned int i= 0 ; i < m_table->s->fields ; i++)
5537
    index+= m_table->s->field[i]->save_field_metadata(&m_field_metadata[index]);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5538
  return(index);
1 by brian
clean slate
5539
}
5540
5541
/*
5542
  Constructor used to build an event for writing to the binary log.
5543
  Mats says tbl->s lives longer than this event so it's ok to copy pointers
5544
  (tbl->s->db etc) and not pointer content.
5545
 */
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
5546
Table_map_log_event::Table_map_log_event(THD *thd, Table *tbl, ulong tid,
212.1.3 by Monty Taylor
Renamed __attribute__((__unused__)) to __attribute__((unused)).
5547
                                         bool is_transactional __attribute__((unused)),
206 by Brian Aker
Removed final uint dead types.
5548
                                         uint16_t flags)
1 by brian
clean slate
5549
  : Log_event(thd, 0, true),
5550
    m_table(tbl),
5551
    m_dbnam(tbl->s->db.str),
5552
    m_dblen(m_dbnam ? tbl->s->db.length : 0),
5553
    m_tblnam(tbl->s->table_name.str),
5554
    m_tbllen(tbl->s->table_name.length),
5555
    m_colcnt(tbl->s->fields),
5556
    m_memory(NULL),
5557
    m_table_id(tid),
5558
    m_flags(flags),
5559
    m_data_size(0),
5560
    m_field_metadata(0),
5561
    m_field_metadata_size(0),
5562
    m_null_bits(0),
5563
    m_meta_memory(NULL)
5564
{
365.2.5 by Monty Taylor
More ~0 removal.
5565
  assert(m_table_id != UINT32_MAX);
1 by brian
clean slate
5566
  /*
5567
    In TABLE_SHARE, "db" and "table_name" are 0-terminated (see this comment in
5568
    table.cc / alloc_table_share():
5569
      Use the fact the key is db/0/table_name/0
5570
    As we rely on this let's assert it.
5571
  */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5572
  assert((tbl->s->db.str == 0) ||
1 by brian
clean slate
5573
              (tbl->s->db.str[tbl->s->db.length] == 0));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5574
  assert(tbl->s->table_name.str[tbl->s->table_name.length] == 0);
1 by brian
clean slate
5575
5576
5577
  m_data_size=  TABLE_MAP_HEADER_LEN;
5578
  m_data_size+= m_dblen + 2;	// Include length and terminating \0
5579
  m_data_size+= m_tbllen + 2;	// Include length and terminating \0
5580
  m_data_size+= 1 + m_colcnt;	// COLCNT and column types
5581
5582
  /* If malloc fails, caught in is_valid() */
481 by Brian Aker
Remove all of uchar.
5583
  if ((m_memory= (unsigned char*) my_malloc(m_colcnt, MYF(MY_WME))))
1 by brian
clean slate
5584
  {
481 by Brian Aker
Remove all of uchar.
5585
    m_coltype= reinterpret_cast<unsigned char*>(m_memory);
1 by brian
clean slate
5586
    for (unsigned int i= 0 ; i < m_table->s->fields ; ++i)
5587
      m_coltype[i]= m_table->field[i]->type();
5588
  }
5589
5590
  /*
5591
    Calculate a bitmap for the results of maybe_null() for all columns.
5592
    The bitmap is used to determine when there is a column from the master
5593
    that is not on the slave and is null and thus not in the row data during
5594
    replication.
5595
  */
482 by Brian Aker
Remove uint.
5596
  uint32_t num_null_bytes= (m_table->s->fields + 7) / 8;
1 by brian
clean slate
5597
  m_data_size+= num_null_bytes;
481 by Brian Aker
Remove all of uchar.
5598
  m_meta_memory= (unsigned char *)my_multi_malloc(MYF(MY_WME),
1 by brian
clean slate
5599
                                 &m_null_bits, num_null_bytes,
5600
                                 &m_field_metadata, (m_colcnt * 2),
5601
                                 NULL);
5602
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
5603
  memset(m_field_metadata, 0, (m_colcnt * 2));
1 by brian
clean slate
5604
5605
  /*
5606
    Create an array for the field metadata and store it.
5607
  */
5608
  m_field_metadata_size= save_field_metadata();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5609
  assert(m_field_metadata_size <= (m_colcnt * 2));
1 by brian
clean slate
5610
5611
  /*
5612
    Now set the size of the data to the size of the field metadata array
5613
    plus one or two bytes for number of elements in the field metadata array.
5614
  */
5615
  if (m_field_metadata_size > 255)
5616
    m_data_size+= m_field_metadata_size + 2; 
5617
  else
5618
    m_data_size+= m_field_metadata_size + 1; 
5619
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
5620
  memset(m_null_bits, 0, num_null_bytes);
1 by brian
clean slate
5621
  for (unsigned int i= 0 ; i < m_table->s->fields ; ++i)
5622
    if (m_table->field[i]->maybe_null())
5623
      m_null_bits[(i / 8)]+= 1 << (i % 8);
5624
5625
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
5626
1 by brian
clean slate
5627
5628
/*
5629
  Constructor used by slave to read the event from the binary log.
5630
 */
482 by Brian Aker
Remove uint.
5631
Table_map_log_event::Table_map_log_event(const char *buf, uint32_t event_len,
1 by brian
clean slate
5632
                                         const Format_description_log_event
5633
                                         *description_event)
5634
5635
  : Log_event(buf, description_event),
5636
    m_table(NULL),
5637
    m_dbnam(NULL), m_dblen(0), m_tblnam(NULL), m_tbllen(0),
5638
    m_colcnt(0), m_coltype(0),
5639
    m_memory(NULL), m_table_id(ULONG_MAX), m_flags(0),
5640
    m_data_size(0), m_field_metadata(0), m_field_metadata_size(0),
5641
    m_null_bits(0), m_meta_memory(NULL)
5642
{
5643
  unsigned int bytes_read= 0;
5644
206 by Brian Aker
Removed final uint dead types.
5645
  uint8_t common_header_len= description_event->common_header_len;
5646
  uint8_t post_header_len= description_event->post_header_len[TABLE_MAP_EVENT-1];
1 by brian
clean slate
5647
5648
  /* Read the post-header */
5649
  const char *post_start= buf + common_header_len;
5650
5651
  post_start+= TM_MAPID_OFFSET;
5652
  if (post_header_len == 6)
5653
  {
5654
    /* Master is of an intermediate source tree before 5.1.4. Id is 4 bytes */
5655
    m_table_id= uint4korr(post_start);
5656
    post_start+= 4;
5657
  }
5658
  else
5659
  {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5660
    assert(post_header_len == TABLE_MAP_HEADER_LEN);
1 by brian
clean slate
5661
    m_table_id= (ulong) uint6korr(post_start);
5662
    post_start+= TM_FLAGS_OFFSET;
5663
  }
5664
365.2.5 by Monty Taylor
More ~0 removal.
5665
  assert(m_table_id != UINT32_MAX);
1 by brian
clean slate
5666
5667
  m_flags= uint2korr(post_start);
5668
5669
  /* Read the variable part of the event */
5670
  const char *const vpart= buf + common_header_len + post_header_len;
5671
5672
  /* Extract the length of the various parts from the buffer */
481 by Brian Aker
Remove all of uchar.
5673
  unsigned char const *const ptr_dblen= (unsigned char const*)vpart + 0;
5674
  m_dblen= *(unsigned char*) ptr_dblen;
1 by brian
clean slate
5675
5676
  /* Length of database name + counter + terminating null */
481 by Brian Aker
Remove all of uchar.
5677
  unsigned char const *const ptr_tbllen= ptr_dblen + m_dblen + 2;
5678
  m_tbllen= *(unsigned char*) ptr_tbllen;
1 by brian
clean slate
5679
5680
  /* Length of table name + counter + terminating null */
481 by Brian Aker
Remove all of uchar.
5681
  unsigned char const *const ptr_colcnt= ptr_tbllen + m_tbllen + 2;
5682
  unsigned char *ptr_after_colcnt= (unsigned char*) ptr_colcnt;
1 by brian
clean slate
5683
  m_colcnt= net_field_length(&ptr_after_colcnt);
5684
5685
  /* Allocate mem for all fields in one go. If fails, caught in is_valid() */
481 by Brian Aker
Remove all of uchar.
5686
  m_memory= (unsigned char*) my_multi_malloc(MYF(MY_WME),
1 by brian
clean slate
5687
                                     &m_dbnam, (uint) m_dblen + 1,
5688
                                     &m_tblnam, (uint) m_tbllen + 1,
5689
                                     &m_coltype, (uint) m_colcnt,
461 by Monty Taylor
Removed NullS. bu-bye.
5690
                                     NULL);
1 by brian
clean slate
5691
5692
  if (m_memory)
5693
  {
5694
    /* Copy the different parts into their memory */
5695
    strncpy(const_cast<char*>(m_dbnam), (const char*)ptr_dblen  + 1, m_dblen + 1);
5696
    strncpy(const_cast<char*>(m_tblnam), (const char*)ptr_tbllen + 1, m_tbllen + 1);
5697
    memcpy(m_coltype, ptr_after_colcnt, m_colcnt);
5698
5699
    ptr_after_colcnt= ptr_after_colcnt + m_colcnt;
481 by Brian Aker
Remove all of uchar.
5700
    bytes_read= ptr_after_colcnt - (unsigned char *)buf;
1 by brian
clean slate
5701
    if (bytes_read < event_len)
5702
    {
5703
      m_field_metadata_size= net_field_length(&ptr_after_colcnt);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5704
      assert(m_field_metadata_size <= (m_colcnt * 2));
482 by Brian Aker
Remove uint.
5705
      uint32_t num_null_bytes= (m_colcnt + 7) / 8;
481 by Brian Aker
Remove all of uchar.
5706
      m_meta_memory= (unsigned char *)my_multi_malloc(MYF(MY_WME),
1 by brian
clean slate
5707
                                     &m_null_bits, num_null_bytes,
5708
                                     &m_field_metadata, m_field_metadata_size,
5709
                                     NULL);
5710
      memcpy(m_field_metadata, ptr_after_colcnt, m_field_metadata_size);
481 by Brian Aker
Remove all of uchar.
5711
      ptr_after_colcnt= (unsigned char*)ptr_after_colcnt + m_field_metadata_size;
1 by brian
clean slate
5712
      memcpy(m_null_bits, ptr_after_colcnt, num_null_bytes);
5713
    }
5714
  }
5715
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5716
  return;
1 by brian
clean slate
5717
}
5718
5719
Table_map_log_event::~Table_map_log_event()
5720
{
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
5721
  free(m_meta_memory);
5722
  free(m_memory);
1 by brian
clean slate
5723
}
5724
5725
/*
5726
  Return value is an error code, one of:
5727
5728
      -1     Failure to open table   [from open_tables()]
5729
       0     Success
5730
       1     No room for more tables [from set_table()]
5731
       2     Out of memory           [from set_table()]
5732
       3     Wrong table definition
5733
       4     Daisy-chaining RBR with SBR not possible
5734
 */
5735
5736
int Table_map_log_event::do_apply_event(Relay_log_info const *rli)
5737
{
327.2.4 by Brian Aker
Refactoring table.h
5738
  RPL_TableList *table_list;
1 by brian
clean slate
5739
  char *db_mem, *tname_mem;
5740
  size_t dummy_len;
5741
  void *memory;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5742
  assert(rli->sql_thd == thd);
1 by brian
clean slate
5743
5744
  /* Step the query id to mark what columns that are actually used. */
5745
  pthread_mutex_lock(&LOCK_thread_count);
5746
  thd->query_id= next_query_id();
5747
  pthread_mutex_unlock(&LOCK_thread_count);
5748
5749
  if (!(memory= my_multi_malloc(MYF(MY_WME),
327.2.4 by Brian Aker
Refactoring table.h
5750
                                &table_list, (uint) sizeof(RPL_TableList),
1 by brian
clean slate
5751
                                &db_mem, (uint) NAME_LEN + 1,
5752
                                &tname_mem, (uint) NAME_LEN + 1,
461 by Monty Taylor
Removed NullS. bu-bye.
5753
                                NULL)))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5754
    return(HA_ERR_OUT_OF_MEM);
1 by brian
clean slate
5755
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
5756
  memset(table_list, 0, sizeof(*table_list));
1 by brian
clean slate
5757
  table_list->db = db_mem;
5758
  table_list->alias= table_list->table_name = tname_mem;
5759
  table_list->lock_type= TL_WRITE;
5760
  table_list->next_global= table_list->next_local= 0;
5761
  table_list->table_id= m_table_id;
5762
  table_list->updating= 1;
411.1.1 by Brian Aker
Work on removing GNU specific calls.
5763
  my_stpcpy(table_list->db, rpl_filter->get_rewrite_db(m_dbnam, &dummy_len));
5764
  my_stpcpy(table_list->table_name, m_tblnam);
1 by brian
clean slate
5765
5766
  int error= 0;
5767
5768
  if (!rpl_filter->db_ok(table_list->db) ||
5769
      (rpl_filter->is_on() && !rpl_filter->tables_ok("", table_list)))
5770
  {
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
5771
    free(memory);
1 by brian
clean slate
5772
  }
5773
  else
5774
  {
5775
    /*
5776
      open_tables() reads the contents of thd->lex, so they must be
5777
      initialized, so we should call lex_start(); to be even safer, we
5778
      call mysql_init_query() which does a more complete set of inits.
5779
    */
5780
    lex_start(thd);
5781
    mysql_reset_thd_for_next_command(thd);
5782
    /*
5783
      Check if the slave is set to use SBR.  If so, it should switch
5784
      to using RBR until the end of the "statement", i.e., next
5785
      STMT_END_F or next error.
5786
    */
5787
    if (!thd->current_stmt_binlog_row_based &&
5788
        mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
5789
    {
5790
      thd->set_current_stmt_binlog_row_based();
5791
    }
5792
5793
    /*
5794
      Open the table if it is not already open and add the table to
5795
      table map.  Note that for any table that should not be
5796
      replicated, a filter is needed.
5797
327.2.4 by Brian Aker
Refactoring table.h
5798
      The creation of a new TableList is used to up-cast the
5799
      table_list consisting of RPL_TableList items. This will work
1 by brian
clean slate
5800
      since the only case where the argument to open_tables() is
5801
      changed, is when thd->lex->query_tables == table_list, i.e.,
5802
      when the statement requires prelocking. Since this is not
5803
      executed when a statement is executed, this case will not occur.
5804
      As a precaution, an assertion is added to ensure that the bad
5805
      case is not a fact.
5806
5807
      Either way, the memory in the list is *never* released
5808
      internally in the open_tables() function, hence we take a copy
5809
      of the pointer to make sure that it's not lost.
5810
    */
482 by Brian Aker
Remove uint.
5811
    uint32_t count;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5812
    assert(thd->lex->query_tables != table_list);
327.2.4 by Brian Aker
Refactoring table.h
5813
    TableList *tmp_table_list= table_list;
1 by brian
clean slate
5814
    if ((error= open_tables(thd, &tmp_table_list, &count, 0)))
5815
    {
5816
      if (thd->is_slave_error || thd->is_fatal_error)
5817
      {
5818
        /*
5819
          Error reporting borrowed from Query_log_event with many excessive
5820
          simplifications (we don't honour --slave-skip-errors)
5821
        */
482 by Brian Aker
Remove uint.
5822
        uint32_t actual_error= thd->main_da.sql_errno();
1 by brian
clean slate
5823
        rli->report(ERROR_LEVEL, actual_error,
398.1.7 by Monty Taylor
Marked some new translations.
5824
                    _("Error '%s' on opening table `%s`.`%s`"),
5825
                    (actual_error
5826
                     ? thd->main_da.message()
5827
                     : _("unexpected success or fatal error")),
1 by brian
clean slate
5828
                    table_list->db, table_list->table_name);
5829
        thd->is_slave_error= 1;
5830
      }
5831
      goto err;
5832
    }
5833
5834
    m_table= table_list->table;
5835
5836
    /*
5837
      This will fail later otherwise, the 'in_use' field should be
5838
      set to the current thread.
5839
    */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5840
    assert(m_table->in_use);
1 by brian
clean slate
5841
5842
    /*
5843
      Use placement new to construct the table_def instance in the
5844
      memory allocated for it inside table_list.
5845
5846
      The memory allocated by the table_def structure (i.e., not the
5847
      memory allocated *for* the table_def structure) is released
5848
      inside Relay_log_info::clear_tables_to_lock() by calling the
5849
      table_def destructor explicitly.
5850
    */
5851
    new (&table_list->m_tabledef) table_def(m_coltype, m_colcnt, 
5852
         m_field_metadata, m_field_metadata_size, m_null_bits);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5853
    table_list->m_tabledef_valid= true;
1 by brian
clean slate
5854
5855
    /*
5856
      We record in the slave's information that the table should be
5857
      locked by linking the table into the list of tables to lock.
5858
    */
5859
    table_list->next_global= table_list->next_local= rli->tables_to_lock;
5860
    const_cast<Relay_log_info*>(rli)->tables_to_lock= table_list;
5861
    const_cast<Relay_log_info*>(rli)->tables_to_lock_count++;
5862
    /* 'memory' is freed in clear_tables_to_lock */
5863
  }
5864
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5865
  return(error);
1 by brian
clean slate
5866
5867
err:
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
5868
  free(memory);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5869
  return(error);
1 by brian
clean slate
5870
}
5871
5872
Log_event::enum_skip_reason
5873
Table_map_log_event::do_shall_skip(Relay_log_info *rli)
5874
{
5875
  /*
5876
    If the slave skip counter is 1, then we should not start executing
5877
    on the next event.
5878
  */
5879
  return continue_group(rli);
5880
}
5881
5882
int Table_map_log_event::do_update_pos(Relay_log_info *rli)
5883
{
5884
  rli->inc_event_relay_log_pos();
5885
  return 0;
5886
}
5887
5888
5889
bool Table_map_log_event::write_data_header(IO_CACHE *file)
5890
{
365.2.5 by Monty Taylor
More ~0 removal.
5891
  assert(m_table_id != UINT32_MAX);
481 by Brian Aker
Remove all of uchar.
5892
  unsigned char buf[TABLE_MAP_HEADER_LEN];
151 by Brian Aker
Ulonglong to uint64_t
5893
  int6store(buf + TM_MAPID_OFFSET, (uint64_t)m_table_id);
1 by brian
clean slate
5894
  int2store(buf + TM_FLAGS_OFFSET, m_flags);
5895
  return (my_b_safe_write(file, buf, TABLE_MAP_HEADER_LEN));
5896
}
5897
5898
bool Table_map_log_event::write_data_body(IO_CACHE *file)
5899
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5900
  assert(m_dbnam != NULL);
5901
  assert(m_tblnam != NULL);
1 by brian
clean slate
5902
  /* We use only one byte per length for storage in event: */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5903
  assert(m_dblen < 128);
5904
  assert(m_tbllen < 128);
1 by brian
clean slate
5905
481 by Brian Aker
Remove all of uchar.
5906
  unsigned char const dbuf[]= { (unsigned char) m_dblen };
5907
  unsigned char const tbuf[]= { (unsigned char) m_tbllen };
1 by brian
clean slate
5908
481 by Brian Aker
Remove all of uchar.
5909
  unsigned char cbuf[sizeof(m_colcnt)];
5910
  unsigned char *const cbuf_end= net_store_length(cbuf, (size_t) m_colcnt);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
5911
  assert(static_cast<size_t>(cbuf_end - cbuf) <= sizeof(cbuf));
1 by brian
clean slate
5912
5913
  /*
5914
    Store the size of the field metadata.
5915
  */
481 by Brian Aker
Remove all of uchar.
5916
  unsigned char mbuf[sizeof(m_field_metadata_size)];
5917
  unsigned char *const mbuf_end= net_store_length(mbuf, m_field_metadata_size);
1 by brian
clean slate
5918
5919
  return (my_b_safe_write(file, dbuf,      sizeof(dbuf)) ||
481 by Brian Aker
Remove all of uchar.
5920
          my_b_safe_write(file, (const unsigned char*)m_dbnam,   m_dblen+1) ||
1 by brian
clean slate
5921
          my_b_safe_write(file, tbuf,      sizeof(tbuf)) ||
481 by Brian Aker
Remove all of uchar.
5922
          my_b_safe_write(file, (const unsigned char*)m_tblnam,  m_tbllen+1) ||
1 by brian
clean slate
5923
          my_b_safe_write(file, cbuf, (size_t) (cbuf_end - cbuf)) ||
5924
          my_b_safe_write(file, m_coltype, m_colcnt) ||
5925
          my_b_safe_write(file, mbuf, (size_t) (mbuf_end - mbuf)) ||
5926
          my_b_safe_write(file, m_field_metadata, m_field_metadata_size),
5927
          my_b_safe_write(file, m_null_bits, (m_colcnt + 7) / 8));
5928
 }
5929
5930
5931
/*
5932
  Print some useful information for the SHOW BINARY LOG information
5933
  field.
5934
 */
5935
5936
void Table_map_log_event::pack_info(Protocol *protocol)
5937
{
5938
    char buf[256];
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
5939
    size_t bytes= snprintf(buf, sizeof(buf),
5940
                           "table_id: %lu (%s.%s)",
5941
                           m_table_id, m_dbnam, m_tblnam);
1 by brian
clean slate
5942
    protocol->store(buf, bytes, &my_charset_bin);
5943
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
5944
1 by brian
clean slate
5945
5946
/**************************************************************************
5947
	Write_rows_log_event member functions
5948
**************************************************************************/
5949
5950
/*
5951
  Constructor used to build an event for writing to the binary log.
5952
 */
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
5953
Write_rows_log_event::Write_rows_log_event(THD *thd_arg, Table *tbl_arg,
1 by brian
clean slate
5954
                                           ulong tid_arg,
5955
                                           bool is_transactional)
5956
  : Rows_log_event(thd_arg, tbl_arg, tid_arg, tbl_arg->write_set, is_transactional)
5957
{
5958
}
5959
5960
/*
5961
  Constructor used by slave to read the event from the binary log.
5962
 */
482 by Brian Aker
Remove uint.
5963
Write_rows_log_event::Write_rows_log_event(const char *buf, uint32_t event_len,
1 by brian
clean slate
5964
                                           const Format_description_log_event
5965
                                           *description_event)
5966
: Rows_log_event(buf, event_len, WRITE_ROWS_EVENT, description_event)
5967
{
5968
}
5969
5970
int 
5971
Write_rows_log_event::do_before_row_operations(const Slave_reporting_capability *const)
5972
{
5973
  int error= 0;
5974
5975
  /**
5976
     todo: to introduce a property for the event (handler?) which forces
5977
     applying the event in the replace (idempotent) fashion.
5978
  */
5979
  if (bit_is_set(slave_exec_mode, SLAVE_EXEC_MODE_IDEMPOTENT) == 1)
5980
  {
5981
    /*
5982
      We are using REPLACE semantics and not INSERT IGNORE semantics
5983
      when writing rows, that is: new rows replace old rows.  We need to
5984
      inform the storage engine that it should use this behaviour.
5985
    */
5986
    
5987
    /* Tell the storage engine that we are using REPLACE semantics. */
5988
    thd->lex->duplicates= DUP_REPLACE;
5989
    
5990
    /*
5991
      Pretend we're executing a REPLACE command: this is needed for
5992
      InnoDB since it is not (properly) checking the
5993
      lex->duplicates flag.
5994
    */
5995
    thd->lex->sql_command= SQLCOM_REPLACE;
5996
    /* 
5997
       Do not raise the error flag in case of hitting to an unique attribute
5998
    */
5999
    m_table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
6000
  }
6001
6002
  m_table->file->ha_start_bulk_insert(0);
6003
  /*
6004
    We need TIMESTAMP_NO_AUTO_SET otherwise ha_write_row() will not use fill
6005
    any TIMESTAMP column with data from the row but instead will use
6006
    the event's current time.
6007
    As we replicate from TIMESTAMP to TIMESTAMP and slave has no extra
6008
    columns, we know that all TIMESTAMP columns on slave will receive explicit
6009
    data from the row, so TIMESTAMP_NO_AUTO_SET is ok.
6010
    When we allow a table without TIMESTAMP to be replicated to a table having
6011
    more columns including a TIMESTAMP column, or when we allow a TIMESTAMP
6012
    column to be replicated into a BIGINT column and the slave's table has a
6013
    TIMESTAMP column, then the slave's TIMESTAMP column will take its value
6014
    from set_time() which we called earlier (consistent with SBR). And then in
6015
    some cases we won't want TIMESTAMP_NO_AUTO_SET (will require some code to
6016
    analyze if explicit data is provided for slave's TIMESTAMP columns).
6017
  */
6018
  m_table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
6019
6020
  return error;
6021
}
6022
6023
int 
6024
Write_rows_log_event::do_after_row_operations(const Slave_reporting_capability *const,
6025
                                              int error)
6026
{
6027
  int local_error= 0;
6028
  if (bit_is_set(slave_exec_mode, SLAVE_EXEC_MODE_IDEMPOTENT) == 1)
6029
  {
6030
    m_table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
6031
    m_table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
6032
    /*
6033
      resetting the extra with 
6034
      table->file->extra(HA_EXTRA_NO_IGNORE_NO_KEY); 
6035
      fires bug#27077
6036
      explanation: file->reset() performs this duty
6037
      ultimately. Still todo: fix
6038
    */
6039
  }
6040
  if ((local_error= m_table->file->ha_end_bulk_insert()))
6041
  {
6042
    m_table->file->print_error(local_error, MYF(0));
6043
  }
6044
  return error? error : local_error;
6045
}
6046
6047
6048
/*
6049
  Check if there are more UNIQUE keys after the given key.
6050
*/
6051
static int
482 by Brian Aker
Remove uint.
6052
last_uniq_key(Table *table, uint32_t keyno)
1 by brian
clean slate
6053
{
6054
  while (++keyno < table->s->keys)
6055
    if (table->key_info[keyno].flags & HA_NOSAME)
6056
      return 0;
6057
  return 1;
6058
}
6059
6060
/**
6061
   Check if an error is a duplicate key error.
6062
6063
   This function is used to check if an error code is one of the
6064
   duplicate key error, i.e., and error code for which it is sensible
6065
   to do a <code>get_dup_key()</code> to retrieve the duplicate key.
6066
6067
   @param errcode The error code to check.
6068
6069
   @return <code>true</code> if the error code is such that
6070
   <code>get_dup_key()</code> will return true, <code>false</code>
6071
   otherwise.
6072
 */
6073
bool
6074
is_duplicate_key_error(int errcode)
6075
{
6076
  switch (errcode)
6077
  {
6078
  case HA_ERR_FOUND_DUPP_KEY:
6079
  case HA_ERR_FOUND_DUPP_UNIQUE:
6080
    return true;
6081
  }
6082
  return false;
6083
}
6084
6085
/**
6086
  Write the current row into event's table.
6087
6088
  The row is located in the row buffer, pointed by @c m_curr_row member.
6089
  Number of columns of the row is stored in @c m_width member (it can be 
6090
  different from the number of columns in the table to which we insert). 
6091
  Bitmap @c m_cols indicates which columns are present in the row. It is assumed 
6092
  that event's table is already open and pointed by @c m_table.
6093
6094
  If the same record already exists in the table it can be either overwritten 
6095
  or an error is reported depending on the value of @c overwrite flag 
6096
  (error reporting not yet implemented). Note that the matching record can be
6097
  different from the row we insert if we use primary keys to identify records in
6098
  the table.
6099
6100
  The row to be inserted can contain values only for selected columns. The 
6101
  missing columns are filled with default values using @c prepare_record() 
6102
  function. If a matching record is found in the table and @c overwritte is
6103
  true, the missing columns are taken from it.
6104
6105
  @param  rli   Relay log info (needed for row unpacking).
6106
  @param  overwrite  
6107
                Shall we overwrite if the row already exists or signal 
6108
                error (currently ignored).
6109
6110
  @returns Error code on failure, 0 on success.
6111
6112
  This method, if successful, sets @c m_curr_row_end pointer to point at the
6113
  next row in the rows buffer. This is done when unpacking the row to be 
6114
  inserted.
6115
6116
  @note If a matching record is found, it is either updated using 
6117
  @c ha_update_row() or first deleted and then new record written.
6118
*/ 
6119
6120
int
6121
Rows_log_event::write_row(const Relay_log_info *const rli,
6122
                          const bool overwrite)
6123
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6124
  assert(m_table != NULL && thd != NULL);
1 by brian
clean slate
6125
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
6126
  Table *table= m_table;  // pointer to event's table
1 by brian
clean slate
6127
  int error;
6128
  int keynum;
6129
  auto_afree_ptr<char> key(NULL);
6130
6131
  /* fill table->record[0] with default values */
6132
6133
  /*
6134
     We only check if the columns have default values for non-NDB
6135
     engines, for NDB we ignore the check since updates are sent as
6136
     writes, causing errors when trying to prepare the record.
6137
6138
     TODO[ndb]: Elimiate this hard-coded dependency on NDB. Ideally,
6139
     the engine should be able to set a flag that it want the default
6140
     values filled in and one flag to handle the case that the default
6141
     values should be checked. Maybe these two flags can be combined.
6142
  */
261.1.3 by Brian Aker
Ranom clean up.
6143
  if ((error= prepare_record(table, &m_cols, m_width, true)))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6144
    return(error);
1 by brian
clean slate
6145
  
6146
  /* unpack row into table->record[0] */
6147
  error= unpack_current_row(rli, &m_cols);
6148
6149
  // Temporary fix to find out why it fails [/Matz]
6150
  memcpy(m_table->write_set->bitmap, m_cols.bitmap, (m_table->write_set->n_bits + 7) / 8);
6151
6152
  /* 
6153
    Try to write record. If a corresponding record already exists in the table,
6154
    we try to change it using ha_update_row() if possible. Otherwise we delete
6155
    it and repeat the whole process again. 
6156
6157
    TODO: Add safety measures against infinite looping. 
6158
   */
6159
6160
  while ((error= table->file->ha_write_row(table->record[0])))
6161
  {
6162
    if (error == HA_ERR_LOCK_DEADLOCK ||
6163
        error == HA_ERR_LOCK_WAIT_TIMEOUT ||
6164
        (keynum= table->file->get_dup_key(error)) < 0 ||
6165
        !overwrite)
6166
    {
6167
      /*
6168
        Deadlock, waiting for lock or just an error from the handler
6169
        such as HA_ERR_FOUND_DUPP_KEY when overwrite is false.
6170
        Retrieval of the duplicate key number may fail
6171
        - either because the error was not "duplicate key" error
6172
        - or because the information which key is not available
6173
      */
6174
      table->file->print_error(error, MYF(0));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6175
      return(error);
1 by brian
clean slate
6176
    }
6177
    /*
6178
       We need to retrieve the old row into record[1] to be able to
6179
       either update or delete the offending record.  We either:
6180
6181
       - use rnd_pos() with a row-id (available as dupp_row) to the
6182
         offending row, if that is possible (MyISAM and Blackhole), or else
6183
6184
       - use index_read_idx() with the key that is duplicated, to
6185
         retrieve the offending row.
6186
     */
6187
    if (table->file->ha_table_flags() & HA_DUPLICATE_POS)
6188
    {
6189
      if (table->file->inited && (error= table->file->ha_index_end()))
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6190
        return(error);
6191
      if ((error= table->file->ha_rnd_init(false)))
6192
        return(error);
1 by brian
clean slate
6193
6194
      error= table->file->rnd_pos(table->record[1], table->file->dup_ref);
6195
      table->file->ha_rnd_end();
6196
      if (error)
6197
      {
6198
        table->file->print_error(error, MYF(0));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6199
        return(error);
1 by brian
clean slate
6200
      }
6201
    }
6202
    else
6203
    {
6204
      if (table->file->extra(HA_EXTRA_FLUSH_CACHE))
6205
      {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6206
        return(my_errno);
1 by brian
clean slate
6207
      }
6208
6209
      if (key.get() == NULL)
6210
      {
6211
        key.assign(static_cast<char*>(my_alloca(table->s->max_unique_length)));
6212
        if (key.get() == NULL)
6213
        {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6214
          return(ENOMEM);
1 by brian
clean slate
6215
        }
6216
      }
6217
481 by Brian Aker
Remove all of uchar.
6218
      key_copy((unsigned char*)key.get(), table->record[0], table->key_info + keynum,
1 by brian
clean slate
6219
               0);
6220
      error= table->file->index_read_idx_map(table->record[1], keynum,
481 by Brian Aker
Remove all of uchar.
6221
                                             (const unsigned char*)key.get(),
1 by brian
clean slate
6222
                                             HA_WHOLE_KEY,
6223
                                             HA_READ_KEY_EXACT);
6224
      if (error)
6225
      {
6226
        table->file->print_error(error, MYF(0));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6227
        return(error);
1 by brian
clean slate
6228
      }
6229
    }
6230
6231
    /*
6232
       Now, record[1] should contain the offending row.  That
6233
       will enable us to update it or, alternatively, delete it (so
6234
       that we can insert the new row afterwards).
6235
     */
6236
6237
    /*
6238
      If row is incomplete we will use the record found to fill 
6239
      missing columns.  
6240
    */
6241
    if (!get_flags(COMPLETE_ROWS_F))
6242
    {
6243
      restore_record(table,record[1]);
6244
      error= unpack_current_row(rli, &m_cols);
6245
    }
6246
6247
    /*
6248
       REPLACE is defined as either INSERT or DELETE + INSERT.  If
6249
       possible, we can replace it with an UPDATE, but that will not
6250
       work on InnoDB if FOREIGN KEY checks are necessary.
6251
6252
       I (Matz) am not sure of the reason for the last_uniq_key()
6253
       check as, but I'm guessing that it's something along the
6254
       following lines.
6255
6256
       Suppose that we got the duplicate key to be a key that is not
6257
       the last unique key for the table and we perform an update:
6258
       then there might be another key for which the unique check will
6259
       fail, so we're better off just deleting the row and inserting
6260
       the correct row.
6261
     */
6262
    if (last_uniq_key(table, keynum) &&
6263
        !table->file->referenced_by_foreign_key())
6264
    {
6265
      error=table->file->ha_update_row(table->record[1],
6266
                                       table->record[0]);
6267
      switch (error) {
6268
                
6269
      case HA_ERR_RECORD_IS_THE_SAME:
6270
        error= 0;
6271
      
6272
      case 0:
6273
        break;
6274
        
6275
      default:    
6276
        table->file->print_error(error, MYF(0));
6277
      }
6278
      
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6279
      return(error);
1 by brian
clean slate
6280
    }
6281
    else
6282
    {
6283
      if ((error= table->file->ha_delete_row(table->record[1])))
6284
      {
6285
        table->file->print_error(error, MYF(0));
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6286
        return(error);
1 by brian
clean slate
6287
      }
6288
      /* Will retry ha_write_row() with the offending row removed. */
6289
    }
6290
  }
6291
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6292
  return(error);
1 by brian
clean slate
6293
}
6294
6295
6296
int 
6297
Write_rows_log_event::do_exec_row(const Relay_log_info *const rli)
6298
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6299
  assert(m_table != NULL);
1 by brian
clean slate
6300
  int error=
6301
    write_row(rli,        /* if 1 then overwrite */
6302
              bit_is_set(slave_exec_mode, SLAVE_EXEC_MODE_IDEMPOTENT) == 1);
6303
    
6304
  if (error && !thd->is_error())
6305
  {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6306
    assert(0);
1 by brian
clean slate
6307
    my_error(ER_UNKNOWN_ERROR, MYF(0));
6308
  }
6309
  
6310
  return error; 
6311
}
6312
6313
6314
/**************************************************************************
6315
	Delete_rows_log_event member functions
6316
**************************************************************************/
6317
6318
/*
6319
  Compares table->record[0] and table->record[1]
6320
6321
  Returns TRUE if different.
6322
*/
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
6323
static bool record_compare(Table *table)
1 by brian
clean slate
6324
{
6325
  /*
6326
    Need to set the X bit and the filler bits in both records since
6327
    there are engines that do not set it correctly.
6328
6329
    In addition, since MyISAM checks that one hasn't tampered with the
6330
    record, it is necessary to restore the old bytes into the record
6331
    after doing the comparison.
6332
6333
    TODO[record format ndb]: Remove it once NDB returns correct
6334
    records. Check that the other engines also return correct records.
6335
   */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6336
  bool result= false;
481 by Brian Aker
Remove all of uchar.
6337
  unsigned char saved_x[2], saved_filler[2];
1 by brian
clean slate
6338
6339
  if (table->s->null_bytes > 0)
6340
  {
6341
    for (int i = 0 ; i < 2 ; ++i)
6342
    {
6343
      saved_x[i]= table->record[i][0];
6344
      saved_filler[i]= table->record[i][table->s->null_bytes - 1];
6345
      table->record[i][0]|= 1U;
6346
      table->record[i][table->s->null_bytes - 1]|=
6347
        256U - (1U << table->s->last_null_bit_pos);
6348
    }
6349
  }
6350
6351
  if (table->s->blob_fields + table->s->varchar_fields == 0)
6352
  {
6353
    result= cmp_record(table,record[1]);
6354
    goto record_compare_exit;
6355
  }
6356
6357
  /* Compare null bits */
6358
  if (memcmp(table->null_flags,
6359
	     table->null_flags+table->s->rec_buff_length,
6360
	     table->s->null_bytes))
6361
  {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6362
    result= true;				// Diff in NULL value
1 by brian
clean slate
6363
    goto record_compare_exit;
6364
  }
6365
6366
  /* Compare updated fields */
6367
  for (Field **ptr=table->field ; *ptr ; ptr++)
6368
  {
6369
    if ((*ptr)->cmp_binary_offset(table->s->rec_buff_length))
6370
    {
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6371
      result= true;
1 by brian
clean slate
6372
      goto record_compare_exit;
6373
    }
6374
  }
6375
6376
record_compare_exit:
6377
  /*
6378
    Restore the saved bytes.
6379
6380
    TODO[record format ndb]: Remove this code once NDB returns the
6381
    correct record format.
6382
  */
6383
  if (table->s->null_bytes > 0)
6384
  {
6385
    for (int i = 0 ; i < 2 ; ++i)
6386
    {
6387
      table->record[i][0]= saved_x[i];
6388
      table->record[i][table->s->null_bytes - 1]= saved_filler[i];
6389
    }
6390
  }
6391
6392
  return result;
6393
}
6394
6395
/**
6396
  Locate the current row in event's table.
6397
6398
  The current row is pointed by @c m_curr_row. Member @c m_width tells how many 
6399
  columns are there in the row (this can be differnet from the number of columns 
6400
  in the table). It is assumed that event's table is already open and pointed 
6401
  by @c m_table.
6402
6403
  If a corresponding record is found in the table it is stored in 
6404
  @c m_table->record[0]. Note that when record is located based on a primary 
6405
  key, it is possible that the record found differs from the row being located.
6406
6407
  If no key is specified or table does not have keys, a table scan is used to 
6408
  find the row. In that case the row should be complete and contain values for
6409
  all columns. However, it can still be shorter than the table, i.e. the table 
6410
  can contain extra columns not present in the row. It is also possible that 
6411
  the table has fewer columns than the row being located. 
6412
6413
  @returns Error code on failure, 0 on success. 
6414
  
6415
  @post In case of success @c m_table->record[0] contains the record found. 
6416
  Also, the internal "cursor" of the table is positioned at the record found.
6417
6418
  @note If the engine allows random access of the records, a combination of
6419
  @c position() and @c rnd_pos() will be used. 
6420
 */
6421
6422
int Rows_log_event::find_row(const Relay_log_info *rli)
6423
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6424
  assert(m_table && m_table->in_use != NULL);
1 by brian
clean slate
6425
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
6426
  Table *table= m_table;
1 by brian
clean slate
6427
  int error;
6428
6429
  /* unpack row - missing fields get default values */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6430
  prepare_record(table, &m_cols, m_width, false/* don't check errors */); 
1 by brian
clean slate
6431
  error= unpack_current_row(rli, &m_cols);
6432
6433
  // Temporary fix to find out why it fails [/Matz]
6434
  memcpy(m_table->read_set->bitmap, m_cols.bitmap, (m_table->read_set->n_bits + 7) / 8);
6435
6436
  if ((table->file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_POSITION) &&
6437
      table->s->primary_key < MAX_KEY)
6438
  {
6439
    /*
6440
      Use a more efficient method to fetch the record given by
6441
      table->record[0] if the engine allows it.  We first compute a
6442
      row reference using the position() member function (it will be
6443
      stored in table->file->ref) and the use rnd_pos() to position
6444
      the "cursor" (i.e., record[0] in this case) at the correct row.
6445
6446
      TODO: Add a check that the correct record has been fetched by
6447
      comparing with the original record. Take into account that the
6448
      record on the master and slave can be of different
6449
      length. Something along these lines should work:
6450
6451
      ADD>>>  store_record(table,record[1]);
6452
              int error= table->file->rnd_pos(table->record[0], table->file->ref);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6453
      ADD>>>  assert(memcmp(table->record[1], table->record[0],
1 by brian
clean slate
6454
                                 table->s->reclength) == 0);
6455
    */
6456
6457
    int error= table->file->rnd_pos_by_record(table->record[0]);
6458
    table->file->ha_rnd_end();
6459
    if (error)
6460
    {
6461
      table->file->print_error(error, MYF(0));
6462
    }
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6463
    return(error);
1 by brian
clean slate
6464
  }
6465
6466
  // We can't use position() - try other methods.
6467
  
6468
  /*
6469
    Save copy of the record in table->record[1]. It might be needed 
6470
    later if linear search is used to find exact match.
6471
   */ 
6472
  store_record(table,record[1]);    
6473
6474
  if (table->s->keys > 0)
6475
  {
6476
    /* We have a key: search the table using the index */
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6477
    if (!table->file->inited && (error= table->file->ha_index_init(0, false)))
1 by brian
clean slate
6478
    {
6479
      table->file->print_error(error, MYF(0));
6480
      goto err;
6481
    }
6482
6483
    /* Fill key data for the row */
6484
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6485
    assert(m_key);
1 by brian
clean slate
6486
    key_copy(m_key, table->record[0], table->key_info, 0);
6487
6488
    /*
6489
      We need to set the null bytes to ensure that the filler bit are
6490
      all set when returning.  There are storage engines that just set
6491
      the necessary bits on the bytes and don't set the filler bits
6492
      correctly.
6493
    */
6494
    my_ptrdiff_t const pos=
6495
      table->s->null_bytes > 0 ? table->s->null_bytes - 1 : 0;
6496
    table->record[0][pos]= 0xFF;
6497
    
6498
    if ((error= table->file->index_read_map(table->record[0], m_key, 
6499
                                            HA_WHOLE_KEY,
6500
                                            HA_READ_KEY_EXACT)))
6501
    {
6502
      table->file->print_error(error, MYF(0));
6503
      table->file->ha_index_end();
6504
      goto err;
6505
    }
6506
6507
    /*
6508
      Below is a minor "optimization".  If the key (i.e., key number
6509
      0) has the HA_NOSAME flag set, we know that we have found the
6510
      correct record (since there can be no duplicates); otherwise, we
6511
      have to compare the record with the one found to see if it is
6512
      the correct one.
6513
6514
      CAVEAT! This behaviour is essential for the replication of,
6515
      e.g., the mysql.proc table since the correct record *shall* be
6516
      found using the primary key *only*.  There shall be no
6517
      comparison of non-PK columns to decide if the correct record is
6518
      found.  I can see no scenario where it would be incorrect to
6519
      chose the row to change only using a PK or an UNNI.
6520
    */
6521
    if (table->key_info->flags & HA_NOSAME)
6522
    {
6523
      table->file->ha_index_end();
6524
      goto ok;
6525
    }
6526
6527
    /*
6528
      In case key is not unique, we still have to iterate over records found
6529
      and find the one which is identical to the row given. A copy of the 
6530
      record we are looking for is stored in record[1].
6531
     */ 
6532
    while (record_compare(table))
6533
    {
6534
      /*
6535
        We need to set the null bytes to ensure that the filler bit
6536
        are all set when returning.  There are storage engines that
6537
        just set the necessary bits on the bytes and don't set the
6538
        filler bits correctly.
6539
6540
        TODO[record format ndb]: Remove this code once NDB returns the
6541
        correct record format.
6542
      */
6543
      if (table->s->null_bytes > 0)
6544
      {
6545
        table->record[0][table->s->null_bytes - 1]|=
6546
          256U - (1U << table->s->last_null_bit_pos);
6547
      }
6548
6549
      if ((error= table->file->index_next(table->record[0])))
6550
      {
6551
        table->file->print_error(error, MYF(0));
6552
        table->file->ha_index_end();
6553
        goto err;
6554
      }
6555
    }
6556
6557
    /*
6558
      Have to restart the scan to be able to fetch the next row.
6559
    */
6560
    table->file->ha_index_end();
6561
  }
6562
  else
6563
  {
6564
    int restart_count= 0; // Number of times scanning has restarted from top
6565
6566
    /* We don't have a key: search the table using rnd_next() */
6567
    if ((error= table->file->ha_rnd_init(1)))
6568
    {
6569
      table->file->print_error(error, MYF(0));
6570
      goto err;
6571
    }
6572
6573
    /* Continue until we find the right record or have made a full loop */
6574
    do
6575
    {
6576
      error= table->file->rnd_next(table->record[0]);
6577
6578
      switch (error) {
6579
6580
      case 0:
6581
      case HA_ERR_RECORD_DELETED:
6582
        break;
6583
6584
      case HA_ERR_END_OF_FILE:
6585
        if (++restart_count < 2)
6586
          table->file->ha_rnd_init(1);
6587
        break;
6588
6589
      default:
6590
        table->file->print_error(error, MYF(0));
6591
        table->file->ha_rnd_end();
6592
        goto err;
6593
      }
6594
    }
6595
    while (restart_count < 2 && record_compare(table));
6596
    
6597
    /* 
6598
      Note: above record_compare will take into accout all record fields 
6599
      which might be incorrect in case a partial row was given in the event
6600
     */
6601
    table->file->ha_rnd_end();
6602
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6603
    assert(error == HA_ERR_END_OF_FILE || error == HA_ERR_RECORD_DELETED || error == 0);
1 by brian
clean slate
6604
    goto err;
6605
  }
6606
ok:
6607
  table->default_column_bitmaps();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6608
  return(0);
1 by brian
clean slate
6609
err:
6610
  table->default_column_bitmaps();
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6611
  return(error);
1 by brian
clean slate
6612
}
6613
6614
6615
/*
6616
  Constructor used to build an event for writing to the binary log.
6617
 */
6618
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
6619
Delete_rows_log_event::Delete_rows_log_event(THD *thd_arg, Table *tbl_arg,
1 by brian
clean slate
6620
                                             ulong tid,
6621
                                             bool is_transactional)
6622
  : Rows_log_event(thd_arg, tbl_arg, tid, tbl_arg->read_set, is_transactional)
6623
{
6624
}
6625
6626
/*
6627
  Constructor used by slave to read the event from the binary log.
6628
 */
482 by Brian Aker
Remove uint.
6629
Delete_rows_log_event::Delete_rows_log_event(const char *buf, uint32_t event_len,
1 by brian
clean slate
6630
                                             const Format_description_log_event
6631
                                             *description_event)
6632
  : Rows_log_event(buf, event_len, DELETE_ROWS_EVENT, description_event)
6633
{
6634
}
6635
6636
6637
int 
6638
Delete_rows_log_event::do_before_row_operations(const Slave_reporting_capability *const)
6639
{
6640
  if ((m_table->file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_POSITION) &&
6641
      m_table->s->primary_key < MAX_KEY)
6642
  {
6643
    /*
6644
      We don't need to allocate any memory for m_key since it is not used.
6645
    */
6646
    return 0;
6647
  }
6648
6649
  if (m_table->s->keys > 0)
6650
  {
6651
    // Allocate buffer for key searches
481 by Brian Aker
Remove all of uchar.
6652
    m_key= (unsigned char*)my_malloc(m_table->key_info->key_length, MYF(MY_WME));
1 by brian
clean slate
6653
    if (!m_key)
6654
      return HA_ERR_OUT_OF_MEM;
6655
  }
6656
6657
  return 0;
6658
}
6659
6660
int 
6661
Delete_rows_log_event::do_after_row_operations(const Slave_reporting_capability *const, 
6662
                                               int error)
6663
{
6664
  /*error= ToDo:find out what this should really be, this triggers close_scan in nbd, returning error?*/
6665
  m_table->file->ha_index_or_rnd_end();
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
6666
  free(m_key);
1 by brian
clean slate
6667
  m_key= NULL;
6668
6669
  return error;
6670
}
6671
6672
int Delete_rows_log_event::do_exec_row(const Relay_log_info *const rli)
6673
{
6674
  int error;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6675
  assert(m_table != NULL);
1 by brian
clean slate
6676
6677
  if (!(error= find_row(rli))) 
6678
  { 
6679
    /*
6680
      Delete the record found, located in record[0]
6681
    */
6682
    error= m_table->file->ha_delete_row(m_table->record[0]);
6683
  }
6684
  return error;
6685
}
6686
6687
6688
/**************************************************************************
6689
	Update_rows_log_event member functions
6690
**************************************************************************/
6691
6692
/*
6693
  Constructor used to build an event for writing to the binary log.
6694
 */
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
6695
Update_rows_log_event::Update_rows_log_event(THD *thd_arg, Table *tbl_arg,
1 by brian
clean slate
6696
                                             ulong tid,
6697
                                             bool is_transactional)
6698
: Rows_log_event(thd_arg, tbl_arg, tid, tbl_arg->read_set, is_transactional)
6699
{
6700
  init(tbl_arg->write_set);
6701
}
6702
6703
void Update_rows_log_event::init(MY_BITMAP const *cols)
6704
{
6705
  /* if bitmap_init fails, caught in is_valid() */
6706
  if (likely(!bitmap_init(&m_cols_ai,
6707
                          m_width <= sizeof(m_bitbuf_ai)*8 ? m_bitbuf_ai : NULL,
6708
                          m_width,
6709
                          false)))
6710
  {
6711
    /* Cols can be zero if this is a dummy binrows event */
6712
    if (likely(cols != NULL))
6713
    {
6714
      memcpy(m_cols_ai.bitmap, cols->bitmap, no_bytes_in_map(cols));
6715
      create_last_word_mask(&m_cols_ai);
6716
    }
6717
  }
6718
}
6719
6720
6721
Update_rows_log_event::~Update_rows_log_event()
6722
{
6723
  if (m_cols_ai.bitmap == m_bitbuf_ai) // no my_malloc happened
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
6724
    m_cols_ai.bitmap= 0; // so no free in bitmap_free
1 by brian
clean slate
6725
  bitmap_free(&m_cols_ai); // To pair with bitmap_init().
6726
}
6727
6728
6729
/*
6730
  Constructor used by slave to read the event from the binary log.
6731
 */
482 by Brian Aker
Remove uint.
6732
Update_rows_log_event::Update_rows_log_event(const char *buf, uint32_t event_len,
1 by brian
clean slate
6733
                                             const
6734
                                             Format_description_log_event
6735
                                             *description_event)
6736
  : Rows_log_event(buf, event_len, UPDATE_ROWS_EVENT, description_event)
6737
{
6738
}
6739
6740
6741
int 
6742
Update_rows_log_event::do_before_row_operations(const Slave_reporting_capability *const)
6743
{
6744
  if (m_table->s->keys > 0)
6745
  {
6746
    // Allocate buffer for key searches
481 by Brian Aker
Remove all of uchar.
6747
    m_key= (unsigned char*)my_malloc(m_table->key_info->key_length, MYF(MY_WME));
1 by brian
clean slate
6748
    if (!m_key)
6749
      return HA_ERR_OUT_OF_MEM;
6750
  }
6751
6752
  m_table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
6753
6754
  return 0;
6755
}
6756
6757
int 
6758
Update_rows_log_event::do_after_row_operations(const Slave_reporting_capability *const, 
6759
                                               int error)
6760
{
6761
  /*error= ToDo:find out what this should really be, this triggers close_scan in nbd, returning error?*/
6762
  m_table->file->ha_index_or_rnd_end();
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
6763
  free(m_key); // Free for multi_malloc
1 by brian
clean slate
6764
  m_key= NULL;
6765
6766
  return error;
6767
}
6768
6769
int 
6770
Update_rows_log_event::do_exec_row(const Relay_log_info *const rli)
6771
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6772
  assert(m_table != NULL);
1 by brian
clean slate
6773
6774
  int error= find_row(rli); 
6775
  if (error)
6776
  {
6777
    /*
6778
      We need to read the second image in the event of error to be
6779
      able to skip to the next pair of updates
6780
    */
6781
    m_curr_row= m_curr_row_end;
6782
    unpack_current_row(rli, &m_cols_ai);
6783
    return error;
6784
  }
6785
6786
  /*
6787
    This is the situation after locating BI:
6788
6789
    ===|=== before image ====|=== after image ===|===
6790
       ^                     ^
6791
       m_curr_row            m_curr_row_end
6792
6793
    BI found in the table is stored in record[0]. We copy it to record[1]
6794
    and unpack AI to record[0].
6795
   */
6796
6797
  store_record(m_table,record[1]);
6798
6799
  m_curr_row= m_curr_row_end;
6800
  error= unpack_current_row(rli, &m_cols_ai); // this also updates m_curr_row_end
6801
6802
  /*
6803
    Now we have the right row to update.  The old row (the one we're
6804
    looking for) is in record[1] and the new row is in record[0].
6805
  */
6806
6807
  // Temporary fix to find out why it fails [/Matz]
6808
  memcpy(m_table->read_set->bitmap, m_cols.bitmap, (m_table->read_set->n_bits + 7) / 8);
6809
  memcpy(m_table->write_set->bitmap, m_cols_ai.bitmap, (m_table->write_set->n_bits + 7) / 8);
6810
6811
  error= m_table->file->ha_update_row(m_table->record[1], m_table->record[0]);
6812
  if (error == HA_ERR_RECORD_IS_THE_SAME)
6813
    error= 0;
6814
6815
  return error;
6816
}
6817
6818
482 by Brian Aker
Remove uint.
6819
Incident_log_event::Incident_log_event(const char *buf, uint32_t event_len,
1 by brian
clean slate
6820
                                       const Format_description_log_event *descr_event)
6821
  : Log_event(buf, descr_event)
6822
{
206 by Brian Aker
Removed final uint dead types.
6823
  uint8_t const common_header_len=
1 by brian
clean slate
6824
    descr_event->common_header_len;
206 by Brian Aker
Removed final uint dead types.
6825
  uint8_t const post_header_len=
1 by brian
clean slate
6826
    descr_event->post_header_len[INCIDENT_EVENT-1];
6827
6828
  m_incident= static_cast<Incident>(uint2korr(buf + common_header_len));
6829
  char const *ptr= buf + common_header_len + post_header_len;
6830
  char const *const str_end= buf + event_len;
206 by Brian Aker
Removed final uint dead types.
6831
  uint8_t len= 0;                   // Assignment to keep compiler happy
1 by brian
clean slate
6832
  const char *str= NULL;          // Assignment to keep compiler happy
6833
  read_str(&ptr, str_end, &str, &len);
6834
  m_message.str= const_cast<char*>(str);
6835
  m_message.length= len;
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6836
  return;
1 by brian
clean slate
6837
}
6838
6839
6840
Incident_log_event::~Incident_log_event()
6841
{
6842
}
6843
6844
6845
const char *
6846
Incident_log_event::description() const
6847
{
6848
  static const char *const description[]= {
6849
    "NOTHING",                                  // Not used
6850
    "LOST_EVENTS"
6851
  };
6852
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6853
  assert(0 <= m_incident);
6854
  assert((size_t) m_incident <= sizeof(description)/sizeof(*description));
1 by brian
clean slate
6855
6856
  return description[m_incident];
6857
}
6858
6859
6860
void Incident_log_event::pack_info(Protocol *protocol)
6861
{
6862
  char buf[256];
6863
  size_t bytes;
6864
  if (m_message.length > 0)
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
6865
    bytes= snprintf(buf, sizeof(buf), "#%d (%s)",
6866
                    m_incident, description());
1 by brian
clean slate
6867
  else
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
6868
    bytes= snprintf(buf, sizeof(buf), "#%d (%s): %s",
6869
                    m_incident, description(), m_message.str);
1 by brian
clean slate
6870
  protocol->store(buf, bytes, &my_charset_bin);
6871
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
6872
6873
1 by brian
clean slate
6874
int
6875
Incident_log_event::do_apply_event(Relay_log_info const *rli)
6876
{
6877
  rli->report(ERROR_LEVEL, ER_SLAVE_INCIDENT,
6878
              ER(ER_SLAVE_INCIDENT),
6879
              description(),
6880
              m_message.length > 0 ? m_message.str : "<none>");
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6881
  return(1);
1 by brian
clean slate
6882
}
438.1.11 by Brian Aker
Removed dead HAVE_REPL needs for embedded server.
6883
1 by brian
clean slate
6884
6885
bool
6886
Incident_log_event::write_data_header(IO_CACHE *file)
6887
{
481 by Brian Aker
Remove all of uchar.
6888
  unsigned char buf[sizeof(int16_t)];
206 by Brian Aker
Removed final uint dead types.
6889
  int2store(buf, (int16_t) m_incident);
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6890
  return(my_b_safe_write(file, buf, sizeof(buf)));
1 by brian
clean slate
6891
}
6892
6893
bool
6894
Incident_log_event::write_data_body(IO_CACHE *file)
6895
{
51.1.31 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
6896
  return(write_str(file, m_message.str, m_message.length));
1 by brian
clean slate
6897
}
6898
482 by Brian Aker
Remove uint.
6899
Heartbeat_log_event::Heartbeat_log_event(const char* buf, uint32_t event_len,
1 by brian
clean slate
6900
                    const Format_description_log_event* description_event)
6901
  :Log_event(buf, description_event)
6902
{
206 by Brian Aker
Removed final uint dead types.
6903
  uint8_t header_size= description_event->common_header_len;
1 by brian
clean slate
6904
  ident_len = event_len - header_size;
6905
  set_if_smaller(ident_len,FN_REFLEN-1);
6906
  log_ident= buf + header_size;
6907
}