1 module dpq2.value;
2 
3 @safe:
4 
5 import dpq2.oids;
6 
7 /// Minimal Postgres value
8 struct Value
9 {
10     bool isNull = true;
11     OidType oidType = OidType.Undefined;
12 
13     package ValueFormat format;
14     package ubyte[] _data;
15 
16     // FIXME:
17     // The pointer returned by PQgetvalue points to storage that is part of the PGresult structure.
18     // One should not modify the data it points to, and one must explicitly copy the data into other
19     // storage if it is to be used past the lifetime of the PGresult structure itself.
20     // Thus, it is need to store reference to Answer here to ensure that result is still available.
21 
22     this(ubyte[] data, in OidType oidType, bool isNull, in ValueFormat format = ValueFormat.BINARY) pure
23     {
24         this._data = data;
25         this.format = format;
26         this.oidType = oidType;
27         this.isNull = isNull;
28     }
29 
30     /// Null Value constructor
31     this(in ValueFormat format, in OidType oidType) pure
32     {
33         this.format = format;
34         this.oidType = oidType;
35     }
36 
37     inout (ubyte[]) data() pure inout
38     {
39         import std.exception;
40         import core.exception;
41 
42         enforceEx!AssertError(!isNull, "Attempt to read NULL value", __FILE__, __LINE__);
43 
44         return _data;
45     }
46 
47     bool isSupportedArray() const
48     {
49         return dpq2.oids.isSupportedArray(oidType);
50     }
51 
52     debug string toString() const @trusted
53     {
54         import vibe.data.bson: Bson;
55         import dpq2.conv.to_bson;
56         import std.conv: to;
57 
58         return this.as!Bson.toString~"::"~oidType.to!string~"("~(format == ValueFormat.TEXT? "t" : "b")~")";
59     }
60 }
61 
62 @trusted unittest
63 {
64     import dpq2.conv.to_d_types;
65     import core.exception: AssertError;
66 
67     Value v = Value(ValueFormat.BINARY, OidType.Int4);
68 
69     bool exceptionFlag = false;
70 
71     try
72         cast(void) v.as!int;
73     catch(AssertError e)
74         exceptionFlag = true;
75 
76     assert(exceptionFlag);
77 }
78 
79 enum ValueFormat : int {
80     TEXT,
81     BINARY
82 }