forked from pszturmaj/ddb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.d
2198 lines (1841 loc) · 61.8 KB
/
postgres.d
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
/**
PostgreSQL client implementation.
Features:
$(UL
$(LI Standalone (does not depend on libpq))
$(LI Binary formatting (avoids parsing overhead))
$(LI Prepared statements)
$(LI Parametrized queries (partially working))
$(LI $(LINK2 http://www.postgresql.org/docs/9.0/static/datatype-enum.html, Enums))
$(LI $(LINK2 http://www.postgresql.org/docs/9.0/static/arrays.html, Arrays))
$(LI $(LINK2 http://www.postgresql.org/docs/9.0/static/rowtypes.html, Composite types))
)
TODOs:
$(UL
$(LI Redesign parametrized queries)
$(LI BigInt/Numeric types support)
$(LI Geometric types support)
$(LI Network types support)
$(LI Bit string types support)
$(LI UUID type support)
$(LI XML types support)
$(LI Transaction support)
$(LI Asynchronous notifications)
$(LI Better memory management)
$(LI More friendly PGFields)
)
Bugs:
$(UL
$(LI Support only cleartext and MD5 $(LINK2 http://www.postgresql.org/docs/9.0/static/auth-methods.html, authentication))
$(LI Unfinished parameter handling)
$(LI interval is converted to Duration, which does not support months)
)
$(B Data type mapping:)
$(TABLE
$(TR $(TH PostgreSQL type) $(TH Aliases) $(TH Default D type) $(TH D type mapping possibilities))
$(TR $(TD smallint) $(TD int2) $(TD short) <td rowspan="19">Any type convertible from default D type</td>)
$(TR $(TD integer) $(TD int4) $(TD int))
$(TR $(TD bigint) $(TD int8) $(TD long))
$(TR $(TD oid) $(TD reg***) $(TD uint))
$(TR $(TD decimal) $(TD numeric) $(TD not yet supported))
$(TR $(TD real) $(TD float4) $(TD float))
$(TR $(TD double precision) $(TD float8) $(TD double))
$(TR $(TD character varying(n)) $(TD varchar(n)) $(TD string))
$(TR $(TD character(n)) $(TD char(n)) $(TD string))
$(TR $(TD text) $(TD) $(TD string))
$(TR $(TD "char") $(TD) $(TD char))
$(TR $(TD bytea) $(TD) $(TD ubyte[]))
$(TR $(TD timestamp without time zone) $(TD timestamp) $(TD DateTime))
$(TR $(TD timestamp with time zone) $(TD timestamptz) $(TD SysTime))
$(TR $(TD date) $(TD) $(TD Date))
$(TR $(TD time without time zone) $(TD time) $(TD TimeOfDay))
$(TR $(TD time with time zone) $(TD timetz) $(TD SysTime))
$(TR $(TD interval) $(TD) $(TD Duration (without months and years)))
$(TR $(TD boolean) $(TD bool) $(TD bool))
$(TR $(TD enums) $(TD) $(TD string) $(TD enum))
$(TR $(TD arrays) $(TD) $(TD Variant[]) $(TD dynamic/static array with compatible element type))
$(TR $(TD composites) $(TD record, row) $(TD Variant[]) $(TD dynamic/static array, struct or Tuple))
)
Examples:
---
import std.stdio;
import postgres;
int main(string[] argv)
{
auto conn = new PGConnection;
conn.open([
"host" : "localhost",
"database" : "test",
"user" : "postgres",
"password" : "postgres"
]);
scope(exit) conn.close;
auto cmd = new PGCommand(conn, "SELECT typname, typlen FROM pg_type");
auto result = cmd.executeQuery;
try
{
foreach (row; result)
{
writeln(row[0], ", ", row[1]);
}
}
finally
{
result.close;
}
return 0;
}
---
Copyright: Copyright Piotr Szturmaj 2011-.
License: $(LINK2 http://boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Piotr Szturmaj
*//*
Documentation contains portions copied from PostgreSQL manual (mainly field information and
connection parameters description). License:
Portions Copyright (c) 1996-2010, The PostgreSQL Global Development Group
Portions Copyright (c) 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its documentation for any purpose,
without fee, and without a written agreement is hereby granted, provided that the above copyright
notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
OR MODIFICATIONS.
*/
module postgres;
import std.socket, std.socketstream;
import std.exception;
import std.conv;
import std.traits;
import std.typecons;
import std.string;
import std.md5;
import std.intrinsic;
import std.variant;
import std.algorithm;
import std.datetime;
public import db;
private:
short hton(short i)
{
version (BigEndian)
{
return i;
}
else
{
ubyte* b = cast(ubyte*)&i;
ubyte l = *b;
*b = *(b + 1);
*(b + 1) = l;
return i;
}
}
int hton(const int i)
{
version (BigEndian)
{
return i;
}
else
{
return cast(int)bswap(cast(uint)i);
}
}
enum PGEpochDate = Date(2000, 1, 1);
enum PGEpochDay = PGEpochDate.dayOfGregorianCal;
enum PGEpochTime = TimeOfDay(0, 0, 0);
enum PGEpochDateTime = DateTime(2000, 1, 1, 0, 0, 0);
class PGStream : SocketStream
{
this(Socket socket)
{
super(socket);
}
override void write(ubyte x)
{
super.write(x);
}
override void write(short x)
{
super.write(hton(x));
}
override void write(int x)
{
super.write(hton(x));
}
override void write(long x)
{
uint u;
u = hton(cast(uint)(x >> 32));
super.write(u);
u = hton(cast(uint)x);
super.write(u);
}
override void write(float x)
{
union U
{
float f;
int i;
}
U u;
u.f = x;
super.write(hton(u.i));
}
override void write(double x)
{
union U
{
double d;
long l;
}
U u;
u.d = x;
write(u.l);
}
void writeCString(string x)
{
super.writeString(x);
super.write('\0');
}
void write(ubyte[] x)
{
static if (x.length.sizeof > int.sizeof)
enforce(x.length <= int.max);
write(cast(int)x.length);
super.write(x);
}
void write(const ref Date x)
{
write(cast(int)(x.dayOfGregorianCal - PGEpochDay));
}
void write(const ref TimeOfDay x)
{
write(cast(int)((x - PGEpochTime).total!"usecs"));
}
void write(const ref DateTime x) // timestamp
{
write(cast(int)((x - PGEpochDateTime).total!"usecs"));
}
void write(const ref SysTime x) // timestamptz
{
write(cast(int)((x - SysTime(PGEpochDateTime, UTC())).total!"usecs"));
}
// BUG: Does not support months
void write(const ref Duration x) // interval
{
int months = 0;
int days = cast(int)x.days;
long usecs = x.total!"usecs" - convert!("days", "usecs")(days);
write(usecs);
write(days);
write(months);
}
void writeTimeTz(const ref SysTime x) // timetz
{
TimeOfDay t = cast(TimeOfDay)x;
write(t);
write(cast(int)0);
}
}
string MD5toHex(in void[][] data...)
{
return tolower(getDigestString(data));
}
struct Message
{
PGConnection conn;
char type;
ubyte[] data;
private size_t position = 0;
private alias hton ntoh;
T read(T, Params...)(Params p)
{
T value;
read(value, p);
return value;
}
void read()(out char x)
{
x = data[position++];
}
void read()(out short x)
{
x = ntoh(*(cast(short*)(data.ptr + position)));
position += 2;
}
void read()(out int x)
{
x = ntoh(*(cast(int*)(data.ptr + position)));
position += 4;
}
void read()(out long x)
{
uint h = ntoh(*(cast(uint*)(data.ptr + position)));
uint l = ntoh(*(cast(uint*)(data.ptr + position + 4)));
x = (cast(long)h << 32) | l;
position += 8;
}
void read()(out float x)
{
union U
{
float f;
int i;
}
U u;
read(u.i);
x = u.f;
}
void read()(out double x)
{
union U
{
double d;
long l;
}
U u;
read(u.l);
x = u.d;
}
string readCString()
{
string x;
readCString(x);
return x;
}
void readCString(out string x)
{
ubyte* p = data.ptr + position;
while (*p > 0)
p++;
x = cast(string)data[position .. cast(size_t)(p - data.ptr)];
position = cast(size_t)(p - data.ptr + 1);
}
string readString(int len)
{
string x;
readString(x, len);
return x;
}
void readString(out string x, int len)
{
x = cast(string)data[position .. position + len];
position += len;
}
void read()(out uint x)
{
x = ntoh(*(cast(uint*)(data.ptr + position)));
position += 4;
}
void read()(out bool x)
{
x = cast(bool)data[position++];
}
void read()(out ubyte[] x, int len)
{
enforce(position + len <= data.length);
x = data[position .. position + len];
position += len;
}
void read()(out Date x) // date
{
int days = read!int; // number of days since 1 Jan 2000
x = PGEpochDate + dur!"days"(days);
}
void read()(out TimeOfDay x) // time
{
long usecs = read!long;
x = PGEpochTime + dur!"usecs"(usecs);
}
void read()(out DateTime x) // timestamp
{
long usecs = read!long;
x = PGEpochDateTime + dur!"usecs"(usecs);
}
void read()(out SysTime x) // timestamptz
{
long usecs = read!long;
x = SysTime(PGEpochDateTime + dur!"usecs"(usecs), UTC());
x.timezone = LocalTime();
}
// BUG: Does not support months
void read()(out Duration x) // interval
{
long usecs = read!long;
int days = read!int;
int months = read!int;
x = dur!"days"(days) + dur!"usecs"(usecs);
}
SysTime readTimeTz() // timetz
{
TimeOfDay time = read!TimeOfDay;
int zone = read!int / 60; // originally in seconds, convert it to minutes
return SysTime(DateTime(Date(0, 1, 1), time), new SimpleTimeZone(zone));
}
T readComposite(T)()
{
alias DBRow!T Record;
static if (Record.hasStaticLength)
{
alias Record.fieldTypes fieldTypes;
static string genFieldAssigns() // CTFE
{
string s = "";
foreach (i; 0 .. fieldTypes.length)
{
s ~= "read(fieldOid);\n";
s ~= "read(fieldLen);\n";
s ~= "if (fieldLen == -1)\n";
s ~= text("record.setNull!(", i, ");\n");
s ~= "else\n";
s ~= text("record.set!(fieldTypes[", i, "], ", i, ")(",
"readBaseType!(fieldTypes[", i, "])(fieldOid, fieldLen)",
");\n");
// text() doesn't work with -inline option, CTFE bug
}
return s;
}
}
Record record;
int fieldCount, fieldLen;
uint fieldOid;
read(fieldCount);
static if (Record.hasStaticLength)
mixin(genFieldAssigns);
else
{
record.setLength(fieldCount);
foreach (i; 0 .. fieldCount)
{
read(fieldOid);
read(fieldLen);
if (fieldLen == -1)
record.setNull(i);
else
record[i] = readBaseType!(Record.ElemType)(fieldOid, fieldLen);
}
}
return record.base;
}
private AT readDimension(AT)(int[] lengths, uint elementOid, int dim)
{
alias typeof(AT[0]) ElemType;
int length = lengths[dim];
AT array;
static if (isDynamicArray!AT)
array.length = length;
int fieldLen;
foreach(i; 0 .. length)
{
static if (isArray!ElemType && !isSomeString!ElemType)
array[i] = readDimension!ElemType(lengths, elementOid, dim + 1);
else
{
static if (isNullable!ElemType)
alias nullableTarget!ElemType E;
else
alias ElemType E;
read(fieldLen);
if (fieldLen == -1)
{
static if (isNullable!ElemType || isSomeString!ElemType)
array[i] = null;
else
throw new Exception("Can't set NULL value to non nullable type");
}
else
array[i] = readBaseType!E(elementOid, fieldLen);
}
}
return array;
}
T readArray(T)()
if (isArray!T)
{
alias multiArrayElemType!T U;
// todo: more validation, better lowerBounds support
int dims, hasNulls;
uint elementOid;
int[] lengths, lowerBounds;
read(dims);
read(hasNulls); // 0 or 1
read(elementOid);
if (dims == 0)
return T.init;
enforce(arrayDimensions!T == dims, "Dimensions of arrays do not match");
static if (!isNullable!U && !isSomeString!U)
enforce(!hasNulls, "PostgreSQL returned NULLs but array elements are not Nullable");
lengths.length = lowerBounds.length = dims;
int elementCount = 1;
foreach(i; 0 .. dims)
{
int len;
read(len);
read(lowerBounds[i]);
lengths[i] = len;
elementCount *= len;
}
T array = readDimension!T(lengths, elementOid, 0);
return array;
}
T readEnum(T)(int len)
{
string genCases() // CTFE
{
string s;
foreach (name; __traits(allMembers, T))
{
s ~= text(`case "`, name, `": return T.`, name, `;`);
}
return s;
}
string enumMember = readString(len);
switch (enumMember)
{
mixin(genCases);
default: throw new ConvException("Can't set enum value '" ~ enumMember ~ "' to enum type " ~ T.stringof);
}
}
T readBaseType(T)(uint oid, int len = 0)
{
void convError(T)()
{
string* type = oid in baseTypes;
throw new ConvException("Can't convert PostgreSQL's type " ~ (type ? *type : to!string(oid)) ~ " to " ~ T.stringof);
}
switch (oid)
{
case 16: // bool
static if (isConvertible!(T, bool))
return _to!T(read!bool);
else
convError!T;
case 26, 24, 2202, 2203, 2204, 2205, 2206, 3734, 3769: // oid and reg*** aliases
static if (isConvertible!(T, uint))
return _to!T(read!uint);
else
convError!T;
case 21: // int2
static if (isConvertible!(T, short))
return _to!T(read!short);
else
convError!T;
case 23: // int4
static if (isConvertible!(T, int))
return _to!T(read!int);
else
convError!T;
case 20: // int8
static if (isConvertible!(T, long))
return _to!T(read!long);
else
convError!T;
case 700: // float4
static if (isConvertible!(T, float))
return _to!T(read!float);
else
convError!T;
case 701: // float8
static if (isConvertible!(T, double))
return _to!T(read!double);
else
convError!T;
case 1042, 1043, 25, 19, 705: // bpchar, varchar, text, name, unknown
static if (isConvertible!(T, string))
return _to!T(readString(len));
else
convError!T;
case 17: // bytea
static if (isConvertible!(T, ubyte[]))
return _to!T(read!(ubyte[])(len));
else
convError!T;
case 18: // "char"
static if (isConvertible!(T, char))
return _to!T(read!char);
else
convError!T;
case 1082: // date
static if (isConvertible!(T, Date))
return _to!T(read!Date);
else
convError!T;
case 1083: // time
static if (isConvertible!(T, TimeOfDay))
return _to!T(read!TimeOfDay);
else
convError!T;
case 1114: // timestamp
static if (isConvertible!(T, DateTime))
return _to!T(read!DateTime);
else
convError!T;
case 1184: // timestamptz
static if (isConvertible!(T, SysTime))
return _to!T(read!SysTime);
else
convError!T;
case 1186: // interval
static if (isConvertible!(T, Duration))
return _to!T(read!Duration);
else
convError!T;
case 1266: // timetz
static if (isConvertible!(T, SysTime))
return _to!T(readTimeTz);
else
convError!T;
case 2249: // record and other composite types
static if (isVariantN!T && T.allowed!(Variant[]))
return T(readComposite!(Variant[]));
else
return readComposite!T;
case 2287: // _record and other arrays
static if (isArray!T && !isSomeString!T)
return readArray!T;
else static if (isVariantN!T && T.allowed!(Variant[]))
return T(readArray!(Variant[]));
else
convError!T;
default:
if (oid in conn.arrayTypes)
goto case 2287;
else if (oid in conn.compositeTypes)
goto case 2249;
else if (oid in conn.enumTypes)
{
static if (is(T == enum))
return readEnum!T(len);
else static if (isConvertible!(T, string))
return _to!T(readString(len));
else
convError!T;
}
}
convError!T;
assert(0);
}
}
// workaround, because std.conv currently doesn't support VariantN
template _to(T)
{
static if (isVariantN!T)
T _to(S)(S value) { T t = value; return t; }
else
T _to(A...)(A args) { return toImpl!T(args); }
}
template isConvertible(T, S)
{
static if (__traits(compiles, { S s; _to!T(s); }) || (isVariantN!T && T.allowed!S))
enum isConvertible = true;
else
enum isConvertible = false;
}
template arrayDimensions(T)
{
static if (isArray!T && !isSomeString!T)
enum arrayDimensions = arrayDimensions!(typeof(T[0])) + 1;
else
enum arrayDimensions = 0;
}
template multiArrayElemType(T)
{
static if (isArray!T && !isSomeString!T)
alias multiArrayElemType!(typeof(T[0])) multiArrayElemType;
else
alias T multiArrayElemType;
}
static assert(arrayDimensions!(int) == 0);
static assert(arrayDimensions!(int[]) == 1);
static assert(arrayDimensions!(int[][]) == 2);
static assert(arrayDimensions!(int[][][]) == 3);
enum TransactionStatus : char { OutsideTransaction = 'I', InsideTransaction = 'T', InsideFailedTransaction = 'E' };
enum string[uint] baseTypes = [
// boolean types
16 : "bool",
// bytea types
17 : "bytea",
// character types
18 : `"char"`, // "char" - 1 byte internal type
1042 : "bpchar", // char(n) - blank padded
1043 : "varchar",
25 : "text",
19 : "name",
// numeric types
21 : "int2",
23 : "int4",
20 : "int8",
700 : "float4",
701 : "float8",
1700 : "numeric"
];
public:
enum PGType : uint
{
OID = 26,
NAME = 19,
REGPROC = 24,
BOOLEAN = 16,
BYTEA = 17,
CHAR = 18, // 1 byte "char", used internally in PostgreSQL
BPCHAR = 1042, // Blank Padded char(n), fixed size
VARCHAR = 1043,
TEXT = 25,
INT2 = 21,
INT4 = 23,
INT8 = 20,
FLOAT4 = 700,
FLOAT8 = 701
};
class ParamException : Exception
{
this(string msg)
{
super(msg);
}
}
/// Exception thrown on server error
class ServerErrorException: Exception
{
/// Contains information about this _error. Aliased to this.
ResponseMessage error;
alias error this;
this(string msg)
{
super(msg);
}
this(ResponseMessage error)
{
super(error.toString());
this.error = error;
}
}
/**
Class encapsulating errors and notices.
This class provides access to fields of ErrorResponse and NoticeResponse
sent by the server. More information about these fields can be found
$(LINK2 http://www.postgresql.org/docs/9.0/static/protocol-error-fields.html,here).
*/
class ResponseMessage
{
private string[char] fields;
private string getOptional(char type)
{
string* p = type in fields;
return p ? *p : "";
}
/// Message fields
@property string severity()
{
return fields['S'];
}
/// ditto
@property string code()
{
return fields['C'];
}
/// ditto
@property string message()
{
return fields['M'];
}
/// ditto
@property string detail()
{
return getOptional('D');
}
/// ditto
@property string hint()
{
return getOptional('H');
}
/// ditto
@property string position()
{
return getOptional('P');
}
/// ditto
@property string internalPosition()
{
return getOptional('p');
}
/// ditto
@property string internalQuery()
{
return getOptional('q');
}
/// ditto
@property string where()
{
return getOptional('W');
}
/// ditto
@property string file()
{
return getOptional('F');
}
/// ditto
@property string line()
{
return getOptional('L');
}
/// ditto
@property string routine()
{
return getOptional('R');
}
/**
Returns summary of this message using the most common fields (severity,
code, message, detail, hint)
*/
override string toString()
{
string s = severity ~ ' ' ~ code ~ ": " ~ message;
string* detail = 'D' in fields;
if (detail)
s ~= "\nDETAIL: " ~ *detail;
string* hint = 'H' in fields;
if (hint)
s ~= "\nHINT: " ~ *hint;
return s;
}
}
/**
Class representing connection to PostgreSQL server.
*/
class PGConnection
{
private:
Socket socket;
PGStream stream;
string[string] serverParams;
int serverProcessID;
int serverSecretKey;
TransactionStatus trStatus;
ulong lastPrepared = 0;
uint[uint] arrayTypes;
uint[][uint] compositeTypes;
string[uint][uint] enumTypes;
bool activeResultSet;
string reservePrepared()
{
synchronized (this)
{
return to!string(lastPrepared++);
}
}
Message getMessage()
{
alias hton ntoh;
char type;
int len;
stream.read(type); // message type
stream.read(len); // message length, doesn't include type byte
len = ntoh(len) - 4;
ubyte[] msg = new ubyte[len];
stream.readExact(msg.ptr, len);
return Message(this, type, msg);
}