forked from pgjdbc/r2dbc-postgresql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresqlConnection.java
524 lines (416 loc) · 18.5 KB
/
PostgresqlConnection.java
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.r2dbc.postgresql;
import io.netty.buffer.ByteBuf;
import io.r2dbc.postgresql.api.ErrorDetails;
import io.r2dbc.postgresql.api.Notification;
import io.r2dbc.postgresql.api.PostgresTransactionDefinition;
import io.r2dbc.postgresql.api.PostgresqlResult;
import io.r2dbc.postgresql.api.PostgresqlStatement;
import io.r2dbc.postgresql.client.Client;
import io.r2dbc.postgresql.client.ConnectionContext;
import io.r2dbc.postgresql.client.PortalNameSupplier;
import io.r2dbc.postgresql.client.SimpleQueryMessageFlow;
import io.r2dbc.postgresql.client.TransactionStatus;
import io.r2dbc.postgresql.codec.Codecs;
import io.r2dbc.postgresql.message.backend.BackendMessage;
import io.r2dbc.postgresql.message.backend.CommandComplete;
import io.r2dbc.postgresql.message.backend.NotificationResponse;
import io.r2dbc.postgresql.util.Assert;
import io.r2dbc.postgresql.util.Operators;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.IsolationLevel;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.TransactionDefinition;
import io.r2dbc.spi.ValidationDepth;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import static io.r2dbc.postgresql.client.TransactionStatus.IDLE;
import static io.r2dbc.postgresql.client.TransactionStatus.OPEN;
/**
* An implementation of {@link Connection} for connecting to a PostgreSQL database.
*/
final class PostgresqlConnection implements io.r2dbc.postgresql.api.PostgresqlConnection {
private final Logger logger = Loggers.getLogger(this.getClass());
private final Client client;
private final ConnectionResources resources;
private final ConnectionContext connectionContext;
private final Codecs codecs;
private final Flux<Long> validationQuery;
private final AtomicReference<NotificationAdapter> notificationAdapter = new AtomicReference<>();
private volatile IsolationLevel isolationLevel;
private volatile IsolationLevel previousIsolationLevel;
PostgresqlConnection(Client client, Codecs codecs, PortalNameSupplier portalNameSupplier, StatementCache statementCache, IsolationLevel isolationLevel,
PostgresqlConnectionConfiguration configuration) {
this.client = Assert.requireNonNull(client, "client must not be null");
this.resources = new ConnectionResources(client, codecs, this, configuration, portalNameSupplier, statementCache);
this.connectionContext = client.getContext();
this.codecs = Assert.requireNonNull(codecs, "codecs must not be null");
this.isolationLevel = Assert.requireNonNull(isolationLevel, "isolationLevel must not be null");
this.validationQuery = new io.r2dbc.postgresql.PostgresqlStatement(this.resources, "SELECT 1").fetchSize(0).execute().flatMap(PostgresqlResult::getRowsUpdated);
}
Client getClient() {
return this.client;
}
@Override
public Mono<Void> beginTransaction() {
return beginTransaction(EmptyTransactionDefinition.INSTANCE);
}
@Override
public Mono<Void> beginTransaction(TransactionDefinition definition) {
Assert.requireNonNull(definition, "definition must not be null");
return useTransactionStatus(transactionStatus -> {
if (IDLE == transactionStatus) {
IsolationLevel isolationLevel = definition.getAttribute(TransactionDefinition.ISOLATION_LEVEL);
Boolean readOnly = definition.getAttribute(TransactionDefinition.READ_ONLY);
Boolean deferrable = definition.getAttribute(PostgresTransactionDefinition.DEFERRABLE);
String begin = "BEGIN";
String transactionMode = "";
if (isolationLevel != null) {
transactionMode = appendTransactionMode(transactionMode, "ISOLATION LEVEL", isolationLevel.asSql());
}
if (readOnly != null) {
transactionMode = appendTransactionMode(transactionMode, readOnly ? "READ ONLY" : "READ WRITE");
}
if (deferrable != null) {
transactionMode = appendTransactionMode(transactionMode, deferrable ? "" : "NOT", "DEFERRABLE");
}
return exchange(transactionMode.isEmpty() ? begin : (begin + " " + transactionMode)).doOnComplete(() -> {
this.previousIsolationLevel = this.isolationLevel;
if (isolationLevel != null) {
this.isolationLevel = isolationLevel;
}
});
} else {
this.logger.debug(this.connectionContext.getMessage("Skipping begin transaction because status is {}"), transactionStatus);
return Mono.empty();
}
});
}
private static String appendTransactionMode(String transactionMode, String... tokens) {
StringBuilder builder = new StringBuilder(transactionMode);
boolean first = true;
if (builder.length() != 0) {
builder.append(", ");
}
for (String token : tokens) {
if (token.isEmpty()) {
continue;
}
if (first) {
first = false;
} else {
builder.append(" ");
}
builder.append(token);
}
return builder.toString();
}
@Override
public Mono<Void> close() {
return this.client.close().doOnSubscribe(subscription -> {
NotificationAdapter notificationAdapter = this.notificationAdapter.get();
if (notificationAdapter != null && this.notificationAdapter.compareAndSet(notificationAdapter, null)) {
notificationAdapter.dispose();
}
}).then(Mono.empty());
}
@Override
public Mono<Void> cancelRequest() {
return this.client.cancelRequest();
}
@Override
public Mono<Void> commitTransaction() {
return useTransactionStatus(transactionStatus -> {
if (IDLE != transactionStatus) {
return Flux.from(exchange("COMMIT"))
.doOnComplete(this::cleanupIsolationLevel)
.filter(CommandComplete.class::isInstance)
.cast(CommandComplete.class)
.<BackendMessage>handle((message, sink) -> {
// Certain backend versions (e.g. 12.2, 11.7, 10.12, 9.6.17, 9.5.21, etc)
// silently rollback the transaction in the response to COMMIT statement
// in case the transaction has failed.
// See discussion in pgsql-hackers: https://www.postgresql.org/message-id/b9fb50dc-0f6e-15fb-6555-8ddb86f4aa71%40postgresfriends.org
if ("ROLLBACK".equalsIgnoreCase(message.getCommand())) {
sink.error(new ExceptionFactory.PostgresqlRollbackException(ErrorDetails.fromMessage("The database returned ROLLBACK, so the transaction cannot be committed. Transaction" +
" " +
"failure is not known (check server logs?)"), "COMMIT"));
return;
}
sink.next(message);
});
} else {
this.logger.debug(this.connectionContext.getMessage("Skipping commit transaction because status is {}"), transactionStatus);
return Mono.empty();
}
});
}
@Override
public PostgresqlBatch createBatch() {
return new PostgresqlBatch(this.resources);
}
@Override
public Mono<Void> createSavepoint(String name) {
Assert.requireNonNull(name, "name must not be null");
return beginTransaction()
.then(useTransactionStatus(transactionStatus -> {
if (OPEN == transactionStatus) {
return exchange(String.format("SAVEPOINT %s", name));
} else {
this.logger.debug(this.connectionContext.getMessage("Skipping create savepoint because status is {}"), transactionStatus);
return Mono.empty();
}
}));
}
@Override
public PostgresqlStatement createStatement(String sql) {
Assert.requireNonNull(sql, "sql must not be null");
return new io.r2dbc.postgresql.PostgresqlStatement(this.resources, sql);
}
/**
* Return a {@link Flux} of {@link Notification} received from {@code LISTEN} registrations.
* The stream is a hot stream producing messages as they are received.
*
* @return a hot {@link Flux} of {@link Notification Notifications}.
*/
@Override
public Flux<Notification> getNotifications() {
NotificationAdapter notifications = this.notificationAdapter.get();
if (notifications == null) {
notifications = new NotificationAdapter();
if (this.notificationAdapter.compareAndSet(null, notifications)) {
notifications.register(this.client);
} else {
notifications = this.notificationAdapter.get();
}
}
return notifications.getEvents();
}
@Override
public PostgresqlConnectionMetadata getMetadata() {
return new PostgresqlConnectionMetadata(this.client.getVersion());
}
@Override
public IsolationLevel getTransactionIsolationLevel() {
return this.isolationLevel;
}
@Override
public boolean isAutoCommit() {
if (this.client.getTransactionStatus() == IDLE) {
return true;
}
return false;
}
@Override
public Mono<Void> releaseSavepoint(String name) {
Assert.requireNonNull(name, "name must not be null");
return useTransactionStatus(transactionStatus -> {
if (OPEN == transactionStatus) {
return exchange(String.format("RELEASE SAVEPOINT %s", name));
} else {
this.logger.debug(this.connectionContext.getMessage("Skipping release savepoint because status is {}"), transactionStatus);
return Mono.empty();
}
});
}
@Override
public Mono<Void> rollbackTransaction() {
return useTransactionStatus(transactionStatus -> {
if (IDLE != transactionStatus) {
return exchange("ROLLBACK").doOnComplete(this::cleanupIsolationLevel);
} else {
this.logger.debug(this.connectionContext.getMessage("Skipping rollback transaction because status is {}"), transactionStatus);
return Mono.empty();
}
});
}
@Override
public Mono<Void> rollbackTransactionToSavepoint(String name) {
Assert.requireNonNull(name, "name must not be null");
return useTransactionStatus(transactionStatus -> {
if (IDLE != transactionStatus) {
return exchange(String.format("ROLLBACK TO SAVEPOINT %s", name));
} else {
this.logger.debug(this.connectionContext.getMessage("Skipping rollback transaction to savepoint because status is {}"), transactionStatus);
return Mono.empty();
}
});
}
@Override
public Mono<Void> setAutoCommit(boolean autoCommit) {
return useTransactionStatus(transactionStatus -> {
this.logger.debug(this.connectionContext.getMessage(String.format("Setting auto-commit mode to [%s]", autoCommit)));
if (isAutoCommit()) {
if (!autoCommit) {
this.logger.debug(this.connectionContext.getMessage("Beginning transaction"));
return beginTransaction();
}
} else {
if (autoCommit) {
this.logger.debug(this.connectionContext.getMessage("Committing pending transactions"));
return commitTransaction();
}
}
return Mono.empty();
});
}
@Override
public Mono<Void> setTransactionIsolationLevel(IsolationLevel isolationLevel) {
Assert.requireNonNull(isolationLevel, "isolationLevel must not be null");
return withTransactionStatus(getTransactionIsolationLevelQuery(isolationLevel))
.flatMapMany(this::exchange)
.then()
.doOnSuccess(ignore -> this.isolationLevel = isolationLevel);
}
@Override
public String toString() {
return "PostgresqlConnection{" +
"client=" + this.client +
", codecs=" + this.codecs +
'}';
}
@Override
public Mono<Boolean> validate(ValidationDepth depth) {
if (depth == ValidationDepth.LOCAL) {
return Mono.fromSupplier(this.client::isConnected);
}
return Mono.create(sink -> {
if (!this.client.isConnected()) {
sink.success(false);
return;
}
this.validationQuery.subscribe(new CoreSubscriber<Long>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Integer.MAX_VALUE);
}
@Override
public void onNext(Long integer) {
}
@Override
public void onError(Throwable t) {
PostgresqlConnection.this.logger.debug(PostgresqlConnection.this.connectionContext.getMessage("Validation failed"), t);
sink.success(false);
}
@Override
public void onComplete() {
sink.success(true);
}
});
});
}
@Override
public Mono<Long> copyIn(String sql, Publisher<ByteBuf> stdin) {
return new PostgresqlCopyIn(resources).copy(sql, stdin);
}
private static Function<TransactionStatus, String> getTransactionIsolationLevelQuery(IsolationLevel isolationLevel) {
return transactionStatus -> {
if (transactionStatus == OPEN) {
return String.format("SET TRANSACTION ISOLATION LEVEL %s", isolationLevel.asSql());
} else {
return String.format("SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL %s", isolationLevel.asSql());
}
};
}
@Override
public Mono<Void> setLockWaitTimeout(Duration lockTimeout) {
Assert.requireNonNull(lockTimeout, "lockTimeout must not be null");
return Mono.defer(() -> Mono.from(exchange(String.format("SET LOCK_TIMEOUT = %s", lockTimeout.toMillis()))).then());
}
@Override
public Mono<Void> setStatementTimeout(Duration statementTimeout) {
Assert.requireNonNull(statementTimeout, "statementTimeout must not be null");
return Mono.defer(() -> Mono.from(exchange(String.format("SET STATEMENT_TIMEOUT = %s", statementTimeout.toMillis()))).then());
}
private Mono<Void> useTransactionStatus(Function<TransactionStatus, Publisher<?>> f) {
return Flux.defer(() -> f.apply(this.client.getTransactionStatus()))
.as(Operators::discardOnCancel)
.then();
}
private <T> Mono<T> withTransactionStatus(Function<TransactionStatus, T> f) {
return Mono.defer(() -> Mono.just(f.apply(this.client.getTransactionStatus())));
}
@SuppressWarnings("unchecked")
private <T> Flux<T> exchange(String sql) {
ExceptionFactory exceptionFactory = ExceptionFactory.withSql(sql);
return (Flux<T>) SimpleQueryMessageFlow.exchange(this.client, sql)
.handle(exceptionFactory::handleErrorResponse);
}
private void cleanupIsolationLevel() {
if (this.previousIsolationLevel != null) {
this.isolationLevel = this.previousIsolationLevel;
}
this.previousIsolationLevel = null;
}
/**
* Adapter to publish {@link Notification}s.
*/
static class NotificationAdapter {
private final Sinks.Many<Notification> sink = Sinks.many().multicast().directBestEffort();
@Nullable
private volatile Disposable subscription = null;
void dispose() {
Disposable subscription = this.subscription;
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
void register(Client client) {
this.subscription = client.addNotificationListener(new Subscriber<NotificationResponse>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(NotificationResponse notificationResponse) {
NotificationAdapter.this.sink.emitNext(new NotificationResponseWrapper(notificationResponse), Sinks.EmitFailureHandler.FAIL_FAST);
}
@Override
public void onError(Throwable throwable) {
NotificationAdapter.this.sink.emitError(throwable, Sinks.EmitFailureHandler.FAIL_FAST);
}
@Override
public void onComplete() {
NotificationAdapter.this.sink.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST);
}
});
}
Flux<Notification> getEvents() {
return this.sink.asFlux();
}
}
enum EmptyTransactionDefinition implements TransactionDefinition {
INSTANCE;
@Override
public <T> T getAttribute(Option<T> option) {
return null;
}
}
}