1 /*
2  * Copyright (C) 2019, HuntLabs
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 module hunt.database.driver.postgresql.impl.codec.PgPreparedStatement;
19 
20 import hunt.database.driver.postgresql.impl.codec.Bind;
21 import hunt.database.driver.postgresql.impl.codec.DataFormat;
22 import hunt.database.driver.postgresql.impl.codec.PgColumnDesc;
23 import hunt.database.driver.postgresql.impl.codec.PgParamDesc;
24 import hunt.database.driver.postgresql.impl.codec.PgRowDesc;
25 
26 import hunt.database.base.impl.PreparedStatement;
27 import hunt.database.base.impl.ParamDesc;
28 
29 import hunt.collection.List;
30 
31 import std.algorithm;
32 import std.array;
33 import std.variant;
34 
35 class PgPreparedStatement : PreparedStatement {
36 
37     private enum PgColumnDesc[] EMPTY_COLUMNS = [];
38 
39     string _sql;
40     Bind bind;
41     PgParamDesc _paramDesc;
42     PgRowDesc _rowDesc;
43 
44     this(string sql, long statement, PgParamDesc paramDesc, PgRowDesc rowDesc) {
45 
46         // Fix to use binary when possible
47         if (rowDesc !is null) {
48             rowDesc = new PgRowDesc(rowDesc.columns
49                 .map!(c => new PgColumnDesc(
50                     c.name,
51                     c.relationId,
52                     c.relationAttributeNo,
53                     c.dataType,
54                     c.length,
55                     c.typeModifier,
56                     c.dataType.supportsBinary ? DataFormat.BINARY : DataFormat.TEXT)
57                 ).array());
58         }
59 
60         this._paramDesc = paramDesc;
61         this._rowDesc = rowDesc;
62         this._sql = sql;
63         this.bind = new Bind(statement, paramDesc !is null ? paramDesc.paramDataTypes() : null, 
64             rowDesc !is null ? rowDesc.columns : EMPTY_COLUMNS);
65     }
66 
67     override
68     ParamDesc paramDesc() {
69         return _paramDesc;
70     }
71 
72     override
73     PgRowDesc rowDesc() {
74         return _rowDesc;
75     }
76 
77     override
78     string sql() {
79         return _sql;
80     }
81 
82     override
83     string prepare(List!(Variant) values) {
84         return paramDesc.prepare(values);
85     }
86 }