forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresClientTests.swift
213 lines (180 loc) · 7.71 KB
/
PostgresClientTests.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
@_spi(ConnectionPool) import PostgresNIO
import XCTest
import NIOPosix
import NIOSSL
import Logging
import Atomics
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
final class PostgresClientTests: XCTestCase {
func testGetConnection() async throws {
var mlogger = Logger(label: "test")
mlogger.logLevel = .debug
let logger = mlogger
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 8)
self.addTeardownBlock {
try await eventLoopGroup.shutdownGracefully()
}
let clientConfig = PostgresClient.Configuration.makeTestConfiguration()
let client = PostgresClient(configuration: clientConfig, eventLoopGroup: eventLoopGroup, backgroundLogger: logger)
await withThrowingTaskGroup(of: Void.self) { taskGroup in
taskGroup.addTask {
await client.run()
}
let iterations = 1000
for _ in 0..<iterations {
taskGroup.addTask {
try await client.withConnection() { connection in
_ = try await connection.query("SELECT 1", logger: logger)
}
}
}
for _ in 0..<iterations {
_ = await taskGroup.nextResult()!
}
taskGroup.cancelAll()
}
}
func testApplicationNameIsForwardedCorrectly() async throws {
var mlogger = Logger(label: "test")
mlogger.logLevel = .debug
let logger = mlogger
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 8)
self.addTeardownBlock {
try await eventLoopGroup.shutdownGracefully()
}
var clientConfig = PostgresClient.Configuration.makeTestConfiguration()
let applicationName = "postgres_nio_test_run"
clientConfig.options.additionalStartupParameters = [("application_name", applicationName)]
let client = PostgresClient(configuration: clientConfig, eventLoopGroup: eventLoopGroup, backgroundLogger: logger)
try await withThrowingTaskGroup(of: Void.self) { taskGroup in
taskGroup.addTask {
await client.run()
}
let rows = try await client.query("select * from pg_stat_activity;");
var applicationNameFound = 0
for try await row in rows {
let randomAccessRow = row.makeRandomAccess()
if try randomAccessRow["application_name"].decode(String?.self) == applicationName {
applicationNameFound += 1
}
}
XCTAssertGreaterThanOrEqual(applicationNameFound, 1)
taskGroup.cancelAll()
}
}
func testQueryDirectly() async throws {
var mlogger = Logger(label: "test")
mlogger.logLevel = .debug
let logger = mlogger
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 8)
self.addTeardownBlock {
try await eventLoopGroup.shutdownGracefully()
}
let clientConfig = PostgresClient.Configuration.makeTestConfiguration()
let client = PostgresClient(configuration: clientConfig, eventLoopGroup: eventLoopGroup, backgroundLogger: logger)
await withThrowingTaskGroup(of: Void.self) { taskGroup in
taskGroup.addTask {
await client.run()
}
for i in 0..<10000 {
taskGroup.addTask {
do {
try await client.query("SELECT 1", logger: logger)
logger.info("Success", metadata: ["run": "\(i)"])
} catch {
XCTFail("Unexpected error: \(error)")
}
}
}
for _ in 0..<10000 {
_ = await taskGroup.nextResult()!
}
taskGroup.cancelAll()
}
}
func testQueryTable() async throws {
let tableName = "test_client_prepared_statement"
var mlogger = Logger(label: "test")
mlogger.logLevel = .debug
let logger = mlogger
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 8)
self.addTeardownBlock {
try await eventLoopGroup.shutdownGracefully()
}
let clientConfig = PostgresClient.Configuration.makeTestConfiguration()
let client = PostgresClient(configuration: clientConfig, eventLoopGroup: eventLoopGroup, backgroundLogger: logger)
do {
try await withThrowingTaskGroup(of: Void.self) { taskGroup in
taskGroup.addTask {
await client.run()
}
try await client.query(
"""
CREATE TABLE IF NOT EXISTS "\(unescaped: tableName)" (
id SERIAL PRIMARY KEY,
uuid UUID NOT NULL
);
""",
logger: logger
)
for _ in 0..<1000 {
try await client.query(
"""
INSERT INTO "\(unescaped: tableName)" (uuid) VALUES (\(UUID()));
""",
logger: logger
)
}
let rows = try await client.query(#"SELECT id, uuid FROM "\#(unescaped: tableName)";"#, logger: logger).decode((Int, UUID).self)
for try await (id, uuid) in rows {
logger.info("id: \(id), uuid: \(uuid.uuidString)")
}
struct Example: PostgresPreparedStatement {
static let sql = "SELECT id, uuid FROM test_client_prepared_statement WHERE id < $1"
typealias Row = (Int, UUID)
var id: Int
func makeBindings() -> PostgresBindings {
var bindings = PostgresBindings()
bindings.append(self.id)
return bindings
}
func decodeRow(_ row: PostgresNIO.PostgresRow) throws -> Row {
try row.decode(Row.self)
}
}
for try await (id, uuid) in try await client.execute(Example(id: 200), logger: logger) {
logger.info("id: \(id), uuid: \(uuid.uuidString)")
}
try await client.query(
"""
DROP TABLE "\(unescaped: tableName)";
""",
logger: logger
)
taskGroup.cancelAll()
}
} catch {
XCTFail("Unexpected error: \(String(reflecting: error))")
}
}
}
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
extension PostgresClient.Configuration {
static func makeTestConfiguration() -> PostgresClient.Configuration {
var tlsConfiguration = TLSConfiguration.makeClientConfiguration()
tlsConfiguration.certificateVerification = .none
var clientConfig = PostgresClient.Configuration(
host: env("POSTGRES_HOSTNAME") ?? "localhost",
port: env("POSTGRES_PORT").flatMap({ Int($0) }) ?? 5432,
username: env("POSTGRES_USER") ?? "test_username",
password: env("POSTGRES_PASSWORD") ?? "test_password",
database: env("POSTGRES_DB") ?? "test_database",
tls: .prefer(tlsConfiguration)
)
clientConfig.options.minimumConnections = 0
clientConfig.options.maximumConnections = 12*4
clientConfig.options.keepAliveBehavior = .init(frequency: .seconds(5))
clientConfig.options.connectionIdleTimeout = .seconds(15)
return clientConfig
}
}