drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
transaction_services.cc
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, Inc.
5 * Copyright (C) 2010 Jay Pipes <[email protected]>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; version 2 of the License.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
49
50#include <config.h>
51#include <drizzled/current_session.h>
52#include <drizzled/error.h>
53#include <drizzled/gettext.h>
54#include <drizzled/probes.h>
55#include <drizzled/sql_parse.h>
56#include <drizzled/session.h>
57#include <drizzled/session/times.h>
58#include <drizzled/sql_base.h>
59#include <drizzled/replication_services.h>
60#include <drizzled/transaction_services.h>
61#include <drizzled/transaction_context.h>
62#include <drizzled/message/transaction.pb.h>
64#include <drizzled/resource_context.h>
65#include <drizzled/lock.h>
66#include <drizzled/item/int.h>
67#include <drizzled/item/empty_string.h>
68#include <drizzled/field/epoch.h>
69#include <drizzled/plugin/client.h>
70#include <drizzled/plugin/monitored_in_transaction.h>
71#include <drizzled/plugin/transactional_storage_engine.h>
72#include <drizzled/plugin/xa_resource_manager.h>
73#include <drizzled/plugin/xa_storage_engine.h>
74#include <drizzled/internal/my_sys.h>
75#include <drizzled/statistics_variables.h>
76#include <drizzled/system_variables.h>
77#include <drizzled/session/transactions.h>
78
79#include <vector>
80#include <algorithm>
81#include <functional>
82#include <google/protobuf/repeated_field.h>
83
84using namespace std;
85using namespace google;
86
87namespace drizzled {
88
306
307static plugin::XaStorageEngine& xa_storage_engine()
308{
309 static plugin::XaStorageEngine& engine= static_cast<plugin::XaStorageEngine&>(*plugin::StorageEngine::findByName("InnoDB"));
310 return engine;
311}
312
316{
317 if (session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
318 {
319 /*
320 * Now we automatically register this resource manager for the
321 * normal transaction. This is fine because a statement
322 * transaction registration should always enlist the resource
323 * in the normal transaction which contains the statement
324 * transaction.
325 */
326 registerResourceForTransaction(session, monitored, engine);
327 }
328
329 TransactionContext& trans= session.transaction.stmt;
330 ResourceContext& resource_context= session.getResourceContext(*monitored, 0);
331
332 if (resource_context.isStarted())
333 return; /* already registered, return */
334
335 assert(monitored->participatesInSqlTransaction());
336 assert(not monitored->participatesInXaTransaction());
337
338 resource_context.setMonitored(monitored);
339 resource_context.setTransactionalStorageEngine(engine);
340 trans.registerResource(&resource_context);
341 trans.no_2pc= true;
342}
343
347 plugin::XaResourceManager *resource_manager)
348{
349 if (session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
350 {
351 /*
352 * Now we automatically register this resource manager for the
353 * normal transaction. This is fine because a statement
354 * transaction registration should always enlist the resource
355 * in the normal transaction which contains the statement
356 * transaction.
357 */
358 registerResourceForTransaction(session, monitored, engine, resource_manager);
359 }
360
361 TransactionContext& trans= session.transaction.stmt;
362 ResourceContext& resource_context= session.getResourceContext(*monitored, 0);
363
364 if (resource_context.isStarted())
365 return; /* already registered, return */
366
367 assert(monitored->participatesInXaTransaction());
368 assert(monitored->participatesInSqlTransaction());
369
370 resource_context.setMonitored(monitored);
371 resource_context.setTransactionalStorageEngine(engine);
372 resource_context.setXaResourceManager(resource_manager);
373 trans.registerResource(&resource_context);
374}
375
379{
380 TransactionContext& trans= session.transaction.all;
381 ResourceContext& resource_context= session.getResourceContext(*monitored, 1);
382
383 if (resource_context.isStarted())
384 return; /* already registered, return */
385
386 session.server_status|= SERVER_STATUS_IN_TRANS;
387
388 trans.registerResource(&resource_context);
389
390 assert(monitored->participatesInSqlTransaction());
391 assert(not monitored->participatesInXaTransaction());
392
393 resource_context.setMonitored(monitored);
394 resource_context.setTransactionalStorageEngine(engine);
395 trans.no_2pc= true;
396
397 if (session.transaction.xid_state.xid.is_null())
398 session.transaction.xid_state.xid.set(session.getQueryId());
399
400 /* Only true if user is executing a BEGIN WORK/START TRANSACTION */
401 if (not session.getResourceContext(*monitored, 0).isStarted())
402 registerResourceForStatement(session, monitored, engine);
403}
404
408 plugin::XaResourceManager *resource_manager)
409{
410 TransactionContext *trans= &session.transaction.all;
411 ResourceContext& resource_context= session.getResourceContext(*monitored, 1);
412
413 if (resource_context.isStarted())
414 return; /* already registered, return */
415
416 session.server_status|= SERVER_STATUS_IN_TRANS;
417
418 trans->registerResource(&resource_context);
419
420 assert(monitored->participatesInSqlTransaction());
421
422 resource_context.setMonitored(monitored);
423 resource_context.setXaResourceManager(resource_manager);
424 resource_context.setTransactionalStorageEngine(engine);
425 trans->no_2pc= true;
426
427 if (session.transaction.xid_state.xid.is_null())
428 session.transaction.xid_state.xid.set(session.getQueryId());
429
430 engine->startTransaction(&session, START_TRANS_NO_OPTIONS);
431
432 /* Only true if user is executing a BEGIN WORK/START TRANSACTION */
433 if (! session.getResourceContext(*monitored, 0).isStarted())
434 registerResourceForStatement(session, monitored, engine, resource_manager);
435}
436
437void TransactionServices::allocateNewTransactionId()
438{
440 {
441 return;
442 }
443
444 Session *my_session= current_session;
445 uint64_t xa_id= xa_storage_engine().getNewTransactionId(my_session);
446 my_session->setXaId(xa_id);
447}
448
449uint64_t TransactionServices::getCurrentTransactionId(Session& session)
450{
451 if (session.getXaId() == 0)
452 {
453 session.setXaId(xa_storage_engine().getNewTransactionId(&session));
454 }
455
456 return session.getXaId();
457}
458
460 bool normal_transaction)
461{
462 int error= 0, cookie= 0;
463 /*
464 'all' means that this is either an explicit commit issued by
465 user, or an implicit commit issued by a DDL.
466 */
467 TransactionContext *trans= normal_transaction ? &session.transaction.all : &session.transaction.stmt;
468 TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();
469
470 bool is_real_trans= normal_transaction || session.transaction.all.getResourceContexts().empty();
471
472 /*
473 We must not commit the normal transaction if a statement
474 transaction is pending. Otherwise statement transaction
475 flags will not get propagated to its normal transaction's
476 counterpart.
477 */
478 assert(session.transaction.stmt.getResourceContexts().empty() ||
479 trans == &session.transaction.stmt);
480
481 if (resource_contexts.empty() == false)
482 {
483 if (is_real_trans && session.wait_if_global_read_lock(false, false))
484 {
485 rollbackTransaction(session, normal_transaction);
486 return 1;
487 }
488
489 /*
490 * If replication is on, we do a PREPARE on the resource managers, push the
491 * Transaction message across the replication stream, and then COMMIT if the
492 * replication stream returned successfully.
493 */
495 {
496 for (TransactionContext::ResourceContexts::reference resource_context : resource_contexts)
497 {
498 if (error)
499 break;
500 /*
501 Do not call two-phase commit if this particular
502 transaction is read-only. This allows for simpler
503 implementation in engines that are always read-only.
504 */
505 if (! resource_context->hasModifiedData())
506 continue;
507
508 plugin::MonitoredInTransaction *resource= resource_context->getMonitored();
509
510 if (resource->participatesInXaTransaction())
511 {
512 if (int err= resource_context->getXaResourceManager()->xaPrepare(&session, normal_transaction))
513 {
514 my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
515 error= 1;
516 }
517 else
518 {
519 session.status_var.ha_prepare_count++;
520 }
521 }
522 }
523 if (error == 0 && is_real_trans)
524 {
525 /*
526 * Push the constructed Transaction messages across to
527 * replicators and appliers.
528 */
529 error= commitTransactionMessage(session);
530 }
531 if (error)
532 {
533 rollbackTransaction(session, normal_transaction);
534 error= 1;
535 goto end;
536 }
537 }
538 error= commitPhaseOne(session, normal_transaction) ? (cookie ? 2 : 1) : 0;
539end:
540 if (is_real_trans)
541 session.startWaitingGlobalReadLock();
542 }
543 return error;
544}
545
551 bool normal_transaction)
552{
553 int error=0;
554 TransactionContext *trans= normal_transaction ? &session.transaction.all : &session.transaction.stmt;
555 TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();
556
557 bool is_real_trans= normal_transaction || session.transaction.all.getResourceContexts().empty();
558 bool all= normal_transaction;
559
560 /* If we're in autocommit then we have a real transaction to commit
561 (except if it's BEGIN)
562 */
563 if (! session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
564 all= true;
565
566 if (resource_contexts.empty() == false)
567 {
568 for (TransactionContext::ResourceContexts::reference resource_context : resource_contexts)
569 {
570 plugin::MonitoredInTransaction *resource= resource_context->getMonitored();
571
572 if (resource->participatesInXaTransaction())
573 {
574 if (int err= resource_context->getXaResourceManager()->xaCommit(&session, all))
575 {
576 my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
577 error= 1;
578 }
579 else if (normal_transaction)
580 {
581 session.status_var.ha_commit_count++;
582 }
583 }
584 else if (resource->participatesInSqlTransaction())
585 {
586 if (int err= resource_context->getTransactionalStorageEngine()->commit(&session, all))
587 {
588 my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
589 error= 1;
590 }
591 else if (normal_transaction)
592 {
593 session.status_var.ha_commit_count++;
594 }
595 }
596 resource_context->reset(); /* keep it conveniently zero-filled */
597 }
598
599 if (is_real_trans)
600 session.transaction.xid_state.xid.set_null();
601
602 if (normal_transaction)
603 {
604 session.variables.tx_isolation= session.session_tx_isolation;
605 session.transaction.cleanup();
606 }
607 }
608 trans->reset();
609 return error;
610}
611
612int TransactionServices::rollbackTransaction(Session& session,
613 bool normal_transaction)
614{
615 int error= 0;
616 TransactionContext *trans= normal_transaction ? &session.transaction.all : &session.transaction.stmt;
617 TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();
618
619 bool is_real_trans= normal_transaction || session.transaction.all.getResourceContexts().empty();
620 bool all = normal_transaction || !session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);
621
622 /*
623 We must not rollback the normal transaction if a statement
624 transaction is pending.
625 */
626 assert(session.transaction.stmt.getResourceContexts().empty() || trans == &session.transaction.stmt);
627
628 if (resource_contexts.empty() == false)
629 {
630 for (TransactionContext::ResourceContexts::reference resource_context : resource_contexts)
631 {
632 plugin::MonitoredInTransaction *resource= resource_context->getMonitored();
633
634 if (resource->participatesInXaTransaction())
635 {
636 if (int err= resource_context->getXaResourceManager()->xaRollback(&session, all))
637 {
638 my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
639 error= 1;
640 }
641 else if (normal_transaction)
642 {
643 session.status_var.ha_rollback_count++;
644 }
645 }
646 else if (resource->participatesInSqlTransaction())
647 {
648 if (int err= resource_context->getTransactionalStorageEngine()->rollback(&session, all))
649 {
650 my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
651 error= 1;
652 }
653 else if (normal_transaction)
654 {
655 session.status_var.ha_rollback_count++;
656 }
657 }
658 resource_context->reset(); /* keep it conveniently zero-filled */
659 }
660
661 /*
662 * We need to signal the ROLLBACK to ReplicationServices here
663 * BEFORE we set the transaction ID to NULL. This is because
664 * if a bulk segment was sent to replicators, we need to send
665 * a rollback statement with the corresponding transaction ID
666 * to rollback.
667 */
668 if (all)
670 else
672
673 if (is_real_trans)
674 session.transaction.xid_state.xid.set_null();
675 if (normal_transaction)
676 {
677 session.variables.tx_isolation=session.session_tx_isolation;
678 session.transaction.cleanup();
679 }
680 }
681 if (normal_transaction)
682 session.transaction_rollback_request= false;
683
684 /*
685 * If a non-transactional table was updated, warn the user
686 */
687 if (is_real_trans &&
688 session.transaction.all.hasModifiedNonTransData() &&
689 session.getKilled() != Session::KILL_CONNECTION)
690 {
691 push_warning(&session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
692 ER_WARNING_NOT_COMPLETE_ROLLBACK,
693 ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
694 }
695 trans->reset();
696 return error;
697}
698
700 int error)
701{
702 /* One GPB Statement message per SQL statement */
703 message::Statement *statement= session.getStatementMessage();
704 if ((statement != NULL) && (! error))
705 finalizeStatementMessage(*statement, session);
706
707 if (session.transaction.stmt.getResourceContexts().empty() == false)
708 {
709 TransactionContext *trans = &session.transaction.stmt;
710 TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();
711 for (TransactionContext::ResourceContexts::reference resource_context : resource_contexts)
712 {
713 resource_context->getTransactionalStorageEngine()->endStatement(&session);
714 }
715
716 if (! error)
717 {
718 if (commitTransaction(session, false))
719 error= 1;
720 }
721 else
722 {
723 (void) rollbackTransaction(session, false);
724 if (session.transaction_rollback_request)
725 {
726 (void) rollbackTransaction(session, true);
727 session.server_status&= ~SERVER_STATUS_IN_TRANS;
728 }
729 }
730
731 session.variables.tx_isolation= session.session_tx_isolation;
732 }
733
734 return error;
735}
736
738{
739 bool operator()(const ResourceContext *lhs, const ResourceContext *rhs) const
740 {
741 /* The below is perfectly fine, since we're simply comparing addresses for the underlying
742 * resources aren't the same... */
743 return reinterpret_cast<uint64_t>(lhs->getMonitored()) < reinterpret_cast<uint64_t>(rhs->getMonitored());
744 }
745};
746
747int TransactionServices::rollbackToSavepoint(Session& session,
748 NamedSavepoint &sv)
749{
750 int error= 0;
751 TransactionContext *trans= &session.transaction.all;
752 TransactionContext::ResourceContexts &tran_resource_contexts= trans->getResourceContexts();
753 TransactionContext::ResourceContexts &sv_resource_contexts= sv.getResourceContexts();
754
755 trans->no_2pc= false;
756 /*
757 rolling back to savepoint in all storage engines that were part of the
758 transaction when the savepoint was set
759 */
760 for (TransactionContext::ResourceContexts::reference resource_context : sv_resource_contexts)
761 {
762 plugin::MonitoredInTransaction *resource= resource_context->getMonitored();
763
764 if (resource->participatesInSqlTransaction())
765 {
766 if (int err= resource_context->getTransactionalStorageEngine()->rollbackToSavepoint(&session, sv))
767 {
768 my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
769 error= 1;
770 }
771 else
772 {
773 session.status_var.ha_savepoint_rollback_count++;
774 }
775 }
776 trans->no_2pc|= not resource->participatesInXaTransaction();
777 }
778 /*
779 rolling back the transaction in all storage engines that were not part of
780 the transaction when the savepoint was set
781 */
782 {
783 TransactionContext::ResourceContexts sorted_tran_resource_contexts(tran_resource_contexts);
784 TransactionContext::ResourceContexts sorted_sv_resource_contexts(sv_resource_contexts);
785 TransactionContext::ResourceContexts set_difference_contexts;
786
787 /*
788 * Bug #542299: segfault during set_difference() below. copy<>() requires pre-allocation
789 * of all elements, including the target, which is why we pre-allocate the set_difference_contexts
790 * here
791 */
792 set_difference_contexts.reserve(max(tran_resource_contexts.size(), sv_resource_contexts.size()));
793
794 sort(sorted_tran_resource_contexts.begin(),
795 sorted_tran_resource_contexts.end(),
796 ResourceContextCompare());
797 sort(sorted_sv_resource_contexts.begin(),
798 sorted_sv_resource_contexts.end(),
799 ResourceContextCompare());
800 set_difference(sorted_tran_resource_contexts.begin(),
801 sorted_tran_resource_contexts.end(),
802 sorted_sv_resource_contexts.begin(),
803 sorted_sv_resource_contexts.end(),
804 set_difference_contexts.begin(),
805 ResourceContextCompare());
806 /*
807 * set_difference_contexts now contains all resource contexts
808 * which are in the transaction context but were NOT in the
809 * savepoint's resource contexts.
810 */
811
812 for (TransactionContext::ResourceContexts::reference resource_context : set_difference_contexts)
813 {
814 plugin::MonitoredInTransaction *resource= resource_context->getMonitored();
815
816 if (resource->participatesInSqlTransaction())
817 {
818 if (int err= resource_context->getTransactionalStorageEngine()->rollback(&session, true))
819 {
820 my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
821 error= 1;
822 }
823 else
824 {
825 session.status_var.ha_rollback_count++;
826 }
827 }
828 resource_context->reset(); /* keep it conveniently zero-filled */
829 }
830 }
831 trans->setResourceContexts(sv_resource_contexts);
832
834 {
836 message::Transaction *savepoint_transaction= sv.getTransactionMessage();
837 if (savepoint_transaction != NULL)
838 {
839 /* Make a copy of the savepoint transaction, this is necessary to assure proper cleanup.
840 Upon commit the savepoint_transaction_copy will be cleaned up by a call to
841 cleanupTransactionMessage(). The Transaction message in NamedSavepoint will be cleaned
842 up when the savepoint is cleaned up. This avoids calling delete twice on the Transaction.
843 */
844 message::Transaction *savepoint_transaction_copy= new message::Transaction(*sv.getTransactionMessage());
845 uint32_t num_statements = savepoint_transaction_copy->statement_size();
846 if (num_statements == 0)
847 {
848 session.setStatementMessage(NULL);
849 }
850 else
851 {
852 session.setStatementMessage(savepoint_transaction_copy->mutable_statement(num_statements - 1));
853 }
854 session.setTransactionMessage(savepoint_transaction_copy);
855 }
856 }
857
858 return error;
859}
860
868 NamedSavepoint &sv)
869{
870 int error= 0;
871 TransactionContext *trans= &session.transaction.all;
872 TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();
873
874 if (resource_contexts.empty() == false)
875 {
876 for (TransactionContext::ResourceContexts::reference resource_context : resource_contexts)
877 {
878 plugin::MonitoredInTransaction *resource= resource_context->getMonitored();
879
880 if (resource->participatesInSqlTransaction())
881 {
882 if (int err= resource_context->getTransactionalStorageEngine()->setSavepoint(&session, sv))
883 {
884 my_error(ER_GET_ERRNO, MYF(0), err);
885 error= 1;
886 }
887 else
888 {
889 session.status_var.ha_savepoint_count++;
890 }
891 }
892 }
893 }
894 /*
895 Remember the list of registered storage engines.
896 */
897 sv.setResourceContexts(resource_contexts);
898
900 {
901 message::Transaction *transaction= session.getTransactionMessage();
902
903 if (transaction != NULL)
904 {
905 message::Transaction *transaction_savepoint=
906 new message::Transaction(*transaction);
907 sv.setTransactionMessage(transaction_savepoint);
908 }
909 }
910
911 return error;
912}
913
914int TransactionServices::releaseSavepoint(Session& session,
915 NamedSavepoint &sv)
916{
917 int error= 0;
918
919 TransactionContext::ResourceContexts &resource_contexts= sv.getResourceContexts();
920
921 for (TransactionContext::ResourceContexts::reference resource_context : resource_contexts)
922 {
923 plugin::MonitoredInTransaction *resource= resource_context->getMonitored();
924
925 if (resource->participatesInSqlTransaction())
926 {
927 if (int err= resource_context->getTransactionalStorageEngine()->releaseSavepoint(&session, sv))
928 {
929 my_error(ER_GET_ERRNO, MYF(0), err);
930 error= 1;
931 }
932 }
933 }
934
935 return error;
936}
937
942
944 bool should_inc_trx_id)
945{
946 message::Transaction *transaction= session.getTransactionMessage();
947
948 if (DRIZZLE_UNLIKELY(transaction == NULL))
949 {
950 /*
951 * Allocate and initialize a new transaction message
952 * for this Session object. Session is responsible for
953 * deleting transaction message when done with it.
954 */
955 transaction= new message::Transaction();
956 initTransactionMessage(*transaction, session, should_inc_trx_id);
957 session.setTransactionMessage(transaction);
958 }
959 return transaction;
960}
961
962void TransactionServices::initTransactionMessage(message::Transaction &transaction,
963 Session& session,
964 bool should_inc_trx_id)
965{
966 message::TransactionContext *trx= transaction.mutable_transaction_context();
967 trx->set_server_id(session.getServerId());
968
969 if (should_inc_trx_id)
970 {
971 trx->set_transaction_id(getCurrentTransactionId(session));
972 session.setXaId(0);
973 }
974 else
975 {
976 /* trx and seg id will get set properly elsewhere */
977 trx->set_transaction_id(0);
978 }
979
980 trx->set_start_timestamp(session.times.getCurrentTimestamp());
981
982 /* segment info may get set elsewhere as needed */
983 transaction.set_segment_id(1);
984 transaction.set_end_segment(true);
985}
986
987void TransactionServices::finalizeTransactionMessage(message::Transaction &transaction,
988 const Session& session)
989{
990 message::TransactionContext *trx= transaction.mutable_transaction_context();
991 trx->set_end_timestamp(session.times.getCurrentTimestamp());
992}
993
994void TransactionServices::cleanupTransactionMessage(message::Transaction *transaction,
995 Session& session)
996{
997 delete transaction;
998 session.setStatementMessage(NULL);
999 session.setTransactionMessage(NULL);
1000 session.setXaId(0);
1001}
1002
1004{
1006 return 0;
1007
1008 /*
1009 * If no Transaction message was ever created, then no data modification
1010 * occurred inside the transaction, so nothing to do.
1011 */
1012 if (session.getTransactionMessage() == NULL)
1013 return 0;
1014
1015 /* If there is an active statement message, finalize it. */
1016 message::Statement *statement= session.getStatementMessage();
1017
1018 if (statement != NULL)
1019 {
1020 finalizeStatementMessage(*statement, session);
1021 }
1022
1023 message::Transaction* transaction= getActiveTransactionMessage(session);
1024
1025 /*
1026 * It is possible that we could have a Transaction without any Statements
1027 * if we had created a Statement but had to roll it back due to it failing
1028 * mid-execution, and no subsequent Statements were added to the Transaction
1029 * message. In this case, we simply clean up the message and not push it.
1030 */
1031 if (transaction->statement_size() == 0)
1032 {
1033 cleanupTransactionMessage(transaction, session);
1034 return 0;
1035 }
1036
1037 finalizeTransactionMessage(*transaction, session);
1038
1039 plugin::ReplicationReturnCode result= ReplicationServices::pushTransactionMessage(session, *transaction);
1040
1041 cleanupTransactionMessage(transaction, session);
1042
1043 return static_cast<int>(result);
1044}
1045
1046void TransactionServices::initStatementMessage(message::Statement &statement,
1047 message::Statement::Type type,
1048 const Session& session)
1049{
1050 statement.set_type(type);
1051 statement.set_start_timestamp(session.times.getCurrentTimestamp());
1052
1053 if (session.variables.replicate_query)
1054 statement.set_sql(session.getQueryString()->c_str());
1055}
1056
1057void TransactionServices::finalizeStatementMessage(message::Statement &statement,
1058 Session& session)
1059{
1060 statement.set_end_timestamp(session.times.getCurrentTimestamp());
1061 session.setStatementMessage(NULL);
1062}
1063
1065{
1067 return;
1068
1069 message::Transaction *transaction= getActiveTransactionMessage(session);
1070
1071 /*
1072 * OK, so there are two situations that we need to deal with here:
1073 *
1074 * 1) We receive an instruction to ROLLBACK the current transaction
1075 * and the currently-stored Transaction message is *self-contained*,
1076 * meaning that no Statement messages in the Transaction message
1077 * contain a message having its segment_id member greater than 1. If
1078 * no non-segment ID 1 members are found, we can simply clear the
1079 * current Transaction message and remove it from memory.
1080 *
1081 * 2) If the Transaction message does indeed have a non-end segment, that
1082 * means that a bulk update/delete/insert Transaction message segment
1083 * has previously been sent over the wire to replicators. In this case,
1084 * we need to package a Transaction with a Statement message of type
1085 * ROLLBACK to indicate to replicators that previously-transmitted
1086 * messages must be un-applied.
1087 */
1088 if (DRIZZLE_UNLIKELY(message::transactionContainsBulkSegment(*transaction)))
1089 {
1090 /* Remember the transaction ID so we can re-use it */
1091 uint64_t trx_id= transaction->transaction_context().transaction_id();
1092 uint32_t seg_id= transaction->segment_id();
1093
1094 /*
1095 * Clear the transaction, create a Rollback statement message,
1096 * attach it to the transaction, and push it to replicators.
1097 */
1098 transaction->Clear();
1099 initTransactionMessage(*transaction, session, false);
1100
1101 /* Set the transaction ID to match the previous messages */
1102 transaction->mutable_transaction_context()->set_transaction_id(trx_id);
1103 transaction->set_segment_id(seg_id);
1104 transaction->set_end_segment(true);
1105
1106 message::Statement *statement= transaction->add_statement();
1107
1108 initStatementMessage(*statement, message::Statement::ROLLBACK, session);
1109 finalizeStatementMessage(*statement, session);
1110
1111 finalizeTransactionMessage(*transaction, session);
1112
1113 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
1114 }
1115
1116 cleanupTransactionMessage(transaction, session);
1117}
1118
1120{
1122 return;
1123
1124 message::Statement *current_statement= session.getStatementMessage();
1125
1126 /* If we never added a Statement message, nothing to undo. */
1127 if (current_statement == NULL)
1128 return;
1129
1130 /*
1131 * If the Statement has been segmented, then we've already pushed a portion
1132 * of this Statement's row changes through the replication stream and we
1133 * need to send a ROLLBACK_STATEMENT message. Otherwise, we can simply
1134 * delete the current Statement message.
1135 */
1136 bool is_segmented= false;
1137
1138 switch (current_statement->type())
1139 {
1140 case message::Statement::INSERT:
1141 if (current_statement->insert_data().segment_id() > 1)
1142 is_segmented= true;
1143 break;
1144
1145 case message::Statement::UPDATE:
1146 if (current_statement->update_data().segment_id() > 1)
1147 is_segmented= true;
1148 break;
1149
1150 case message::Statement::DELETE:
1151 if (current_statement->delete_data().segment_id() > 1)
1152 is_segmented= true;
1153 break;
1154
1155 default:
1156 break;
1157 }
1158
1159 /*
1160 * Remove the Statement message we've been working with (same as
1161 * current_statement).
1162 */
1163 message::Transaction *transaction= getActiveTransactionMessage(session);
1164 google::protobuf::RepeatedPtrField<message::Statement> *statements_in_txn;
1165 statements_in_txn= transaction->mutable_statement();
1166 statements_in_txn->RemoveLast();
1167 session.setStatementMessage(NULL);
1168
1169 /*
1170 * Create the ROLLBACK_STATEMENT message, if we need to. This serves as
1171 * an indicator to cancel the previous Statement message which should have
1172 * had its end_segment attribute set to false.
1173 */
1174 if (is_segmented)
1175 {
1176 current_statement= transaction->add_statement();
1177 initStatementMessage(*current_statement,
1178 message::Statement::ROLLBACK_STATEMENT,
1179 session);
1180 finalizeStatementMessage(*current_statement, session);
1181 }
1182}
1183
1185 message::Transaction *transaction)
1186{
1187 uint64_t trx_id= transaction->transaction_context().transaction_id();
1188 uint32_t seg_id= transaction->segment_id();
1189
1190 transaction->set_end_segment(false);
1191 commitTransactionMessage(session);
1192 transaction= getActiveTransactionMessage(session, false);
1193
1194 /* Set the transaction ID to match the previous messages */
1195 transaction->mutable_transaction_context()->set_transaction_id(trx_id);
1196 transaction->set_segment_id(seg_id + 1);
1197 transaction->set_end_segment(true);
1198
1199 return transaction;
1200}
1201
1203 Table &table,
1204 uint32_t *next_segment_id)
1205{
1206 message::Statement *statement= session.getStatementMessage();
1207 message::Transaction *transaction= NULL;
1208
1209 /*
1210 * If statement is NULL, this is a new statement.
1211 * If statement is NOT NULL, this a continuation of the same statement.
1212 * This is because autocommitOrRollback() finalizes the statement so that
1213 * we guarantee only one Statement message per statement (i.e., we no longer
1214 * share a single GPB message for multiple statements).
1215 */
1216 if (statement == NULL)
1217 {
1218 transaction= getActiveTransactionMessage(session);
1219
1220 if (transaction->ByteSizeLong() >= transaction_message_threshold)
1221 {
1222 transaction= segmentTransactionMessage(session, transaction);
1223 }
1224
1225 statement= transaction->add_statement();
1226 setInsertHeader(*statement, session, table);
1227 session.setStatementMessage(statement);
1228 }
1229 else
1230 {
1231 transaction= getActiveTransactionMessage(session);
1232
1233 /*
1234 * If we've passed our threshold for the statement size (possible for
1235 * a bulk insert), we'll finalize the Statement and Transaction (doing
1236 * the Transaction will keep it from getting huge).
1237 */
1238 if (transaction->ByteSizeLong() >= transaction_message_threshold)
1239 {
1240 /* Remember the transaction ID so we can re-use it */
1241 uint64_t trx_id= transaction->transaction_context().transaction_id();
1242 uint32_t seg_id= transaction->segment_id();
1243
1244 message::InsertData *current_data= statement->mutable_insert_data();
1245
1246 /* Caller should use this value when adding a new record */
1247 *next_segment_id= current_data->segment_id() + 1;
1248
1249 current_data->set_end_segment(false);
1250 transaction->set_end_segment(false);
1251
1252 /*
1253 * Send the trx message to replicators after finalizing the
1254 * statement and transaction. This will also set the Transaction
1255 * and Statement objects in Session to NULL.
1256 */
1257 commitTransactionMessage(session);
1258
1259 /*
1260 * Statement and Transaction should now be NULL, so new ones will get
1261 * created. We reuse the transaction id since we are segmenting
1262 * one transaction.
1263 */
1264 transaction= getActiveTransactionMessage(session, false);
1265 assert(transaction != NULL);
1266
1267 statement= transaction->add_statement();
1268 setInsertHeader(*statement, session, table);
1269 session.setStatementMessage(statement);
1270
1271 /* Set the transaction ID to match the previous messages */
1272 transaction->mutable_transaction_context()->set_transaction_id(trx_id);
1273 transaction->set_segment_id(seg_id + 1);
1274 transaction->set_end_segment(true);
1275 }
1276 else
1277 {
1278 /*
1279 * Continuation of the same statement. Carry forward the existing
1280 * segment id.
1281 */
1282 const message::InsertData &current_data= statement->insert_data();
1283 *next_segment_id= current_data.segment_id();
1284 }
1285 }
1286
1287 return *statement;
1288}
1289
1290void TransactionServices::setInsertHeader(message::Statement &statement,
1291 const Session& session,
1292 Table &table)
1293{
1294 initStatementMessage(statement, message::Statement::INSERT, session);
1295
1296 /*
1297 * Now we construct the specialized InsertHeader message inside
1298 * the generalized message::Statement container...
1299 */
1300 /* Set up the insert header */
1301 message::InsertHeader *header= statement.mutable_insert_header();
1302 message::TableMetadata *table_metadata= header->mutable_table_metadata();
1303
1304 table_metadata->set_schema_name(table.getShare()->getSchemaName());
1305 table_metadata->set_table_name(table.getShare()->getTableName());
1306
1307 Field **table_fields= table.getFields();
1308
1309 message::FieldMetadata *field_metadata;
1310
1311 /* We will read all the table's fields... */
1312 table.setReadSet();
1313
1314 while (Field* current_field= *table_fields++)
1315 {
1316 field_metadata= header->add_field_metadata();
1317 field_metadata->set_name(current_field->field_name);
1318 field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
1319 }
1320}
1321
1323 Table &table)
1324{
1326 return false;
1327
1328 if (not table.getShare()->is_replicated())
1329 return false;
1330
1339 if (not table.getShare()->hasPrimaryKey())
1340 {
1341 my_error(ER_NO_PRIMARY_KEY_ON_REPLICATED_TABLE, MYF(0));
1342 return true;
1343 }
1344
1345 uint32_t next_segment_id= 1;
1346 message::Statement &statement= getInsertStatement(session, table, &next_segment_id);
1347
1348 message::InsertData *data= statement.mutable_insert_data();
1349 data->set_segment_id(next_segment_id);
1350 data->set_end_segment(true);
1351 message::InsertRecord *record= data->add_record();
1352
1353 Field *current_field;
1354 Field **table_fields= table.getFields();
1355
1356 String *string_value= new (session.mem_root) String(TransactionServices::DEFAULT_RECORD_SIZE);
1357 string_value->set_charset(system_charset_info);
1358
1359 /* We will read all the table's fields... */
1360 table.setReadSet();
1361
1362 while ((current_field= *table_fields++) != NULL)
1363 {
1364 if (current_field->is_null())
1365 {
1366 record->add_is_null(true);
1367 record->add_insert_value("", 0);
1368 }
1369 else
1370 {
1371 string_value= current_field->val_str_internal(string_value);
1372 record->add_is_null(false);
1373 record->add_insert_value(string_value->c_ptr(), string_value->length());
1374 string_value->free();
1375 }
1376 }
1377 return false;
1378}
1379
1381 Table &table,
1382 const unsigned char *old_record,
1383 const unsigned char *new_record,
1384 uint32_t *next_segment_id)
1385{
1386 message::Statement *statement= session.getStatementMessage();
1387 message::Transaction *transaction= NULL;
1388
1389 /*
1390 * If statement is NULL, this is a new statement.
1391 * If statement is NOT NULL, this a continuation of the same statement.
1392 * This is because autocommitOrRollback() finalizes the statement so that
1393 * we guarantee only one Statement message per statement (i.e., we no longer
1394 * share a single GPB message for multiple statements).
1395 */
1396 if (statement == NULL)
1397 {
1398 transaction= getActiveTransactionMessage(session);
1399
1400 if (transaction->ByteSizeLong() >= transaction_message_threshold)
1401 {
1402 transaction= segmentTransactionMessage(session, transaction);
1403 }
1404
1405 statement= transaction->add_statement();
1406 setUpdateHeader(*statement, session, table, old_record, new_record);
1407 session.setStatementMessage(statement);
1408 }
1409 else
1410 {
1411 transaction= getActiveTransactionMessage(session);
1412
1413 /*
1414 * If we've passed our threshold for the statement size (possible for
1415 * a bulk insert), we'll finalize the Statement and Transaction (doing
1416 * the Transaction will keep it from getting huge).
1417 */
1418 if (transaction->ByteSizeLong() >= transaction_message_threshold)
1419 {
1420 /* Remember the transaction ID so we can re-use it */
1421 uint64_t trx_id= transaction->transaction_context().transaction_id();
1422 uint32_t seg_id= transaction->segment_id();
1423
1424 message::UpdateData *current_data= statement->mutable_update_data();
1425
1426 /* Caller should use this value when adding a new record */
1427 *next_segment_id= current_data->segment_id() + 1;
1428
1429 current_data->set_end_segment(false);
1430 transaction->set_end_segment(false);
1431
1432 /*
1433 * Send the trx message to replicators after finalizing the
1434 * statement and transaction. This will also set the Transaction
1435 * and Statement objects in Session to NULL.
1436 */
1437 commitTransactionMessage(session);
1438
1439 /*
1440 * Statement and Transaction should now be NULL, so new ones will get
1441 * created. We reuse the transaction id since we are segmenting
1442 * one transaction.
1443 */
1444 transaction= getActiveTransactionMessage(session, false);
1445 assert(transaction != NULL);
1446
1447 statement= transaction->add_statement();
1448 setUpdateHeader(*statement, session, table, old_record, new_record);
1449 session.setStatementMessage(statement);
1450
1451 /* Set the transaction ID to match the previous messages */
1452 transaction->mutable_transaction_context()->set_transaction_id(trx_id);
1453 transaction->set_segment_id(seg_id + 1);
1454 transaction->set_end_segment(true);
1455 }
1456 else
1457 {
1458 /*
1459 * Continuation of the same statement. Carry forward the existing
1460 * segment id.
1461 */
1462 const message::UpdateData &current_data= statement->update_data();
1463 *next_segment_id= current_data.segment_id();
1464 }
1465 }
1466
1467 return *statement;
1468}
1469
1470void TransactionServices::setUpdateHeader(message::Statement &statement,
1471 const Session& session,
1472 Table &table,
1473 const unsigned char *old_record,
1474 const unsigned char *new_record)
1475{
1476 initStatementMessage(statement, message::Statement::UPDATE, session);
1477
1478 /*
1479 * Now we construct the specialized UpdateHeader message inside
1480 * the generalized message::Statement container...
1481 */
1482 /* Set up the update header */
1483 message::UpdateHeader *header= statement.mutable_update_header();
1484 message::TableMetadata *table_metadata= header->mutable_table_metadata();
1485
1486 table_metadata->set_schema_name(table.getShare()->getSchemaName());
1487 table_metadata->set_table_name(table.getShare()->getTableName());
1488
1489 Field *current_field;
1490 Field **table_fields= table.getFields();
1491
1492 message::FieldMetadata *field_metadata;
1493
1494 /* We will read all the table's fields... */
1495 table.setReadSet();
1496
1497 while ((current_field= *table_fields++) != NULL)
1498 {
1499 /*
1500 * We add the "key field metadata" -- i.e. the fields which is
1501 * the primary key for the table.
1502 */
1503 if (table.getShare()->fieldInPrimaryKey(current_field))
1504 {
1505 field_metadata= header->add_key_field_metadata();
1506 field_metadata->set_name(current_field->field_name);
1507 field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
1508 }
1509
1510 if (isFieldUpdated(current_field, table, old_record, new_record))
1511 {
1512 /* Field is changed from old to new */
1513 field_metadata= header->add_set_field_metadata();
1514 field_metadata->set_name(current_field->field_name);
1515 field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
1516 }
1517 }
1518}
1519
1521 Table &table,
1522 const unsigned char *old_record,
1523 const unsigned char *new_record)
1524{
1526 return;
1527
1528 if (not table.getShare()->is_replicated())
1529 return;
1530
1531 uint32_t next_segment_id= 1;
1532 message::Statement &statement= getUpdateStatement(session, table, old_record, new_record, &next_segment_id);
1533
1534 message::UpdateData *data= statement.mutable_update_data();
1535 data->set_segment_id(next_segment_id);
1536 data->set_end_segment(true);
1537 message::UpdateRecord *record= data->add_record();
1538
1539 Field *current_field;
1540 Field **table_fields= table.getFields();
1541 String *string_value= new (session.mem_root) String(TransactionServices::DEFAULT_RECORD_SIZE);
1542 string_value->set_charset(system_charset_info);
1543
1544 while ((current_field= *table_fields++) != NULL)
1545 {
1546 /*
1547 * Here, we add the SET field values. We used to do this in the setUpdateHeader() method,
1548 * but then realized that an UPDATE statement could potentially have different values for
1549 * the SET field. For instance, imagine this SQL scenario:
1550 *
1551 * CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY, count INT NOT NULL);
1552 * INSERT INTO t1 (id, counter) VALUES (1,1),(2,2),(3,3);
1553 * UPDATE t1 SET counter = counter + 1 WHERE id IN (1,2);
1554 *
1555 * We will generate two UpdateRecord messages with different set_value byte arrays.
1556 */
1557 if (isFieldUpdated(current_field, table, old_record, new_record))
1558 {
1559 /* Store the original "read bit" for this field */
1560 bool is_read_set= current_field->isReadSet();
1561
1562 /* We need to mark that we will "read" this field... */
1563 table.setReadSet(current_field->position());
1564
1565 /* Read the string value of this field's contents */
1566 string_value= current_field->val_str_internal(string_value);
1567
1568 /*
1569 * Reset the read bit after reading field to its original state. This
1570 * prevents the field from being included in the WHERE clause
1571 */
1572 current_field->setReadSet(is_read_set);
1573
1574 if (current_field->is_null())
1575 {
1576 record->add_is_null(true);
1577 record->add_after_value("", 0);
1578 }
1579 else
1580 {
1581 record->add_is_null(false);
1582 record->add_after_value(string_value->c_ptr(), string_value->length());
1583 }
1584 string_value->free();
1585 }
1586
1587 /*
1588 * Add the WHERE clause values now...for now, this means the
1589 * primary key field value. Replication only supports tables
1590 * with a primary key.
1591 */
1592 if (table.getShare()->fieldInPrimaryKey(current_field))
1593 {
1599 string_value= current_field->val_str_internal(string_value,
1600 old_record +
1601 current_field->offset(const_cast<unsigned char *>(new_record)));
1602 record->add_key_value(string_value->c_ptr(), string_value->length());
1603 string_value->free();
1604 }
1605
1606 }
1607}
1608
1610 Table &table,
1611 const unsigned char *old_record,
1612 const unsigned char *new_record)
1613{
1614 /*
1615 * The below really should be moved into the Field API and Record API. But for now
1616 * we do this crazy pointer fiddling to figure out if the current field
1617 * has been updated in the supplied record raw byte pointers.
1618 */
1619 const unsigned char *old_ptr= (const unsigned char *) old_record + (ptrdiff_t) (current_field->ptr - table.getInsertRecord());
1620 const unsigned char *new_ptr= (const unsigned char *) new_record + (ptrdiff_t) (current_field->ptr - table.getInsertRecord());
1621
1622 uint32_t field_length= current_field->pack_length();
1623
1624 bool old_value_is_null= current_field->is_null_in_record(old_record);
1625 bool new_value_is_null= current_field->is_null_in_record(new_record);
1626
1627 bool isUpdated= false;
1628 if (old_value_is_null != new_value_is_null)
1629 {
1630 if ((old_value_is_null) && (! new_value_is_null)) /* old value is NULL, new value is non NULL */
1631 {
1632 isUpdated= true;
1633 }
1634 else if ((! old_value_is_null) && (new_value_is_null)) /* old value is non NULL, new value is NULL */
1635 {
1636 isUpdated= true;
1637 }
1638 }
1639
1640 if (! isUpdated)
1641 {
1642 if (memcmp(old_ptr, new_ptr, field_length) != 0)
1643 {
1644 isUpdated= true;
1645 }
1646 }
1647 return isUpdated;
1648}
1649
1651 Table &table,
1652 uint32_t *next_segment_id)
1653{
1654 message::Statement *statement= session.getStatementMessage();
1655 message::Transaction *transaction= NULL;
1656
1657 /*
1658 * If statement is NULL, this is a new statement.
1659 * If statement is NOT NULL, this a continuation of the same statement.
1660 * This is because autocommitOrRollback() finalizes the statement so that
1661 * we guarantee only one Statement message per statement (i.e., we no longer
1662 * share a single GPB message for multiple statements).
1663 */
1664 if (statement == NULL)
1665 {
1666 transaction= getActiveTransactionMessage(session);
1667
1668 if (transaction->ByteSizeLong() >= transaction_message_threshold)
1669 {
1670 transaction= segmentTransactionMessage(session, transaction);
1671 }
1672
1673 statement= transaction->add_statement();
1674 setDeleteHeader(*statement, session, table);
1675 session.setStatementMessage(statement);
1676 }
1677 else
1678 {
1679 transaction= getActiveTransactionMessage(session);
1680
1681 /*
1682 * If we've passed our threshold for the statement size (possible for
1683 * a bulk insert), we'll finalize the Statement and Transaction (doing
1684 * the Transaction will keep it from getting huge).
1685 */
1686 if (transaction->ByteSizeLong() >= transaction_message_threshold)
1687 {
1688 /* Remember the transaction ID so we can re-use it */
1689 uint64_t trx_id= transaction->transaction_context().transaction_id();
1690 uint32_t seg_id= transaction->segment_id();
1691
1692 message::DeleteData *current_data= statement->mutable_delete_data();
1693
1694 /* Caller should use this value when adding a new record */
1695 *next_segment_id= current_data->segment_id() + 1;
1696
1697 current_data->set_end_segment(false);
1698 transaction->set_end_segment(false);
1699
1700 /*
1701 * Send the trx message to replicators after finalizing the
1702 * statement and transaction. This will also set the Transaction
1703 * and Statement objects in Session to NULL.
1704 */
1705 commitTransactionMessage(session);
1706
1707 /*
1708 * Statement and Transaction should now be NULL, so new ones will get
1709 * created. We reuse the transaction id since we are segmenting
1710 * one transaction.
1711 */
1712 transaction= getActiveTransactionMessage(session, false);
1713 assert(transaction != NULL);
1714
1715 statement= transaction->add_statement();
1716 setDeleteHeader(*statement, session, table);
1717 session.setStatementMessage(statement);
1718
1719 /* Set the transaction ID to match the previous messages */
1720 transaction->mutable_transaction_context()->set_transaction_id(trx_id);
1721 transaction->set_segment_id(seg_id + 1);
1722 transaction->set_end_segment(true);
1723 }
1724 else
1725 {
1726 /*
1727 * Continuation of the same statement. Carry forward the existing
1728 * segment id.
1729 */
1730 const message::DeleteData &current_data= statement->delete_data();
1731 *next_segment_id= current_data.segment_id();
1732 }
1733 }
1734
1735 return *statement;
1736}
1737
1738void TransactionServices::setDeleteHeader(message::Statement &statement,
1739 const Session& session,
1740 Table &table)
1741{
1742 initStatementMessage(statement, message::Statement::DELETE, session);
1743
1744 /*
1745 * Now we construct the specialized DeleteHeader message inside
1746 * the generalized message::Statement container...
1747 */
1748 message::DeleteHeader *header= statement.mutable_delete_header();
1749 message::TableMetadata *table_metadata= header->mutable_table_metadata();
1750
1751 table_metadata->set_schema_name(table.getShare()->getSchemaName());
1752 table_metadata->set_table_name(table.getShare()->getTableName());
1753
1754 Field *current_field;
1755 Field **table_fields= table.getFields();
1756
1757 message::FieldMetadata *field_metadata;
1758
1759 while ((current_field= *table_fields++) != NULL)
1760 {
1761 /*
1762 * Add the WHERE clause values now...for now, this means the
1763 * primary key field value. Replication only supports tables
1764 * with a primary key.
1765 */
1766 if (table.getShare()->fieldInPrimaryKey(current_field))
1767 {
1768 field_metadata= header->add_key_field_metadata();
1769 field_metadata->set_name(current_field->field_name);
1770 field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
1771 }
1772 }
1773}
1774
1776 Table &table,
1777 bool use_update_record)
1778{
1780 return;
1781
1782 if (not table.getShare()->is_replicated())
1783 return;
1784
1785 uint32_t next_segment_id= 1;
1786 message::Statement &statement= getDeleteStatement(session, table, &next_segment_id);
1787
1788 message::DeleteData *data= statement.mutable_delete_data();
1789 data->set_segment_id(next_segment_id);
1790 data->set_end_segment(true);
1791 message::DeleteRecord *record= data->add_record();
1792
1793 Field *current_field;
1794 Field **table_fields= table.getFields();
1795 String *string_value= new (session.mem_root) String(TransactionServices::DEFAULT_RECORD_SIZE);
1796 string_value->set_charset(system_charset_info);
1797
1798 while ((current_field= *table_fields++) != NULL)
1799 {
1800 /*
1801 * Add the WHERE clause values now...for now, this means the
1802 * primary key field value. Replication only supports tables
1803 * with a primary key.
1804 */
1805 if (table.getShare()->fieldInPrimaryKey(current_field))
1806 {
1807 if (use_update_record)
1808 {
1809 /*
1810 * Temporarily point to the update record to get its value.
1811 * This is pretty much a hack in order to get the PK value from
1812 * the update record rather than the insert record. Field::val_str()
1813 * should not change anything in Field::ptr, so this should be safe.
1814 * We are careful not to change anything in old_ptr.
1815 */
1816 const unsigned char *old_ptr= current_field->ptr;
1817 current_field->ptr= table.getUpdateRecord() + static_cast<ptrdiff_t>(old_ptr - table.getInsertRecord());
1818 string_value= current_field->val_str_internal(string_value);
1819 current_field->ptr= const_cast<unsigned char *>(old_ptr);
1820 }
1821 else
1822 {
1823 string_value= current_field->val_str_internal(string_value);
1827 }
1828 record->add_key_value(string_value->c_ptr(), string_value->length());
1829 string_value->free();
1830 }
1831 }
1832}
1833
1835 const message::Table &table)
1836{
1838 return;
1839
1840 if (not message::is_replicated(table))
1841 return;
1842
1843 message::Transaction *transaction= getActiveTransactionMessage(session);
1844 message::Statement *statement= transaction->add_statement();
1845
1846 initStatementMessage(*statement, message::Statement::CREATE_TABLE, session);
1847
1848 /*
1849 * Construct the specialized CreateTableStatement message and attach
1850 * it to the generic Statement message
1851 */
1852 message::CreateTableStatement *create_table_statement= statement->mutable_create_table_statement();
1853 message::Table *new_table_message= create_table_statement->mutable_table();
1854 *new_table_message= table;
1855
1856 finalizeStatementMessage(*statement, session);
1857
1858 finalizeTransactionMessage(*transaction, session);
1859
1860 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
1861
1862 cleanupTransactionMessage(transaction, session);
1863
1864}
1865
1867 const message::Schema &schema)
1868{
1870 return;
1871
1872 if (not message::is_replicated(schema))
1873 return;
1874
1875 message::Transaction *transaction= getActiveTransactionMessage(session);
1876 message::Statement *statement= transaction->add_statement();
1877
1878 initStatementMessage(*statement, message::Statement::CREATE_SCHEMA, session);
1879
1880 /*
1881 * Construct the specialized CreateSchemaStatement message and attach
1882 * it to the generic Statement message
1883 */
1884 message::CreateSchemaStatement *create_schema_statement= statement->mutable_create_schema_statement();
1885 message::Schema *new_schema_message= create_schema_statement->mutable_schema();
1886 *new_schema_message= schema;
1887
1888 finalizeStatementMessage(*statement, session);
1889
1890 finalizeTransactionMessage(*transaction, session);
1891
1892 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
1893
1894 cleanupTransactionMessage(transaction, session);
1895
1896}
1897
1899 const identifier::Schema& identifier,
1900 message::schema::const_reference schema)
1901{
1903 return;
1904
1905 if (not message::is_replicated(schema))
1906 return;
1907
1908 message::Transaction *transaction= getActiveTransactionMessage(session);
1909 message::Statement *statement= transaction->add_statement();
1910
1911 initStatementMessage(*statement, message::Statement::DROP_SCHEMA, session);
1912
1913 /*
1914 * Construct the specialized DropSchemaStatement message and attach
1915 * it to the generic Statement message
1916 */
1917 message::DropSchemaStatement *drop_schema_statement= statement->mutable_drop_schema_statement();
1918
1919 drop_schema_statement->set_schema_name(identifier.getSchemaName());
1920
1921 finalizeStatementMessage(*statement, session);
1922
1923 finalizeTransactionMessage(*transaction, session);
1924
1925 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
1926
1927 cleanupTransactionMessage(transaction, session);
1928}
1929
1931 const message::Schema &old_schema,
1932 const message::Schema &new_schema)
1933{
1935 return;
1936
1937 if (not message::is_replicated(old_schema))
1938 return;
1939
1940 message::Transaction *transaction= getActiveTransactionMessage(session);
1941 message::Statement *statement= transaction->add_statement();
1942
1943 initStatementMessage(*statement, message::Statement::ALTER_SCHEMA, session);
1944
1945 /*
1946 * Construct the specialized AlterSchemaStatement message and attach
1947 * it to the generic Statement message
1948 */
1949 message::AlterSchemaStatement *alter_schema_statement= statement->mutable_alter_schema_statement();
1950
1951 message::Schema *before= alter_schema_statement->mutable_before();
1952 message::Schema *after= alter_schema_statement->mutable_after();
1953
1954 *before= old_schema;
1955 *after= new_schema;
1956
1957 finalizeStatementMessage(*statement, session);
1958
1959 finalizeTransactionMessage(*transaction, session);
1960
1961 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
1962
1963 cleanupTransactionMessage(transaction, session);
1964}
1965
1967 const identifier::Table& identifier,
1968 message::table::const_reference table,
1969 bool if_exists)
1970{
1972 return;
1973
1974 if (not message::is_replicated(table))
1975 return;
1976
1977 message::Transaction *transaction= getActiveTransactionMessage(session);
1978 message::Statement *statement= transaction->add_statement();
1979
1980 initStatementMessage(*statement, message::Statement::DROP_TABLE, session);
1981
1982 /*
1983 * Construct the specialized DropTableStatement message and attach
1984 * it to the generic Statement message
1985 */
1986 message::DropTableStatement *drop_table_statement= statement->mutable_drop_table_statement();
1987
1988 drop_table_statement->set_if_exists_clause(if_exists);
1989
1990 message::TableMetadata *table_metadata= drop_table_statement->mutable_table_metadata();
1991
1992 table_metadata->set_schema_name(identifier.getSchemaName());
1993 table_metadata->set_table_name(identifier.getTableName());
1994
1995 finalizeStatementMessage(*statement, session);
1996
1997 finalizeTransactionMessage(*transaction, session);
1998
1999 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
2000
2001 cleanupTransactionMessage(transaction, session);
2002}
2003
2005{
2007 return;
2008
2009 if (not table.getShare()->is_replicated())
2010 return;
2011
2012 message::Transaction *transaction= getActiveTransactionMessage(session);
2013 message::Statement *statement= transaction->add_statement();
2014
2015 initStatementMessage(*statement, message::Statement::TRUNCATE_TABLE, session);
2016
2017 /*
2018 * Construct the specialized TruncateTableStatement message and attach
2019 * it to the generic Statement message
2020 */
2021 message::TruncateTableStatement *truncate_statement= statement->mutable_truncate_table_statement();
2022 message::TableMetadata *table_metadata= truncate_statement->mutable_table_metadata();
2023
2024 table_metadata->set_schema_name(table.getShare()->getSchemaName());
2025 table_metadata->set_table_name(table.getShare()->getTableName());
2026
2027 finalizeStatementMessage(*statement, session);
2028
2029 finalizeTransactionMessage(*transaction, session);
2030
2031 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
2032
2033 cleanupTransactionMessage(transaction, session);
2034}
2035
2037 const string &query,
2038 const string &schema)
2039{
2041 return;
2042
2043 message::Transaction *transaction= getActiveTransactionMessage(session);
2044 message::Statement *statement= transaction->add_statement();
2045
2046 initStatementMessage(*statement, message::Statement::RAW_SQL, session);
2047 statement->set_sql(query);
2048 if (not schema.empty())
2049 statement->set_raw_sql_schema(schema);
2050 finalizeStatementMessage(*statement, session);
2051
2052 finalizeTransactionMessage(*transaction, session);
2053
2054 (void) ReplicationServices::pushTransactionMessage(session, *transaction);
2055
2056 cleanupTransactionMessage(transaction, session);
2057}
2058
2059int TransactionServices::sendEvent(Session& session, const message::Event &event)
2060{
2062 return 0;
2063 message::Transaction transaction;
2064
2065 // set server id, start timestamp
2066 initTransactionMessage(transaction, session, true);
2067
2068 // set end timestamp
2069 finalizeTransactionMessage(transaction, session);
2070
2071 message::Event *trx_event= transaction.mutable_event();
2072 trx_event->CopyFrom(event);
2073 plugin::ReplicationReturnCode result= ReplicationServices::pushTransactionMessage(session, transaction);
2074 return result;
2075}
2076
2078{
2079 message::Event event;
2080 event.set_type(message::Event::STARTUP);
2081 return not sendEvent(session, event);
2082}
2083
2085{
2086 message::Event event;
2087 event.set_type(message::Event::SHUTDOWN);
2088 return not sendEvent(session, event);
2089}
2090
2091} /* namespace drizzled */
unsigned char * ptr
Definition field.h:73
virtual uint32_t pack_length() const
Definition field.cc:707
const char * field_name
Definition field.h:104
static plugin::ReplicationReturnCode pushTransactionMessage(Session &in_session, message::Transaction &to_push)
void setMonitored(plugin::MonitoredInTransaction *in_monitored)
plugin::XaResourceManager * getXaResourceManager() const
plugin::MonitoredInTransaction * getMonitored() const
void setTransactionalStorageEngine(plugin::TransactionalStorageEngine *in_trx_storage_engine)
plugin::TransactionalStorageEngine * getTransactionalStorageEngine() const
void setXaResourceManager(plugin::XaResourceManager *in_xa_resource_manager)
bool transaction_rollback_request
Definition session.h:542
drizzle_system_variables & variables
Definition session.h:195
void setStatementMessage(message::Statement *in_message)
Definition session.h:922
void setTransactionMessage(message::Transaction *in_message)
Definition session.h:911
void registerResource(ResourceContext *resource)
static bool insertRecord(Session &, Table &in_table)
static bool sendShutdownEvent(Session &)
static void rawStatement(Session &, const std::string &query, const std::string &schema)
static void finalizeStatementMessage(message::Statement &, Session &)
static void setUpdateHeader(message::Statement &, const Session &, Table &, const unsigned char *old_record, const unsigned char *new_record)
static int commitTransaction(Session &, bool all)
static void createTable(Session &, const message::Table &)
static message::Statement & getInsertStatement(Session &, Table &, uint32_t *next_segment_id)
static void registerResourceForStatement(Session &, plugin::MonitoredInTransaction *, plugin::TransactionalStorageEngine *)
static void initStatementMessage(message::Statement &, message::Statement::Type type, const Session &)
static message::Statement & getDeleteStatement(Session &, Table &, uint32_t *next_segment_id)
static message::Transaction * segmentTransactionMessage(Session &, message::Transaction *)
static bool isFieldUpdated(Field *current_field, Table &, const unsigned char *old_record, const unsigned char *new_record)
static int commitPhaseOne(Session &, bool all)
static void setDeleteHeader(message::Statement &, const Session &, Table &)
static int commitTransactionMessage(Session &)
static void rollbackStatementMessage(Session &)
static void registerResourceForTransaction(Session &, plugin::MonitoredInTransaction *, plugin::TransactionalStorageEngine *)
static void deleteRecord(Session &, Table &, bool use_update_record=false)
static void truncateTable(Session &, Table &)
static void alterSchema(Session &, const message::Schema &old_schema, const message::Schema &new_schema)
static void dropSchema(Session &, const identifier::Schema &identifier, message::schema::const_reference schema)
static void createSchema(Session &, const message::Schema &schema)
static void cleanupTransactionMessage(message::Transaction *transaction, Session &)
static void setInsertHeader(message::Statement &, const Session &, Table &)
static void rollbackTransactionMessage(Session &)
static void initTransactionMessage(message::Transaction &, Session &, bool should_inc_trx_id)
static int setSavepoint(Session &, NamedSavepoint &sv)
static bool sendStartupEvent(Session &)
static message::Transaction * getActiveTransactionMessage(Session &, bool should_inc_trx_id=true)
static message::Statement & getUpdateStatement(Session &, Table &, const unsigned char *old_record, const unsigned char *new_record, uint32_t *next_segment_id)
static void updateRecord(Session &, Table &, const unsigned char *old_record, const unsigned char *new_record)
static int autocommitOrRollback(Session &, int error)
static void dropTable(Session &, const identifier::Table &identifier, message::table::const_reference table, bool if_exists)
static int sendEvent(Session &, const message::Event &event)
static void finalizeTransactionMessage(message::Transaction &, const Session &)
virtual bool participatesInSqlTransaction() const =0
virtual bool participatesInXaTransaction() const =0
Convert from decimal to binary representation.
Definition common_fwd.h:215
TODO: Rename this file - func.h is stupid.
STL namespace.
bool transactionContainsBulkSegment(const Transaction &transaction)