forked from pgjdbc/r2dbc-postgresql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresqlSegmentResult.java
342 lines (262 loc) · 10.4 KB
/
PostgresqlSegmentResult.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
/*
* Copyright 2021 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.util.AbstractReferenceCounted;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
import io.r2dbc.postgresql.api.ErrorDetails;
import io.r2dbc.postgresql.message.backend.BackendMessage;
import io.r2dbc.postgresql.message.backend.CommandComplete;
import io.r2dbc.postgresql.message.backend.DataRow;
import io.r2dbc.postgresql.message.backend.ErrorResponse;
import io.r2dbc.postgresql.message.backend.NoticeResponse;
import io.r2dbc.postgresql.message.backend.RowDescription;
import io.r2dbc.postgresql.util.Assert;
import io.r2dbc.spi.R2dbcException;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* An implementation of {@link Result} based on {@link Segment}.
*
* @since 0.9
*/
final class PostgresqlSegmentResult extends AbstractReferenceCounted implements io.r2dbc.postgresql.api.PostgresqlResult {
private final Flux<Segment> segments;
private PostgresqlSegmentResult(Flux<Segment> segments) {
this.segments = segments;
}
PostgresqlSegmentResult(ConnectionResources resources, Flux<BackendMessage> messages, ExceptionFactory factory) {
Assert.requireNonNull(resources, "resources must not be null");
Assert.requireNonNull(messages, "messages must not be null");
Assert.requireNonNull(factory, "factory must not be null");
AtomicReference<RowDescription> rowDescriptionHolder = new AtomicReference<>();
AtomicReference<PostgresqlRowMetadata> metadataHolder = new AtomicReference<>();
this.segments = messages
.doOnNext(message -> {
if (message instanceof RowDescription) {
rowDescriptionHolder.set((RowDescription) message);
metadataHolder.set(PostgresqlRowMetadata.toRowMetadata(resources.getCodecs(), (RowDescription) message));
}
}).handle((message, sink) -> {
if (message instanceof ErrorResponse) {
sink.next(new PostgresErrorSegment((ErrorResponse) message, factory));
return;
}
if (message instanceof NoticeResponse) {
sink.next(new PostgresNoticeSegment((NoticeResponse) message, factory));
return;
}
if (message instanceof CommandComplete) {
Long rowCount = ((CommandComplete) message).getRows();
if (rowCount != null) {
sink.next(new PostgresqlUpdateCountSegment(rowCount));
}
return;
}
if (message instanceof DataRow) {
RowDescription rowDescription = rowDescriptionHolder.get();
PostgresqlRowMetadata metadata = metadataHolder.get();
if (rowDescription == null) {
sink.error(new IllegalStateException("DataRow without RowDescription"));
return;
}
if (metadata == null) {
sink.error(new IllegalStateException("DataRow without PostgresqlRowMetadata"));
return;
}
sink.next(new PostgresqlRowSegment(PostgresqlRow.toRow(resources, (DataRow) message, metadata, rowDescription), (DataRow) message));
return;
}
ReferenceCountUtil.release(message);
});
}
@Override
public Mono<Long> getRowsUpdated() {
return this.segments
.<Integer>handle((segment, sink) -> {
try {
if (segment instanceof PostgresErrorSegment) {
sink.error(((PostgresErrorSegment) segment).exception());
return;
}
if (segment instanceof UpdateCount) {
sink.next((int) (((UpdateCount) segment).value()));
}
} finally {
ReferenceCountUtil.release(segment);
}
}).collectList().handle((list, sink) -> {
if (list.isEmpty()) {
return;
}
long sum = 0;
for (Integer integer : list) {
sum += integer;
}
sink.next(sum);
});
}
@Override
public <T> Flux<T> map(BiFunction<Row, RowMetadata, ? extends T> f) {
Assert.requireNonNull(f, "f must not be null");
return this.segments
.handle((segment, sink) -> {
try {
if (segment instanceof PostgresErrorSegment) {
sink.error(((PostgresErrorSegment) segment).exception());
return;
}
if (segment instanceof RowSegment) {
RowSegment row = (RowSegment) segment;
sink.next(f.apply(row.row(), row.row().getMetadata()));
}
} finally {
ReferenceCountUtil.release(segment);
}
});
}
@Override
public PostgresqlSegmentResult filter(Predicate<Segment> filter) {
Assert.requireNonNull(filter, "filter must not be null");
return new PostgresqlSegmentResult(this.segments.filter(it -> {
boolean result = filter.test(it);
if (!result) {
ReferenceCountUtil.release(it);
}
return result;
}));
}
@Override
@SuppressWarnings("unchecked")
public <T> Publisher<T> flatMap(Function<Segment, ? extends Publisher<? extends T>> mappingFunction) {
Assert.requireNonNull(mappingFunction, "mappingFunction must not be null");
return this.segments.concatMap(segment -> {
Publisher<? extends T> result = mappingFunction.apply(segment);
if (result == null) {
return Mono.error(new IllegalStateException("The mapper returned a null Publisher"));
}
// doAfterTerminate to not release resources before they had a chance to get emitted
if (result instanceof Mono) {
return ((Mono<T>) result).doFinally(s -> ReferenceCountUtil.release(segment));
}
return Flux.from(result).doFinally(s -> ReferenceCountUtil.release(segment));
});
}
@Override
protected void deallocate() {
// drain messages for cleanup
this.getRowsUpdated().subscribe();
}
@Override
public ReferenceCounted touch(Object hint) {
return this;
}
@Override
public String toString() {
return "PostgresqlSegmentResult{" +
"segments=" + this.segments +
'}';
}
static PostgresqlSegmentResult toResult(ConnectionResources resources, Flux<BackendMessage> messages, ExceptionFactory factory) {
return new PostgresqlSegmentResult(resources, messages, factory);
}
static class PostgresqlRowSegment extends AbstractReferenceCounted implements Result.RowSegment {
private final Row row;
private final ReferenceCounted releaseable;
public PostgresqlRowSegment(Row row, ReferenceCounted releaseable) {
this.row = row;
this.releaseable = releaseable;
}
@Override
public Row row() {
return this.row;
}
@Override
protected void deallocate() {
ReferenceCountUtil.release(this.releaseable);
}
@Override
public ReferenceCounted touch(Object hint) {
return this;
}
}
static class PostgresqlUpdateCountSegment implements Result.UpdateCount {
private final long value;
public PostgresqlUpdateCountSegment(long value) {
this.value = value;
}
@Override
public long value() {
return this.value;
}
}
static class PostgresErrorSegment implements Result.Message {
private final ExceptionFactory factory;
private final ErrorDetails details;
public PostgresErrorSegment(ErrorResponse response, ExceptionFactory factory) {
this.factory = factory;
this.details = new ErrorDetails(response.getFields());
}
@Override
public R2dbcException exception() {
return this.factory.createException(this.details);
}
@Override
public int errorCode() {
return 0;
}
@Override
public String sqlState() {
return this.details.getCode();
}
@Override
public String message() {
return this.details.getMessage();
}
}
static class PostgresNoticeSegment implements Result.Message {
private final ExceptionFactory factory;
private final ErrorDetails details;
public PostgresNoticeSegment(NoticeResponse response, ExceptionFactory factory) {
this.factory = factory;
this.details = new ErrorDetails(response.getFields());
}
@Override
public R2dbcException exception() {
return this.factory.createException(this.details);
}
@Override
public int errorCode() {
return 0;
}
@Override
public String sqlState() {
return this.details.getCode();
}
@Override
public String message() {
return this.details.getMessage();
}
}
}