-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathRecordRow.swift
79 lines (67 loc) · 2.54 KB
/
RecordRow.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
import ArgumentParser
import Foundation
import InfluxDBSwift
import InfluxDBSwiftApis
@main
struct RecordRow: AsyncParsableCommand {
@Option(name: .shortAndLong, help: "The name or id of the bucket destination.")
private var bucket: String
@Option(name: .shortAndLong, help: "The name or id of the organization destination.")
private var org: String
@Option(name: .shortAndLong, help: "Authentication token.")
private var token: String
@Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
private var url: String
}
extension RecordRow {
mutating func run() async throws {
//
// Creating client
//
let client = InfluxDBClient(
url: url,
token: token,
options: InfluxDBClient.InfluxDBOptions(bucket: bucket, org: org))
//
// Write test data into InfluxDB
//
for i in 1...5 {
let point = InfluxDBClient
.Point("point")
.addField(key: "table", value: .string("my-table"))
.addField(key: "result", value: .double(Double(i)))
try await client.makeWriteAPI().write(point: point)
}
//
// Query data with pivot
//
let query = """
from(bucket: "\(self.bucket)")
|> range(start: -1m)
|> filter(fn: (r) => (r["_measurement"] == "point"))
|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
"""
let records = try await client.queryAPI.query(query: query)
//
// Write data to output
//
var values: Array<String> = Array()
var row: Array<String> = Array()
try records.forEach { record in
values.append(record.values.sorted(by: { $0.0 < $1.0 }).map {
val in
"\(val.key): \(val.value)"
}
.joined(separator: ", "))
row.append(record.row.compactMap { val in
"\(val)"
}
.joined(separator: ", "))
}
print("------------------------------------------ FluxRecord.values ------------------------------------------")
print(values.joined(separator: "\n"))
print("-------------------------------------------- FluxRecord.row -------------------------------------------")
print(row.joined(separator: "\n"))
client.close()
}
}