summaryrefslogtreecommitdiff
path: root/src/context/pool_session_context.c
blob: eea8df13601a6d5ea7e794daf1a92bc2b2fc5a9f (plain)
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
/* -*-pgsql-c-*- */
/*
 *
 * pgpool: a language independent connection pool server for PostgreSQL
 * written by Tatsuo Ishii
 *
 * Copyright (c) 2003-2024	PgPool Global Development Group
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear in all
 * copies and that both that copyright notice and this permission
 * notice appear in supporting documentation, and that the name of the
 * author not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior
 * permission. The author makes no representations about the
 * suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 *
 */
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include "pool.h"
#include "utils/palloc.h"
#include "utils/memutils.h"
#include "utils/elog.h"
#include "pool_config.h"
#include "protocol/pool_proto_modules.h"
#include "protocol/pool_process_query.h"
#include "protocol/pool_connection_pool.h"
#include "protocol/pool_pg_utils.h"
#include "context/pool_session_context.h"

static POOL_SESSION_CONTEXT session_context_d;
static POOL_SESSION_CONTEXT * session_context = NULL;
static void GetTranIsolationErrorCb(void *arg);
static void init_sent_message_list(void);
static POOL_PENDING_MESSAGE * copy_pending_message(POOL_PENDING_MESSAGE * message);
static void dump_sent_message(char *caller, POOL_SENT_MESSAGE * m);
static void dml_adaptive_init(void);
static void dml_adaptive_destroy(void);

#ifdef PENDING_MESSAGE_DEBUG
static int	Elevel = LOG;
#else
static int	Elevel = DEBUG2;
#endif

/*
 * Initialize per session context
 */
void
pool_init_session_context(POOL_CONNECTION * frontend, POOL_CONNECTION_POOL * backend)
{
	session_context = &session_context_d;
	ProcessInfo *process_info;
	int			node_id;
	int			i;

	/* Clear session context memory */
	memset(&session_context_d, 0, sizeof(session_context_d));

	/* Get Process context */
	session_context->process_context = pool_get_process_context();
	if (!session_context->process_context)
		ereport(ERROR,
				(errmsg("failed to get process context")));

	/* Set connection info */
	session_context->frontend = frontend;
	session_context->backend = backend;

	/* Initialize query context */
	session_context->query_context = NULL;

	/* Initialize local session id */
	pool_increment_local_session_id();

	/* Create memory context */
	/* TODO re-think about the parent for this context ?? */
	session_context->memory_context = AllocSetContextCreate(ProcessLoopContext,
															"SessionContext",
															ALLOCSET_SMALL_MINSIZE,
															ALLOCSET_SMALL_INITSIZE,
															ALLOCSET_SMALL_MAXSIZE);

	/* Initialize sent message list */
	init_sent_message_list();

	process_info = pool_get_my_process_info();

	if (!process_info)
		ereport(ERROR,
				(errmsg("failed to get process info for current process")));

	/* Choose load balancing node if necessary */
	if (!RAW_MODE && pool_config->load_balance_mode)
	{
		node_id = select_load_balancing_node();
	}
	else
	{
		node_id = SL_MODE ? PRIMARY_NODE_ID : MAIN_NODE_ID;
	}

	session_context->load_balance_node_id = node_id;

	for (i = 0; i < NUM_BACKENDS; i++)
	{
		pool_coninfo(session_context->process_context->proc_id,
					 pool_pool_index(), i)->load_balancing_node = node_id;
	}

	ereport(DEBUG5,
			(errmsg("initializing session context"),
			 errdetail("selected load balancing node: %d", node_id)));

	/* Unset query is in progress */
	pool_unset_query_in_progress();

	/* The command in progress has not succeeded yet */
	pool_unset_command_success();

	/* We don't have a write query in this transaction yet */
	pool_unset_writing_transaction();

	/* Error doesn't occur in this transaction yet */
	pool_unset_failed_transaction();

	/* Forget transaction isolation mode */
	pool_unset_transaction_isolation();

	/* We don't skip reading from backends */
	pool_unset_skip_reading_from_backends();

	/* Backends have not ignored messages yet */
	pool_unset_ignore_till_sync();

	/* Unset suspend reading from frontend flag */
	pool_unset_suspend_reading_from_frontend();

	/*
	 * Reset flag to indicate difference in number of affected tuples in
	 * UPDATE/DELETE.
	 */
	session_context->mismatch_ntuples = false;

	if (pool_config->memory_cache_enabled)
	{
		session_context->query_cache_array = pool_create_query_cache_array();
		session_context->num_selects = 0;
	}

	/* Initialize pending message list */
	pool_pending_messages_init();

	/* Initialize previous pending message */
	pool_pending_message_reset_previous_message();

	/* Initialize temp tables */
	pool_temp_tables_init();
	
	/* Snapshot isolation state */
	session_context->si_state = SI_NO_SNAPSHOT;

	/* Transaction read only */
	session_context->transaction_read_only = false;

	dml_adaptive_init();

	unset_tx_started_by_multi_statement_query();

	unset_query_cache_disabled();

	unset_query_cache_disabled_tx();
}

/*
 * Destroy session context.
 */
void
pool_session_context_destroy(void)
{
	if (session_context)
	{
		pool_clear_sent_message_list();
		pfree(session_context->message_list.sent_messages);
		if (pool_config->memory_cache_enabled)
		{
			pool_discard_query_cache_array(session_context->query_cache_array);
			session_context->num_selects = 0;
		}

		if (session_context->query_context)
			pool_query_context_destroy(session_context->query_context);
		MemoryContextDelete(session_context->memory_context);

		dml_adaptive_destroy();
	}
	/* XXX For now, just zap memory */
	memset(&session_context_d, 0, sizeof(session_context_d));
	session_context = NULL;
}

/*
 * Return session context
 */
POOL_SESSION_CONTEXT *
pool_get_session_context(bool noerror)
{
	if (!session_context && !noerror)
	{
		ereport(FATAL,
				(return_code(2),
				 errmsg("unable to get session context")));
	}
	return session_context;
}

/*
 * Return local session id
 */
int
pool_get_local_session_id(void)
{
	return pool_get_session_context(false)->process_context->local_session_id;
}

/*
 * Return true if query is in progress
 */
bool
pool_is_query_in_progress(void)
{
	return pool_get_session_context(false)->in_progress;
}

/*
 * Set query is in progress
 */
void
pool_set_query_in_progress(void)
{
	ereport(DEBUG5,
			(errmsg("session context: setting query in progress. DONE")));

	pool_get_session_context(false)->in_progress = true;
}

/*
 * Unset query is in progress
 */
void
pool_unset_query_in_progress(void)
{
	POOL_SESSION_CONTEXT *s = pool_get_session_context(false);

	ereport(DEBUG5,
			(errmsg("session context: unsetting query in progress. DONE")));

	s->in_progress = false;

	/* Restore where_to_send map if necessary */
	if (s->need_to_restore_where_to_send)
	{
		memcpy(s->query_context->where_to_send, s->where_to_send_save, sizeof(s->where_to_send_save));
	}
	s->need_to_restore_where_to_send = false;
}

/*
 * Return true if we skip reading from backends
 */
bool
pool_is_skip_reading_from_backends(void)
{
	return pool_get_session_context(false)->skip_reading_from_backends;
}

/*
 * Set skip_reading_from_backends
 */
void
pool_set_skip_reading_from_backends(void)
{
	ereport(DEBUG5,
			(errmsg("session context: setting skip reading from backends. DONE")));


	pool_get_session_context(false)->skip_reading_from_backends = true;
}

/*
 * Unset skip_reading_from_backends
 */
void
pool_unset_skip_reading_from_backends(void)
{
	ereport(DEBUG5,
			(errmsg("session context: clearing skip reading from backends. DONE")));

	pool_get_session_context(false)->skip_reading_from_backends = false;
}

/*
 * Return true if we are doing extended query message
 */
bool
pool_is_doing_extended_query_message(void)
{
	return pool_get_session_context(false)->doing_extended_query_message;
}

/*
 * Set doing_extended_query_message
 */
void
pool_set_doing_extended_query_message(void)
{
	ereport(DEBUG5,
			(errmsg("session context: setting doing extended query messaging. DONE")));

	pool_get_session_context(false)->doing_extended_query_message = true;
}

/*
 * Unset doing_extended_query_message
 */
void
pool_unset_doing_extended_query_message(void)
{
	ereport(DEBUG5,
			(errmsg("session context: clearing doing extended query messaging. DONE")));

	pool_get_session_context(false)->doing_extended_query_message = false;
}

/*
 * Return true if backends ignore extended query message
 */
bool
pool_is_ignore_till_sync(void)
{
	return pool_get_session_context(false)->ignore_till_sync;
}

/*
 * Set ignore_till_sync
 */
void
pool_set_ignore_till_sync(void)
{
	ereport(DEBUG5,
			(errmsg("session context: setting ignore till sync. DONE")));

	pool_get_session_context(false)->ignore_till_sync = true;
}

/*
 * Unset ignore_till_sync
 */
void
pool_unset_ignore_till_sync(void)
{
	ereport(DEBUG5,
			(errmsg("session context: clearing ignore till sync. DONE")));

	pool_get_session_context(false)->ignore_till_sync = false;
}

/*
 * Remove a sent message
 */
bool
pool_remove_sent_message(char kind, const char *name)
{
	int			i;
	POOL_SENT_MESSAGE_LIST *msglist;

	if (kind == 0 || name == NULL)
		return false;

	msglist = &pool_get_session_context(false)->message_list;

	for (i = 0; i < msglist->size; i++)
	{
		if (msglist->sent_messages[i]->kind == kind &&
			!strcmp(msglist->sent_messages[i]->name, name))
		{
			pool_sent_message_destroy(msglist->sent_messages[i]);
			break;
		}
	}

	/* sent message not found */
	if (i == msglist->size)
		return false;

	if (i != msglist->size - 1)
	{
		memmove(&msglist->sent_messages[i], &msglist->sent_messages[i + 1],
				sizeof(POOL_SENT_MESSAGE *) * (msglist->size - i - 1));
	}

	msglist->size--;

	return true;
}

/*
 * Remove same kind of sent messages
 */
void
pool_remove_sent_messages(char kind)
{
	int			i;
	POOL_SENT_MESSAGE_LIST *msglist;

	msglist = &pool_get_session_context(false)->message_list;

	for (i = 0; i < msglist->size; i++)
	{
		if (msglist->sent_messages[i]->kind == kind)
		{
			if (pool_remove_sent_message(kind, msglist->sent_messages[i]->name))
				i--;			/* for relocation by removing */
		}
	}
}

/*
 * Destroy sent message
 */
void
pool_sent_message_destroy(POOL_SENT_MESSAGE * message)
{
	bool		in_progress;
	POOL_QUERY_CONTEXT *qc = NULL;

	dump_sent_message("pool_sent_message_destroy", message);

	in_progress = pool_is_query_in_progress();

	if (message)
	{
		if (message->contents)
			pfree(message->contents);

		if (message->name)
			pfree(message->name);

		if (message->query_context)
		{
			if (session_context->query_context != message->query_context)
				qc = session_context->query_context;

			if (can_query_context_destroy(message->query_context))
			{
				pool_query_context_destroy(message->query_context);

				/*
				 * set in_progress flag, because pool_query_context_destroy()
				 * unsets in_progress flag
				 */
				if (in_progress)
					pool_set_query_in_progress();

				/*
				 * set query_context of session_context, because
				 * pool_query_context_destroy() sets it to NULL.
				 */
				if (qc)
					session_context->query_context = qc;
			}
		}

		if (session_context->memory_context)
			pfree(message);
	}
}

/*
 * Clear sent message list
 */
void
pool_clear_sent_message_list(void)
{
	POOL_SENT_MESSAGE_LIST *msglist;

	msglist = &pool_get_session_context(false)->message_list;

	while (msglist->size > 0)
	{
		pool_remove_sent_messages(msglist->sent_messages[0]->kind);
	}
}

/*
 * Zap query context info in sent messages to indicate that the query context
 * has been already removed.
 */
void
pool_zap_query_context_in_sent_messages(POOL_QUERY_CONTEXT *query_context)
{
	int			i;
	POOL_SENT_MESSAGE_LIST *msglist;

	msglist = &pool_get_session_context(false)->message_list;

	for (i = 0; i < msglist->size; i++)
	{
		elog(DEBUG5, "checking zapping sent message: %p query_context: %p",
			 &msglist->sent_messages[i], msglist->sent_messages[i]->query_context);
		if (msglist->sent_messages[i]->query_context == query_context)
		{
			msglist->sent_messages[i]->query_context = NULL;
			elog(DEBUG5, "Zap sent message: %p", &msglist->sent_messages[i]);
		}
	}
}

static void
dump_sent_message(char *caller, POOL_SENT_MESSAGE * m)
{
	ereport(DEBUG5,
			(errmsg("called by %s: sent message: address: %p kind: %c name: =%s= state:%d",
					caller, m, m->kind, m->name, m->state)));
}

static void
dml_adaptive_init(void)
{
	if (pool_config->disable_load_balance_on_write == DLBOW_DML_ADAPTIVE)
	{
		session_context->is_in_transaction = false;
		session_context->transaction_temp_write_list = NIL;
	}
}

static void
dml_adaptive_destroy(void)
{
	if (pool_config->disable_load_balance_on_write == DLBOW_DML_ADAPTIVE && session_context)
	{
		if (session_context->transaction_temp_write_list != NIL)
			list_free_deep(session_context->transaction_temp_write_list);
	}
}

/*
 * Create a sent message.
 * kind: one of 'P':Parse, 'B':Bind or 'Q':Query(PREPARE)
 * len: message length in host order
 * contents: message contents
 * num_tsparams: number of timestamp parameters
 * name: prepared statement name or portal name
 */
POOL_SENT_MESSAGE *
pool_create_sent_message(char kind, int len, char *contents,
						 int num_tsparams, const char *name,
						 POOL_QUERY_CONTEXT * query_context)
{
	POOL_SENT_MESSAGE *msg;

	if (!session_context)
		ereport(ERROR,
				(errmsg("unable to create message"),
				 errdetail("cannot get the session context")));

	MemoryContext old_context = MemoryContextSwitchTo(session_context->memory_context);

	msg = palloc(sizeof(POOL_SENT_MESSAGE));
	msg->kind = kind;
	msg->len = len;
	msg->contents = palloc(len);
	memcpy(msg->contents, contents, len);
	msg->state = POOL_SENT_MESSAGE_CREATED;
	msg->num_tsparams = num_tsparams;
	msg->name = pstrdup(name);
	msg->query_context = query_context;
	MemoryContextSwitchTo(old_context);

	return msg;
}

/*
 * Add a sent message to sent message list
 */
void
pool_add_sent_message(POOL_SENT_MESSAGE * message)
{
	POOL_SENT_MESSAGE *old_msg;
	POOL_SENT_MESSAGE_LIST *msglist;

	dump_sent_message("pool_add_sent_message", message);

	if (!message)
	{
		ereport(DEBUG5,
				(errmsg("adding sent message to list"),
				 errdetail("message is null")));
		return;
	}

	old_msg = pool_get_sent_message(message->kind, message->name, POOL_SENT_MESSAGE_CREATED);

	if (old_msg == message)
	{
		/*
		 * It is likely caller tries to add the exact same message previously
		 * added. We should ignore this because pool_remove_sent_message()
		 * will free memory allocated in the message.
		 */
		ereport(DEBUG5,
				(errmsg("adding sent message to list"),
				 errdetail("adding exactly same message is prohibited")));
		return;
	}

	msglist = &session_context->message_list;

	if (old_msg)
	{
		if (message->kind == 'B')
			ereport(DEBUG5,
					(errmsg("adding sent message to list"),
					 errdetail("portal \"%s\" already exists", message->name)));
		else
			ereport(DEBUG5,
					(errmsg("adding sent message to list"),
					 errdetail("prepared statement \"%s\" already exists", message->name)));

		if (*message->name == '\0')
			pool_remove_sent_message(old_msg->kind, old_msg->name);
		else
			return;
	}

	if (msglist->size == msglist->capacity)
	{
		msglist->capacity *= 2;

		MemoryContext oldContext = MemoryContextSwitchTo(session_context->memory_context);

		msglist->sent_messages = repalloc(msglist->sent_messages,
										  sizeof(POOL_SENT_MESSAGE *) * msglist->capacity);

		MemoryContextSwitchTo(oldContext);
	}

	msglist->sent_messages[msglist->size++] = message;
}

/*
 * Find a sent message by kind and name.
 */
POOL_SENT_MESSAGE *
pool_get_sent_message(char kind, const char *name, POOL_SENT_MESSAGE_STATE state)
{
	int			i;
	POOL_SENT_MESSAGE_LIST *msglist;

	msglist = &pool_get_session_context(false)->message_list;

	if (kind == 0 || name == NULL)
		return NULL;

	for (i = 0; i < msglist->size; i++)
	{
		if (msglist->sent_messages[i]->kind == kind &&
			!strcmp(msglist->sent_messages[i]->name, name) &&
			msglist->sent_messages[i]->state == state)
			return msglist->sent_messages[i];
	}

	return NULL;
}

/*
 * Find a sent message by query context.
 */
POOL_SENT_MESSAGE *
pool_get_sent_message_by_query_context(POOL_QUERY_CONTEXT * query_context)
{
	int			i;
	POOL_SENT_MESSAGE_LIST *msglist;

	msglist = &pool_get_session_context(false)->message_list;

	if (query_context == NULL)
		return NULL;

	for (i = 0; i < msglist->size; i++)
	{
		if (msglist->sent_messages[i]->query_context == query_context)
			return msglist->sent_messages[i];
	}

	return NULL;
}

/*
 * Set message state to POOL_SENT_MESSAGE_STATE to POOL_SENT_MESSAGE_CLOSED.
 */
void
pool_set_sent_message_state(POOL_SENT_MESSAGE * message)
{
	ereport(DEBUG5,
			(errmsg("pool_set_sent_message_state: name:%s kind:%c previous state: %d",
					message->name, message->kind, message->state)));
	message->state = POOL_SENT_MESSAGE_CLOSED;
}

/*
 * We don't have a write query in this transaction yet.
 */
void
pool_unset_writing_transaction(void)
{
	/*
	 * If disable_transaction_on_write is 'always', then never turn off
	 * writing transaction flag.
	 */
	if (pool_config->disable_load_balance_on_write != DLBOW_ALWAYS)
	{
		pool_get_session_context(false)->writing_transaction = false;
		ereport(DEBUG5,
				(errmsg("session context: clearing writing transaction. DONE")));
	}
}

/*
 * We have a write query in this transaction.
 */
void
pool_set_writing_transaction(void)
{
	/*
	 * If disable_transaction_on_write is 'off' or 'dml_adaptive', then never turn on writing
	 * transaction flag.
	 */
	if (pool_config->disable_load_balance_on_write != DLBOW_OFF && pool_config->disable_load_balance_on_write != DLBOW_DML_ADAPTIVE)
	{
		pool_get_session_context(false)->writing_transaction = true;
		ereport(DEBUG5,
				(errmsg("session context: setting writing transaction. DONE")));
	}
}

/*
 * Do we have a write query in this transaction?
 */
bool
pool_is_writing_transaction(void)
{
	return pool_get_session_context(false)->writing_transaction;
}

/*
 * Error doesn't occur in this transaction yet.
 */
void
pool_unset_failed_transaction(void)
{
	ereport(DEBUG5,
			(errmsg("session context: clearing failed transaction. DONE")));

	pool_get_session_context(false)->failed_transaction = false;
}

/*
 * Error occurred in this transaction.
 */
void
pool_set_failed_transaction(void)
{
	ereport(DEBUG5,
			(errmsg("session context: setting failed transaction. DONE")));

	pool_get_session_context(false)->failed_transaction = true;
}

/*
 * Did error occur in this transaction?
 */
bool
pool_is_failed_transaction(void)
{
	return pool_get_session_context(false)->failed_transaction;
}

/*
 * Forget transaction isolation mode
 */
void
pool_unset_transaction_isolation(void)
{
	ereport(DEBUG5,
			(errmsg("session context: clearing failed transaction. DONE")));
	pool_get_session_context(false)->transaction_isolation = POOL_UNKNOWN;
}

/*
 * Set transaction isolation mode
 */
void
pool_set_transaction_isolation(POOL_TRANSACTION_ISOLATION isolation_level)
{
	ereport(DEBUG5,
			(errmsg("session context: setting transaction isolation. DONE")));
	pool_get_session_context(false)->transaction_isolation = isolation_level;
}

/*
 * Get or return cached transaction isolation mode
 */
POOL_TRANSACTION_ISOLATION
pool_get_transaction_isolation(void)
{
	POOL_SELECT_RESULT *res;
	POOL_TRANSACTION_ISOLATION ret;
	ErrorContextCallback callback;

	if (!session_context)
	{
		ereport(WARNING,
				(errmsg("error while getting transaction isolation, session context is not initialized")));
		return POOL_UNKNOWN;
	}

	/* It seems cached result is usable. Return it. */
	if (session_context->transaction_isolation != POOL_UNKNOWN)
		return session_context->transaction_isolation;

	/*
	 * Register a error context callback to throw proper context message
	 */
	callback.callback = GetTranIsolationErrorCb;
	callback.arg = NULL;
	callback.previous = error_context_stack;
	error_context_stack = &callback;

	/* No cached data is available. Ask backend. */

	do_query(MAIN(session_context->backend),
			 "SELECT current_setting('transaction_isolation')", &res, MAJOR(session_context->backend));

	error_context_stack = callback.previous;

	if (res->numrows <= 0)
	{
		ereport(WARNING,
				(errmsg("error while getting transaction isolation, do_query returns no rows")));
		free_select_result(res);
		return POOL_UNKNOWN;
	}
	if (res->data[0] == NULL)
	{
		ereport(WARNING,
				(errmsg("error while getting transaction isolation, do_query returns no data")));

		free_select_result(res);
		return POOL_UNKNOWN;
	}
	if (res->nullflags[0] == -1)
	{
		ereport(WARNING,
				(errmsg("error while getting transaction isolation, do_query returns NULL")));
		free_select_result(res);
		return POOL_UNKNOWN;
	}

	if (!strcmp(res->data[0], "read uncommitted"))
		ret = POOL_READ_UNCOMMITTED;
	else if (!strcmp(res->data[0], "read committed"))
		ret = POOL_READ_COMMITTED;
	else if (!strcmp(res->data[0], "repeatable read"))
		ret = POOL_REPEATABLE_READ;
	else if (!strcmp(res->data[0], "serializable"))
		ret = POOL_SERIALIZABLE;
	else
	{
		ereport(WARNING,
				(errmsg("error while getting transaction isolation, unknown transaction isolation level:%s", res->data[0])));

		ret = POOL_UNKNOWN;
	}

	free_select_result(res);

	if (ret != POOL_UNKNOWN)
		session_context->transaction_isolation = ret;

	return ret;
}

static void
GetTranIsolationErrorCb(void *arg)
{
	errcontext("while getting transaction isolation");
}


/*
 * The command in progress has not succeeded yet.
 */
void
pool_unset_command_success(void)
{
	ereport(DEBUG5,
			(errmsg("session context: clearing transaction isolation. DONE")));
	pool_get_session_context(false)->command_success = false;
}

/*
 * The command in progress has succeeded.
 */
void
pool_set_command_success(void)
{
	ereport(DEBUG5,
			(errmsg("session context: setting command success. DONE")));

	pool_get_session_context(false)->command_success = true;
}

/*
 * Has the command in progress succeeded?
 */
bool
pool_is_command_success(void)
{
	return pool_get_session_context(false)->command_success;
}

/*
 * Copy send map
 */
void
pool_copy_prep_where(bool *src, bool *dest)
{
	memcpy(dest, src, sizeof(bool) * MAX_NUM_BACKENDS);
}

/*
 * Initialize sent message list
 */
static void
init_sent_message_list(void)
{
	POOL_SENT_MESSAGE_LIST *msglist;

	msglist = &session_context->message_list;
	msglist->size = 0;
	msglist->capacity = INIT_LIST_SIZE;

	MemoryContext oldContext = MemoryContextSwitchTo(session_context->memory_context);

	msglist->sent_messages = palloc(sizeof(POOL_SENT_MESSAGE *) * INIT_LIST_SIZE);

	MemoryContextSwitchTo(oldContext);
}

/*
 * Look for extended message list to check if given query context qc
 * is used. Returns true if it is not used.
 */
bool
can_query_context_destroy(POOL_QUERY_CONTEXT * qc)
{
	int			i;
	int			count = 0;
	POOL_SENT_MESSAGE_LIST *msglist;
	ListCell   *cell;
	ListCell   *next;

	msglist = &session_context->message_list;

	for (i = 0; i < msglist->size; i++)
	{
		if (msglist->sent_messages[i]->query_context == qc)
			count++;
	}
	if (count > 1)
	{
		ereport(DEBUG5,
				(errmsg("checking if query context can be safely destroyed"),
				 errdetail("query context %p is still used %d times in sent message list. query:\"%s\"",
						   qc, count, qc->original_query)));
		return false;
	}

	count = 0;

	for (cell = list_head(session_context->pending_messages); cell; cell = next)
	{
		POOL_PENDING_MESSAGE *message = (POOL_PENDING_MESSAGE *) lfirst(cell);

		if (message->query_context == qc)
		{
			count++;
		}
		next = lnext(session_context->pending_messages, cell);
	}

	if (count >= 1)
	{
		ereport(DEBUG5,
				(errmsg("checking if query context can be safely destroyed"),
				 errdetail("query context %p is still used %d times in pending message list. query:%s", qc, count, qc->original_query)));
		return false;
	}

	return true;
}

/*
 * Initialize pending message list
 */
void
pool_pending_messages_init(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_pending_message_init: session context is not initialized")));

	session_context->pending_messages = NIL;
}

/*
 * Destroy pending message list
 */
void
pool_pending_messages_destroy(void)
{
	ListCell   *cell;
	POOL_PENDING_MESSAGE *msg;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_pending_message_destroy: session context is not initialized")));

	foreach(cell, session_context->pending_messages)
	{
		msg = (POOL_PENDING_MESSAGE *) lfirst(cell);
		pfree(msg->contents);
	}
	list_free(session_context->pending_messages);
}

/*
 * Create one message.
 */
POOL_PENDING_MESSAGE *
pool_pending_message_create(char kind, int len, char *contents)
{
	POOL_PENDING_MESSAGE *msg;
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_pending_message_create: session context is not initialized")));

	old_context = MemoryContextSwitchTo(session_context->memory_context);
	msg = palloc(sizeof(POOL_PENDING_MESSAGE));

	switch (kind)
	{
		case 'P':
			msg->type = POOL_PARSE;
			break;

		case 'B':
			msg->type = POOL_BIND;
			break;

		case 'E':
			msg->type = POOL_EXECUTE;
			break;

		case 'D':
			msg->type = POOL_DESCRIBE;
			break;

		case 'C':
			msg->type = POOL_CLOSE;
			break;

		case 'S':
			msg->type = POOL_SYNC;
			break;

		default:
			ereport(ERROR,
					(errmsg("pool_pending_message_create: unknown kind: %c", kind)));
			break;
	}

	if (len > 0)
	{
		msg->contents = palloc(len);
		memcpy(msg->contents, contents, len);
	}
	else
		msg->contents = NULL;

	msg->contents_len = len;
	msg->query[0] = '\0';
	msg->statement[0] = '\0';
	msg->portal[0] = '\0';
	msg->is_rows_returned = false;
	msg->not_forward_to_frontend = false;
	memset(msg->node_ids, false, sizeof(msg->node_ids));
	msg->flush_pending = false;

	MemoryContextSwitchTo(old_context);

	return msg;
}

/*
 * Set node_ids field of message which indicates which backend nodes the
 * message was sent.
 */
void
pool_pending_message_dest_set(POOL_PENDING_MESSAGE * message, POOL_QUERY_CONTEXT * query_context)
{
	memcpy(message->node_ids, query_context->where_to_send, sizeof(message->node_ids));

	message->query_context = query_context;

	if (is_select_query(query_context->parse_tree, query_context->original_query))
	{
		message->is_rows_returned = true;
	}
}

/*
 * Set where_to_send field in query_context from node_ids field of message
 * which indicates which backend nodes the message was sent.
 */
void
pool_pending_message_query_context_dest_set(POOL_PENDING_MESSAGE * message, POOL_QUERY_CONTEXT * query_context)
{
	int			i;

	POOL_SESSION_CONTEXT *s = pool_get_session_context(false);

	/* Save where_to_send map */
	memcpy(s->where_to_send_save, query_context->where_to_send, sizeof(s->where_to_send_save));
	s->need_to_restore_where_to_send = true;

	/* Rewrite where_to_send map */
	memset(query_context->where_to_send, 0, sizeof(query_context->where_to_send));

	for (i = 0; i < MAX_NUM_BACKENDS; i++)
	{
		if (message->node_ids[i])
		{
			query_context->where_to_send[i] = 1;
		}
	}
}

/*
 * Set query field of message.
 */
void
pool_pending_message_query_set(POOL_PENDING_MESSAGE * message, POOL_QUERY_CONTEXT * query_context)
{
	StrNCpy(message->query, query_context->original_query, sizeof(message->query));
}

/*
 * Add one message to the tail of the list.
 */
void
pool_pending_message_add(POOL_PENDING_MESSAGE * message)
{
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_pending_message_add: session context is not initialized")));

	switch (message->type)
	{
		case POOL_PARSE:
			StrNCpy(message->statement, message->contents, sizeof(message->statement));
			StrNCpy(message->query, message->contents + strlen(message->contents) + 1, sizeof(message->query));
			break;

		case POOL_BIND:
			StrNCpy(message->portal, message->contents, sizeof(message->portal));
			StrNCpy(message->statement, message->contents + strlen(message->contents) + 1, sizeof(message->statement));
			break;

		case POOL_EXECUTE:
			StrNCpy(message->portal, message->contents, sizeof(message->portal));
			break;

		case POOL_CLOSE:
		case POOL_DESCRIBE:
			if (*message->contents == 'S')
				StrNCpy(message->statement, message->contents + 1, sizeof(message->statement));
			else
				StrNCpy(message->portal, message->contents + 1, sizeof(message->portal));
			break;

		case POOL_SYNC:
			break;

		default:
			ereport(ERROR,
					(errmsg("pool_pending_message_add: unknown message type:%d", message->type)));
			return;
			break;
	}

	if (message->type != POOL_SYNC)
		ereport(Elevel,
				(errmsg("pool_pending_message_add: message type:%s message len:%d query:%s statement:%s portal:%s node_ids[0]:%d node_ids[1]:%d",
						pool_pending_message_type_to_string(message->type),
						message->contents_len, message->query, message->statement, message->portal,
						message->node_ids[0], message->node_ids[1])));
	else
		ereport(Elevel,
				(errmsg("pool_pending_message_add: message type: sync")));

	old_context = MemoryContextSwitchTo(session_context->memory_context);
	session_context->pending_messages = lappend(session_context->pending_messages, message);
	MemoryContextSwitchTo(old_context);
}

/*
 * Return the message from the head of the list.  If the list is not empty, a
 * copy of the message is returned. If the list is empty, returns NULL.
 */
POOL_PENDING_MESSAGE *
pool_pending_message_head_message(void)
{
	ListCell   *cell;
	POOL_PENDING_MESSAGE *message;
	POOL_PENDING_MESSAGE *m;
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_pending_message_head_message: session context is not initialized")));

	if (list_length(session_context->pending_messages) == 0)
	{
		return NULL;
	}

	old_context = MemoryContextSwitchTo(session_context->memory_context);

	cell = list_head(session_context->pending_messages);
	m = (POOL_PENDING_MESSAGE *) lfirst(cell);
	message = copy_pending_message(m);
	ereport(Elevel,
			(errmsg("pool_pending_message_head_message: message type:%s message len:%d query:%s statement:%s portal:%s node_ids[0]:%d node_ids[1]:%d",
					pool_pending_message_type_to_string(message->type),
					message->contents_len, message->query, message->statement, message->portal,
					message->node_ids[0], message->node_ids[1])));

	MemoryContextSwitchTo(old_context);
	return message;
}


/*
 * Remove one message from the head of the list.  If the list is not empty, a
 * copy of the message is returned and the message is removed the message
 * list. If the list is empty, returns NULL.
 */
POOL_PENDING_MESSAGE *
pool_pending_message_pull_out(void)
{
	ListCell   *cell;
	POOL_PENDING_MESSAGE *message;
	POOL_PENDING_MESSAGE *m;
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_pending_message_pull_out: session context is not initialized")));

	if (list_length(session_context->pending_messages) == 0)
	{
		return NULL;
	}

	old_context = MemoryContextSwitchTo(session_context->memory_context);

	cell = list_head(session_context->pending_messages);
	m = (POOL_PENDING_MESSAGE *) lfirst(cell);
	message = copy_pending_message(m);
	ereport(Elevel,
			(errmsg("pool_pending_message_pull_out: message type:%s message len:%d query:%s statement:%s portal:%s node_ids[0]:%d node_ids[1]:%d",
					pool_pending_message_type_to_string(message->type),
					message->contents_len, message->query, message->statement, message->portal,
					message->node_ids[0], message->node_ids[1])));

	pool_pending_message_free_pending_message(m);
	session_context->pending_messages =
		list_delete_cell(session_context->pending_messages, cell);

	MemoryContextSwitchTo(old_context);
	return message;
}

/*
 * Try to find the first message specified by the message type in the message
 * list. If found, a copy of the message is returned. If not, returns NULL.
 */
POOL_PENDING_MESSAGE *
pool_pending_message_get(POOL_MESSAGE_TYPE type)
{
	ListCell   *cell;
	ListCell   *next;
	POOL_PENDING_MESSAGE *msg;
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_pending_message_remove: session context is not initialized")));

	old_context = MemoryContextSwitchTo(session_context->memory_context);

	msg = NULL;

	for (cell = list_head(session_context->pending_messages); cell; cell = next)
	{
		POOL_PENDING_MESSAGE *m = (POOL_PENDING_MESSAGE *) lfirst(cell);

		next = lnext(session_context->pending_messages, cell);

		if (m->type == type)
		{
			msg = copy_pending_message(m);
			break;
		}
	}

	MemoryContextSwitchTo(old_context);
	return msg;
}

/*
 * Get message specification (either statement ('S') or portal ('P')) from a
 * close message.
 */
char
pool_get_close_message_spec(POOL_PENDING_MESSAGE * msg)
{
	return *msg->contents;
}

/*
 * Get statement or portal name from close message.
 * The returned pointer is within "msg".
 */
char *
pool_get_close_message_name(POOL_PENDING_MESSAGE * msg)
{
	return (msg->contents) + 1;
}

/*
 * Perform deep copy of POOL_PENDING_MESSAGE object in the current memory
 * context except the query context.
 */
static POOL_PENDING_MESSAGE * copy_pending_message(POOL_PENDING_MESSAGE * message)
{
	POOL_PENDING_MESSAGE *msg;

	msg = palloc(sizeof(POOL_PENDING_MESSAGE));
	memcpy(msg, message, sizeof(POOL_PENDING_MESSAGE));
	msg->contents = palloc(msg->contents_len);
	memcpy(msg->contents, message->contents, msg->contents_len);

	return msg;
}

/*
 * Free POOL_PENDING_MESSAGE object in the current memory
 * context except the query context.
 */
void
pool_pending_message_free_pending_message(POOL_PENDING_MESSAGE * message)
{
	if (message == NULL)
		return;

	if (message->contents)
		pfree(message->contents);

	pfree(message);
}

/*
 * Reset previous message.
 */
void
pool_pending_message_reset_previous_message(void)
{
	if (!session_context)
	{
		ereport(ERROR,
				(errmsg("pool_pending_message_reset_previous_message: session context is not initialized")));
		return;
	}
	session_context->previous_message_exists = false;
}

/*
 * Set previous message.
 */
void
pool_pending_message_set_previous_message(POOL_PENDING_MESSAGE * message)
{
	if (!session_context)
	{
		ereport(ERROR,
				(errmsg("pool_pending_message_set_previous_message: session context is not initialized")));
		return;
	}
	session_context->previous_message_exists = true;
	memcpy(&session_context->previous_message, message, sizeof(POOL_PENDING_MESSAGE));
}

/*
 * Get previous message. This actually returns the address of memory. Do not
 * try to free using pool_pending_message_free_pending_message().
 */
POOL_PENDING_MESSAGE *
pool_pending_message_get_previous_message(void)
{
	if (!session_context)
	{
		ereport(ERROR,
				(errmsg("pool_pending_message_get_previous_message: session context is not initialized")));
		return NULL;
	}
	if (session_context->previous_message_exists == false)
		return NULL;

	return &session_context->previous_message;
}

/*
 * Return true if there's any pending message.
 */
bool
pool_pending_message_exists(void)
{
	return list_length(session_context->pending_messages) > 0;
}

/*
 * Convert enum pending message type to string. The returned string must not
 * be modified or freed.
 */
const char *
pool_pending_message_type_to_string(POOL_MESSAGE_TYPE type)
{
	static const char *pending_msg_string[] = {"Parse", "Bind", "Execute",
	"Describe", "Close", "Sync"};

	if (type < 0 || type > POOL_SYNC)
		return "unknown type";
	return pending_msg_string[type];
}

/*
 * Check consistency the message type and backend message kind.
 * This function is intended to be used for debugging.
 */
void
pool_check_pending_message_and_reply(POOL_MESSAGE_TYPE type, char kind)
{
	/*
	 * Backend response message sorted by POOL_MESSAGE_TYPE
	 */
	static char backend_response_kind[] = {
		'1',					/* POOL_PARSE, parse complete */
		'2',					/* POOL_BIND, bind complete */
		'*',					/* POOL_EXECUTE, skip checking */
		'*',					/* POOL_DESCRIBE, skip checking */
		'3',					/* POOL_CLOSE, close complete */
		'Z'						/* POOL_SYNC, ready for query */
	};

	if (type < POOL_PARSE || type > POOL_SYNC)
	{
		ereport(DEBUG5,
				(errmsg("pool_check_pending_message_and_reply: type out of range: %d", type)));
		return;
	}

	if (backend_response_kind[type] == '*')
	{
		return;
	}

	if (backend_response_kind[type] != kind)
	{
		ereport(DEBUG5,
				(errmsg("pool_check_pending_message_and_reply: type: %s but is kind: %c",
						pool_pending_message_type_to_string(type), kind)));
	}
	return;
}

/*
 * Find the latest pending message having specified query context.  The
 * returned message is a pointer to the message list. So do not free it using
 * pool_pending_message_free_pending_message.
 */
POOL_PENDING_MESSAGE *
pool_pending_message_find_lastest_by_query_context(POOL_QUERY_CONTEXT * qc)
{
	List	   *msgs;
	POOL_PENDING_MESSAGE *msg;
	int			len;
	ListCell   *cell;

	if (!session_context)
	{
		ereport(ERROR,
				(errmsg("pool_pending_message_find_lastest_by_query_context: session context is not initialized")));
	}

	if (!session_context->pending_messages)
		return NULL;

	msgs = session_context->pending_messages;

	len = list_length(msgs);
	if (len <= 0)
		return NULL;

	ereport(DEBUG5,
			(errmsg("pool_pending_message_find_lastest_by_query_context: num messages: %d",
					len)));

	while (len--)
	{
		cell = list_nth_cell(msgs, len);
		if (cell)
		{
			msg = (POOL_PENDING_MESSAGE *) lfirst(cell);
			if (msg->query_context == qc)
			{
				ereport(DEBUG5,
						(errmsg("pool_pending_message_find_lastest_by_query_context: msg found. type: %s",
								pool_pending_message_type_to_string(msg->type))));
				return msg;
			}
			ereport(DEBUG5,
					(errmsg("pool_pending_message_find_lastest_by_query_context: type: %s",
							pool_pending_message_type_to_string(msg->type))));
		}
	}
	return NULL;
}

/*
 * Get target backend id from pending message assuming that the destination for
 * the pending message is one of primary or standby node.
 */
int
pool_pending_message_get_target_backend_id(POOL_PENDING_MESSAGE * msg)
{
	int			backend_id = -1;
	int			i;

	for (i = 0; i < MAX_NUM_BACKENDS; i++)
	{
		if (msg->node_ids[i])
		{
			backend_id = i;
			break;
		}
	}

	if (backend_id == -1)
		ereport(ERROR,
				(errmsg("pool_pending_message_get_target_backend_id: no target backend id found")));

	return backend_id;
}

/*
 * Get number of pending message list entries of which target backend is same as specified one.
 */
int
pool_pending_message_get_message_num_by_backend_id(int backend_id)
{
	ListCell   *cell;
	ListCell   *next;
	int        cnt = 0;
	int        i;

	if (!session_context)
	{
		ereport(ERROR,
				(errmsg("pool_pending_message_get_message_num_by_backend_id: session context is not initialized")));
		return 0;
	}

	for (cell = list_head(session_context->pending_messages); cell; cell = next)
	{
		POOL_PENDING_MESSAGE *msg = (POOL_PENDING_MESSAGE *) lfirst(cell);

		for (i = 0; i < MAX_NUM_BACKENDS; i++)
		{
			if (msg->node_ids[i] && i == backend_id)
			{
				cnt++;
				break;
			}
		}

		next = lnext(session_context->pending_messages, cell);
	}
	return cnt;
}

/*
 * Set flush request flag
 */
void
pool_pending_message_set_flush_request(void)
{
	ListCell   *msg_item;

	foreach(msg_item, session_context->pending_messages)
	{
		POOL_PENDING_MESSAGE *msg = (POOL_PENDING_MESSAGE *) lfirst(msg_item);
		msg->flush_pending = true;
		ereport(DEBUG5,
				(errmsg("pool_pending_message_set_flush_request: msg: %s",
						pool_pending_message_type_to_string(msg->type))));
	}
}

/*
 * Dump whole pending message list
 */
void
dump_pending_message(void)
{
	ListCell   *cell;
	ListCell   *next;

	if (!session_context)
	{
		ereport(ERROR,
				(errmsg("dump_pending_message: session context is not initialized")));
		return;
	}

	if (!message_level_is_interesting(DEBUG5))
		return;

	ereport(DEBUG5,
			(errmsg("start dumping pending message list")));

	for (cell = list_head(session_context->pending_messages); cell; cell = next)
	{
		POOL_PENDING_MESSAGE *message = (POOL_PENDING_MESSAGE *) lfirst(cell);

		ereport(DEBUG5,
				(errmsg("pool_pending_message_dump: message type:%d message len:%d query:%s statement:%s portal:%s node_ids[0]:%d node_ids[1]:%d",
						message->type, message->contents_len, message->query, message->statement, message->portal,
						message->node_ids[0], message->node_ids[1])));

		next = lnext(session_context->pending_messages, cell);
	}

	ereport(DEBUG5,
			(errmsg("end dumping pending message list")));
}

/*
 * Set protocol major version number
 */
void
pool_set_major_version(int major)
{
	if (session_context)
	{
		session_context->major = major;
	}
}

/*
 * Get protocol major version number
 */
int
pool_get_major_version(void)
{
	if (session_context)
	{
		return session_context->major;
	}
	return PROTO_MAJOR_V3;
}

/*
 * Set protocol minor version number
 */
void
pool_set_minor_version(int minor)
{
	if (session_context)
	{
		session_context->minor = minor;
	}
}

/*
 * Get protocol minor version number
 */
int
pool_get_minor_version(void)
{
	if (session_context)
	{
		return session_context->minor;
	}
	return 0;
}

/*
 * Is suspend_reading_from_frontend flag set?
 */
bool
pool_is_suspend_reading_from_frontend(void)
{
	return session_context->suspend_reading_from_frontend;
}

/*
 * Set suspend_reading_from_frontend flag.
 */
void
pool_set_suspend_reading_from_frontend(void)
{
	session_context->suspend_reading_from_frontend = true;
}

/*
 * Unset suspend_reading_from_frontend flag.
 */
void
pool_unset_suspend_reading_from_frontend(void)
{
	session_context->suspend_reading_from_frontend = false;
}

/*-----------------------------------------------------------------------
 * Temporary table list management modules.
 *-----------------------------------------------------------------------
 */

/*
 * Initialize temp table list
 */
void
pool_temp_tables_init(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_init: session context is not initialized")));

	session_context->temp_tables = NIL;
}

/*
 * Destroy temp table list
 */
void
pool_temp_tables_destroy(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_destroy: session context is not initialized")));

	list_free(session_context->temp_tables);
}

/*
 * Add a temp table to the tail of the list.
 * If the table already exists, just replace state.
 */
void
pool_temp_tables_add(char * tablename, POOL_TEMP_TABLE_STATE state)
{
	MemoryContext old_context;
	POOL_TEMP_TABLE * table;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_add: session context is not initialized")));

	old_context = MemoryContextSwitchTo(session_context->memory_context);

	table = pool_temp_tables_find(tablename);
	if (table)
	{
		/* Table already exists. Just replace state. */
		table->state = state;
	}
	else
	{
		table = palloc(sizeof(POOL_TEMP_TABLE));
		StrNCpy(table->tablename, tablename, sizeof(table->tablename));
		table->state = state;
		session_context->temp_tables = lappend(session_context->temp_tables, table);
	}

	MemoryContextSwitchTo(old_context);
}

/*
 * Returns pointer to the table cell if specified tablename is in the temp table list.
 */

POOL_TEMP_TABLE *
pool_temp_tables_find(char * tablename)
{
	ListCell   *cell;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_find: session context is not initialized")));

	foreach(cell, session_context->temp_tables)
	{
		POOL_TEMP_TABLE * table = (POOL_TEMP_TABLE *)lfirst(cell);
		if (strcmp(tablename, table->tablename) == 0)
			return table;
	}
	return NULL;
}

/*
 * If requested state or table state is TEMP_TABLE_DROP_COMMITTED, removes the
 * temp table entry from the list.  Otherwise just set the requested state to
 * the table state.
 */
void
pool_temp_tables_delete(char * tablename, POOL_TEMP_TABLE_STATE state)
{
	POOL_TEMP_TABLE * table;
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_delete: session context is not initialized")));

	ereport(LOG,
			(errmsg("pool_temp_tables_delete: table: %s state: %d", tablename, state)));

	old_context = MemoryContextSwitchTo(session_context->memory_context);

	table = pool_temp_tables_find(tablename);

	if (table)
	{
		if (table->state == TEMP_TABLE_DROP_COMMITTED)
		{
			ereport(DEBUG1,
					(errmsg("pool_temp_tables_delete: remove %s. previous state: %d requested state: %d",
							table->tablename, table->state, state)));

			session_context->temp_tables = list_delete_ptr(session_context->temp_tables, table);
		}
		else
		{
			ereport(DEBUG1,
					(errmsg("pool_temp_tables_delete: set state %s. previous state: %d requested state: %d",
							table->tablename, table->state, state)));
			table->state = state;
		}
	}

	MemoryContextSwitchTo(old_context);
}

/*
 * Commits creating entries. Also remove dropping entries. This is supposed to
 * be called when an explicit transaction commits.
 */
void
pool_temp_tables_commit_pending(void)
{
	ListCell   *cell;
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_commit_pending: session context is not initialized")));

	old_context = MemoryContextSwitchTo(session_context->memory_context);

	pool_temp_tables_dump();

Retry:
	foreach(cell, session_context->temp_tables)
	{
		POOL_TEMP_TABLE * table = (POOL_TEMP_TABLE *)lfirst(cell);

		if (table->state == TEMP_TABLE_CREATING)
		{
			ereport(DEBUG1,
					(errmsg("pool_temp_tables_commit_pending: commit: %s", table->tablename)));

			table->state = TEMP_TABLE_CREATE_COMMITTED;
		}
		else if (table->state == TEMP_TABLE_DROPPING)
		{
			ereport(DEBUG1,
					(errmsg("pool_temp_tables_commit_pending: remove: %s", table->tablename)));
			session_context->temp_tables = list_delete_cell(session_context->temp_tables, cell);
			pool_temp_tables_dump();
			goto Retry;
		}
	}

	MemoryContextSwitchTo(old_context);
}

/*
 * Removes all ongoing creating or dropping entries. This is supposed to be
 * called when an explicit transaction aborts.
 */
void
pool_temp_tables_remove_pending(void)
{
	ListCell   *cell;
	MemoryContext old_context;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_remove_pending: session context is not initialized")));

	old_context = MemoryContextSwitchTo(session_context->memory_context);

	pool_temp_tables_dump();

Retry:
	foreach(cell, session_context->temp_tables)
	{
		POOL_TEMP_TABLE * table = (POOL_TEMP_TABLE *)lfirst(cell);

		if (table->state == TEMP_TABLE_CREATING || table->state == TEMP_TABLE_DROPPING)
		{
			ereport(DEBUG1,
					(errmsg("pool_temp_tables_remove_pending: remove: %s", table->tablename)));

			session_context->temp_tables = list_delete_cell(session_context->temp_tables, cell);
			pool_temp_tables_dump();
			goto Retry;
		}
	}

	MemoryContextSwitchTo(old_context);
}

void
pool_temp_tables_dump(void)
{
#ifdef TEMP_TABLES_DEBUG
	ListCell   *cell;

	if (!session_context)
		ereport(ERROR,
				(errmsg("pool_temp_tables_dump: session context is not initialized")));

	foreach(cell, session_context->temp_tables)
	{
		POOL_TEMP_TABLE * table = (POOL_TEMP_TABLE *)lfirst(cell);
		ereport(DEBUG1,
				(errmsg("pool_temp_tables_dump: table %s state: %d",
						table->tablename, table->state)));
	}
#endif

}

/*
 * Return true if an explicit transaction has been started by a
 * multi-statement-query
 */
bool
is_tx_started_by_multi_statement_query(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("is_tx_started_by_multi_statement_query: session context is not initialized")));

	return session_context->is_tx_started_by_multi_statement;
}

/*
 * Remember that an explicit transaction has been started by a
 * multi-statement-query
 */
void
set_tx_started_by_multi_statement_query(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("set_tx_started_by_multi_statement_query: session context is not initialized")));

	session_context->is_tx_started_by_multi_statement = true;
}

/*
 * Forget that an explicit transaction has been started by a
 * multi-statement-query
 */
void
unset_tx_started_by_multi_statement_query(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("unset_tx_started_by_multi_statement_query: session context is not initialized")));

	session_context->is_tx_started_by_multi_statement = false;
}

/*
 * Set query_cache_disabled
 */
void
set_query_cache_disabled(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("set_query_cache_disabled: session context is not initialized")));

	session_context->query_cache_disabled = true;
}

/*
 * Unset query_cache_disabled
 */
void
unset_query_cache_disabled(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("unset_query_cache_disabled: session context is not initialized")));

	session_context->query_cache_disabled = false;
}

/*
 * Get query_cache_disabled
 */
bool
query_cache_disabled(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("query_cache_disabled: session context is not initialized")));

	return session_context->query_cache_disabled ||
		session_context->query_cache_disabled_tx;
}

/*
 * Set query_cache_disabled in transaction
 */
void
set_query_cache_disabled_tx(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("set_query_cache_disabled_tx: session context is not initialized")));

	session_context->query_cache_disabled_tx = true;
}

/*
 * Unset query_cache_disabled in transaction
 */
void
unset_query_cache_disabled_tx(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("unset_query_cache_disabled_tx: session context is not initialized")));

	session_context->query_cache_disabled_tx = false;
}

/*
 * Get query_cache_disabled in transaction
 */
bool
query_cache_disabled_tx(void)
{
	if (!session_context)
		ereport(ERROR,
				(errmsg("query_cache_disabled_tx: session context is not initialized")));

	return session_context->query_cache_disabled_tx;
}