~drizzle-trunk/drizzle/development

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