Skip to content

Commit 09c998c

Browse files
feat: add parameterized queries (#45)
1 parent e305ab7 commit 09c998c

File tree

10 files changed

+1082
-6
lines changed

10 files changed

+1082
-6
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@
55
### Bug Fixes
66
1. [#46](https://github.com/influxdata/influxdb-client-swift/pull/46): Add missing PermissionResources from Cloud API definition
77

8+
### Features
9+
1. [#45](https://github.com/influxdata/influxdb-client-swift/pull/45): Add support for Parameterized Queries
10+
11+
### Documentation
12+
1. [#45](https://github.com/influxdata/influxdb-client-swift/pull/45): Add Parameterized Queries example
13+
814
## 0.9.0 [2021-11-26]
915

1016
### Documentation
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
opt_in_rules:
2+
- array_init
3+
- collection_alignment
4+
- contains_over_first_not_nil
5+
- closure_end_indentation
6+
- closure_spacing
7+
- conditional_returns_on_newline
8+
- empty_count
9+
- empty_string
10+
- explicit_init
11+
- explicit_self
12+
- fatal_error_message
13+
- first_where
14+
- implicit_return
15+
- missing_docs
16+
- modifier_order
17+
- multiline_arguments
18+
- multiline_literal_brackets
19+
- multiline_parameters
20+
- operator_usage_whitespace
21+
- pattern_matching_keywords
22+
- redundant_nil_coalescing
23+
- redundant_type_annotation
24+
- sorted_first_last
25+
- sorted_imports
26+
- trailing_closure
27+
- unneeded_parentheses_in_closure_argument
28+
- unused_import
29+
- unused_declaration
30+
- vertical_parameter_alignment_on_call
31+
- vertical_whitespace_closing_braces
32+
- vertical_whitespace_opening_braces
33+
34+
excluded:
35+
- Package.swift
36+
- .build/
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// swift-tools-version:5.3
2+
3+
import PackageDescription
4+
5+
let package = Package(
6+
name: "ParameterizedQuery",
7+
products: [
8+
.executable(name: "parameterized-query", targets: ["ParameterizedQuery"])
9+
],
10+
dependencies: [
11+
.package(name: "influxdb-client-swift", path: "../../"),
12+
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
13+
],
14+
targets: [
15+
.target(name: "ParameterizedQuery", dependencies: [
16+
.product(name: "InfluxDBSwift", package: "influxdb-client-swift"),
17+
.product(name: "ArgumentParser", package: "swift-argument-parser")
18+
])
19+
]
20+
)
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# ParameterizedQuery
2+
3+
This is an example how to query with query parameters.
4+
The Telegraf sends data from [CPU Input Plugin](https://github.com/influxdata/telegraf/blob/master/plugins/inputs/cpu/README.md) into InfluxDB 2.0.
5+
6+
## Prerequisites:
7+
- Docker
8+
- Cloned examples:
9+
```bash
10+
git clone [email protected]:influxdata/influxdb-client-swift.git
11+
cd Examples/ParameterizedQuery
12+
```
13+
14+
## Sources:
15+
- [Package.swift](/Examples/ParameterizedQuery/Package.swift)
16+
- [main.swift](/Examples/ParameterizedQuery/Sources/ParameterizedQuery/main.swift)
17+
18+
## How to test:
19+
1. Start InfluxDB:
20+
```bash
21+
docker run --rm \
22+
--name influxdb_v2 \
23+
--detach \
24+
--publish 8086:8086 \
25+
influxdb:latest
26+
```
27+
1. Configure your username, password, organization, bucket and token:
28+
```bash
29+
docker run --rm \
30+
--link influxdb_v2 \
31+
curlimages/curl -s -i -X POST http://influxdb_v2:8086/api/v2/setup \
32+
-H 'accept: application/json' \
33+
-d '{"username": "my-user", "password": "my-password", "org": "my-org", "bucket": "my-bucket", "token": "my-token"}'
34+
```
35+
1. Start Telegraf as a source of data:
36+
```bash
37+
docker run --rm \
38+
--name telegraf \
39+
--link influxdb_v2 \
40+
--detach \
41+
--env HOST_ETC=/hostfs/etc \
42+
--env HOST_PROC=/hostfs/proc \
43+
--env HOST_SYS=/hostfs/sys \
44+
--env HOST_VAR=/hostfs/var \
45+
--env HOST_RUN=/hostfs/run \
46+
--env HOST_MOUNT_PREFIX=/hostfs \
47+
--volume /:/hostfs:ro \
48+
--volume $PWD/telegraf.conf:/etc/telegraf/telegraf.conf:ro \
49+
telegraf
50+
```
51+
1. Start SwiftCLI by:
52+
```bash
53+
docker run --rm \
54+
--link influxdb_v2 \
55+
--privileged \
56+
--interactive \
57+
--tty \
58+
--volume $PWD/../..:/client \
59+
--workdir /client/Examples/ParameterizedQuery \
60+
swift:5.3 /bin/bash
61+
```
62+
1. Execute Query by:
63+
```bash
64+
swift run parameterized-query --org my-org --bucket my-bucket --token my-token --url http://influxdb_v2:8086
65+
```
66+
67+
## Expected output
68+
69+
```bash
70+
Query to execute:
71+
72+
from(bucket: "my-bucket")
73+
|> range(start: -10m)
74+
|> filter(fn: (r) => r["_measurement"] == "cpu")
75+
|> filter(fn: (r) => r["cpu"] == "cpu-total")
76+
|> filter(fn: (r) => r["_field"] == "usage_user" or r["_field"] == "usage_system")
77+
|> last()
78+
79+
Success response...
80+
81+
CPU usage:
82+
usage_system: 22.717622080683473
83+
usage_user: 61.46496815287725
84+
```
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
//
2+
// Warning: Parameterized Queries are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.
3+
//
4+
5+
import ArgumentParser
6+
import Foundation
7+
import InfluxDBSwift
8+
9+
struct ParameterizedQuery: ParsableCommand {
10+
@Option(name: .shortAndLong, help: "The bucket to query. The name or id of the bucket destination.")
11+
private var bucket: String
12+
13+
@Option(name: .shortAndLong,
14+
help: "The organization executing the query. Takes either the `ID` or `Name` interchangeably.")
15+
private var org: String
16+
17+
@Option(name: .shortAndLong, help: "Authentication token.")
18+
private var token: String
19+
20+
@Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
21+
private var url: String
22+
23+
public func run() {
24+
// Initialize Client with default Organization
25+
let client = InfluxDBClient(
26+
url: url,
27+
token: token,
28+
options: InfluxDBClient.InfluxDBOptions(org: self.org))
29+
30+
// Flux query
31+
let query = """
32+
from(bucket: params.bucketParam)
33+
|> range(start: duration(v: params.startParam))
34+
|> filter(fn: (r) => r["_measurement"] == "cpu")
35+
|> filter(fn: (r) => r["cpu"] == "cpu-total")
36+
|> filter(fn: (r) => r["_field"] == "usage_user" or r["_field"] == "usage_system")
37+
|> last()
38+
"""
39+
// Query parameters [String:String]
40+
let queryParams = [ "bucketParam":"\(self.bucket)", "startParam":"-10m" ]
41+
42+
print("\nQuery to execute:\n\n\(query)\n\n\(queryParams)")
43+
44+
client.queryAPI.query(query: query, params: queryParams) { response, error in
45+
// For handle error
46+
if let error = error {
47+
self.atExit(client: client, error: error)
48+
}
49+
50+
// For Success response
51+
if let response = response {
52+
print("\nSuccess response...\n")
53+
print("CPU usage:")
54+
do {
55+
try response.forEach { record in
56+
print("\t\(record.values["_field"]!): \(record.values["_value"]!)")
57+
}
58+
} catch {
59+
self.atExit(client: client, error: InfluxDBClient.InfluxDBError.cause(error))
60+
}
61+
}
62+
63+
self.atExit(client: client)
64+
}
65+
66+
// Wait to end of script
67+
RunLoop.current.run()
68+
}
69+
70+
private func atExit(client: InfluxDBClient, error: InfluxDBClient.InfluxDBError? = nil) {
71+
// Dispose the Client
72+
client.close()
73+
// Exit script
74+
Self.exit(withError: error)
75+
}
76+
}
77+
78+
ParameterizedQuery.main()

0 commit comments

Comments
 (0)