1 module dpq2.args;
2 
3 @safe:
4 
5 public import dpq2.types.from_d_types;
6 public import dpq2.types.from_bson;
7 
8 import dpq2;
9 
10 /// Query parameters
11 struct QueryParams
12 {
13     string sqlCommand; /// SQL command
14     Value[] args; /// SQL command arguments
15     ValueFormat resultFormat = ValueFormat.BINARY; /// Result value format
16 
17     /// Useful for simple text-only query params
18     /// Postgres infers a data type for the parameter in the same way it would do for an untyped literal string.
19     @property void argsFromArray(in string[] arr)
20     {
21         args.length = arr.length;
22 
23         foreach(i, ref a; args)
24             a = toValue(arr[i], ValueFormat.TEXT);
25     }
26 
27     @property string preparedStatementName() const { return sqlCommand; }
28     @property void preparedStatementName(string s){ sqlCommand = s; }
29 
30     private
31     {
32         Oid[] oids;
33         int[] formats;
34         int[] lengths;
35         const(ubyte)*[] values;
36     }
37 
38     private void prepareArgs() pure
39     {
40         oids = new Oid[args.length];
41         formats = new int[args.length];
42         lengths = new int[args.length];
43         values = new const(ubyte)* [args.length];
44 
45         for(int i = 0; i < args.length; ++i)
46         {
47             oids[i] = args[i].oidType;
48             formats[i] = args[i].format;
49 
50             if(!args[i].isNull)
51             {
52                 lengths[i] = args[i].data.length.to!int;
53                 values[i] = args[i].data.ptr;
54             }
55         }
56     }
57 
58     package:
59 
60     /// used by PQexecParams-like functions
61     const(char)* command() pure const
62     {
63         return cast(const(char)*) sqlCommand.toStringz;
64     }
65 
66     /// ditto
67     const(char)* stmtName() pure const
68     {
69         return command();
70     }
71 
72     /// ditto
73     int nParams() pure const
74     {
75         return args.length.to!int;
76     }
77 
78     /// ditto
79     const(Oid)* paramTypes() pure
80     {
81         prepareArgs();
82         return oids.ptr;
83     }
84 
85     /// ditto
86     const(ubyte*)* paramValues() pure
87     {
88         prepareArgs();
89         return values.ptr;
90     }
91 
92     /// ditto
93     const(int)* paramLengths() pure
94     {
95         prepareArgs();
96         return lengths.ptr;
97     }
98 
99     /// ditto
100     const(int)* paramFormats() pure
101     {
102         prepareArgs();
103         return formats.ptr;
104     }
105 }