~drizzle-trunk/drizzle/development

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Copyright (C) 2008-2009 Sun Microsystems
 *
 *  Authors:
 *
 *    Jay Pipes <joinfu@sun.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

/**
 * @file Server-side utility which is responsible for managing the 
 * communication between the kernel, replicator plugins, and applier plugins.
 *
 * ReplicationServices is a bridge between modules and the kernel, and its
 * primary function is to take internal events (for instance the start of a 
 * transaction, the changing of a record, or the rollback of a transaction) 
 * and construct GPB Messages that are passed to the registered replicator and
 * applier plugins.
 *
 * The reason for this functionality is to encapsulate all communication
 * between the kernel and the replicator/applier plugins into GPB Messages.
 * Instead of the plugin having to understand the (often fluidly changing)
 * mechanics of the kernel, all the plugin needs to understand is the message
 * format, and GPB messages provide a nice, clear, and versioned format for 
 * these messages.
 *
 * @see /drizzled/message/transaction.proto
 *
 * @todo
 *
 * We really should store the raw bytes in the messages, not the
 * String value of the Field.  But, to do that, the
 * statement_transform library needs first to be updated
 * to include the transformation code to convert raw
 * Drizzle-internal Field byte representation into something
 * plugins can understand.
 */

#include "config.h"
#include "drizzled/replication_services.h"
#include "drizzled/plugin/transaction_replicator.h"
#include "drizzled/plugin/transaction_applier.h"
#include "drizzled/message/transaction.pb.h"
#include "drizzled/message/table.pb.h"
#include "drizzled/gettext.h"
#include "drizzled/session.h"
#include "drizzled/error.h"

#include <vector>

using namespace std;

namespace drizzled
{

static message::Table::Field::FieldType internalFieldTypeToFieldProtoType(enum enum_field_types in_type);

ReplicationServices::ReplicationServices()
{
  is_active= false;
}

void ReplicationServices::evaluateActivePlugins()
{
  /* 
   * We loop through replicators and appliers, evaluating
   * whether or not there is at least one active replicator
   * and one active applier.  If not, we set is_active
   * to false.
   */
  bool tmp_is_active= false;

  if (replicators.empty() || appliers.empty())
  {
    is_active= false;
    return;
  }

  /* 
   * Determine if any remaining replicators and if those
   * replicators are active...if not, set is_active
   * to false
   */
  for (Replicators::iterator repl_iter= replicators.begin();
       repl_iter != replicators.end();
       ++repl_iter)
  {
    if ((*repl_iter)->isEnabled())
    {
      tmp_is_active= true;
      break;
    }
  }
  if (! tmp_is_active)
  {
    /* No active replicators. Set is_active to false and exit. */
    is_active= false;
    return;
  }

  /* 
   * OK, we know there's at least one active replicator.
   *
   * Now determine if any remaining replicators and if those
   * replicators are active...if not, set is_active
   * to false
   */
  for (Appliers::iterator appl_iter= appliers.begin();
       appl_iter != appliers.end();
       ++appl_iter)
  {
    if ((*appl_iter)->isEnabled())
    {
      is_active= true;
      return;
    }
  }
  /* If we get here, there are no active appliers */
  is_active= false;
}

void ReplicationServices::attachReplicator(plugin::TransactionReplicator *in_replicator)
{
  replicators.push_back(in_replicator);
  evaluateActivePlugins();
}

void ReplicationServices::detachReplicator(plugin::TransactionReplicator *in_replicator)
{
  replicators.erase(std::find(replicators.begin(), replicators.end(), in_replicator));
  evaluateActivePlugins();
}

void ReplicationServices::attachApplier(plugin::TransactionApplier *in_applier)
{
  appliers.push_back(in_applier);
  evaluateActivePlugins();
}

void ReplicationServices::detachApplier(plugin::TransactionApplier *in_applier)
{
  appliers.erase(std::find(appliers.begin(), appliers.end(), in_applier));
  evaluateActivePlugins();
}

bool ReplicationServices::isActive() const
{
  return is_active;
}

message::Transaction *ReplicationServices::getActiveTransaction(Session *in_session) const
{
  message::Transaction *transaction= in_session->getTransactionMessage();

  if (unlikely(transaction == NULL))
  {
    /* 
     * Allocate and initialize a new transaction message 
     * for this Session object.  Session is responsible for
     * deleting transaction message when done with it.
     */
    transaction= new (nothrow) message::Transaction();
    initTransaction(*transaction, in_session);
    in_session->setTransactionMessage(transaction);
    return transaction;
  }
  else
    return transaction;
}

void ReplicationServices::initTransaction(message::Transaction &in_transaction,
                                          Session *in_session) const
{
  message::TransactionContext *trx= in_transaction.mutable_transaction_context();
  trx->set_server_id(in_session->getServerId());
  trx->set_transaction_id(in_session->getTransactionId());
  trx->set_start_timestamp(in_session->getCurrentTimestamp());
}

void ReplicationServices::finalizeTransaction(message::Transaction &in_transaction,
                                              Session *in_session) const
{
  message::TransactionContext *trx= in_transaction.mutable_transaction_context();
  trx->set_end_timestamp(in_session->getCurrentTimestamp());
}

void ReplicationServices::cleanupTransaction(message::Transaction *in_transaction,
                                             Session *in_session) const
{
  delete in_transaction;
  in_session->setStatementMessage(NULL);
  in_session->setTransactionMessage(NULL);
}

bool ReplicationServices::transactionContainsBulkSegment(const message::Transaction &transaction) const
{
  size_t num_statements= transaction.statement_size();
  if (num_statements == 0)
    return false;

  /*
   * Only INSERT, UPDATE, and DELETE statements can possibly
   * have bulk segments.  So, we loop through the statements
   * checking for segment_id > 1 in those specific submessages.
   */
  size_t x;
  for (x= 0; x < num_statements; ++x)
  {
    const message::Statement &statement= transaction.statement(x);
    message::Statement::Type type= statement.type();

    switch (type)
    {
      case message::Statement::INSERT:
        if (statement.insert_data().segment_id() > 1)
          return true;
        break;
      case message::Statement::UPDATE:
        if (statement.update_data().segment_id() > 1)
          return true;
        break;
      case message::Statement::DELETE:
        if (statement.delete_data().segment_id() > 1)
          return true;
        break;
      default:
        break;
    }
  }
  return false;
}
void ReplicationServices::commitTransaction(Session *in_session)
{
  if (! is_active)
    return;

  /* If there is an active statement message, finalize it */
  message::Statement *statement= in_session->getStatementMessage();

  if (statement != NULL)
  {
    finalizeStatement(*statement, in_session);
  }
  else
    return; /* No data modification occurred inside the transaction */
  
  message::Transaction* transaction= getActiveTransaction(in_session);

  finalizeTransaction(*transaction, in_session);
  
  push(*transaction);

  cleanupTransaction(transaction, in_session);
}

void ReplicationServices::initStatement(message::Statement &statement,
                                        message::Statement::Type in_type,
                                        Session *in_session) const
{
  statement.set_type(in_type);
  statement.set_start_timestamp(in_session->getCurrentTimestamp());
  /** @TODO Set sql string optionally */
}

void ReplicationServices::finalizeStatement(message::Statement &statement,
                                            Session *in_session) const
{
  statement.set_end_timestamp(in_session->getCurrentTimestamp());
  in_session->setStatementMessage(NULL);
}

void ReplicationServices::rollbackTransaction(Session *in_session)
{
  if (! is_active)
    return;
  
  message::Transaction *transaction= getActiveTransaction(in_session);

  /*
   * OK, so there are two situations that we need to deal with here:
   *
   * 1) We receive an instruction to ROLLBACK the current transaction
   *    and the currently-stored Transaction message is *self-contained*, 
   *    meaning that no Statement messages in the Transaction message
   *    contain a message having its segment_id member greater than 1.  If
   *    no non-segment ID 1 members are found, we can simply clear the
   *    current Transaction message and remove it from memory.
   *
   * 2) If the Transaction message does indeed have a non-end segment, that
   *    means that a bulk update/delete/insert Transaction message segment
   *    has previously been sent over the wire to replicators.  In this case, 
   *    we need to package a Transaction with a Statement message of type
   *    ROLLBACK to indicate to replicators that previously-transmitted
   *    messages must be un-applied.
   */
  if (unlikely(transactionContainsBulkSegment(*transaction)))
  {
    /*
     * Clear the transaction, create a Rollback statement message, 
     * attach it to the transaction, and push it to replicators.
     */
    transaction->Clear();
    initTransaction(*transaction, in_session);

    message::Statement *statement= transaction->add_statement();

    initStatement(*statement, message::Statement::ROLLBACK, in_session);
    finalizeStatement(*statement, in_session);

    finalizeTransaction(*transaction, in_session);
    
    push(*transaction);
  }
  cleanupTransaction(transaction, in_session);
}

message::Statement &ReplicationServices::getInsertStatement(Session *in_session,
                                                                 Table *in_table) const
{
  message::Statement *statement= in_session->getStatementMessage();
  /*
   * We check to see if the current Statement message is of type INSERT.
   * If it is not, we finalize the current Statement and ensure a new
   * InsertStatement is created.
   */
  if (statement != NULL &&
      statement->type() != message::Statement::INSERT)
  {
    finalizeStatement(*statement, in_session);
    statement= in_session->getStatementMessage();
  }

  if (statement == NULL)
  {
    message::Transaction *transaction= getActiveTransaction(in_session);
    /* 
     * Transaction message initialized and set, but no statement created
     * yet.  We construct one and initialize it, here, then return the
     * message after attaching the new Statement message pointer to the 
     * Session for easy retrieval later...
     */
    statement= transaction->add_statement();
    setInsertHeader(*statement, in_session, in_table);
    in_session->setStatementMessage(statement);
  }
  return *statement;
}

void ReplicationServices::setInsertHeader(message::Statement &statement,
                                          Session *in_session,
                                          Table *in_table) const
{
  initStatement(statement, message::Statement::INSERT, in_session);

  /* 
   * Now we construct the specialized InsertHeader message inside
   * the generalized message::Statement container...
   */
  /* Set up the insert header */
  message::InsertHeader *header= statement.mutable_insert_header();
  message::TableMetadata *table_metadata= header->mutable_table_metadata();

  const char *schema_name= in_table->getShare()->db.str;
  const char *table_name= in_table->getShare()->table_name.str;

  table_metadata->set_schema_name(schema_name);
  table_metadata->set_table_name(table_name);

  Field *current_field;
  Field **table_fields= in_table->field;

  message::FieldMetadata *field_metadata;

  /* We will read all the table's fields... */
  in_table->setReadSet();

  while ((current_field= *table_fields++) != NULL) 
  {
    field_metadata= header->add_field_metadata();
    field_metadata->set_name(current_field->field_name);
    field_metadata->set_type(internalFieldTypeToFieldProtoType(current_field->type()));
  }
}

bool ReplicationServices::insertRecord(Session *in_session, Table *in_table)
{
  if (! is_active)
    return false;
  /**
   * We do this check here because we don't want to even create a 
   * statement if there isn't a primary key on the table...
   *
   * @todo
   *
   * Multi-column primary keys are handled how exactly?
   */
  if (in_table->s->primary_key == MAX_KEY)
  {
    my_error(ER_NO_PRIMARY_KEY_ON_REPLICATED_TABLE, MYF(0));
    return true;
  }

  message::Statement &statement= getInsertStatement(in_session, in_table);

  message::InsertData *data= statement.mutable_insert_data();
  data->set_segment_id(1);
  data->set_end_segment(true);
  message::InsertRecord *record= data->add_record();

  Field *current_field;
  Field **table_fields= in_table->field;

  String *string_value= new (in_session->mem_root) String(ReplicationServices::DEFAULT_RECORD_SIZE);
  string_value->set_charset(system_charset_info);

  /* We will read all the table's fields... */
  in_table->setReadSet();

  while ((current_field= *table_fields++) != NULL) 
  {
    string_value= current_field->val_str(string_value);
    record->add_insert_value(string_value->c_ptr(), string_value->length());
    string_value->free();
  }
  return false;
}

message::Statement &ReplicationServices::getUpdateStatement(Session *in_session,
                                                            Table *in_table,
                                                            const unsigned char *old_record, 
                                                            const unsigned char *new_record) const
{
  message::Statement *statement= in_session->getStatementMessage();
  /*
   * We check to see if the current Statement message is of type UPDATE.
   * If it is not, we finalize the current Statement and ensure a new
   * UpdateStatement is created.
   */
  if (statement != NULL &&
      statement->type() != message::Statement::UPDATE)
  {
    finalizeStatement(*statement, in_session);
    statement= in_session->getStatementMessage();
  }

  if (statement == NULL)
  {
    message::Transaction *transaction= getActiveTransaction(in_session);
    /* 
     * Transaction message initialized and set, but no statement created
     * yet.  We construct one and initialize it, here, then return the
     * message after attaching the new Statement message pointer to the 
     * Session for easy retrieval later...
     */
    statement= transaction->add_statement();
    setUpdateHeader(*statement, in_session, in_table, old_record, new_record);
    in_session->setStatementMessage(statement);
  }
  return *statement;
}

void ReplicationServices::setUpdateHeader(message::Statement &statement,
                                          Session *in_session,
                                          Table *in_table,
                                          const unsigned char *old_record, 
                                          const unsigned char *new_record) const
{
  initStatement(statement, message::Statement::UPDATE, in_session);

  /* 
   * Now we construct the specialized UpdateHeader message inside
   * the generalized message::Statement container...
   */
  /* Set up the update header */
  message::UpdateHeader *header= statement.mutable_update_header();
  message::TableMetadata *table_metadata= header->mutable_table_metadata();

  const char *schema_name= in_table->getShare()->db.str;
  const char *table_name= in_table->getShare()->table_name.str;

  table_metadata->set_schema_name(schema_name);
  table_metadata->set_table_name(table_name);

  Field *current_field;
  Field **table_fields= in_table->field;

  message::FieldMetadata *field_metadata;

  /* We will read all the table's fields... */
  in_table->setReadSet();

  while ((current_field= *table_fields++) != NULL) 
  {
    /*
     * We add the "key field metadata" -- i.e. the fields which is
     * the primary key for the table.
     */
    if (in_table->s->primary_key == current_field->field_index)
    {
      field_metadata= header->add_key_field_metadata();
      field_metadata->set_name(current_field->field_name);
      field_metadata->set_type(internalFieldTypeToFieldProtoType(current_field->type()));
    }

    /*
     * The below really should be moved into the Field API and Record API.  But for now
     * we do this crazy pointer fiddling to figure out if the current field
     * has been updated in the supplied record raw byte pointers.
     */
    const unsigned char *old_ptr= (const unsigned char *) old_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]); 
    const unsigned char *new_ptr= (const unsigned char *) new_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]); 

    uint32_t field_length= current_field->pack_length(); /** @TODO This isn't always correct...check varchar diffs. */

    if (memcmp(old_ptr, new_ptr, field_length) != 0)
    {
      /* Field is changed from old to new */
      field_metadata= header->add_set_field_metadata();
      field_metadata->set_name(current_field->field_name);
      field_metadata->set_type(internalFieldTypeToFieldProtoType(current_field->type()));
    }
  }
}
void ReplicationServices::updateRecord(Session *in_session,
                                       Table *in_table, 
                                       const unsigned char *old_record, 
                                       const unsigned char *new_record)
{
  if (! is_active)
    return;

  message::Statement &statement= getUpdateStatement(in_session, in_table, old_record, new_record);

  message::UpdateData *data= statement.mutable_update_data();
  data->set_segment_id(1);
  data->set_end_segment(true);
  message::UpdateRecord *record= data->add_record();

  Field *current_field;
  Field **table_fields= in_table->field;
  String *string_value= new (in_session->mem_root) String(ReplicationServices::DEFAULT_RECORD_SIZE);
  string_value->set_charset(system_charset_info);

  while ((current_field= *table_fields++) != NULL) 
  {
    /*
     * Here, we add the SET field values.  We used to do this in the setUpdateHeader() method, 
     * but then realized that an UPDATE statement could potentially have different values for
     * the SET field.  For instance, imagine this SQL scenario:
     *
     * CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY, count INT NOT NULL);
     * INSERT INTO t1 (id, counter) VALUES (1,1),(2,2),(3,3);
     * UPDATE t1 SET counter = counter + 1 WHERE id IN (1,2);
     *
     * We will generate two UpdateRecord messages with different set_value byte arrays.
     *
     * The below really should be moved into the Field API and Record API.  But for now
     * we do this crazy pointer fiddling to figure out if the current field
     * has been updated in the supplied record raw byte pointers.
     */
    const unsigned char *old_ptr= (const unsigned char *) old_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]); 
    const unsigned char *new_ptr= (const unsigned char *) new_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]); 

    uint32_t field_length= current_field->pack_length(); /** @TODO This isn't always correct...check varchar diffs. */

    if (memcmp(old_ptr, new_ptr, field_length) != 0)
    {
      /* Store the original "read bit" for this field */
      bool is_read_set= current_field->isReadSet();

      /* We need to mark that we will "read" this field... */
      in_table->setReadSet(current_field->field_index);

      /* Read the string value of this field's contents */
      string_value= current_field->val_str(string_value);

      /* 
       * Reset the read bit after reading field to its original state.  This 
       * prevents the field from being included in the WHERE clause
       */
      current_field->setReadSet(is_read_set);

      record->add_after_value(string_value->c_ptr(), string_value->length());
      string_value->free();
    }

    /* 
     * Add the WHERE clause values now...for now, this means the
     * primary key field value.  Replication only supports tables
     * with a primary key.
     */
    if (in_table->s->primary_key == current_field->field_index)
    {
      /**
       * To say the below is ugly is an understatement. But it works.
       * 
       * @todo Move this crap into a real Record API.
       */
      string_value= current_field->val_str(string_value,
                                           old_record + 
                                           current_field->offset(const_cast<unsigned char *>(new_record)));
      record->add_key_value(string_value->c_ptr(), string_value->length());
      string_value->free();
    }

  }
}

message::Statement &ReplicationServices::getDeleteStatement(Session *in_session,
                                                            Table *in_table) const
{
  message::Statement *statement= in_session->getStatementMessage();
  /*
   * We check to see if the current Statement message is of type DELETE.
   * If it is not, we finalize the current Statement and ensure a new
   * DeleteStatement is created.
   */
  if (statement != NULL &&
      statement->type() != message::Statement::DELETE)
  {
    finalizeStatement(*statement, in_session);
    statement= in_session->getStatementMessage();
  }

  if (statement == NULL)
  {
    message::Transaction *transaction= getActiveTransaction(in_session);
    /* 
     * Transaction message initialized and set, but no statement created
     * yet.  We construct one and initialize it, here, then return the
     * message after attaching the new Statement message pointer to the 
     * Session for easy retrieval later...
     */
    statement= transaction->add_statement();
    setDeleteHeader(*statement, in_session, in_table);
    in_session->setStatementMessage(statement);
  }
  return *statement;
}

void ReplicationServices::setDeleteHeader(message::Statement &statement,
                                          Session *in_session,
                                          Table *in_table) const
{
  initStatement(statement, message::Statement::DELETE, in_session);

  /* 
   * Now we construct the specialized DeleteHeader message inside
   * the generalized message::Statement container...
   */
  message::DeleteHeader *header= statement.mutable_delete_header();
  message::TableMetadata *table_metadata= header->mutable_table_metadata();

  const char *schema_name= in_table->getShare()->db.str;
  const char *table_name= in_table->getShare()->table_name.str;

  table_metadata->set_schema_name(schema_name);
  table_metadata->set_table_name(table_name);

  Field *current_field;
  Field **table_fields= in_table->field;

  message::FieldMetadata *field_metadata;

  while ((current_field= *table_fields++) != NULL) 
  {
    /* 
     * Add the WHERE clause values now...for now, this means the
     * primary key field value.  Replication only supports tables
     * with a primary key.
     */
    if (in_table->s->primary_key == current_field->field_index)
    {
      field_metadata= header->add_key_field_metadata();
      field_metadata->set_name(current_field->field_name);
      field_metadata->set_type(internalFieldTypeToFieldProtoType(current_field->type()));
    }
  }
}

void ReplicationServices::deleteRecord(Session *in_session, Table *in_table)
{
  if (! is_active)
    return;

  message::Statement &statement= getDeleteStatement(in_session, in_table);

  message::DeleteData *data= statement.mutable_delete_data();
  data->set_segment_id(1);
  data->set_end_segment(true);
  message::DeleteRecord *record= data->add_record();

  Field *current_field;
  Field **table_fields= in_table->field;
  String *string_value= new (in_session->mem_root) String(ReplicationServices::DEFAULT_RECORD_SIZE);
  string_value->set_charset(system_charset_info);

  while ((current_field= *table_fields++) != NULL) 
  {
    /* 
     * Add the WHERE clause values now...for now, this means the
     * primary key field value.  Replication only supports tables
     * with a primary key.
     */
    if (in_table->s->primary_key == current_field->field_index)
    {
      string_value= current_field->val_str(string_value);
      record->add_key_value(string_value->c_ptr(), string_value->length());
      /**
       * @TODO Store optional old record value in the before data member
       */
      string_value->free();
    }
  }
}

void ReplicationServices::truncateTable(Session *in_session, Table *in_table)
{
  if (! is_active)
    return;
  
  message::Transaction *transaction= getActiveTransaction(in_session);
  message::Statement *statement= transaction->add_statement();

  initStatement(*statement, message::Statement::TRUNCATE_TABLE, in_session);

  /* 
   * Construct the specialized TruncateTableStatement message and attach
   * it to the generic Statement message
   */
  message::TruncateTableStatement *truncate_statement= statement->mutable_truncate_table_statement();
  message::TableMetadata *table_metadata= truncate_statement->mutable_table_metadata();

  const char *schema_name= in_table->getShare()->db.str;
  const char *table_name= in_table->getShare()->table_name.str;

  table_metadata->set_schema_name(schema_name);
  table_metadata->set_table_name(table_name);

  finalizeStatement(*statement, in_session);

  finalizeTransaction(*transaction, in_session);
  
  push(*transaction);

  cleanupTransaction(transaction, in_session);
}

void ReplicationServices::rawStatement(Session *in_session, const char *in_query, size_t in_query_len)
{
  if (! is_active)
    return;
  
  message::Transaction *transaction= getActiveTransaction(in_session);
  message::Statement *statement= transaction->add_statement();

  initStatement(*statement, message::Statement::RAW_SQL, in_session);
  string query(in_query, in_query_len);
  statement->set_sql(query);
  finalizeStatement(*statement, in_session);

  finalizeTransaction(*transaction, in_session);
  
  push(*transaction);

  cleanupTransaction(transaction, in_session);
}

void ReplicationServices::push(drizzled::message::Transaction &to_push)
{
  vector<plugin::TransactionReplicator *>::iterator repl_iter= replicators.begin();
  vector<plugin::TransactionApplier *>::iterator appl_start_iter, appl_iter;
  appl_start_iter= appliers.begin();

  plugin::TransactionReplicator *cur_repl;
  plugin::TransactionApplier *cur_appl;

  while (repl_iter != replicators.end())
  {
    cur_repl= *repl_iter;
    if (! cur_repl->isEnabled())
    {
      ++repl_iter;
      continue;
    }
    
    appl_iter= appl_start_iter;
    while (appl_iter != appliers.end())
    {
      cur_appl= *appl_iter;

      if (! cur_appl->isEnabled())
      {
        ++appl_iter;
        continue;
      }

      cur_repl->replicate(cur_appl, to_push);
      
      /* 
       * We update the timestamp for the last applied Transaction so that
       * publisher plugins can ask the replication services when the
       * last known applied Transaction was using the getLastAppliedTimestamp()
       * method.
       */
      last_applied_timestamp.fetch_and_store(to_push.transaction_context().end_timestamp());
      ++appl_iter;
    }
    ++repl_iter;
  }
}

static message::Table::Field::FieldType internalFieldTypeToFieldProtoType(enum enum_field_types in_type)
{
  switch (in_type)
  {
    case DRIZZLE_TYPE_LONGLONG:
      return message::Table::Field::BIGINT;
    case DRIZZLE_TYPE_LONG:
      return message::Table::Field::INTEGER;
    case DRIZZLE_TYPE_DECIMAL:
      return message::Table::Field::DECIMAL;
    case DRIZZLE_TYPE_DOUBLE:
      return message::Table::Field::DOUBLE;
    case DRIZZLE_TYPE_DATE:
      return message::Table::Field::DATE;
    case DRIZZLE_TYPE_DATETIME:
      return message::Table::Field::DATETIME;
    case DRIZZLE_TYPE_TIMESTAMP:
      return message::Table::Field::TIMESTAMP;
    case DRIZZLE_TYPE_VARCHAR:
      return message::Table::Field::VARCHAR;
    case DRIZZLE_TYPE_BLOB:
      return message::Table::Field::BLOB;
    case DRIZZLE_TYPE_ENUM:
      return message::Table::Field::ENUM;
    default:
      return message::Table::Field::VARCHAR;
  }
}

} /* namespace drizzled */