~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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Copyright (C) 2008 Sun Microsystems, Inc.
 *  Copyright (C) 2010 Jay Pipes <jaypipes@gmail.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 Transaction processing code
 *
 * @note
 *
 * The TransactionServices component takes internal events (for instance the start of a 
 * transaction, the changing of a record, or the rollback of a transaction) 
 * and constructs GPB Messages that are passed to the ReplicationServices
 * component and used during replication.
 *
 * 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/current_session.h>
#include <drizzled/error.h>
#include <drizzled/gettext.h>
#include <drizzled/probes.h>
#include <drizzled/sql_parse.h>
#include <drizzled/session.h>
#include <drizzled/session/times.h>
#include <drizzled/sql_base.h>
#include <drizzled/replication_services.h>
#include <drizzled/transaction_services.h>
#include <drizzled/transaction_context.h>
#include <drizzled/message/transaction.pb.h>
#include <drizzled/message/statement_transform.h>
#include <drizzled/resource_context.h>
#include <drizzled/lock.h>
#include <drizzled/item/int.h>
#include <drizzled/item/empty_string.h>
#include <drizzled/field/epoch.h>
#include <drizzled/plugin/client.h>
#include <drizzled/plugin/monitored_in_transaction.h>
#include <drizzled/plugin/transactional_storage_engine.h>
#include <drizzled/plugin/xa_resource_manager.h>
#include <drizzled/plugin/xa_storage_engine.h>
#include <drizzled/internal/my_sys.h>
#include <drizzled/statistics_variables.h>
#include <drizzled/system_variables.h>
#include <drizzled/session/transactions.h>

#include <vector>
#include <algorithm>
#include <functional>
#include <google/protobuf/repeated_field.h>

using namespace std;
using namespace google;

namespace drizzled {

/**
 * @defgroup Transactions
 *
 * @brief
 *
 * Transaction handling in the server
 *
 * @detail
 *
 * In each client connection, Drizzle maintains two transaction
 * contexts representing the state of the:
 *
 * 1) Statement Transaction
 * 2) Normal Transaction
 *
 * These two transaction contexts represent the transactional
 * state of a Session's SQL and XA transactions for a single
 * SQL statement or a series of SQL statements.
 *
 * When the Session's connection is in AUTOCOMMIT mode, there
 * is no practical difference between the statement and the
 * normal transaction, as each SQL statement is committed or
 * rolled back depending on the success or failure of the
 * indvidual SQL statement.
 *
 * When the Session's connection is NOT in AUTOCOMMIT mode, OR
 * the Session has explicitly begun a normal SQL transaction using
 * a BEGIN WORK/START TRANSACTION statement, then the normal
 * transaction context tracks the aggregate transaction state of
 * the SQL transaction's individual statements, and the SQL
 * transaction's commit or rollback is done atomically for all of
 * the SQL transaction's statement's data changes.
 *
 * Technically, a statement transaction can be viewed as a savepoint 
 * which is maintained automatically in order to make effects of one
 * statement atomic.
 *
 * The normal transaction is started by the user and is typically
 * ended (COMMIT or ROLLBACK) upon an explicity user request as well.
 * The exception to this is that DDL statements implicitly COMMIT
 * any previously active normal transaction before they begin executing.
 *
 * In Drizzle, unlike MySQL, plugins other than a storage engine
 * may participate in a transaction.  All plugin::TransactionalStorageEngine
 * plugins will automatically be monitored by Drizzle's transaction 
 * manager (implemented in this source file), as will all plugins which
 * implement plugin::XaResourceManager and register with the transaction
 * manager.
 *
 * If Drizzle's transaction manager sees that more than one resource
 * manager (transactional storage engine or XA resource manager) has modified
 * data state during a statement or normal transaction, the transaction
 * manager will automatically use a two-phase commit protocol for all
 * resources which support XA's distributed transaction protocol.  Unlike
 * MySQL, storage engines need not manually register with the transaction
 * manager during a statement's execution.  Previously, in MySQL, all
 * handlertons would have to call trans_register_ha() at some point after
 * modifying data state in order to have MySQL include that handler in
 * an XA transaction.  Drizzle does all of this grunt work behind the
 * scenes for the storage engine implementers.
 *
 * When a connection is closed, the current normal transaction, if
 * any is currently active, is rolled back.
 *
 * Transaction life cycle
 * ----------------------
 *
 * When a new connection is established, session->transaction
 * members are initialized to an empty state. If a statement uses any tables, 
 * all affected engines are registered in the statement engine list automatically
 * in plugin::StorageEngine::startStatement() and 
 * plugin::TransactionalStorageEngine::startTransaction().
 *
 * You can view the lifetime of a normal transaction in the following
 * call-sequence:
 *
 * drizzled::statement::Statement::execute()
 *   drizzled::plugin::TransactionalStorageEngine::startTransaction()
 *     drizzled::TransactionServices::registerResourceForTransaction()
 *     drizzled::TransactionServices::registerResourceForStatement()
 *     drizzled::plugin::StorageEngine::startStatement()
 *       drizzled::Cursor::write_row() <-- example...could be update_row(), etc
 *     drizzled::plugin::StorageEngine::endStatement()
 *   drizzled::TransactionServices::autocommitOrRollback()
 *     drizzled::TransactionalStorageEngine::commit() <-- or ::rollback()
 *     drizzled::XaResourceManager::xaCommit() <-- or rollback()
 *
 * Roles and responsibilities
 * --------------------------
 *
 * Beginning of SQL Statement (and Statement Transaction)
 * ------------------------------------------------------
 *
 * At the start of each SQL statement, for each storage engine
 * <strong>that is involved in the SQL statement</strong>, the kernel 
 * calls the engine's plugin::StoragEngine::startStatement() method.  If the
 * engine needs to track some data for the statement, it should use
 * this method invocation to initialize this data.  This is the
 * beginning of what is called the "statement transaction".
 *
 * <strong>For transaction storage engines (those storage engines
 * that inherit from plugin::TransactionalStorageEngine)</strong>, the
 * kernel automatically determines if the start of the SQL statement 
 * transaction should <em>also</em> begin the normal SQL transaction.
 * This occurs when the connection is in NOT in autocommit mode. If
 * the kernel detects this, then the kernel automatically starts the
 * normal transaction w/ plugin::TransactionalStorageEngine::startTransaction()
 * method and then calls plugin::StorageEngine::startStatement()
 * afterwards.
 *
 * Beginning of an SQL "Normal" Transaction
 * ----------------------------------------
 *
 * As noted above, a "normal SQL transaction" may be started when
 * an SQL statement is started in a connection and the connection is
 * NOT in AUTOCOMMIT mode.  This is automatically done by the kernel.
 *
 * In addition, when a user executes a START TRANSACTION or
 * BEGIN WORK statement in a connection, the kernel explicitly
 * calls each transactional storage engine's startTransaction() method.
 *
 * Ending of an SQL Statement (and Statement Transaction)
 * ------------------------------------------------------
 *
 * At the end of each SQL statement, for each of the aforementioned
 * involved storage engines, the kernel calls the engine's
 * plugin::StorageEngine::endStatement() method.  If the engine
 * has initialized or modified some internal data about the
 * statement transaction, it should use this method to reset or destroy
 * this data appropriately.
 *
 * Ending of an SQL "Normal" Transaction
 * -------------------------------------
 *
 * The end of a normal transaction is either a ROLLBACK or a COMMIT, 
 * depending on the success or failure of the statement transaction(s) 
 * it encloses.
 *
 * The end of a "normal transaction" occurs when any of the following
 * occurs:
 *
 * 1) If a statement transaction has completed and AUTOCOMMIT is ON,
 *    then the normal transaction which encloses the statement
 *    transaction ends
 * 2) If a COMMIT or ROLLBACK statement occurs on the connection
 * 3) Just before a DDL operation occurs, the kernel will implicitly
 *    commit the active normal transaction
 *
 * Transactions and Non-transactional Storage Engines
 * --------------------------------------------------
 *
 * For non-transactional engines, this call can be safely ignored, an
 * the kernel tracks whether a non-transactional engine has changed
 * any data state, and warns the user appropriately if a transaction
 * (statement or normal) is rolled back after such non-transactional
 * data changes have been made.
 *
 * XA Two-phase Commit Protocol
 * ----------------------------
 *
 * During statement execution, whenever any of data-modifying
 * PSEA API methods is used, e.g. Cursor::write_row() or
 * Cursor::update_row(), the read-write flag is raised in the
 * statement transaction for the involved engine.
 * Currently All PSEA calls are "traced", and the data can not be
 * changed in a way other than issuing a PSEA call. Important:
 * unless this invariant is preserved the server will not know that
 * a transaction in a given engine is read-write and will not
 * involve the two-phase commit protocol!
 *
 * At the end of a statement, TransactionServices::autocommitOrRollback()
 * is invoked. This call in turn
 * invokes plugin::XaResourceManager::xapPepare() for every involved XA
 * resource manager.
 *
 * Prepare is followed by a call to plugin::TransactionalStorageEngine::commit()
 * or plugin::XaResourceManager::xaCommit() (depending on what the resource
 * is...)
 * 
 * If a one-phase commit will suffice, plugin::StorageEngine::prepare() is not
 * invoked and the server only calls plugin::StorageEngine::commit_one_phase().
 * At statement commit, the statement-related read-write engine
 * flag is propagated to the corresponding flag in the normal
 * transaction.  When the commit is complete, the list of registered
 * engines is cleared.
 *
 * Rollback is handled in a similar fashion.
 *
 * Additional notes on DDL and the normal transaction.
 * ---------------------------------------------------
 *
 * CREATE TABLE .. SELECT can start a *new* normal transaction
 * because of the fact that SELECTs on a transactional storage
 * engine participate in the normal SQL transaction (due to
 * isolation level issues and consistent read views).
 *
 * Behaviour of the server in this case is currently badly
 * defined.
 *
 * DDL statements use a form of "semantic" logging
 * to maintain atomicity: if CREATE TABLE .. SELECT failed,
 * the newly created table is deleted.
 * 
 * In addition, some DDL statements issue interim transaction
 * commits: e.g. ALTER TABLE issues a COMMIT after data is copied
 * from the original table to the internal temporary table. Other
 * statements, e.g. CREATE TABLE ... SELECT do not always commit
 * after itself.
 *
 * And finally there is a group of DDL statements such as
 * RENAME/DROP TABLE that doesn't start a new transaction
 * and doesn't commit.
 *
 * A consistent behaviour is perhaps to always commit the normal
 * transaction after all DDLs, just like the statement transaction
 * is always committed at the end of all statements.
 */
TransactionServices::TransactionServices()
{
  xa_storage_engine= static_cast<plugin::XaStorageEngine*>(plugin::StorageEngine::findByName("InnoDB"));
}

void TransactionServices::registerResourceForStatement(Session& session,
                                                       plugin::MonitoredInTransaction *monitored,
                                                       plugin::TransactionalStorageEngine *engine)
{
  if (session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
  {
    /* 
     * Now we automatically register this resource manager for the
     * normal transaction.  This is fine because a statement
     * transaction registration should always enlist the resource
     * in the normal transaction which contains the statement
     * transaction.
     */
    registerResourceForTransaction(session, monitored, engine);
  }

  TransactionContext *trans= &session.transaction.stmt;
  ResourceContext& resource_context= session.getResourceContext(*monitored, 0);

  if (resource_context.isStarted())
    return; /* already registered, return */

  assert(monitored->participatesInSqlTransaction());
  assert(not monitored->participatesInXaTransaction());

  resource_context.setMonitored(monitored);
  resource_context.setTransactionalStorageEngine(engine);
  trans->registerResource(&resource_context);

  trans->no_2pc= true;
}

void TransactionServices::registerResourceForStatement(Session& session,
                                                       plugin::MonitoredInTransaction *monitored,
                                                       plugin::TransactionalStorageEngine *engine,
                                                       plugin::XaResourceManager *resource_manager)
{
  if (session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
  {
    /* 
     * Now we automatically register this resource manager for the
     * normal transaction.  This is fine because a statement
     * transaction registration should always enlist the resource
     * in the normal transaction which contains the statement
     * transaction.
     */
    registerResourceForTransaction(session, monitored, engine, resource_manager);
  }

  TransactionContext *trans= &session.transaction.stmt;
  ResourceContext& resource_context= session.getResourceContext(*monitored, 0);

  if (resource_context.isStarted())
    return; /* already registered, return */

  assert(monitored->participatesInXaTransaction());
  assert(monitored->participatesInSqlTransaction());

  resource_context.setMonitored(monitored);
  resource_context.setTransactionalStorageEngine(engine);
  resource_context.setXaResourceManager(resource_manager);
  trans->registerResource(&resource_context);
}

void TransactionServices::registerResourceForTransaction(Session& session,
                                                         plugin::MonitoredInTransaction *monitored,
                                                         plugin::TransactionalStorageEngine *engine)
{
  TransactionContext *trans= &session.transaction.all;
  ResourceContext& resource_context= session.getResourceContext(*monitored, 1);

  if (resource_context.isStarted())
    return; /* already registered, return */

  session.server_status|= SERVER_STATUS_IN_TRANS;

  trans->registerResource(&resource_context);

  assert(monitored->participatesInSqlTransaction());
  assert(not monitored->participatesInXaTransaction());

  resource_context.setMonitored(monitored);
  resource_context.setTransactionalStorageEngine(engine);
  trans->no_2pc= true;

  if (session.transaction.xid_state.xid.is_null())
    session.transaction.xid_state.xid.set(session.getQueryId());

  /* Only true if user is executing a BEGIN WORK/START TRANSACTION */
  if (not session.getResourceContext(*monitored, 0).isStarted())
    registerResourceForStatement(session, monitored, engine);
}

void TransactionServices::registerResourceForTransaction(Session& session,
                                                         plugin::MonitoredInTransaction *monitored,
                                                         plugin::TransactionalStorageEngine *engine,
                                                         plugin::XaResourceManager *resource_manager)
{
  TransactionContext *trans= &session.transaction.all;
  ResourceContext& resource_context= session.getResourceContext(*monitored, 1);

  if (resource_context.isStarted())
    return; /* already registered, return */

  session.server_status|= SERVER_STATUS_IN_TRANS;

  trans->registerResource(&resource_context);

  assert(monitored->participatesInSqlTransaction());

  resource_context.setMonitored(monitored);
  resource_context.setXaResourceManager(resource_manager);
  resource_context.setTransactionalStorageEngine(engine);
  trans->no_2pc= true;

  if (session.transaction.xid_state.xid.is_null())
    session.transaction.xid_state.xid.set(session.getQueryId());

  engine->startTransaction(&session, START_TRANS_NO_OPTIONS);

  /* Only true if user is executing a BEGIN WORK/START TRANSACTION */
  if (! session.getResourceContext(*monitored, 0).isStarted())
    registerResourceForStatement(session, monitored, engine, resource_manager);
}

void TransactionServices::allocateNewTransactionId()
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
  {
    return;
  }

  Session *my_session= current_session;
  uint64_t xa_id= xa_storage_engine->getNewTransactionId(my_session);
  my_session->setXaId(xa_id);
}

uint64_t TransactionServices::getCurrentTransactionId(Session& session)
{
  if (session.getXaId() == 0)
  {
    session.setXaId(xa_storage_engine->getNewTransactionId(&session)); 
  }

  return session.getXaId();
}

int TransactionServices::commitTransaction(Session& session,
                                           bool normal_transaction)
{
  int error= 0, cookie= 0;
  /*
    'all' means that this is either an explicit commit issued by
    user, or an implicit commit issued by a DDL.
  */
  TransactionContext *trans= normal_transaction ? &session.transaction.all : &session.transaction.stmt;
  TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();

  bool is_real_trans= normal_transaction || session.transaction.all.getResourceContexts().empty();

  /*
    We must not commit the normal transaction if a statement
    transaction is pending. Otherwise statement transaction
    flags will not get propagated to its normal transaction's
    counterpart.
  */
  assert(session.transaction.stmt.getResourceContexts().empty() ||
              trans == &session.transaction.stmt);

  if (resource_contexts.empty() == false)
  {
    if (is_real_trans && session.wait_if_global_read_lock(false, false))
    {
      rollbackTransaction(session, normal_transaction);
      return 1;
    }

    /*
     * If replication is on, we do a PREPARE on the resource managers, push the
     * Transaction message across the replication stream, and then COMMIT if the
     * replication stream returned successfully.
     */
    if (shouldConstructMessages())
    {
      for (TransactionContext::ResourceContexts::iterator it= resource_contexts.begin();
           it != resource_contexts.end() && ! error;
           ++it)
      {
        ResourceContext *resource_context= *it;
        int err;
        /*
          Do not call two-phase commit if this particular
          transaction is read-only. This allows for simpler
          implementation in engines that are always read-only.
        */
        if (! resource_context->hasModifiedData())
          continue;

        plugin::MonitoredInTransaction *resource= resource_context->getMonitored();

        if (resource->participatesInXaTransaction())
        {
          if ((err= resource_context->getXaResourceManager()->xaPrepare(&session, normal_transaction)))
          {
            my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
            error= 1;
          }
          else
          {
            session.status_var.ha_prepare_count++;
          }
        }
      }
      if (error == 0 && is_real_trans)
      {
        /*
         * Push the constructed Transaction messages across to
         * replicators and appliers.
         */
        error= commitTransactionMessage(session);
      }
      if (error)
      {
        rollbackTransaction(session, normal_transaction);
        error= 1;
        goto end;
      }
    }
    error= commitPhaseOne(session, normal_transaction) ? (cookie ? 2 : 1) : 0;
end:
    if (is_real_trans)
      session.startWaitingGlobalReadLock();
  }
  return error;
}

/**
  @note
  This function does not care about global read lock. A caller should.
*/
int TransactionServices::commitPhaseOne(Session& session,
                                        bool normal_transaction)
{
  int error=0;
  TransactionContext *trans= normal_transaction ? &session.transaction.all : &session.transaction.stmt;
  TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();

  bool is_real_trans= normal_transaction || session.transaction.all.getResourceContexts().empty();
  bool all= normal_transaction;

  /* If we're in autocommit then we have a real transaction to commit
     (except if it's BEGIN)
  */
  if (! session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
    all= true;

  if (resource_contexts.empty() == false)
  {
    for (TransactionContext::ResourceContexts::iterator it= resource_contexts.begin();
         it != resource_contexts.end();
         ++it)
    {
      int err;
      ResourceContext *resource_context= *it;

      plugin::MonitoredInTransaction *resource= resource_context->getMonitored();

      if (resource->participatesInXaTransaction())
      {
        if ((err= resource_context->getXaResourceManager()->xaCommit(&session, all)))
        {
          my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
          error= 1;
        }
        else if (normal_transaction)
        {
          session.status_var.ha_commit_count++;
        }
      }
      else if (resource->participatesInSqlTransaction())
      {
        if ((err= resource_context->getTransactionalStorageEngine()->commit(&session, all)))
        {
          my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
          error= 1;
        }
        else if (normal_transaction)
        {
          session.status_var.ha_commit_count++;
        }
      }
      resource_context->reset(); /* keep it conveniently zero-filled */
    }

    if (is_real_trans)
      session.transaction.xid_state.xid.set_null();

    if (normal_transaction)
    {
      session.variables.tx_isolation= session.session_tx_isolation;
      session.transaction.cleanup();
    }
  }
  trans->reset();
  return error;
}

int TransactionServices::rollbackTransaction(Session& session,
                                             bool normal_transaction)
{
  int error= 0;
  TransactionContext *trans= normal_transaction ? &session.transaction.all : &session.transaction.stmt;
  TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();

  bool is_real_trans= normal_transaction || session.transaction.all.getResourceContexts().empty();
  bool all = normal_transaction || !session_test_options(&session, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN);

  /*
    We must not rollback the normal transaction if a statement
    transaction is pending.
  */
  assert(session.transaction.stmt.getResourceContexts().empty() ||
              trans == &session.transaction.stmt);

  if (resource_contexts.empty() == false)
  {
    for (TransactionContext::ResourceContexts::iterator it= resource_contexts.begin();
         it != resource_contexts.end();
         ++it)
    {
      int err;
      ResourceContext *resource_context= *it;

      plugin::MonitoredInTransaction *resource= resource_context->getMonitored();

      if (resource->participatesInXaTransaction())
      {
        if ((err= resource_context->getXaResourceManager()->xaRollback(&session, all)))
        {
          my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
          error= 1;
        }
        else if (normal_transaction)
        {
          session.status_var.ha_rollback_count++;
        }
      }
      else if (resource->participatesInSqlTransaction())
      {
        if ((err= resource_context->getTransactionalStorageEngine()->rollback(&session, all)))
        {
          my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
          error= 1;
        }
        else if (normal_transaction)
        {
          session.status_var.ha_rollback_count++;
        }
      }
      resource_context->reset(); /* keep it conveniently zero-filled */
    }
    
    /* 
     * We need to signal the ROLLBACK to ReplicationServices here
     * BEFORE we set the transaction ID to NULL.  This is because
     * if a bulk segment was sent to replicators, we need to send
     * a rollback statement with the corresponding transaction ID
     * to rollback.
     */
    if (all)
      rollbackTransactionMessage(session);
    else
      rollbackStatementMessage(session);

    if (is_real_trans)
      session.transaction.xid_state.xid.set_null();
    if (normal_transaction)
    {
      session.variables.tx_isolation=session.session_tx_isolation;
      session.transaction.cleanup();
    }
  }
  if (normal_transaction)
    session.transaction_rollback_request= false;

  /*
   * If a non-transactional table was updated, warn the user
   */
  if (is_real_trans &&
      session.transaction.all.hasModifiedNonTransData() &&
      session.getKilled() != Session::KILL_CONNECTION)
  {
    push_warning(&session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
                 ER_WARNING_NOT_COMPLETE_ROLLBACK,
                 ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
  }
  trans->reset();
  return error;
}

int TransactionServices::autocommitOrRollback(Session& session,
                                              int error)
{
  /* One GPB Statement message per SQL statement */
  message::Statement *statement= session.getStatementMessage();
  if ((statement != NULL) && (! error))
    finalizeStatementMessage(*statement, session);

  if (session.transaction.stmt.getResourceContexts().empty() == false)
  {
    TransactionContext *trans = &session.transaction.stmt;
    TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();
    for (TransactionContext::ResourceContexts::iterator it= resource_contexts.begin();
         it != resource_contexts.end();
         ++it)
    {
      ResourceContext *resource_context= *it;

      resource_context->getTransactionalStorageEngine()->endStatement(&session);
    }

    if (! error)
    {
      if (commitTransaction(session, false))
        error= 1;
    }
    else
    {
      (void) rollbackTransaction(session, false);
      if (session.transaction_rollback_request)
      {
        (void) rollbackTransaction(session, true);
        session.server_status&= ~SERVER_STATUS_IN_TRANS;
      }
    }

    session.variables.tx_isolation= session.session_tx_isolation;
  }

  return error;
}

struct ResourceContextCompare : public std::binary_function<ResourceContext *, ResourceContext *, bool>
{
  result_type operator()(const ResourceContext *lhs, const ResourceContext *rhs) const
  {
    /* The below is perfectly fine, since we're simply comparing addresses for the underlying
     * resources aren't the same... */
    return reinterpret_cast<uint64_t>(lhs->getMonitored()) < reinterpret_cast<uint64_t>(rhs->getMonitored());
  }
};

int TransactionServices::rollbackToSavepoint(Session& session,
                                             NamedSavepoint &sv)
{
  int error= 0;
  TransactionContext *trans= &session.transaction.all;
  TransactionContext::ResourceContexts &tran_resource_contexts= trans->getResourceContexts();
  TransactionContext::ResourceContexts &sv_resource_contexts= sv.getResourceContexts();

  trans->no_2pc= false;
  /*
    rolling back to savepoint in all storage engines that were part of the
    transaction when the savepoint was set
  */
  for (TransactionContext::ResourceContexts::iterator it= sv_resource_contexts.begin();
       it != sv_resource_contexts.end();
       ++it)
  {
    int err;
    ResourceContext *resource_context= *it;

    plugin::MonitoredInTransaction *resource= resource_context->getMonitored();

    if (resource->participatesInSqlTransaction())
    {
      if ((err= resource_context->getTransactionalStorageEngine()->rollbackToSavepoint(&session, sv)))
      {
        my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
        error= 1;
      }
      else
      {
        session.status_var.ha_savepoint_rollback_count++;
      }
    }
    trans->no_2pc|= not resource->participatesInXaTransaction();
  }
  /*
    rolling back the transaction in all storage engines that were not part of
    the transaction when the savepoint was set
  */
  {
    TransactionContext::ResourceContexts sorted_tran_resource_contexts(tran_resource_contexts);
    TransactionContext::ResourceContexts sorted_sv_resource_contexts(sv_resource_contexts);
    TransactionContext::ResourceContexts set_difference_contexts;

    /* 
     * Bug #542299: segfault during set_difference() below.  copy<>() requires pre-allocation
     * of all elements, including the target, which is why we pre-allocate the set_difference_contexts
     * here
     */
    set_difference_contexts.reserve(max(tran_resource_contexts.size(), sv_resource_contexts.size()));

    sort(sorted_tran_resource_contexts.begin(),
         sorted_tran_resource_contexts.end(),
         ResourceContextCompare());
    sort(sorted_sv_resource_contexts.begin(),
         sorted_sv_resource_contexts.end(),
         ResourceContextCompare());
    set_difference(sorted_tran_resource_contexts.begin(),
                   sorted_tran_resource_contexts.end(),
                   sorted_sv_resource_contexts.begin(),
                   sorted_sv_resource_contexts.end(),
                   set_difference_contexts.begin(),
                   ResourceContextCompare());
    /* 
     * set_difference_contexts now contains all resource contexts
     * which are in the transaction context but were NOT in the
     * savepoint's resource contexts.
     */
        
    for (TransactionContext::ResourceContexts::iterator it= set_difference_contexts.begin();
         it != set_difference_contexts.end();
         ++it)
    {
      ResourceContext *resource_context= *it;
      int err;

      plugin::MonitoredInTransaction *resource= resource_context->getMonitored();

      if (resource->participatesInSqlTransaction())
      {
        if ((err= resource_context->getTransactionalStorageEngine()->rollback(&session, !(0))))
        {
          my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
          error= 1;
        }
        else
        {
          session.status_var.ha_rollback_count++;
        }
      }
      resource_context->reset(); /* keep it conveniently zero-filled */
    }
  }
  trans->setResourceContexts(sv_resource_contexts);

  if (shouldConstructMessages())
  {
    cleanupTransactionMessage(getActiveTransactionMessage(session), session);
    message::Transaction *savepoint_transaction= sv.getTransactionMessage();
    if (savepoint_transaction != NULL)
    {
      /* Make a copy of the savepoint transaction, this is necessary to assure proper cleanup. 
         Upon commit the savepoint_transaction_copy will be cleaned up by a call to 
         cleanupTransactionMessage(). The Transaction message in NamedSavepoint will be cleaned
         up when the savepoint is cleaned up. This avoids calling delete twice on the Transaction.
      */ 
      message::Transaction *savepoint_transaction_copy= new message::Transaction(*sv.getTransactionMessage());
      uint32_t num_statements = savepoint_transaction_copy->statement_size();
      if (num_statements == 0)
      {    
        session.setStatementMessage(NULL);
      }    
      else 
      {
        session.setStatementMessage(savepoint_transaction_copy->mutable_statement(num_statements - 1));    
      }    
      session.setTransactionMessage(savepoint_transaction_copy);
    }
  }

  return error;
}

/**
  @note
  according to the sql standard (ISO/IEC 9075-2:2003)
  section "4.33.4 SQL-statements and transaction states",
  NamedSavepoint is *not* transaction-initiating SQL-statement
*/
int TransactionServices::setSavepoint(Session& session,
                                      NamedSavepoint &sv)
{
  int error= 0;
  TransactionContext *trans= &session.transaction.all;
  TransactionContext::ResourceContexts &resource_contexts= trans->getResourceContexts();

  if (resource_contexts.empty() == false)
  {
    for (TransactionContext::ResourceContexts::iterator it= resource_contexts.begin();
         it != resource_contexts.end();
         ++it)
    {
      ResourceContext *resource_context= *it;
      int err;

      plugin::MonitoredInTransaction *resource= resource_context->getMonitored();

      if (resource->participatesInSqlTransaction())
      {
        if ((err= resource_context->getTransactionalStorageEngine()->setSavepoint(&session, sv)))
        {
          my_error(ER_GET_ERRNO, MYF(0), err);
          error= 1;
        }
        else
        {
          session.status_var.ha_savepoint_count++;
        }
      }
    }
  }
  /*
    Remember the list of registered storage engines.
  */
  sv.setResourceContexts(resource_contexts);

  if (shouldConstructMessages())
  {
    message::Transaction *transaction= session.getTransactionMessage();
                  
    if (transaction != NULL)
    {
      message::Transaction *transaction_savepoint= 
        new message::Transaction(*transaction);
      sv.setTransactionMessage(transaction_savepoint);
    }
  } 

  return error;
}

int TransactionServices::releaseSavepoint(Session& session,
                                          NamedSavepoint &sv)
{
  int error= 0;

  TransactionContext::ResourceContexts &resource_contexts= sv.getResourceContexts();

  for (TransactionContext::ResourceContexts::iterator it= resource_contexts.begin();
       it != resource_contexts.end();
       ++it)
  {
    int err;
    ResourceContext *resource_context= *it;

    plugin::MonitoredInTransaction *resource= resource_context->getMonitored();

    if (resource->participatesInSqlTransaction())
    {
      if ((err= resource_context->getTransactionalStorageEngine()->releaseSavepoint(&session, sv)))
      {
        my_error(ER_GET_ERRNO, MYF(0), err);
        error= 1;
      }
    }
  }
  
  return error;
}

bool TransactionServices::shouldConstructMessages()
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  return replication_services.isActive();
}

message::Transaction *TransactionServices::getActiveTransactionMessage(Session& session,
                                                                       bool should_inc_trx_id)
{
  message::Transaction *transaction= 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 message::Transaction();
    initTransactionMessage(*transaction, session, should_inc_trx_id);
    session.setTransactionMessage(transaction);
  }
  return transaction;
}

void TransactionServices::initTransactionMessage(message::Transaction &transaction,
                                                 Session& session,
                                                 bool should_inc_trx_id)
{
  message::TransactionContext *trx= transaction.mutable_transaction_context();
  trx->set_server_id(session.getServerId());

  if (should_inc_trx_id)
  {
    trx->set_transaction_id(getCurrentTransactionId(session));
    session.setXaId(0);
  }
  else
  {
    /* trx and seg id will get set properly elsewhere */
    trx->set_transaction_id(0);
  }

  trx->set_start_timestamp(session.times.getCurrentTimestamp());
  
  /* segment info may get set elsewhere as needed */
  transaction.set_segment_id(1);
  transaction.set_end_segment(true);
}

void TransactionServices::finalizeTransactionMessage(message::Transaction &transaction,
                                                     const Session& session)
{
  message::TransactionContext *trx= transaction.mutable_transaction_context();
  trx->set_end_timestamp(session.times.getCurrentTimestamp());
}

void TransactionServices::cleanupTransactionMessage(message::Transaction *transaction,
                                                    Session& session)
{
  delete transaction;
  session.setStatementMessage(NULL);
  session.setTransactionMessage(NULL);
  session.setXaId(0);
}

int TransactionServices::commitTransactionMessage(Session& session)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return 0;

  /*
   * If no Transaction message was ever created, then no data modification
   * occurred inside the transaction, so nothing to do.
   */
  if (session.getTransactionMessage() == NULL)
    return 0;
  
  /* If there is an active statement message, finalize it. */
  message::Statement *statement= session.getStatementMessage();

  if (statement != NULL)
  {
    finalizeStatementMessage(*statement, session);
  }

  message::Transaction* transaction= getActiveTransactionMessage(session);

  /*
   * It is possible that we could have a Transaction without any Statements
   * if we had created a Statement but had to roll it back due to it failing
   * mid-execution, and no subsequent Statements were added to the Transaction
   * message. In this case, we simply clean up the message and not push it.
   */
  if (transaction->statement_size() == 0)
  {
    cleanupTransactionMessage(transaction, session);
    return 0;
  }
  
  finalizeTransactionMessage(*transaction, session);
  
  plugin::ReplicationReturnCode result= replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);

  return static_cast<int>(result);
}

void TransactionServices::initStatementMessage(message::Statement &statement,
                                               message::Statement::Type type,
                                               const Session& session)
{
  statement.set_type(type);
  statement.set_start_timestamp(session.times.getCurrentTimestamp());

  if (session.variables.replicate_query)
    statement.set_sql(session.getQueryString()->c_str());
}

void TransactionServices::finalizeStatementMessage(message::Statement &statement,
                                                   Session& session)
{
  statement.set_end_timestamp(session.times.getCurrentTimestamp());
  session.setStatementMessage(NULL);
}

void TransactionServices::rollbackTransactionMessage(Session& session)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;
  
  message::Transaction *transaction= getActiveTransactionMessage(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(message::transactionContainsBulkSegment(*transaction)))
  {
    /* Remember the transaction ID so we can re-use it */
    uint64_t trx_id= transaction->transaction_context().transaction_id();
    uint32_t seg_id= transaction->segment_id();

    /*
     * Clear the transaction, create a Rollback statement message, 
     * attach it to the transaction, and push it to replicators.
     */
    transaction->Clear();
    initTransactionMessage(*transaction, session, false);

    /* Set the transaction ID to match the previous messages */
    transaction->mutable_transaction_context()->set_transaction_id(trx_id);
    transaction->set_segment_id(seg_id);
    transaction->set_end_segment(true);

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

    initStatementMessage(*statement, message::Statement::ROLLBACK, session);
    finalizeStatementMessage(*statement, session);

    finalizeTransactionMessage(*transaction, session);
    
    (void) replication_services.pushTransactionMessage(session, *transaction);
  }

  cleanupTransactionMessage(transaction, session);
}

void TransactionServices::rollbackStatementMessage(Session& session)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;

  message::Statement *current_statement= session.getStatementMessage();

  /* If we never added a Statement message, nothing to undo. */
  if (current_statement == NULL)
    return;

  /*
   * If the Statement has been segmented, then we've already pushed a portion
   * of this Statement's row changes through the replication stream and we
   * need to send a ROLLBACK_STATEMENT message. Otherwise, we can simply
   * delete the current Statement message.
   */
  bool is_segmented= false;

  switch (current_statement->type())
  {
    case message::Statement::INSERT:
      if (current_statement->insert_data().segment_id() > 1)
        is_segmented= true;
      break;

    case message::Statement::UPDATE:
      if (current_statement->update_data().segment_id() > 1)
        is_segmented= true;
      break;

    case message::Statement::DELETE:
      if (current_statement->delete_data().segment_id() > 1)
        is_segmented= true;
      break;

    default:
      break;
  }

  /*
   * Remove the Statement message we've been working with (same as
   * current_statement).
   */
  message::Transaction *transaction= getActiveTransactionMessage(session);
  google::protobuf::RepeatedPtrField<message::Statement> *statements_in_txn;
  statements_in_txn= transaction->mutable_statement();
  statements_in_txn->RemoveLast();
  session.setStatementMessage(NULL);
  
  /*
   * Create the ROLLBACK_STATEMENT message, if we need to. This serves as
   * an indicator to cancel the previous Statement message which should have
   * had its end_segment attribute set to false.
   */
  if (is_segmented)
  {
    current_statement= transaction->add_statement();
    initStatementMessage(*current_statement,
                         message::Statement::ROLLBACK_STATEMENT,
                         session);
    finalizeStatementMessage(*current_statement, session);
  }
}

message::Transaction *TransactionServices::segmentTransactionMessage(Session& session,
                                                                     message::Transaction *transaction)
{
  uint64_t trx_id= transaction->transaction_context().transaction_id();
  uint32_t seg_id= transaction->segment_id();
  
  transaction->set_end_segment(false);
  commitTransactionMessage(session);
  transaction= getActiveTransactionMessage(session, false);
  
  /* Set the transaction ID to match the previous messages */
  transaction->mutable_transaction_context()->set_transaction_id(trx_id);
  transaction->set_segment_id(seg_id + 1);
  transaction->set_end_segment(true);

  return transaction;
}

message::Statement &TransactionServices::getInsertStatement(Session& session,
                                                            Table &table,
                                                            uint32_t *next_segment_id)
{
  message::Statement *statement= session.getStatementMessage();
  message::Transaction *transaction= NULL;
  
  /*
   * If statement is NULL, this is a new statement.
   * If statement is NOT NULL, this a continuation of the same statement.
   * This is because autocommitOrRollback() finalizes the statement so that
   * we guarantee only one Statement message per statement (i.e., we no longer
   * share a single GPB message for multiple statements).
   */
  if (statement == NULL)
  {
    transaction= getActiveTransactionMessage(session);

    if (static_cast<size_t>(transaction->ByteSize()) >= 
        transaction_message_threshold)
    {
      transaction= segmentTransactionMessage(session, transaction);
    }

    statement= transaction->add_statement();
    setInsertHeader(*statement, session, table);
    session.setStatementMessage(statement);
  }
  else
  {
    transaction= getActiveTransactionMessage(session);
    
    /*
     * If we've passed our threshold for the statement size (possible for
     * a bulk insert), we'll finalize the Statement and Transaction (doing
     * the Transaction will keep it from getting huge).
     */
    if (static_cast<size_t>(transaction->ByteSize()) >= 
        transaction_message_threshold)
    {
      /* Remember the transaction ID so we can re-use it */
      uint64_t trx_id= transaction->transaction_context().transaction_id();
      uint32_t seg_id= transaction->segment_id();
      
      message::InsertData *current_data= statement->mutable_insert_data();
      
      /* Caller should use this value when adding a new record */
      *next_segment_id= current_data->segment_id() + 1;
      
      current_data->set_end_segment(false);
      transaction->set_end_segment(false);
      
      /* 
       * Send the trx message to replicators after finalizing the 
       * statement and transaction. This will also set the Transaction
       * and Statement objects in Session to NULL.
       */
      commitTransactionMessage(session);
      
      /*
       * Statement and Transaction should now be NULL, so new ones will get
       * created. We reuse the transaction id since we are segmenting
       * one transaction.
       */
      transaction= getActiveTransactionMessage(session, false);
      assert(transaction != NULL);

      statement= transaction->add_statement();
      setInsertHeader(*statement, session, table);
      session.setStatementMessage(statement);
            
      /* Set the transaction ID to match the previous messages */
      transaction->mutable_transaction_context()->set_transaction_id(trx_id);
      transaction->set_segment_id(seg_id + 1);
      transaction->set_end_segment(true);
    }
    else
    {
      /*
       * Continuation of the same statement. Carry forward the existing
       * segment id.
       */
      const message::InsertData &current_data= statement->insert_data();
      *next_segment_id= current_data.segment_id();
    }
  }
  
  return *statement;
}

void TransactionServices::setInsertHeader(message::Statement &statement,
                                          const Session& session,
                                          Table &table)
{
  initStatementMessage(statement, message::Statement::INSERT, 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();

  string schema_name;
  (void) table.getShare()->getSchemaName(schema_name);
  string table_name;
  (void) table.getShare()->getTableName(table_name);

  table_metadata->set_schema_name(schema_name.c_str(), schema_name.length());
  table_metadata->set_table_name(table_name.c_str(), table_name.length());

  Field *current_field;
  Field **table_fields= table.getFields();

  message::FieldMetadata *field_metadata;

  /* We will read all the table's fields... */
  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(message::internalFieldTypeToFieldProtoType(current_field->type()));
  }
}

bool TransactionServices::insertRecord(Session& session,
                                       Table &table)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return false;

  if (not table.getShare()->is_replicated())
    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 (not table.getShare()->hasPrimaryKey())
  {
    my_error(ER_NO_PRIMARY_KEY_ON_REPLICATED_TABLE, MYF(0));
    return true;
  }

  uint32_t next_segment_id= 1;
  message::Statement &statement= getInsertStatement(session, table, &next_segment_id);

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

  Field *current_field;
  Field **table_fields= table.getFields();

  String *string_value= new (session.mem_root) String(TransactionServices::DEFAULT_RECORD_SIZE);
  string_value->set_charset(system_charset_info);

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

  while ((current_field= *table_fields++) != NULL) 
  {
    if (current_field->is_null())
    {
      record->add_is_null(true);
      record->add_insert_value("", 0);
    } 
    else 
    {
      string_value= current_field->val_str_internal(string_value);
      record->add_is_null(false);
      record->add_insert_value(string_value->c_ptr(), string_value->length());
      string_value->free();
    }
  }
  return false;
}

message::Statement &TransactionServices::getUpdateStatement(Session& session,
                                                            Table &table,
                                                            const unsigned char *old_record, 
                                                            const unsigned char *new_record,
                                                            uint32_t *next_segment_id)
{
  message::Statement *statement= session.getStatementMessage();
  message::Transaction *transaction= NULL;

  /*
   * If statement is NULL, this is a new statement.
   * If statement is NOT NULL, this a continuation of the same statement.
   * This is because autocommitOrRollback() finalizes the statement so that
   * we guarantee only one Statement message per statement (i.e., we no longer
   * share a single GPB message for multiple statements).
   */
  if (statement == NULL)
  {
    transaction= getActiveTransactionMessage(session);
    
    if (static_cast<size_t>(transaction->ByteSize()) >= 
        transaction_message_threshold)
    {
      transaction= segmentTransactionMessage(session, transaction);
    }
    
    statement= transaction->add_statement();
    setUpdateHeader(*statement, session, table, old_record, new_record);
    session.setStatementMessage(statement);
  }
  else
  {
    transaction= getActiveTransactionMessage(session);
    
    /*
     * If we've passed our threshold for the statement size (possible for
     * a bulk insert), we'll finalize the Statement and Transaction (doing
     * the Transaction will keep it from getting huge).
     */
    if (static_cast<size_t>(transaction->ByteSize()) >= 
        transaction_message_threshold)
    {
      /* Remember the transaction ID so we can re-use it */
      uint64_t trx_id= transaction->transaction_context().transaction_id();
      uint32_t seg_id= transaction->segment_id();
      
      message::UpdateData *current_data= statement->mutable_update_data();
      
      /* Caller should use this value when adding a new record */
      *next_segment_id= current_data->segment_id() + 1;
      
      current_data->set_end_segment(false);
      transaction->set_end_segment(false);
      
      /* 
       * Send the trx message to replicators after finalizing the 
       * statement and transaction. This will also set the Transaction
       * and Statement objects in Session to NULL.
       */
      commitTransactionMessage(session);
      
      /*
       * Statement and Transaction should now be NULL, so new ones will get
       * created. We reuse the transaction id since we are segmenting
       * one transaction.
       */
      transaction= getActiveTransactionMessage(session, false);
      assert(transaction != NULL);
      
      statement= transaction->add_statement();
      setUpdateHeader(*statement, session, table, old_record, new_record);
      session.setStatementMessage(statement);
      
      /* Set the transaction ID to match the previous messages */
      transaction->mutable_transaction_context()->set_transaction_id(trx_id);
      transaction->set_segment_id(seg_id + 1);
      transaction->set_end_segment(true);
    }
    else
    {
      /*
       * Continuation of the same statement. Carry forward the existing
       * segment id.
       */
      const message::UpdateData &current_data= statement->update_data();
      *next_segment_id= current_data.segment_id();
    }
  }
  
  return *statement;
}

void TransactionServices::setUpdateHeader(message::Statement &statement,
                                          const Session& session,
                                          Table &table,
                                          const unsigned char *old_record, 
                                          const unsigned char *new_record)
{
  initStatementMessage(statement, message::Statement::UPDATE, 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();

  string schema_name;
  (void) table.getShare()->getSchemaName(schema_name);
  string table_name;
  (void) table.getShare()->getTableName(table_name);

  table_metadata->set_schema_name(schema_name.c_str(), schema_name.length());
  table_metadata->set_table_name(table_name.c_str(), table_name.length());

  Field *current_field;
  Field **table_fields= table.getFields();

  message::FieldMetadata *field_metadata;

  /* We will read all the table's fields... */
  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 (table.getShare()->fieldInPrimaryKey(current_field))
    {
      field_metadata= header->add_key_field_metadata();
      field_metadata->set_name(current_field->field_name);
      field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
    }

    if (isFieldUpdated(current_field, table, old_record, new_record))
    {
      /* 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(message::internalFieldTypeToFieldProtoType(current_field->type()));
    }
  }
}

void TransactionServices::updateRecord(Session& session,
                                       Table &table, 
                                       const unsigned char *old_record, 
                                       const unsigned char *new_record)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;

  if (not table.getShare()->is_replicated())
    return;

  uint32_t next_segment_id= 1;
  message::Statement &statement= getUpdateStatement(session, table, old_record, new_record, &next_segment_id);

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

  Field *current_field;
  Field **table_fields= table.getFields();
  String *string_value= new (session.mem_root) String(TransactionServices::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.
     */
    if (isFieldUpdated(current_field, table, old_record, new_record))
    {
      /* 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... */
      table.setReadSet(current_field->position());

      /* Read the string value of this field's contents */
      string_value= current_field->val_str_internal(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);

      if (current_field->is_null())
      {
        record->add_is_null(true);
        record->add_after_value("", 0);
      }
      else
      {
        record->add_is_null(false);
        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 (table.getShare()->fieldInPrimaryKey(current_field))
    {
      /**
       * 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_internal(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();
    }

  }
}

bool TransactionServices::isFieldUpdated(Field *current_field,
                                         Table &table,
                                         const unsigned char *old_record,
                                         const unsigned char *new_record)
{
  /*
   * 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 - table.getInsertRecord());
  const unsigned char *new_ptr= (const unsigned char *) new_record + (ptrdiff_t) (current_field->ptr - table.getInsertRecord());

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

  bool old_value_is_null= current_field->is_null_in_record(old_record);
  bool new_value_is_null= current_field->is_null_in_record(new_record);

  bool isUpdated= false;
  if (old_value_is_null != new_value_is_null)
  {
    if ((old_value_is_null) && (! new_value_is_null)) /* old value is NULL, new value is non NULL */
    {
      isUpdated= true;
    }
    else if ((! old_value_is_null) && (new_value_is_null)) /* old value is non NULL, new value is NULL */
    {
      isUpdated= true;
    }
  }

  if (! isUpdated)
  {
    if (memcmp(old_ptr, new_ptr, field_length) != 0)
    {
      isUpdated= true;
    }
  }
  return isUpdated;
}  

message::Statement &TransactionServices::getDeleteStatement(Session& session,
                                                            Table &table,
                                                            uint32_t *next_segment_id)
{
  message::Statement *statement= session.getStatementMessage();
  message::Transaction *transaction= NULL;

  /*
   * If statement is NULL, this is a new statement.
   * If statement is NOT NULL, this a continuation of the same statement.
   * This is because autocommitOrRollback() finalizes the statement so that
   * we guarantee only one Statement message per statement (i.e., we no longer
   * share a single GPB message for multiple statements).
   */
  if (statement == NULL)
  {
    transaction= getActiveTransactionMessage(session);
    
    if (static_cast<size_t>(transaction->ByteSize()) >= 
        transaction_message_threshold)
    {
      transaction= segmentTransactionMessage(session, transaction);
    }
    
    statement= transaction->add_statement();
    setDeleteHeader(*statement, session, table);
    session.setStatementMessage(statement);
  }
  else
  {
    transaction= getActiveTransactionMessage(session);
    
    /*
     * If we've passed our threshold for the statement size (possible for
     * a bulk insert), we'll finalize the Statement and Transaction (doing
     * the Transaction will keep it from getting huge).
     */
    if (static_cast<size_t>(transaction->ByteSize()) >= 
        transaction_message_threshold)
    {
      /* Remember the transaction ID so we can re-use it */
      uint64_t trx_id= transaction->transaction_context().transaction_id();
      uint32_t seg_id= transaction->segment_id();
      
      message::DeleteData *current_data= statement->mutable_delete_data();
      
      /* Caller should use this value when adding a new record */
      *next_segment_id= current_data->segment_id() + 1;
      
      current_data->set_end_segment(false);
      transaction->set_end_segment(false);
      
      /* 
       * Send the trx message to replicators after finalizing the 
       * statement and transaction. This will also set the Transaction
       * and Statement objects in Session to NULL.
       */
      commitTransactionMessage(session);
      
      /*
       * Statement and Transaction should now be NULL, so new ones will get
       * created. We reuse the transaction id since we are segmenting
       * one transaction.
       */
      transaction= getActiveTransactionMessage(session, false);
      assert(transaction != NULL);
      
      statement= transaction->add_statement();
      setDeleteHeader(*statement, session, table);
      session.setStatementMessage(statement);
      
      /* Set the transaction ID to match the previous messages */
      transaction->mutable_transaction_context()->set_transaction_id(trx_id);
      transaction->set_segment_id(seg_id + 1);
      transaction->set_end_segment(true);
    }
    else
    {
      /*
       * Continuation of the same statement. Carry forward the existing
       * segment id.
       */
      const message::DeleteData &current_data= statement->delete_data();
      *next_segment_id= current_data.segment_id();
    }
  }
  
  return *statement;
}

void TransactionServices::setDeleteHeader(message::Statement &statement,
                                          const Session& session,
                                          Table &table)
{
  initStatementMessage(statement, message::Statement::DELETE, 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();

  string schema_name;
  (void) table.getShare()->getSchemaName(schema_name);
  string table_name;
  (void) table.getShare()->getTableName(table_name);

  table_metadata->set_schema_name(schema_name.c_str(), schema_name.length());
  table_metadata->set_table_name(table_name.c_str(), table_name.length());

  Field *current_field;
  Field **table_fields= table.getFields();

  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 (table.getShare()->fieldInPrimaryKey(current_field))
    {
      field_metadata= header->add_key_field_metadata();
      field_metadata->set_name(current_field->field_name);
      field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
    }
  }
}

void TransactionServices::deleteRecord(Session& session,
                                       Table &table,
                                       bool use_update_record)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;

  if (not table.getShare()->is_replicated())
    return;

  uint32_t next_segment_id= 1;
  message::Statement &statement= getDeleteStatement(session, table, &next_segment_id);

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

  Field *current_field;
  Field **table_fields= table.getFields();
  String *string_value= new (session.mem_root) String(TransactionServices::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 (table.getShare()->fieldInPrimaryKey(current_field))
    {
      if (use_update_record)
      {
        /*
         * Temporarily point to the update record to get its value.
         * This is pretty much a hack in order to get the PK value from
         * the update record rather than the insert record. Field::val_str()
         * should not change anything in Field::ptr, so this should be safe.
         * We are careful not to change anything in old_ptr.
         */
        const unsigned char *old_ptr= current_field->ptr;
        current_field->ptr= table.getUpdateRecord() + static_cast<ptrdiff_t>(old_ptr - table.getInsertRecord());
        string_value= current_field->val_str_internal(string_value);
        current_field->ptr= const_cast<unsigned char *>(old_ptr);
      }
      else
      {
        string_value= current_field->val_str_internal(string_value);
        /**
         * @TODO Store optional old record value in the before data member
         */
      }
      record->add_key_value(string_value->c_ptr(), string_value->length());
      string_value->free();
    }
  }
}

void TransactionServices::createTable(Session& session,
                                      const message::Table &table)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (not replication_services.isActive())
    return;

  if (not message::is_replicated(table))
    return;

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

  initStatementMessage(*statement, message::Statement::CREATE_TABLE, session);

  /* 
   * Construct the specialized CreateTableStatement message and attach
   * it to the generic Statement message
   */
  message::CreateTableStatement *create_table_statement= statement->mutable_create_table_statement();
  message::Table *new_table_message= create_table_statement->mutable_table();
  *new_table_message= table;

  finalizeStatementMessage(*statement, session);

  finalizeTransactionMessage(*transaction, session);
  
  (void) replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);

}

void TransactionServices::createSchema(Session& session,
                                       const message::Schema &schema)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;

  if (not message::is_replicated(schema))
    return;

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

  initStatementMessage(*statement, message::Statement::CREATE_SCHEMA, session);

  /* 
   * Construct the specialized CreateSchemaStatement message and attach
   * it to the generic Statement message
   */
  message::CreateSchemaStatement *create_schema_statement= statement->mutable_create_schema_statement();
  message::Schema *new_schema_message= create_schema_statement->mutable_schema();
  *new_schema_message= schema;

  finalizeStatementMessage(*statement, session);

  finalizeTransactionMessage(*transaction, session);
  
  (void) replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);

}

void TransactionServices::dropSchema(Session& session,
                                     const identifier::Schema& identifier,
                                     message::schema::const_reference schema)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (not replication_services.isActive())
    return;

  if (not message::is_replicated(schema))
    return;

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

  initStatementMessage(*statement, message::Statement::DROP_SCHEMA, session);

  /* 
   * Construct the specialized DropSchemaStatement message and attach
   * it to the generic Statement message
   */
  message::DropSchemaStatement *drop_schema_statement= statement->mutable_drop_schema_statement();

  drop_schema_statement->set_schema_name(identifier.getSchemaName());

  finalizeStatementMessage(*statement, session);

  finalizeTransactionMessage(*transaction, session);
  
  (void) replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);
}

void TransactionServices::alterSchema(Session& session,
                                      const message::Schema &old_schema,
                                      const message::Schema &new_schema)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;

  if (not message::is_replicated(old_schema))
    return;

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

  initStatementMessage(*statement, message::Statement::ALTER_SCHEMA, session);

  /* 
   * Construct the specialized AlterSchemaStatement message and attach
   * it to the generic Statement message
   */
  message::AlterSchemaStatement *alter_schema_statement= statement->mutable_alter_schema_statement();

  message::Schema *before= alter_schema_statement->mutable_before();
  message::Schema *after= alter_schema_statement->mutable_after();

  *before= old_schema;
  *after= new_schema;

  finalizeStatementMessage(*statement, session);

  finalizeTransactionMessage(*transaction, session);
  
  (void) replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);
}

void TransactionServices::dropTable(Session& session,
                                    const identifier::Table& identifier,
                                    message::table::const_reference table,
                                    bool if_exists)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;

  if (not message::is_replicated(table))
    return;

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

  initStatementMessage(*statement, message::Statement::DROP_TABLE, session);

  /* 
   * Construct the specialized DropTableStatement message and attach
   * it to the generic Statement message
   */
  message::DropTableStatement *drop_table_statement= statement->mutable_drop_table_statement();

  drop_table_statement->set_if_exists_clause(if_exists);

  message::TableMetadata *table_metadata= drop_table_statement->mutable_table_metadata();

  table_metadata->set_schema_name(identifier.getSchemaName());
  table_metadata->set_table_name(identifier.getTableName());

  finalizeStatementMessage(*statement, session);

  finalizeTransactionMessage(*transaction, session);
  
  (void) replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);
}

void TransactionServices::truncateTable(Session& session,
                                        Table &table)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;

  if (not table.getShare()->is_replicated())
    return;

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

  initStatementMessage(*statement, message::Statement::TRUNCATE_TABLE, 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();

  string schema_name;
  (void) table.getShare()->getSchemaName(schema_name);

  string table_name;
  (void) table.getShare()->getTableName(table_name);

  table_metadata->set_schema_name(schema_name.c_str(), schema_name.length());
  table_metadata->set_table_name(table_name.c_str(), table_name.length());

  finalizeStatementMessage(*statement, session);

  finalizeTransactionMessage(*transaction, session);
  
  (void) replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);
}

void TransactionServices::rawStatement(Session& session,
                                       const string &query,
                                       const string &schema)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (! replication_services.isActive())
    return;
 
  message::Transaction *transaction= getActiveTransactionMessage(session);
  message::Statement *statement= transaction->add_statement();

  initStatementMessage(*statement, message::Statement::RAW_SQL, session);
  statement->set_sql(query);
  if (not schema.empty())
    statement->set_raw_sql_schema(schema);
  finalizeStatementMessage(*statement, session);

  finalizeTransactionMessage(*transaction, session);
  
  (void) replication_services.pushTransactionMessage(session, *transaction);

  cleanupTransactionMessage(transaction, session);
}

int TransactionServices::sendEvent(Session& session, const message::Event &event)
{
  ReplicationServices &replication_services= ReplicationServices::singleton();
  if (not replication_services.isActive())
    return 0;
  message::Transaction transaction;

  // set server id, start timestamp
  initTransactionMessage(transaction, session, true);

  // set end timestamp
  finalizeTransactionMessage(transaction, session);

  message::Event *trx_event= transaction.mutable_event();
  trx_event->CopyFrom(event);
  plugin::ReplicationReturnCode result= replication_services.pushTransactionMessage(session, transaction);
  return result;
}

bool TransactionServices::sendStartupEvent(Session& session)
{
  message::Event event;
  event.set_type(message::Event::STARTUP);
  return not sendEvent(session, event);
}

bool TransactionServices::sendShutdownEvent(Session& session)
{
  message::Event event;
  event.set_type(message::Event::SHUTDOWN);
  return not sendEvent(session, event);
}

} /* namespace drizzled */