aboutsummaryrefslogtreecommitdiff
path: root/src/database_postgres.cc
blob: 1cbd4e7a1091199672daa2753097965c5048863a (plain) (blame)
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
#if DATABASE_POSTGRESQL
#include "querymanager.hh"
#include "libpq-fe.h"

// IMPORTANT(fusion): With PostgreSQL being a distributed database, we cannot
// rely on automatic schema upgrades like in the case of SQLite. It must be
// managed manually and there must be an agreement on the current version
// which is why there is a `SchemaInfo` table.
#define POSTGRESQL_SCHEMA_VERSION 1

// IMPORTANT(fusion): These are the OIDs for a few of built-in data types in
// PostgreSQL. They're taken from `catalog/pg_type_d.h` which is not included
// with libpq but should be STABLE across different versions and are needed
// for properly handling binary data from the server.
#define BOOLOID 16
#define BYTEAOID 17
#define CHAROID 18
#define INT8OID 20
#define INT2OID 21
#define INT4OID 23
#define TEXTOID 25
#define FLOAT4OID 700
#define FLOAT8OID 701
#define CIDROID 650
#define INETOID 869
#define VARCHAROID 1043
#define DATEOID 1082
#define TIMEOID 1083
#define TIMESTAMPOID 1114
#define TIMESTAMPTZOID 1184
#define INTERVALOID 1186
#define TIMETZOID 1266

struct TCachedStatement{
	char             Name[16];
	int              LastUsed;
	uint32           Hash;
	char             *Text;
};

struct TDatabase{
	PGconn           *Handle;
	int              MaxCachedStatements;
	TCachedStatement *CachedStatements;
};

// Param Buffer
//==============================================================================
struct ParamBuffer{
	const char **Values;
	int *Lengths;
	int *Formats;
	int NumParams;
	int MaxParams;
	int PreferredFormat;

	// NOTE(fusion): 8KB should be more than enough for all case scenarios. We'll
	// know if it's not.
	int ArenaPos;
	uint8 Arena[KB(8)];
};

static void *ParamAllocImpl(ParamBuffer *Params, int Size, int Alignment){
	usize ArenaStart = (usize)Params->Arena;
	usize ArenaEnd   = ArenaStart + sizeof(Params->Arena);
	usize ArenaPos   = ArenaStart + Params->ArenaPos;
	usize AllocStart = AlignUp(ArenaPos, Alignment);
	usize AllocEnd   = AllocStart + Size;
	if(AllocEnd > ArenaEnd){
		PANIC("Param buffer is FULL");
	}

	Params->ArenaPos = (int)(AllocEnd - ArenaStart);
	return (void*)AllocStart;
}

template<typename T>
static T *ParamAlloc(ParamBuffer *Params, int Count){
	ASSERT(Count > 0);
	return (T*)ParamAllocImpl(Params, sizeof(T) * Count, alignof(T));
}

static void ParamBegin(ParamBuffer *Params, int MaxParams, int PreferredFormat){
	ASSERT(MaxParams > 0);

	// NOTE(fusion): Reset arena.
	memset(Params->Arena, 0, sizeof(Params->Arena));
	Params->ArenaPos = 0;

	// NOTE(fusion): Reset params.
	Params->Values = ParamAlloc<const char*>(Params, MaxParams);
	Params->Lengths = ParamAlloc<int>(Params, MaxParams);
	Params->Formats = ParamAlloc<int>(Params, MaxParams);
	Params->NumParams = 0;
	Params->MaxParams = MaxParams;
	Params->PreferredFormat = PreferredFormat;
}

static void InsertParam(ParamBuffer *Params, const char *Param, int Length, int Format){
	if(Params->NumParams >= Params->MaxParams){
		PANIC("Too many parameters specified (%d/%d)",
				Params->NumParams + 1, Params->MaxParams);
	}

	Params->Values[Params->NumParams] = Param;
	Params->Lengths[Params->NumParams] = Length;
	Params->Formats[Params->NumParams] = Format;
	Params->NumParams += 1;
}

static void InsertTextParam(ParamBuffer *Params, const char *Text){
	int TextLength = (int)strlen(Text);
	char *Copy = ParamAlloc<char>(Params, TextLength + 1);
	memcpy(Copy, Text, TextLength + 1);
	InsertParam(Params, Copy, TextLength, 0);
}

static void InsertBinaryParam(ParamBuffer *Params, const uint8 *Data, int Length){
	uint8 *Copy = ParamAlloc<uint8>(Params, Length);
	memcpy(Copy, Data, Length);
	InsertParam(Params, (const char*)Copy, Length, 1);
}

static void ParamBool(ParamBuffer *Params, bool Value){
	if(Params->PreferredFormat == 1){ // BINARY FORMAT
		uint8 Data = (Value ? 0x01 : 0x00);
		InsertBinaryParam(Params, &Data, 1);
	}else{                            // TEXT FORMAT
		InsertTextParam(Params, (Value ? "TRUE" : "FALSE"));
	}
}

static void ParamInteger(ParamBuffer *Params, int Value){
	if(Params->PreferredFormat == 1){ // BINARY FORMAT
		uint8 Data[4];
		BufferWrite32BE(Data, (uint32)Value);
		InsertBinaryParam(Params, Data, 4);
	}else{
		char Text[16] = {};
		StringBufFormat(Text, "%d", Value);
		InsertTextParam(Params, Text);
	}
}

static void ParamText(ParamBuffer *Params, const char *Text){
	// NOTE(fusion): Always use TEXT format.
	InsertTextParam(Params, Text);
}

static void ParamByteA(ParamBuffer *Params, const uint8 *Data, int Length){
	// TODO(fusion): Always use BINARY format?
	InsertBinaryParam(Params, Data, Length);
}

// Result Helpers
//==============================================================================
struct AutoResultClear{
private:
	PGresult *m_Result;

public:
	AutoResultClear(PGresult *Result){
		m_Result = Result;
	}

	~AutoResultClear(void){
		if(m_Result != NULL){
			PQclear(m_Result);
			m_Result = NULL;
		}
	}
};

static bool GetResultBool(PGresult *Result, int Row, int Col){
	bool Value = false;
	int Format = PQfformat(Result, Col);
	Oid Type = PQftype(Result, Col);
	if(Format == 0){       // TEXT FORMAT
		if(!ParseBoolean(&Value, PQgetvalue(Result, Row, Col))){
			LOG_ERR("Failed to properly parse column (%d) %s as BOOLEAN",
					Col, PQfname(Result, Col));
		}
	}else if(Format == 1){ // BINARY FORMAT
		switch(Type){
			case BOOLOID:{
				ASSERT(PQgetlength(Result, Row, Col) == 1);
				Value = (BufferRead8((const uint8*)PQgetvalue(Result, Row, Col)) != 0);
				break;
			}

			case INT8OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 8);
				Value = (BufferRead64BE((const uint8*)PQgetvalue(Result, Row, Col)) != 0);
				break;
			}

			case INT2OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 2);
				Value = (BufferRead16BE((const uint8*)PQgetvalue(Result, Row, Col)) != 0);
				break;
			}

			case INT4OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 4);
				Value = (BufferRead32BE((const uint8*)PQgetvalue(Result, Row, Col)) != 0);
				break;
			}

			case TEXTOID:
			case VARCHAROID:{
				if(!ParseBoolean(&Value, PQgetvalue(Result, Row, Col))){
					LOG_WARN("Failed to properly convert column (%d) %s from TEXT to BOOLEAN",
							Col, PQfname(Result, Col));
				}
				break;
			}

			default:{
				LOG_ERR("Column (%d) %s has OID %d which is not convertible to BOOLEAN",
						Col, PQfname(Result, Col), Type);
				break;
			}
		}
	}
	return Value;
}

static int GetResultInt(PGresult *Result, int Row, int Col){
	int Value = 0;
	int Format = PQfformat(Result, Col);
	Oid Type = PQftype(Result, Col);
	ASSERT(Format == 0 || Format == 1);
	if(Format == 0){       // TEXT FORMAT
		if(!ParseInteger(&Value, PQgetvalue(Result, Row, Col))){
			LOG_ERR("Failed to properly parse column (%d) %s as INT4",
					Col, PQfname(Result, Col));
		}
	}else if(Format == 1){ // BINARY FORMAT
		switch(Type){
			case BOOLOID:{
				ASSERT(PQgetlength(Result, Row, Col) == 1);
				Value = BufferRead8((const uint8*)PQgetvalue(Result, Row, Col));
				break;
			}

			case INT8OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 8);
				int64 Temp = (int64)BufferRead64BE((const uint8*)PQgetvalue(Result, Row, Col));
				if(Temp < INT_MIN || Temp > INT_MAX){
					LOG_WARN("Lossy conversion of column (%d) %s from INT8 to INT4",
							Col, PQfname(Result, Col));
				}

				Value = (int)Temp;
				break;
			}

			case INT2OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 2);
				Value = (int16)BufferRead16BE((const uint8*)PQgetvalue(Result, Row, Col));
				break;
			}

			case INT4OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 4);
				Value = (int)BufferRead32BE((const uint8*)PQgetvalue(Result, Row, Col));
				break;
			}

			case TEXTOID:
			case VARCHAROID:{
				if(!ParseInteger(&Value, PQgetvalue(Result, Row, Col))){
					LOG_WARN("Failed to properly convert column (%d) %s from TEXT to INT4",
							Col, PQfname(Result, Col));
				}
				break;
			}

			default:{
				LOG_ERR("Column (%d) %s has OID %d which is not convertible to INT4",
						Col, PQfname(Result, Col), Type);
				break;
			}
		}
	}
	return Value;
}

static const char *GetResultText(PGresult *Result, int Row, int Col){
	const char *Text = "";
	int Format = PQfformat(Result, Col);
	Oid Type = PQftype(Result, Col);
	ASSERT(Format == 0 || Format == 1);
	if(Format == 0){       // TEXT FORMAT
		Text = PQgetvalue(Result, Row, Col);
	}else if(Format == 1){ // BINARY FORMAT
		switch(Type){
			case TEXTOID:
			case VARCHAROID:{
				Text = PQgetvalue(Result, Row, Col);
				break;
			}

			default:{
				// IMPORTANT(fusion): There is no trivial way to convert whatever
				// value we received back to string. We'd either need to allocate
				// or modify the prototype of this function to accept an output
				// buffer.
				//  The fact is, we shouldn't expect implicit conversions to work
				// when using the binary format, PERIOD.
				LOG_ERR("Column (%d) %s has OID %d which is not trivially convertible to TEXT",
						Col, PQfname(Result, Col), Type);
				break;
			}
		}
	}
	return Text;
}

static int GetResultByteA(PGresult *Result, int Row, int Col, uint8 *Buffer, int BufferSize){
	int Size = -1;
	int Format = PQfformat(Result, Col);
	ASSERT(Format == 0 || Format == 1);
	if(Format == 0){       // TEXT FORMAT
		const char *String = PQgetvalue(Result, Row, Col);
		if(String[0] == '\\' && String[1] == 'x'){
			Size = ParseHexString(Buffer, BufferSize, String + 2);
		}else{
			LOG_ERR("Column (%d) %s (OID %d) doesn't contain a valid BYTEA literal",
					Col, PQfname(Result, Col), PQftype(Result, Col));
		}
	}else if(Format == 1){ // BINARY FORMAT
		Size = PQgetlength(Result, Row, Col);
		if(Size > 0 && Size < BufferSize){
			memcpy(Buffer, PQgetvalue(Result, Row, Col), Size);
		}
	}

	ASSERT(Size <= BufferSize);
	return Size;
}

static int GetResultIPAddress(PGresult *Result, int Row, int Col){
	int IPAddress = 0;
	int Format = PQfformat(Result, Col);
	Oid Type = PQftype(Result, Col);
	ASSERT(Format == 0 || Format == 1);
	if(Format == 0){       // TEXT FORMAT
		if(!ParseIPAddress(&IPAddress, PQgetvalue(Result, Row, Col))){
			LOG_ERR("Failed to parse column (%d) %s as IPV4",
					Col, PQfname(Result, Col));
		}
	}else if(Format == 1){ // BINARY FORMAT
		switch(Type){
			case INT8OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 8);
				int64 Temp = (int64)BufferRead64BE((const uint8*)PQgetvalue(Result, Row, Col));
				if(Temp < INT_MIN || Temp > INT_MAX){
					LOG_WARN("Lossy conversion of column (%d) %s from INT8 to IPV4",
							Col, PQfname(Result, Col));
				}

				IPAddress = (int)Temp;
				break;
			}

			case INT4OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 4);
				IPAddress = (int)BufferRead32BE((const uint8*)PQgetvalue(Result, Row, Col));
				break;
			}


			case TEXTOID:
			case VARCHAROID:{
				if(!ParseIPAddress(&IPAddress, PQgetvalue(Result, Row, Col))){
					LOG_ERR("Failed to convert column (%d) %s from TEXT to IPV4",
							Col, PQfname(Result, Col));
				}
				break;
			}

			case CIDROID:
			case INETOID:{
				int Size = PQgetlength(Result, Row, Col);
				const uint8 *Data = (const uint8*)PQgetvalue(Result, Row, Col);
				if(Size >= 4){
					int AddressType = (int)Data[0]; // 0x02 for IPV4, 0x03 for IPV6
					// Data[1]; // mask bits
					// Data[2]; // always ZERO for INET, always ONE for CIDR
					int AddressSize = (int)Data[3];
					if(AddressType == 2 && AddressSize == 4 && Size >= 8){
						IPAddress = (int)BufferRead32BE(Data + 4);
					}else{
						LOG_ERR("CIDR/INET column (%d) %s doesn't contain IPV4 address",
								Col, PQfname(Result, Col));
					}
				}else{
					LOG_ERR("CIDR/INET column (%d) %s has unexpected binary format",
							Col, PQfname(Result, Col));
				}
				break;
			}

			default:{
				LOG_ERR("Column (%d) %s has OID %d which is not convertible to IPV4",
						Col, PQfname(Result, Col), Type);
				break;
			}
		}
	}
	return IPAddress;

}

static bool ParseTimestamp(int *Dest, const char *String){
	// TODO(fusion): I don't think this function exists on Windows but neither
	// are we running on Windows so does it even matter? There might be better
	// ways to properly parse this timestamp format.
	struct tm tm = {};
	const char *Rem = strptime(String, "%Y-%m-%d %H:%M:%S", &tm);
	if(Rem == NULL){
		LOG_ERR("Invalid timestamp format \"%s\"", String);
		return false;
	}

	// NOTE(fusion): Skip optional milliseconds/microseconds.
	if(Rem[0] == '.'){
		Rem += 1;
		while(isdigit(Rem[0])){
			Rem += 1;
		}
	}

	// NOTE(fusion): Parse optional timezone.
	int TimezoneOffset = 0;
	if(Rem[0] == '-' || Rem[0] == '+'){
		if(isdigit(Rem[1]) && isdigit(Rem[2])){
			TimezoneOffset = (Rem[1] - '0') * 10
							+ (Rem[2] - '0');
			if(Rem[0] == '+'){
				TimezoneOffset = -TimezoneOffset;
			}
		}
	}

	*Dest = (int)timegm(&tm) + TimezoneOffset * 3600;
	return true;
}

static int GetResultTimestamp(PGresult *Result, int Row, int Col){
	int Timestamp = 0;
	int Format = PQfformat(Result, Col);
	Oid Type = PQftype(Result, Col);
	ASSERT(Format == 0 || Format == 1);
	if(Format == 0){       // TEXT FORMAT
		if(!ParseTimestamp(&Timestamp, PQgetvalue(Result, Row, Col))){
			LOG_ERR("Failed to parse column (%d) %s as TIMESTAMP",
					Col, PQfname(Result, Col));
		}
	}else if(Format == 1){ // BINARY FORMAT
		switch(Type){
			case INT8OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 8);
				int64 Temp = (int64)BufferRead64BE((const uint8*)PQgetvalue(Result, Row, Col));
				if(Temp < INT_MIN || Temp > INT_MAX){
					LOG_WARN("Lossy conversion of column (%d) %s from INT8 to TIMESTAMP",
							Col, PQfname(Result, Col));
				}

				Timestamp = (int)Temp;
				break;
			}

			case INT4OID:{
				ASSERT(PQgetlength(Result, Row, Col) == 4);
				Timestamp = (int)BufferRead32BE((const uint8*)PQgetvalue(Result, Row, Col));
				break;
			}

			case TEXTOID:
			case VARCHAROID:{
				if(!ParseTimestamp(&Timestamp, PQgetvalue(Result, Row, Col))){
					LOG_ERR("Failed to convert column (%d) %s from TEXT to TIMESTAMP",
							Col, PQfname(Result, Col));
				}
				break;
			}

			case TIMESTAMPOID:
			case TIMESTAMPTZOID:{
				ASSERT(PQgetlength(Result, Row, Col) == 8);
				// IMPORTANT(fusion): The timestamp used by PostgreSQL is the number
				// of microseconds since 2000-01-01 00:00:00, with negative values
				// for timestamps before it.
				constexpr int64 PGEpoch = 946692000; // 2000-01-01 00:00:00
				int64 PGTimestamp = (int64)BufferRead64BE((const uint8*)PQgetvalue(Result, Row, Col));
				int64 Timestamp64 = ((PGTimestamp / 1000000) + PGEpoch);
				if(Timestamp64 < INT_MIN){
					Timestamp = INT_MIN;
				}else if(Timestamp64 > INT_MAX){
					Timestamp = INT_MAX;
				}else{
					Timestamp = (int)Timestamp64;
				}
				break;
			}

			default:{
				LOG_ERR("Column (%d) %s has OID %d which is not convertible to TIMESTAMP",
						Col, PQfname(Result, Col), Type);
				break;
			}
		}
	}
	return Timestamp;
}

// Internal Helpers
//==============================================================================
static bool ExecInternal(TDatabase *Database, const char *Format, ...) ATTR_PRINTF(2, 3);
static bool ExecInternal(TDatabase *Database, const char *Format, ...){
	va_list ap;
	va_start(ap, Format);
	char Text[1024];
	int Written = vsnprintf(Text, sizeof(Text), Format, ap);
	va_end(ap);

	if(Written >= (int)sizeof(Text)){
		LOG_ERR("Query is too long");
		return false;
	}

	PGresult *Result = PQexec(Database->Handle, Text);
	AutoResultClear ResultGuard(Result);
	bool Status = PQresultStatus(Result) == PGRES_COMMAND_OK
			|| PQresultStatus(Result) == PGRES_TUPLES_OK;
	if(!Status){
		char Preview[30];
		StringBufCopyEllipsis(Preview, Text);
		LOG_ERR("Failed to execute query \"%s\": %s",
				Preview, PQerrorMessage(Database->Handle));
	}
	return Status;
}

static bool GetSchemaVersion(TDatabase *Database, int *Version){
	PGresult *Result = PQexec(Database->Handle,
			"SELECT Value FROM SchemaInfo WHERE Key = 'VERSION'");
	AutoResultClear ResultGuard(Result);
	if(PQresultStatus(Result) != PGRES_TUPLES_OK){
		LOG_ERR("Failed to execute query: %s",
				PQerrorMessage(Database->Handle));
		return false;
	}

	if(PQntuples(Result) == 0){
		LOG_ERR("Query returned no rows");
		return false;
	}

	*Version = GetResultInt(Result, 0, 0);
	return true;
}

// Statement Cache
//==============================================================================
// NOTE(fusion): Prepared statements are stored server-side and only referenced
// by name. They're not shared between sessions and are automatically cleaned up
// when the connection is CLOSED or RESET.

void EnsureStatementCache(TDatabase *Database){
	ASSERT(Database != NULL);
	if(Database->CachedStatements == NULL){
		ASSERT(g_Config.PostgreSQL.MaxCachedStatements > 0);
		Database->MaxCachedStatements = g_Config.PostgreSQL.MaxCachedStatements;
		if(Database->MaxCachedStatements > 9999){
			LOG_WARN("There is currently a hard limit of 9999 max cached statements"
					" for PostgreSQL but it should be way more than needed because"
					" there are ABSOLUTELY NOT 9999 different queries.");
			Database->MaxCachedStatements = 9999;
		}

		Database->CachedStatements = (TCachedStatement*)calloc(
				Database->MaxCachedStatements, sizeof(TCachedStatement));
		for(int i = 0; i < Database->MaxCachedStatements; i += 1){
			if(!StringBufFormat(Database->CachedStatements[i].Name, "STMT%d", i)){
				PANIC("Failed to format statement cache entry name for STMT%d", i);
			}
		}
	}
}

void DeleteStatementCache(TDatabase *Database){
	ASSERT(Database != NULL);
	if(Database->CachedStatements != NULL){
		ASSERT(Database->MaxCachedStatements > 0);
		for(int i = 0; i < Database->MaxCachedStatements; i += 1){
			TCachedStatement *Entry = &Database->CachedStatements[i];
			if(Entry->Text != NULL){
				free(Entry->Text);
				Entry->LastUsed = 0;
				Entry->Hash = 0;
				Entry->Text = NULL;
			}
		}

		// NOTE(fusion): This function would usually be called along with `PQreset`
		// or `PQfinish` but it's probably a good idea to close all prepared statements
		// if the connection is still going. There is no libpq wrapper but we can
		// execute `DEALLOCATE ALL`.
		if(PQstatus(Database->Handle) == CONNECTION_OK){
			if(!ExecInternal(Database, "DEALLOCATE ALL")){
				LOG_WARN("Failed to close all prepared statements");
			}
		}

		free(Database->CachedStatements);
		Database->MaxCachedStatements = 0;
		Database->CachedStatements = NULL;
	}
}

// IMPORTANT(fusion): Even though it is possible to declare parameter types with
// OIDs, it is simpler to use explicit casts such as `$1::INTEGER` to enforce types.
// It also makes so all relevant information about the query is packed into `Text`
// so we don't need to track anything else to ensure statements with different
// types are kept separate.
const char *PrepareQuery(TDatabase *Database, const char *Text){
	ASSERT(Database != NULL);
	EnsureStatementCache(Database);

	TCachedStatement *Stmt = NULL;
	int LeastRecentlyUsed = 0;
	int LeastRecentlyUsedTime = Database->CachedStatements[0].LastUsed;
	uint32 Hash = HashString(Text);
	for(int i = 0; i < Database->MaxCachedStatements; i += 1){
		TCachedStatement *Entry = &Database->CachedStatements[i];

		if(Entry->LastUsed < LeastRecentlyUsedTime){
			LeastRecentlyUsed = i;
			LeastRecentlyUsedTime = Entry->LastUsed;
		}

		if(Entry->Text != NULL && Entry->Hash == Hash){
			if(StringEq(Entry->Text, Text)){
				Stmt = Entry;
				Entry->LastUsed = GetMonotonicUptimeMS();
				break;
			}
		}
	}

	if(Stmt == NULL){
		Stmt = &Database->CachedStatements[LeastRecentlyUsed];

		if(Stmt->Text != NULL){
			PGresult *Result = PQclosePrepared(Database->Handle, Stmt->Name);
			AutoResultClear ResultGuard(Result);
			if(PQresultStatus(Result) != PGRES_COMMAND_OK){
				char OldPreview[30];
				StringBufCopyEllipsis(OldPreview, Stmt->Text);
				LOG_ERR("Failed to close prepared query \"%s\": %s",
						OldPreview, PQerrorMessage(Database->Handle));
			}
			free(Stmt->Text);
		}

		{
			PGresult *Result = PQprepare(Database->Handle, Stmt->Name, Text, 0, NULL);
			AutoResultClear ResultGuard(Result);
			if(PQresultStatus(Result) != PGRES_COMMAND_OK){
				char NewPreview[30];
				StringBufCopyEllipsis(NewPreview, Text);
				LOG_ERR("Failed to prepare query \"%s\": %s",
						NewPreview, PQerrorMessage(Database->Handle));
				return NULL;
			}
		}


		Stmt->LastUsed = GetMonotonicUptimeMS();
		Stmt->Hash = Hash;
		Stmt->Text = strdup(Text);
		ASSERT(Stmt->Text != NULL);

#if 1 // DEBUG_STATEMENT_CACHE
		{
			char Preview[30];
			StringBufCopyEllipsis(Preview, Text);
			LOG("New statement cached: \"%s\"", Preview);

			PGresult *Result = PQdescribePrepared(Database->Handle, Stmt->Name);
			AutoResultClear ResultGuard(Result);
			if(PQresultStatus(Result) == PGRES_COMMAND_OK){
				LOG("  PARAM OIDs:");
				for(int i = 0; i < PQnparams(Result); i += 1){
					LOG("    $%d: %d", i, PQparamtype(Result, i));
				}

				LOG("  RESULT OIDs:");
				for(int i = 0; i < PQnfields(Result); i += 1){
					LOG("    (%d) %s: %d", i, PQfname(Result, i), PQftype(Result, i));
				}
			}
		}
#endif
	}

	return Stmt->Name;
}

// TransactionScope
//==============================================================================
TransactionScope::TransactionScope(const char *Context){
	m_Context = (Context != NULL ? Context : "NOCONTEXT");
	m_Database = NULL;
}

TransactionScope::~TransactionScope(void){
	if(m_Database != NULL){
		if(!ExecInternal(m_Database, "ROLLBACK")){
			LOG_ERR("Failed to rollback transaction (%s)", m_Context);
		}

		m_Database = NULL;
	}
}

bool TransactionScope::Begin(TDatabase *Database){
	if(m_Database != NULL){
		LOG_ERR("Transaction (%s) already running", m_Context);
		return false;
	}

	if(!ExecInternal(Database, "BEGIN")){
		LOG_ERR("Failed to begin transaction (%s)", m_Context);
		return false;
	}

	m_Database = Database;
	return true;
}

bool TransactionScope::Commit(void){
	if(m_Database == NULL){
		LOG_ERR("Transaction (%s) not running", m_Context);
		return false;
	}

	if(!ExecInternal(m_Database, "COMMIT")){
		LOG_ERR("Failed to commit transaction (%s)", m_Context);
		return false;
	}

	m_Database = NULL;
	return true;
}

// Database Management
//==============================================================================
void DatabaseClose(TDatabase *Database){
	if(Database != NULL){
		if(Database->Handle != NULL){
			PQfinish(Database->Handle);
			Database->Handle = NULL;
		}

		free(Database);
	}
}

TDatabase *DatabaseOpen(void){
	const char *Keys[] = {
		"host",
		"port",
		"dbname",
		"user",
		"password",
		"connect_timeout",
		"client_encoding",
		"application_name",
		"sslmode",
		"sslrootcert",
		NULL, // sentinel
	};

	const char *Values[] = {
		g_Config.PostgreSQL.Host,
		g_Config.PostgreSQL.Port,
		g_Config.PostgreSQL.DBName,
		g_Config.PostgreSQL.User,
		g_Config.PostgreSQL.Password,
		g_Config.PostgreSQL.ConnectTimeout,
		g_Config.PostgreSQL.ClientEncoding,
		g_Config.PostgreSQL.ApplicationName,
		g_Config.PostgreSQL.SSLMode,
		g_Config.PostgreSQL.SSLRootCert,
		NULL, // sentinel
	};

	TDatabase *Database = (TDatabase*)calloc(1, sizeof(TDatabase));
	Database->Handle = PQconnectdbParams(Keys, Values, 0);
	if(Database->Handle == NULL){
		LOG_ERR("Failed to allocate database connection");
		DatabaseClose(Database);
		return NULL;
	}

	if(PQstatus(Database->Handle) != CONNECTION_OK){
		LOG_ERR("Failed to establish connection: %s", PQerrorMessage(Database->Handle));
		DatabaseClose(Database);
		return NULL;
	}

	int SchemaVersion;
	if(!GetSchemaVersion(Database, &SchemaVersion)){
		LOG_ERR("Failed to retrieve schema version..."
				" Database schema may not have been initialized");
		DatabaseClose(Database);
		return NULL;
	}

	if(SchemaVersion != POSTGRESQL_SCHEMA_VERSION){
		LOG_ERR("Schema version MISMATCH (expected %d, got %d)",
				POSTGRESQL_SCHEMA_VERSION, SchemaVersion);
		DatabaseClose(Database);
		return NULL;
	}

	return Database;
}

int DatabaseChanges(TDatabase *Database){
	ASSERT(Database != NULL);
	// TODO?
	return 0;
}

bool DatabaseCheckpoint(TDatabase *Database){
	ASSERT(Database != NULL);
	bool Result = true;
	if(PQstatus(Database->Handle) != CONNECTION_OK){
		DeleteStatementCache(Database);
		PQreset(Database->Handle);
		Result = (PQstatus(Database->Handle) == CONNECTION_OK);
	}
	return Result;
}

int DatabaseMaxConcurrency(void){
	return INT_MAX;
}

// Primary Tables
//==============================================================================
bool GetWorldID(TDatabase *Database, const char *World, int *WorldID){
	ASSERT(Database != NULL && World != NULL && WorldID != NULL);
	const char *Stmt = PrepareQuery(Database,
			"SELECT WorldID FROM Worlds WHERE Name = $1::TEXT");
	if(Stmt == NULL){
		LOG_ERR("Failed to prepare query");
		return false;
	}

	//	TODO(fusion): In this specific case it doesn't make a difference but
	// we'll probably need some helper struct to organize query parameters.
	// It would have an internal buffer which would be used as an arena.
	//ParamBuffer Params = {};
	//ParamBegin(&Params, 1, 1);
	//ParamText(&Params, World);
	//PGresult *Result = PQexecPrepared(Database->Handle, Stmt, Params.NumParams,
	//						Params.Values, Params.Lengths, Params.Formats, 1);

	const char *ParamValues[] = { World };
	PGresult *Result = PQexecPrepared(Database->Handle, Stmt, 1, ParamValues, NULL, NULL, 1);
	AutoResultClear ResultGuard(Result);
	if(PQresultStatus(Result) != PGRES_TUPLES_OK){
		LOG_ERR("Failed to execute query: %s", PQerrorMessage(Database->Handle));
		return false;
	}

	*WorldID = (PQntuples(Result) > 0 ? GetResultInt(Result, 0, 0) : 0);
	return true;
}

bool GetWorlds(TDatabase *Database, DynamicArray<TWorld> *Worlds){
	ASSERT(Database != NULL && Worlds != NULL);
	const char *Stmt = PrepareQuery(Database,
			"WITH N (WorldID, NumPlayers) AS ("
				"SELECT WorldID, COUNT(*) FROM OnlineCharacters GROUP BY WorldID"
			")"
			" SELECT W.Name, W.Type, COALESCE(N.NumPlayers, 0), W.MaxPlayers,"
				" W.OnlineRecord, W.OnlineRecordTimestamp"
			" FROM Worlds AS W"
			" LEFT JOIN N ON W.WorldID = N.WorldID");
	if(Stmt == NULL){
		LOG_ERR("Failed to prepare query");
		return false;
	}

	PGresult *Result = PQexecPrepared(Database->Handle, Stmt, 0, NULL, NULL, NULL, 1);
	AutoResultClear ResultGuard(Result);
	if(PQresultStatus(Result) != PGRES_TUPLES_OK){
		LOG_ERR("Failed to execute query: %s", PQerrorMessage(Database->Handle));
		return false;
	}

	int NumRows = PQntuples(Result);
	for(int Row = 0; Row < NumRows; Row += 1){
		TWorld World = {};
		StringBufCopy(World.Name, GetResultText(Result, Row, 0));
		World.Type = GetResultInt(Result, Row, 1);
		World.NumPlayers = GetResultInt(Result, Row, 2);
		World.MaxPlayers = GetResultInt(Result, Row, 3);
		World.OnlineRecord = GetResultInt(Result, Row, 4);
		World.OnlineRecordTimestamp = GetResultTimestamp(Result, Row, 5);
		Worlds->Push(World);
	}

	return true;
}

bool GetWorldConfig(TDatabase *Database, int WorldID, TWorldConfig *WorldConfig){
	ASSERT(Database != NULL && WorldConfig != NULL);
	const char *Stmt = PrepareQuery(Database,
			"SELECT Type, RebootTime, Host, Port, MaxPlayers,"
				" PremiumPlayerBuffer, MaxNewbies, PremiumNewbieBuffer"
			" FROM Worlds WHERE WorldID = $1::INTEGER");
	if(Stmt == NULL){
		LOG_ERR("Failed to prepare query");
		return false;
	}

	ParamBuffer Params = {};
	ParamBegin(&Params, 1, 1);
	ParamInteger(&Params, WorldID);
	PGresult *Result = PQexecPrepared(Database->Handle, Stmt, Params.NumParams,
							Params.Values, Params.Lengths, Params.Formats, 1);
	AutoResultClear ResultGuard(Result);
	if(PQresultStatus(Result) != PGRES_TUPLES_OK){
		LOG_ERR("Failed to execute query: %s", PQerrorMessage(Database->Handle));
		return false;
	}

	// TODO(fusion): We probably need a way to differentiate a failure from an
	// empty result set.
	memset(WorldConfig, 0, sizeof(TWorldConfig));
	if(PQntuples(Result) > 0){
		WorldConfig->Type = GetResultInt(Result, 0, 0);
		WorldConfig->RebootTime = GetResultInt(Result, 0, 1);
		StringBufCopy(WorldConfig->HostName, GetResultText(Result, 0, 2));
		WorldConfig->Port = GetResultInt(Result, 0, 3);
		WorldConfig->MaxPlayers = GetResultInt(Result, 0, 4);
		WorldConfig->PremiumPlayerBuffer = GetResultInt(Result, 0, 5);
		WorldConfig->MaxNewbies = GetResultInt(Result, 0, 6);
		WorldConfig->PremiumNewbieBuffer = GetResultInt(Result, 0, 7);
	}

	return true;
}

bool AccountExists(TDatabase *Database, int AccountID, const char *Email, bool *Result){
	return false;
}

bool AccountNumberExists(TDatabase *Database, int AccountID, bool *Result){
	return false;
}

bool AccountEmailExists(TDatabase *Database, const char *Email, bool *Result){
	return false;
}

bool CreateAccount(TDatabase *Database, int AccountID, const char *Email, const uint8 *Auth, int AuthSize){
	return false;
}

bool GetAccountData(TDatabase *Database, int AccountID, TAccount *Account){
	return false;
}

bool GetAccountOnlineCharacters(TDatabase *Database, int AccountID, int *OnlineCharacters){
	return false;
}

bool IsCharacterOnline(TDatabase *Database, int CharacterID, bool *Result){
	return false;
}

bool ActivatePendingPremiumDays(TDatabase *Database, int AccountID){
	return false;
}

bool GetCharacterEndpoints(TDatabase *Database, int AccountID, DynamicArray<TCharacterEndpoint> *Characters){
	return false;
}

bool GetCharacterSummaries(TDatabase *Database, int AccountID, DynamicArray<TCharacterSummary> *Characters){
	return false;
}

bool CharacterNameExists(TDatabase *Database, const char *Name, bool *Result){
	return false;
}

bool CreateCharacter(TDatabase *Database, int WorldID, int AccountID, const char *Name, int Sex){
	return false;
}

bool GetCharacterID(TDatabase *Database, int WorldID, const char *CharacterName, int *CharacterID){
	return false;
}

bool GetCharacterLoginData(TDatabase *Database, const char *CharacterName, TCharacterLoginData *Character){
	return false;
}

bool GetCharacterProfile(TDatabase *Database, const char *CharacterName, TCharacterProfile *Character){
	return false;
}

bool GetCharacterRight(TDatabase *Database, int CharacterID, const char *Right, bool *Result){
	return false;
}

bool GetCharacterRights(TDatabase *Database, int CharacterID, DynamicArray<TCharacterRight> *Rights){
	return false;
}

bool GetGuildLeaderStatus(TDatabase *Database, int WorldID, int CharacterID, bool *Result){
	return false;
}

bool IncrementIsOnline(TDatabase *Database, int WorldID, int CharacterID){
	return false;
}

bool DecrementIsOnline(TDatabase *Database, int WorldID, int CharacterID){
	return false;
}

bool ClearIsOnline(TDatabase *Database, int WorldID, int *NumAffectedCharacters){
	return false;
}

bool LogoutCharacter(TDatabase *Database, int WorldID, int CharacterID, int Level,
		const char *Profession, const char *Residence, int LastLoginTime, int TutorActivities){
	return false;
}

bool GetCharacterIndexEntries(TDatabase *Database, int WorldID, int MinimumCharacterID,
		int MaxEntries, int *NumEntries, TCharacterIndexEntry *Entries){
	return false;
}

bool InsertCharacterDeath(TDatabase *Database, int WorldID, int CharacterID, int Level,
		int OffenderID, const char *Remark, bool Unjustified, int Timestamp){
	return false;
}

bool InsertBuddy(TDatabase *Database, int WorldID, int AccountID, int BuddyID){
	return false;
}

bool DeleteBuddy(TDatabase *Database, int WorldID, int AccountID, int BuddyID){
	return false;
}

bool GetBuddies(TDatabase *Database, int WorldID, int AccountID, DynamicArray<TAccountBuddy> *Buddies){
	return false;
}

bool GetWorldInvitation(TDatabase *Database, int WorldID, int CharacterID, bool *Result){
	return false;
}

bool InsertLoginAttempt(TDatabase *Database, int AccountID, int IPAddress, bool Failed){
	return false;
}

bool GetAccountFailedLoginAttempts(TDatabase *Database, int AccountID, int TimeWindow, int *Result){
	return false;
}

bool GetIPAddressFailedLoginAttempts(TDatabase *Database, int IPAddress, int TimeWindow, int *Result){
	return false;
}


// House Tables
//==============================================================================
bool FinishHouseAuctions(TDatabase *Database, int WorldID, DynamicArray<THouseAuction> *Auctions){
	return false;
}

bool FinishHouseTransfers(TDatabase *Database, int WorldID, DynamicArray<THouseTransfer> *Transfers){
	return false;
}

bool GetFreeAccountEvictions(TDatabase *Database, int WorldID, DynamicArray<THouseEviction> *Evictions){
	return false;
}

bool GetDeletedCharacterEvictions(TDatabase *Database, int WorldID, DynamicArray<THouseEviction> *Evictions){
	return false;
}

bool InsertHouseOwner(TDatabase *Database, int WorldID, int HouseID, int OwnerID, int PaidUntil){
	return false;
}

bool UpdateHouseOwner(TDatabase *Database, int WorldID, int HouseID, int OwnerID, int PaidUntil){
	return false;
}

bool DeleteHouseOwner(TDatabase *Database, int WorldID, int HouseID){
	return false;
}

bool GetHouseOwners(TDatabase *Database, int WorldID, DynamicArray<THouseOwner> *Owners){
	return false;
}

bool GetHouseAuctions(TDatabase *Database, int WorldID, DynamicArray<int> *Auctions){
	return false;
}

bool StartHouseAuction(TDatabase *Database, int WorldID, int HouseID){
	return false;
}

bool DeleteHouses(TDatabase *Database, int WorldID){
	return false;
}

bool InsertHouses(TDatabase *Database, int WorldID, int NumHouses, THouse *Houses){
	return false;
}

bool ExcludeFromAuctions(TDatabase *Database, int WorldID, int CharacterID, int Duration, int BanishmentID){
	return false;
}


// Banishment Tables
//==============================================================================
bool IsCharacterNamelocked(TDatabase *Database, int CharacterID, bool *Result){
	return false;
}

bool GetNamelockStatus(TDatabase *Database, int CharacterID, TNamelockStatus *Status){
	return false;
}

bool InsertNamelock(TDatabase *Database, int CharacterID, int IPAddress,
		int GamemasterID, const char *Reason, const char *Comment){
	return false;
}

bool IsAccountBanished(TDatabase *Database, int AccountID, bool *Result){
	return false;
}

bool GetBanishmentStatus(TDatabase *Database, int CharacterID, TBanishmentStatus *Status){
	return false;
}

bool InsertBanishment(TDatabase *Database, int CharacterID, int IPAddress, int GamemasterID,
		const char *Reason, const char *Comment, bool FinalWarning, int Duration, int *BanishmentID){
	return false;
}

bool GetNotationCount(TDatabase *Database, int CharacterID, int *Result){
	return false;
}

bool InsertNotation(TDatabase *Database, int CharacterID, int IPAddress,
		int GamemasterID, const char *Reason, const char *Comment){
	return false;
}

bool IsIPBanished(TDatabase *Database, int IPAddress, bool *Result){
	return false;
}

bool InsertIPBanishment(TDatabase *Database, int CharacterID, int IPAddress,
		int GamemasterID, const char *Reason, const char *Comment, int Duration){
	return false;
}

bool IsStatementReported(TDatabase *Database, int WorldID, TStatement *Statement, bool *Result){
	return false;
}

bool InsertStatements(TDatabase *Database, int WorldID, int NumStatements, TStatement *Statements){
	return false;
}

bool InsertReportedStatement(TDatabase *Database, int WorldID, TStatement *Statement,
		int BanishmentID, int ReporterID, const char *Reason, const char *Comment){
	return false;
}


// Info Tables
//==============================================================================
bool GetKillStatistics(TDatabase *Database, int WorldID, DynamicArray<TKillStatistics> *Stats){
	return false;
}

bool MergeKillStatistics(TDatabase *Database, int WorldID, int NumStats, TKillStatistics *Stats){
	return false;
}

bool GetOnlineCharacters(TDatabase *Database, int WorldID, DynamicArray<TOnlineCharacter> *Characters){
	return false;
}

bool DeleteOnlineCharacters(TDatabase *Database, int WorldID){
	return false;
}

bool InsertOnlineCharacters(TDatabase *Database, int WorldID,
		int NumCharacters, TOnlineCharacter *Characters){
	return false;
}

bool CheckOnlineRecord(TDatabase *Database, int WorldID, int NumCharacters, bool *NewRecord){
	return false;
}

#endif //DATABASE_POSTGRESQL