-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathPostgreSQL.swift
More file actions
420 lines (355 loc) · 12.4 KB
/
PostgreSQL.swift
File metadata and controls
420 lines (355 loc) · 12.4 KB
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
//
// PostgreSQL.swift
// PostgreSQL
//
// Created by Kyle Jessup on 2015-07-29.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import libpq
/// result object
public final class PGResult: Sequence, IteratorProtocol {
/// Result Status enum
public enum StatusType {
case emptyQuery
case commandOK
case tuplesOK
case badResponse
case nonFatalError
case fatalError
case singleTuple
case unknown
}
var count:Int = 0
var res: OpaquePointer? = OpaquePointer(bitPattern: 0)
init(_ res: OpaquePointer?) {
self.res = res
}
deinit {
self.close()
}
/// close result object
public func close() {
self.clear()
}
/// clear and disconnect result object
public func clear() {
if let res = self.res {
PQclear(res)
self.res = OpaquePointer(bitPattern: 0)
}
}
/// Result Status number as Int
public func statusInt() -> Int {
let s = PQresultStatus(self.res!)
return Int(s.rawValue)
}
/// Result Status Value
public func status() -> StatusType {
guard let res = self.res else {
return .unknown
}
let s = PQresultStatus(res)
switch(s.rawValue) {
case PGRES_EMPTY_QUERY.rawValue:
return .emptyQuery
case PGRES_COMMAND_OK.rawValue:
return .commandOK
case PGRES_TUPLES_OK.rawValue:
return .tuplesOK
case PGRES_BAD_RESPONSE.rawValue:
return .badResponse
case PGRES_NONFATAL_ERROR.rawValue:
return .nonFatalError
case PGRES_FATAL_ERROR.rawValue:
return .fatalError
case PGRES_SINGLE_TUPLE.rawValue:
return .singleTuple
default:
print("Unhandled PQresult status type \(s.rawValue)")
}
return .unknown
}
/// Result Status Message
public func errorMessage() -> String {
guard let res = self.res else {
return ""
}
return String(validatingUTF8: PQresultErrorMessage(res)) ?? ""
}
/// Result field count
public func numFields() -> Int {
guard let res = self.res else {
return 0
}
return Int(PQnfields(res))
}
/// Field name for index value
public func fieldName(index: Int) -> String? {
if let fn = PQfname(self.res!, Int32(index)) {
return String(validatingUTF8: fn) ?? ""
}
return nil
}
/// Field type for index value
public func fieldType(index: Int) -> Oid? {
let fn = PQftype(self.res!, Int32(index))
return fn
}
/// number of rows (Tuples) returned in result
public func numTuples() -> Int {
guard let res = self.res else {
return 0
}
return Int(PQntuples(res))
}
/// test null field at row index for field index
public func fieldIsNull(tupleIndex: Int, fieldIndex: Int) -> Bool {
return 1 == PQgetisnull(self.res!, Int32(tupleIndex), Int32(fieldIndex))
}
/// return value for String field type with row and field indexes provided
public func getFieldString(tupleIndex: Int, fieldIndex: Int) -> String? {
guard let v = PQgetvalue(self.res, Int32(tupleIndex), Int32(fieldIndex)) else {
return nil
}
return String(validatingUTF8: v)
}
/// return value for Int field type with row and field indexes provided
public func getFieldInt(tupleIndex: Int, fieldIndex: Int) -> Int? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return Int(s)
}
/// return value for Bool field type with row and field indexes provided
public func getFieldBool(tupleIndex: Int, fieldIndex: Int) -> Bool? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return s == "t"
}
/// return value for Int8 field type with row and field indexes provided
public func getFieldInt8(tupleIndex: Int, fieldIndex: Int) -> Int8? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return Int8(s)
}
/// return value for Int16 field type with row and field indexes provided
public func getFieldInt16(tupleIndex: Int, fieldIndex: Int) -> Int16? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return Int16(s)
}
/// return value for Int32 field type with row and field indexes provided
public func getFieldInt32(tupleIndex: Int, fieldIndex: Int) -> Int32? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return Int32(s)
}
/// return value for Int64 field type with row and field indexes provided
public func getFieldInt64(tupleIndex: Int, fieldIndex: Int) -> Int64? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return Int64(s)
}
/// return value for Double field type with row and field indexes provided
public func getFieldDouble(tupleIndex: Int, fieldIndex: Int) -> Double? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return Double(s)
}
/// return value for Float field type with row and field indexes provided
public func getFieldFloat(tupleIndex: Int, fieldIndex: Int) -> Float? {
guard let s = getFieldString(tupleIndex: tupleIndex, fieldIndex: fieldIndex) else {
return nil
}
return Float(s)
}
/// return value for Blob field type with row and field indexes provided
public func getFieldBlob(tupleIndex: Int, fieldIndex: Int) -> [Int8]? {
guard let ip = UnsafePointer<Int8>(PQgetvalue(self.res!, Int32(tupleIndex), Int32(fieldIndex))) else {
return nil
}
let length = Int(PQgetlength(self.res!, Int32(tupleIndex), Int32(fieldIndex)))
var ret = [Int8]()
for idx in 0..<length {
ret.append(ip[idx])
}
return ret
}
///provides basic index based retrieval of rows in result set
public func getRow(_ rowIndex: Int) -> PGRow? {
return PGRow(fromResult: self, row: rowIndex)
}
///returns next row in the result set. Required for Sequence and IteratorProtocol conformance. Allows use of for - in syntax without having to iterate thru a range of index numbers
public func next() -> PGRow? {
if (count == self.numTuples()) {
count = 0
return nil
} else {
defer { count += 1}
return PGRow(fromResult: self, row: count)
}
}
/// returns specified row by index
public subscript(rowIndex: Int) -> PGRow? {
return getRow(rowIndex)
}
}
/// connection management class
public final class PGConnection {
/// Connection Status enum
public enum StatusType {
case ok
case bad
}
var conn = OpaquePointer(bitPattern: 0)
var connectInfo: String = ""
/// empty init
public init() {
}
deinit {
self.close()
}
/// Makes a new connection to the database server.
public func connectdb(_ info: String) -> StatusType {
self.conn = PQconnectdb(info)
self.connectInfo = info
return self.status()
}
/// Close db connection
public func close() {
self.finish()
}
/// Closes the connection to the server. Also frees memory used by the PGconn object.
public func finish() {
if self.conn != nil {
PQfinish(self.conn)
self.conn = OpaquePointer(bitPattern: 0)
}
}
/// Returns the status of the connection.
public func status() -> StatusType {
let status = PQstatus(self.conn)
return status == CONNECTION_OK ? .ok : .bad
}
/// Returns the error message most recently generated by an operation on the connection.
public func errorMessage() -> String {
return String(validatingUTF8: PQerrorMessage(self.conn)) ?? ""
}
/// Submits a command to the server and waits for the result.
public func exec(statement: String) -> PGResult {
return PGResult(PQexec(self.conn, statement))
}
// !FIX! does not handle binary data
/// Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
public func exec(statement: String, params: [String]) -> PGResult {
var asStrings = [String]()
for item in params {
asStrings.append(String(item))
}
let count = asStrings.count
let values = UnsafeMutablePointer<UnsafePointer<Int8>?>.allocate(capacity: count)
defer {
values.deinitialize(count: count) ; values.deallocate(capacity: count)
}
var temps = [Array<UInt8>]()
for idx in 0..<count {
let s = asStrings[idx]
let utf8 = s.utf8
var aa = Array<UInt8>(utf8)
aa.append(0)
temps.append(aa)
values[idx] = UnsafePointer<Int8>(OpaquePointer(temps.last!))
}
let r = PQexecParams(self.conn, statement, Int32(count), nil, values, nil, nil, Int32(0))
return PGResult(r)
}
}
///Provides Sequence and Iterator access to the row data from a PGResult
public struct PGRow: Sequence, IteratorProtocol {
var rowPosition:Int
let row:Int
let res:PGResult
var fields = [String:Any?]()
///access fields from a specified row in PGResult
init(fromResult set: PGResult, row:Int){
self.res = set
self.row = row
rowPosition = 0
while let f = self.next() {
if(res.fieldIsNull(tupleIndex: self.row, fieldIndex: rowPosition-1)) {
fields[f.0] = nil
} else {
fields[f.0] = f.2
}
}
}
///Returns a Tuple made up of (fieldName:String, fieldType:Int, fieldValue:Any?) for a field specified by index. This method attempts to return proper type thru use of fieldType Integer, but needs a more complete reference to the field type list to be complete
func getFieldTuple(_ fieldIndex: Int)-> (String, Int, Any?) {
if(res.fieldIsNull(tupleIndex: row, fieldIndex: fieldIndex)) {
return (res.fieldName(index: rowPosition)!, Int(res.fieldType(index: fieldIndex)!), nil)
} else {
let fieldtype = Int(res.fieldType(index: fieldIndex)!)
switch fieldtype {
case 700, 701:
return (res.fieldName(index: fieldIndex)!, Int(res.fieldType(index: fieldIndex)!), res.getFieldFloat(tupleIndex: row, fieldIndex: fieldIndex))
case 21, 22, 23, 26, 27, 28, 29, 30:
return (res.fieldName(index: fieldIndex)!, Int(res.fieldType(index: fieldIndex)!), res.getFieldInt(tupleIndex: row, fieldIndex: fieldIndex))
case 20:
return (res.fieldName(index: fieldIndex)!, Int(res.fieldType(index: fieldIndex)!), res.getFieldInt8(tupleIndex: row, fieldIndex: fieldIndex))
case 16:
return (res.fieldName(index: fieldIndex)!, Int(res.fieldType(index: fieldIndex)!), res.getFieldBool(tupleIndex: row, fieldIndex: fieldIndex))
default:
if let fieldString = res.getFieldString(tupleIndex: row, fieldIndex:fieldIndex) {
return (res.fieldName(index: fieldIndex)!, Int(res.fieldType(index: fieldIndex)!), fieldString)
} else {
return (res.fieldName(index: fieldIndex)!, Int(res.fieldType(index: fieldIndex)!), "")
}
}
}
}
func getFieldValue(_ fieldIndex: Int) -> Any? {
return getFieldTuple(fieldIndex).2
}
func getFieldName(_ fieldIndex: Int) -> String? {
return res.fieldName(index: fieldIndex)
}
func getFieldType(_ fieldIndex: Int) -> Int? {
return Int(res.fieldType(index: fieldIndex)!)
}
///returns next field in the row. Required for Sequence and IteratorProtocol conformance. Allows use of for - in syntax without having to iterate thru a range of index numbers
public mutating func next() -> (String,Int,Any?)? {
let curIndex = rowPosition
if (curIndex >= res.numFields()) {
rowPosition = 0
return nil
} else {
rowPosition += 1
return getFieldTuple(curIndex)
}
}
/// subscript by field Index, returns field value
public subscript(fieldIndex: Int) -> Any? {
return getFieldValue(fieldIndex)
}
/// subscript by field Name, returns field value
public subscript(fieldName: String) -> Any? {
return fields[fieldName]
}
}