-
Notifications
You must be signed in to change notification settings - Fork 8
/
QueryAPI.swift
367 lines (345 loc) · 14.9 KB
/
QueryAPI.swift
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
//
// Created by Jakub Bednář on 27/11/2020.
//
#if canImport(Combine)
import Combine
#endif
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import Gzip
/// The asynchronous API to Query InfluxDB 2.x.
///
/// ### Example: ###
/// #### Query into sequence of `FluxRecord` ####
/// ````
/// let query = """
/// from(bucket: "my-bucket")
/// |> range(start: -10m)
/// |> filter(fn: (r) => r["_measurement"] == "cpu")
/// |> filter(fn: (r) => r["cpu"] == "cpu-total")
/// |> filter(fn: (r) => r["_field"] == "usage_user" or r["_field"] == "usage_system")
/// |> last()
/// """
///
/// print("\nQuery to execute:\n\(query)\n")
///
/// let records = try await client.queryAPI.query(query: query)
///
/// print("Query results:")
/// try records.forEach { print(" > \($0.values["_field"]!): \($0.values["_value"]!)") }
/// ````
/// #### Query into `Data` ####
/// ````
/// let response = try await client.queryAPI.queryRaw(query: query)
///
/// let csv = String(decoding: response, as: UTF8.self)
/// print("InfluxDB response: \(csv)")
///
/// client.close()
/// ````
public struct QueryAPI {
/// The default Query Dialect with annotation = ["datatype", "group", "default"]
public static let defaultDialect = Dialect(annotations:
[
Dialect.Annotations.datatype,
Dialect.Annotations.group,
Dialect.Annotations._default
])
/// Shared client.
private let client: InfluxDBClient
/// Create a new QueryAPI for a InfluxDB.
///
/// - Parameters
/// - client: Client with shared configuration and http library.
init(client: InfluxDBClient) {
self.client = client
}
/// Query executes a query and returns the response as a `Cursor<FluxRecord>`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - completion: The handler to receive the data and the error objects.
public func query(query: String,
org: String? = nil,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main,
completion: @escaping (_ response: FluxRecordCursor?,
_ error: InfluxDBClient.InfluxDBError?) -> Void) {
self.query(query: query, org: org, params: params, responseQueue: responseQueue) { result -> Void in
switch result {
case let .success(cursor):
completion(cursor, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/// Query executes a query and returns the response as a `Cursor<FluxRecord>`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - completion: completion handler to receive the `Swift.Result`
public func query(query: String,
org: String? = nil,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main,
completion: @escaping (
_ result: Swift.Result<FluxRecordCursor, InfluxDBClient.InfluxDBError>) -> Void) {
self.queryRaw(
query: query,
org: org,
dialect: QueryAPI.defaultDialect,
params: params,
responseQueue: responseQueue) { result -> Void in
switch result {
case let .success(data):
do {
try completion(.success(FluxRecordCursor(data: data)))
} catch {
completion(.failure(InfluxDBClient.InfluxDBError.cause(error)))
}
case let .failure(error):
completion(.failure(error))
}
}
}
#if canImport(Combine)
/// Query executes a query and returns the response as a `Cursor<FluxRecord>`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - Returns: Publisher to attach a subscriber
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public func query(query: String,
org: String? = nil,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main)
-> AnyPublisher<FluxRecordCursor, InfluxDBClient.InfluxDBError> {
Future<FluxRecordCursor, InfluxDBClient.InfluxDBError> { promise in
self.query(query: query, org: org, params: params, responseQueue: responseQueue) { result -> Void in
switch result {
case let .success(data):
promise(.success(data))
case let .failure(error):
promise(.failure(error))
}
}
}
.eraseToAnyPublisher()
}
#endif
#if swift(>=5.5)
/// Query executes a query and asynchronously returns the response as a `Cursor<FluxRecord>`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - Returns: `Cursor<FluxRecord>`
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public func query(query: String,
org: String? = nil,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main) async throws -> FluxRecordCursor {
try await withCheckedThrowingContinuation { continuation in
self.query(query: query, org: org, params: params, responseQueue: responseQueue) { result in
switch result {
case .success(let value):
continuation.resume(returning: value)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
#endif
/// QueryRaw executes a query and returns the response as a `Data`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - dialect: The Dialect are options to change the default CSV output format.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - completion: handler to receive the data and the error objects
public func queryRaw(query: String,
org: String? = nil,
dialect: Dialect = defaultDialect,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main,
completion: @escaping (_ response: Data?, _ error: InfluxDBClient.InfluxDBError?) -> Void) {
self.queryRaw(query: query,
org: org,
dialect: dialect,
params: params,
responseQueue: responseQueue) { result -> Void in
switch result {
case let .success(data):
completion(data, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/// QueryRaw executes a query and returns the response as a `Data`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - dialect: The Dialect are options to change the default CSV output format.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - completion: completion handler to receive the `Swift.Result`
public func queryRaw(query: String,
org: String? = nil,
dialect: Dialect = defaultDialect,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main,
completion: @escaping (_ result: Swift.Result<Data, InfluxDBClient.InfluxDBError>) -> Void) {
guard let org = org ?? client.options.org else {
responseQueue.async {
let error = InfluxDBClient.InfluxDBError.generic(
"The organization executing the query should be specified.")
return completion(.failure(error))
}
return
}
let model = Query(query: query, params: params, dialect: dialect)
var url = URLComponents(string: client.url + "/api/v2/query")
url?.queryItems = [
URLQueryItem(name: "org", value: org)
]
client.queryRequest(model, url, InfluxDBClient.GZIPMode.response, responseQueue, completion)
}
#if canImport(Combine)
/// QueryRaw executes a query and returns the response as a `Data`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - dialect: The Dialect are options to change the default CSV output format.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - Returns: Publisher to attach a subscriber
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public func queryRaw(query: String,
org: String? = nil,
dialect: Dialect = defaultDialect,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main) -> AnyPublisher<Data, InfluxDBClient.InfluxDBError> {
Future<Data, InfluxDBClient.InfluxDBError> { promise in
self.queryRaw(query: query,
org: org,
dialect: dialect,
params: params,
responseQueue: responseQueue) { result -> Void in
switch result {
case let .success(data):
promise(.success(data))
case let .failure(error):
promise(.failure(error))
}
}
}
.eraseToAnyPublisher()
}
#endif
#if swift(>=5.5)
/// QueryRaw executes a query and asynchronously returns the response as a `Data`.
///
/// - Parameters:
/// - query: The Flux query to execute.
/// - org: The organization executing the query. Takes either the `ID` or `Name` interchangeably.
/// - params: params represent key/value pairs parameters to be injected into query
/// - responseQueue: The queue on which api response is dispatched.
/// - Returns: `Cursor<FluxRecord>`
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public func queryRaw(query: String,
org: String? = nil,
params: [String: String]? = nil,
responseQueue: DispatchQueue = .main) async throws -> Data {
try await withCheckedThrowingContinuation { continuation in
self.queryRaw(query: query, org: org, params: params, responseQueue: responseQueue) { result in
switch result {
case .success(let value):
continuation.resume(returning: value)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
#endif
}
extension QueryAPI {
/// FluxTable holds flux query result table information represented by collection of columns.
public class FluxTable {
/// The list of columns in Table.
public var columns: [FluxColumn] = []
}
/// FluxColumn holds flux query table column properties
public class FluxColumn {
/// The index of column.
public let index: Int
/// The name of column.
public var name: String = ""
/// Description of the type of data contained within the column.
public let dataType: String
/// Boolean flag indicating if the column is part of the table's group key
public var group = false
/// Default value to be used for rows whose string value is the empty string.
public var defaultValue: String = ""
/// Initialize FluxColumn structure
///
/// - Parameters:
/// - index: index in table
/// - dataType: type of column
public init(index: Int, dataType: String) {
self.index = index
self.dataType = dataType
}
}
/// FluxRecord represents row in the flux query result table
public class FluxRecord: Equatable {
/// The list of values in Record
public let values: [String: Decodable]
/// The array of record's columns
public let row: [Any]
/// Initialize records with values.
///
/// - Parameter values: record values
/// row: record's columns
public init(values: [String: Decodable], row: [Any]) {
self.values = values
self.row = row
}
public static func == (lhs: FluxRecord, rhs: FluxRecord) -> Bool {
NSDictionary(dictionary: lhs.values).isEqual(rhs.values)
}
}
}
extension QueryAPI {
/// Cursor for `FluxRecord`.
public final class FluxRecordCursor: Cursor {
private let _parser: FluxCSVParser
init(data: Data, responseMode: FluxCSVParser.ResponseMode = .full) throws {
_parser = try FluxCSVParser(data: data, responseMode: responseMode)
}
/// Get next element and returns it, or nil if no next element exists.
public func next() throws -> FluxRecord? {
try _parser.next()?.record
}
}
}