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
|
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Copyright (C) 2008 Sun Microsystems
* 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/my_hash.h"
#include "drizzled/error.h"
#include "drizzled/gettext.h"
#include "drizzled/probes.h"
#include "drizzled/sql_parse.h"
#include "drizzled/session.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/timestamp.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/internal/my_sys.h"
using namespace std;
#include <vector>
#include <algorithm>
#include <functional>
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.
*/
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);
trans->no_2pc|= false;
}
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());
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);
}
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);
}
/**
Check if we can skip the two-phase commit.
A helper function to evaluate if two-phase commit is mandatory.
As a side effect, propagates the read-only/read-write flags
of the statement transaction to its enclosing normal transaction.
@retval true we must run a two-phase commit. Returned
if we have at least two engines with read-write changes.
@retval false Don't need two-phase commit. Even if we have two
transactional engines, we can run two independent
commits if changes in one of the engines are read-only.
*/
static
bool
ha_check_and_coalesce_trx_read_only(Session *session,
TransactionContext::ResourceContexts &resource_contexts,
bool normal_transaction)
{
/* The number of storage engines that have actual changes. */
unsigned num_resources_modified_data= 0;
ResourceContext *resource_context;
for (TransactionContext::ResourceContexts::iterator it= resource_contexts.begin();
it != resource_contexts.end();
++it)
{
resource_context= *it;
if (resource_context->hasModifiedData())
++num_resources_modified_data;
if (! normal_transaction)
{
ResourceContext *resource_context_normal= session->getResourceContext(resource_context->getMonitored(), true);
assert(resource_context != resource_context_normal);
/*
Merge read-only/read-write information about statement
transaction to its enclosing normal transaction. Do this
only if in a real transaction -- that is, if we know
that resource_context_all is registered in session->transaction.all.
Since otherwise we only clutter the normal transaction flags.
*/
if (resource_context_normal->isStarted()) /* false if autocommit. */
resource_context_normal->coalesceWith(resource_context);
}
else if (num_resources_modified_data > 1)
{
/*
It is a normal transaction, so we don't need to merge read/write
information up, and the need for two-phase commit has been
already established. Break the loop prematurely.
*/
break;
}
}
return num_resources_modified_data > 1;
}
/**
@retval
0 ok
@retval
1 transaction was rolled back
@retval
2 error during commit, data may be inconsistent
@todo
Since we don't support nested statement transactions in 5.0,
we can't commit or rollback stmt transactions while we are inside
stored functions or triggers. So we simply do nothing now.
TODO: This should be fixed in later ( >= 5.1) releases.
*/
int TransactionServices::ha_commit_trans(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)
{
bool must_2pc;
if (is_real_trans && wait_if_global_read_lock(session, 0, 0))
{
ha_rollback_trans(session, normal_transaction);
return 1;
}
must_2pc= ha_check_and_coalesce_trx_read_only(session, resource_contexts, normal_transaction);
if (! trans->no_2pc && must_2pc)
{
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
{
status_var_increment(session->status_var.ha_prepare_count);
}
}
}
if (error)
{
ha_rollback_trans(session, normal_transaction);
error= 1;
goto end;
}
}
error= ha_commit_one_phase(session, normal_transaction) ? (cookie ? 2 : 1) : 0;
end:
if (is_real_trans)
start_waiting_global_read_lock(session);
}
return error;
}
/**
@note
This function does not care about global read lock. A caller should.
*/
int TransactionServices::ha_commit_one_phase(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();
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, normal_transaction)))
{
my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
error= 1;
}
else if (normal_transaction)
{
status_var_increment(session->status_var.ha_commit_count);
}
}
else if (resource->participatesInSqlTransaction())
{
if ((err= resource_context->getTransactionalStorageEngine()->commit(session, normal_transaction)))
{
my_error(ER_ERROR_DURING_COMMIT, MYF(0), err);
error= 1;
}
else if (normal_transaction)
{
status_var_increment(session->status_var.ha_commit_count);
}
}
resource_context->reset(); /* keep it conveniently zero-filled */
}
if (is_real_trans)
session->transaction.xid_state.xid.null();
if (normal_transaction)
{
session->variables.tx_isolation= session->session_tx_isolation;
session->transaction.cleanup();
}
}
trans->reset();
if (error == 0)
{
if (is_real_trans)
{
/*
* We commit the normal transaction by finalizing the transaction message
* and propogating the message to all registered replicators.
*/
commitTransactionMessage(session);
}
}
return error;
}
int TransactionServices::ha_rollback_trans(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();
/*
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, normal_transaction)))
{
my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
error= 1;
}
else if (normal_transaction)
{
status_var_increment(session->status_var.ha_rollback_count);
}
}
else if (resource->participatesInSqlTransaction())
{
if ((err= resource_context->getTransactionalStorageEngine()->rollback(session, normal_transaction)))
{
my_error(ER_ERROR_DURING_ROLLBACK, MYF(0), err);
error= 1;
}
else if (normal_transaction)
{
status_var_increment(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.
*/
rollbackTransactionMessage(session);
if (is_real_trans)
session->transaction.xid_state.xid.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->killed != 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;
}
/**
This is used to commit or rollback a single statement depending on
the value of error.
@note
Note that if the autocommit is on, then the following call inside
InnoDB will commit or rollback the whole transaction (= the statement). The
autocommit mechanism built into InnoDB is based on counting locks, but if
the user has used LOCK TABLES then that mechanism does not know to do the
commit.
*/
int TransactionServices::ha_autocommit_or_rollback(Session *session, int error)
{
if (session->transaction.stmt.getResourceContexts().empty() == false)
{
if (! error)
{
if (ha_commit_trans(session, false))
error= 1;
}
else
{
(void) ha_rollback_trans(session, false);
if (session->transaction_rollback_request)
(void) ha_rollback_trans(session, true);
}
session->variables.tx_isolation= session->session_tx_isolation;
}
return error;
}
/**
return the list of XID's to a client, the same way SHOW commands do.
@note
I didn't find in XA specs that an RM cannot return the same XID twice,
so mysql_xa_recover does not filter XID's to ensure uniqueness.
It can be easily fixed later, if necessary.
*/
bool TransactionServices::mysql_xa_recover(Session *session)
{
List<Item> field_list;
int i= 0;
XID_STATE *xs;
field_list.push_back(new Item_int("formatID", 0, MY_INT32_NUM_DECIMAL_DIGITS));
field_list.push_back(new Item_int("gtrid_length", 0, MY_INT32_NUM_DECIMAL_DIGITS));
field_list.push_back(new Item_int("bqual_length", 0, MY_INT32_NUM_DECIMAL_DIGITS));
field_list.push_back(new Item_empty_string("data", DRIZZLE_XIDDATASIZE));
if (session->client->sendFields(&field_list))
return 1;
pthread_mutex_lock(&LOCK_xid_cache);
while ((xs= (XID_STATE*)hash_element(&xid_cache, i++)))
{
if (xs->xa_state==XA_PREPARED)
{
session->client->store((int64_t)xs->xid.formatID);
session->client->store((int64_t)xs->xid.gtrid_length);
session->client->store((int64_t)xs->xid.bqual_length);
session->client->store(xs->xid.data,
xs->xid.gtrid_length+xs->xid.bqual_length);
if (session->client->flush())
{
pthread_mutex_unlock(&LOCK_xid_cache);
return 1;
}
}
}
pthread_mutex_unlock(&LOCK_xid_cache);
session->my_eof();
return 0;
}
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::ha_rollback_to_savepoint(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
{
status_var_increment(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;
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
{
status_var_increment(session->status_var.ha_rollback_count);
}
}
resource_context->reset(); /* keep it conveniently zero-filled */
}
}
trans->setResourceContexts(sv_resource_contexts);
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::ha_savepoint(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
{
status_var_increment(session->status_var.ha_savepoint_count);
}
}
}
}
/*
Remember the list of registered storage engines.
*/
sv.setResourceContexts(resource_contexts);
return error;
}
int TransactionServices::ha_release_savepoint(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;
}
message::Transaction *TransactionServices::getActiveTransactionMessage(Session *in_session)
{
message::Transaction *transaction= in_session->getTransactionMessage();
if (unlikely(transaction == NULL))
{
/*
* Allocate and initialize a new transaction message
* for this Session object. Session is responsible for
* deleting transaction message when done with it.
*/
transaction= new (nothrow) message::Transaction();
initTransactionMessage(*transaction, in_session);
in_session->setTransactionMessage(transaction);
return transaction;
}
else
return transaction;
}
void TransactionServices::initTransactionMessage(message::Transaction &in_transaction,
Session *in_session)
{
message::TransactionContext *trx= in_transaction.mutable_transaction_context();
trx->set_server_id(in_session->getServerId());
trx->set_transaction_id(in_session->getQueryId());
trx->set_start_timestamp(in_session->getCurrentTimestamp());
}
void TransactionServices::finalizeTransactionMessage(message::Transaction &in_transaction,
Session *in_session)
{
message::TransactionContext *trx= in_transaction.mutable_transaction_context();
trx->set_end_timestamp(in_session->getCurrentTimestamp());
}
void TransactionServices::cleanupTransactionMessage(message::Transaction *in_transaction,
Session *in_session)
{
delete in_transaction;
in_session->setStatementMessage(NULL);
in_session->setTransactionMessage(NULL);
}
void TransactionServices::commitTransactionMessage(Session *in_session)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
/* If there is an active statement message, finalize it */
message::Statement *statement= in_session->getStatementMessage();
if (statement != NULL)
{
finalizeStatementMessage(*statement, in_session);
}
else
return; /* No data modification occurred inside the transaction */
message::Transaction* transaction= getActiveTransactionMessage(in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
cleanupTransactionMessage(transaction, in_session);
}
void TransactionServices::initStatementMessage(message::Statement &statement,
message::Statement::Type in_type,
Session *in_session)
{
statement.set_type(in_type);
statement.set_start_timestamp(in_session->getCurrentTimestamp());
/** @TODO Set sql string optionally */
}
void TransactionServices::finalizeStatementMessage(message::Statement &statement,
Session *in_session)
{
statement.set_end_timestamp(in_session->getCurrentTimestamp());
in_session->setStatementMessage(NULL);
}
void TransactionServices::rollbackTransactionMessage(Session *in_session)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Transaction *transaction= getActiveTransactionMessage(in_session);
/*
* OK, so there are two situations that we need to deal with here:
*
* 1) We receive an instruction to ROLLBACK the current transaction
* and the currently-stored Transaction message is *self-contained*,
* meaning that no Statement messages in the Transaction message
* contain a message having its segment_id member greater than 1. If
* no non-segment ID 1 members are found, we can simply clear the
* current Transaction message and remove it from memory.
*
* 2) If the Transaction message does indeed have a non-end segment, that
* means that a bulk update/delete/insert Transaction message segment
* has previously been sent over the wire to replicators. In this case,
* we need to package a Transaction with a Statement message of type
* ROLLBACK to indicate to replicators that previously-transmitted
* messages must be un-applied.
*/
if (unlikely(message::transactionContainsBulkSegment(*transaction)))
{
/*
* Clear the transaction, create a Rollback statement message,
* attach it to the transaction, and push it to replicators.
*/
transaction->Clear();
initTransactionMessage(*transaction, in_session);
message::Statement *statement= transaction->add_statement();
initStatementMessage(*statement, message::Statement::ROLLBACK, in_session);
finalizeStatementMessage(*statement, in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
}
cleanupTransactionMessage(transaction, in_session);
}
message::Statement &TransactionServices::getInsertStatement(Session *in_session,
Table *in_table)
{
message::Statement *statement= in_session->getStatementMessage();
/*
* We check to see if the current Statement message is of type INSERT.
* If it is not, we finalize the current Statement and ensure a new
* InsertStatement is created.
*/
if (statement != NULL &&
statement->type() != message::Statement::INSERT)
{
finalizeStatementMessage(*statement, in_session);
statement= in_session->getStatementMessage();
}
if (statement == NULL)
{
message::Transaction *transaction= getActiveTransactionMessage(in_session);
/*
* Transaction message initialized and set, but no statement created
* yet. We construct one and initialize it, here, then return the
* message after attaching the new Statement message pointer to the
* Session for easy retrieval later...
*/
statement= transaction->add_statement();
setInsertHeader(*statement, in_session, in_table);
in_session->setStatementMessage(statement);
}
return *statement;
}
void TransactionServices::setInsertHeader(message::Statement &statement,
Session *in_session,
Table *in_table)
{
initStatementMessage(statement, message::Statement::INSERT, in_session);
/*
* Now we construct the specialized InsertHeader message inside
* the generalized message::Statement container...
*/
/* Set up the insert header */
message::InsertHeader *header= statement.mutable_insert_header();
message::TableMetadata *table_metadata= header->mutable_table_metadata();
string schema_name;
(void) in_table->getShare()->getSchemaName(schema_name);
string table_name;
(void) in_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= in_table->field;
message::FieldMetadata *field_metadata;
/* We will read all the table's fields... */
in_table->setReadSet();
while ((current_field= *table_fields++) != NULL)
{
field_metadata= header->add_field_metadata();
field_metadata->set_name(current_field->field_name);
field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
}
}
bool TransactionServices::insertRecord(Session *in_session, Table *in_table)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return false;
/**
* We do this check here because we don't want to even create a
* statement if there isn't a primary key on the table...
*
* @todo
*
* Multi-column primary keys are handled how exactly?
*/
if (in_table->s->primary_key == MAX_KEY)
{
my_error(ER_NO_PRIMARY_KEY_ON_REPLICATED_TABLE, MYF(0));
return true;
}
message::Statement &statement= getInsertStatement(in_session, in_table);
message::InsertData *data= statement.mutable_insert_data();
data->set_segment_id(1);
data->set_end_segment(true);
message::InsertRecord *record= data->add_record();
Field *current_field;
Field **table_fields= in_table->field;
String *string_value= new (in_session->mem_root) String(TransactionServices::DEFAULT_RECORD_SIZE);
string_value->set_charset(system_charset_info);
/* We will read all the table's fields... */
in_table->setReadSet();
while ((current_field= *table_fields++) != NULL)
{
string_value= current_field->val_str(string_value);
record->add_insert_value(string_value->c_ptr(), string_value->length());
string_value->free();
}
return false;
}
message::Statement &TransactionServices::getUpdateStatement(Session *in_session,
Table *in_table,
const unsigned char *old_record,
const unsigned char *new_record)
{
message::Statement *statement= in_session->getStatementMessage();
/*
* We check to see if the current Statement message is of type UPDATE.
* If it is not, we finalize the current Statement and ensure a new
* UpdateStatement is created.
*/
if (statement != NULL &&
statement->type() != message::Statement::UPDATE)
{
finalizeStatementMessage(*statement, in_session);
statement= in_session->getStatementMessage();
}
if (statement == NULL)
{
message::Transaction *transaction= getActiveTransactionMessage(in_session);
/*
* Transaction message initialized and set, but no statement created
* yet. We construct one and initialize it, here, then return the
* message after attaching the new Statement message pointer to the
* Session for easy retrieval later...
*/
statement= transaction->add_statement();
setUpdateHeader(*statement, in_session, in_table, old_record, new_record);
in_session->setStatementMessage(statement);
}
return *statement;
}
void TransactionServices::setUpdateHeader(message::Statement &statement,
Session *in_session,
Table *in_table,
const unsigned char *old_record,
const unsigned char *new_record)
{
initStatementMessage(statement, message::Statement::UPDATE, in_session);
/*
* Now we construct the specialized UpdateHeader message inside
* the generalized message::Statement container...
*/
/* Set up the update header */
message::UpdateHeader *header= statement.mutable_update_header();
message::TableMetadata *table_metadata= header->mutable_table_metadata();
string schema_name;
(void) in_table->getShare()->getSchemaName(schema_name);
string table_name;
(void) in_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= in_table->field;
message::FieldMetadata *field_metadata;
/* We will read all the table's fields... */
in_table->setReadSet();
while ((current_field= *table_fields++) != NULL)
{
/*
* We add the "key field metadata" -- i.e. the fields which is
* the primary key for the table.
*/
if (in_table->s->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()));
}
/*
* The below really should be moved into the Field API and Record API. But for now
* we do this crazy pointer fiddling to figure out if the current field
* has been updated in the supplied record raw byte pointers.
*/
const unsigned char *old_ptr= (const unsigned char *) old_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]);
const unsigned char *new_ptr= (const unsigned char *) new_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]);
uint32_t field_length= current_field->pack_length(); /** @TODO This isn't always correct...check varchar diffs. */
if (memcmp(old_ptr, new_ptr, field_length) != 0)
{
/* Field is changed from old to new */
field_metadata= header->add_set_field_metadata();
field_metadata->set_name(current_field->field_name);
field_metadata->set_type(message::internalFieldTypeToFieldProtoType(current_field->type()));
}
}
}
void TransactionServices::updateRecord(Session *in_session,
Table *in_table,
const unsigned char *old_record,
const unsigned char *new_record)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Statement &statement= getUpdateStatement(in_session, in_table, old_record, new_record);
message::UpdateData *data= statement.mutable_update_data();
data->set_segment_id(1);
data->set_end_segment(true);
message::UpdateRecord *record= data->add_record();
Field *current_field;
Field **table_fields= in_table->field;
String *string_value= new (in_session->mem_root) String(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.
*
* The below really should be moved into the Field API and Record API. But for now
* we do this crazy pointer fiddling to figure out if the current field
* has been updated in the supplied record raw byte pointers.
*/
const unsigned char *old_ptr= (const unsigned char *) old_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]);
const unsigned char *new_ptr= (const unsigned char *) new_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]);
uint32_t field_length= current_field->pack_length(); /** @TODO This isn't always correct...check varchar diffs. */
if (memcmp(old_ptr, new_ptr, field_length) != 0)
{
/* Store the original "read bit" for this field */
bool is_read_set= current_field->isReadSet();
/* We need to mark that we will "read" this field... */
in_table->setReadSet(current_field->field_index);
/* Read the string value of this field's contents */
string_value= current_field->val_str(string_value);
/*
* Reset the read bit after reading field to its original state. This
* prevents the field from being included in the WHERE clause
*/
current_field->setReadSet(is_read_set);
record->add_after_value(string_value->c_ptr(), string_value->length());
string_value->free();
}
/*
* Add the WHERE clause values now...for now, this means the
* primary key field value. Replication only supports tables
* with a primary key.
*/
if (in_table->s->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(string_value,
old_record +
current_field->offset(const_cast<unsigned char *>(new_record)));
record->add_key_value(string_value->c_ptr(), string_value->length());
string_value->free();
}
}
}
message::Statement &TransactionServices::getDeleteStatement(Session *in_session,
Table *in_table)
{
message::Statement *statement= in_session->getStatementMessage();
/*
* We check to see if the current Statement message is of type DELETE.
* If it is not, we finalize the current Statement and ensure a new
* DeleteStatement is created.
*/
if (statement != NULL &&
statement->type() != message::Statement::DELETE)
{
finalizeStatementMessage(*statement, in_session);
statement= in_session->getStatementMessage();
}
if (statement == NULL)
{
message::Transaction *transaction= getActiveTransactionMessage(in_session);
/*
* Transaction message initialized and set, but no statement created
* yet. We construct one and initialize it, here, then return the
* message after attaching the new Statement message pointer to the
* Session for easy retrieval later...
*/
statement= transaction->add_statement();
setDeleteHeader(*statement, in_session, in_table);
in_session->setStatementMessage(statement);
}
return *statement;
}
void TransactionServices::setDeleteHeader(message::Statement &statement,
Session *in_session,
Table *in_table)
{
initStatementMessage(statement, message::Statement::DELETE, in_session);
/*
* Now we construct the specialized DeleteHeader message inside
* the generalized message::Statement container...
*/
message::DeleteHeader *header= statement.mutable_delete_header();
message::TableMetadata *table_metadata= header->mutable_table_metadata();
string schema_name;
(void) in_table->getShare()->getSchemaName(schema_name);
string table_name;
(void) in_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= in_table->field;
message::FieldMetadata *field_metadata;
while ((current_field= *table_fields++) != NULL)
{
/*
* Add the WHERE clause values now...for now, this means the
* primary key field value. Replication only supports tables
* with a primary key.
*/
if (in_table->s->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 *in_session, Table *in_table)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Statement &statement= getDeleteStatement(in_session, in_table);
message::DeleteData *data= statement.mutable_delete_data();
data->set_segment_id(1);
data->set_end_segment(true);
message::DeleteRecord *record= data->add_record();
Field *current_field;
Field **table_fields= in_table->field;
String *string_value= new (in_session->mem_root) String(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 (in_table->s->fieldInPrimaryKey(current_field))
{
string_value= current_field->val_str(string_value);
record->add_key_value(string_value->c_ptr(), string_value->length());
/**
* @TODO Store optional old record value in the before data member
*/
string_value->free();
}
}
}
void TransactionServices::createTable(Session *in_session,
const message::Table &table)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Transaction *transaction= getActiveTransactionMessage(in_session);
message::Statement *statement= transaction->add_statement();
initStatementMessage(*statement, message::Statement::CREATE_TABLE, in_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, in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
cleanupTransactionMessage(transaction, in_session);
}
void TransactionServices::createSchema(Session *in_session,
const message::Schema &schema)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Transaction *transaction= getActiveTransactionMessage(in_session);
message::Statement *statement= transaction->add_statement();
initStatementMessage(*statement, message::Statement::CREATE_SCHEMA, in_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, in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
cleanupTransactionMessage(transaction, in_session);
}
void TransactionServices::dropSchema(Session *in_session, const string &schema_name)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Transaction *transaction= getActiveTransactionMessage(in_session);
message::Statement *statement= transaction->add_statement();
initStatementMessage(*statement, message::Statement::DROP_SCHEMA, in_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(schema_name);
finalizeStatementMessage(*statement, in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
cleanupTransactionMessage(transaction, in_session);
}
void TransactionServices::dropTable(Session *in_session,
const string &schema_name,
const string &table_name,
bool if_exists)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Transaction *transaction= getActiveTransactionMessage(in_session);
message::Statement *statement= transaction->add_statement();
initStatementMessage(*statement, message::Statement::DROP_TABLE, in_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(schema_name);
table_metadata->set_table_name(table_name);
finalizeStatementMessage(*statement, in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
cleanupTransactionMessage(transaction, in_session);
}
void TransactionServices::truncateTable(Session *in_session, Table *in_table)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Transaction *transaction= getActiveTransactionMessage(in_session);
message::Statement *statement= transaction->add_statement();
initStatementMessage(*statement, message::Statement::TRUNCATE_TABLE, in_session);
/*
* Construct the specialized TruncateTableStatement message and attach
* it to the generic Statement message
*/
message::TruncateTableStatement *truncate_statement= statement->mutable_truncate_table_statement();
message::TableMetadata *table_metadata= truncate_statement->mutable_table_metadata();
string schema_name;
(void) in_table->getShare()->getSchemaName(schema_name);
string table_name;
(void) in_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, in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
cleanupTransactionMessage(transaction, in_session);
}
void TransactionServices::rawStatement(Session *in_session, const string &query)
{
ReplicationServices &replication_services= ReplicationServices::singleton();
if (! replication_services.isActive())
return;
message::Transaction *transaction= getActiveTransactionMessage(in_session);
message::Statement *statement= transaction->add_statement();
initStatementMessage(*statement, message::Statement::RAW_SQL, in_session);
statement->set_sql(query);
finalizeStatementMessage(*statement, in_session);
finalizeTransactionMessage(*transaction, in_session);
replication_services.pushTransactionMessage(*transaction);
cleanupTransactionMessage(transaction, in_session);
}
} /* namespace drizzled */
|