-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathconnection.dart
More file actions
1460 lines (1280 loc) · 42.7 KB
/
Copy pathconnection.dart
File metadata and controls
1460 lines (1280 loc) · 42.7 KB
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:async/async.dart' as async;
import 'package:charcode/ascii.dart';
import 'package:meta/meta.dart';
import 'package:pool/pool.dart' as pool;
import 'package:stack_trace/stack_trace.dart';
import 'package:stream_channel/stream_channel.dart';
import '../../postgres.dart';
import '../auth/auth.dart';
import '../exceptions.dart';
import '../messages/logical_replication_messages.dart';
import '../types/type_registry.dart';
import 'connection_info.dart';
import 'database_info.dart';
import 'protocol.dart';
import 'query_description.dart';
import 'resolved_settings.dart';
const _debugLog = false;
String _identifier(String source) {
// To avoid complex ambiguity rules, we always wrap identifier in double
// quotes. That means the only character we need to escape are double quotes
// in the source.
final escaped = source.replaceAll('"', '""');
return '"$escaped"';
}
abstract class _PgSessionBase implements Session {
/// The lock to guard operations that must run sequentially, like sending
/// RPC messages to the postgres server and waiting for them to complete.
///
/// Each session base has its own operation lock, but child sessions hold the
/// parent lock while they are active. For instance, when starting a
/// transaction,the [_operationLock] of the connection is held until the
/// transaction completes. This ensures that no other statement can use the
/// connection in the meantime.
final _operationLock = pool.Pool(1);
final Completer<void> _sessionClosedCompleter = Completer();
bool get _sessionClosed => _sessionClosedCompleter.isCompleted;
PgConnectionImplementation get _connection;
ResolvedSessionSettings get _settings;
Encoding get encoding => _connection._settings.encoding;
void _closeSession() {
if (!_sessionClosed) {
_sessionClosedCompleter.complete();
}
}
void _checkActive() {
if (_sessionClosed) {
throw PgException(
'Session or transaction has already finished, did you forget to await a statement?',
);
} else if (_connection._isClosing) {
throw PgException('Connection is closing down');
}
}
/// Runs [callback], guarded by [_operationLock] and cleans up the pending
/// resource afterwards.
Future<T> _withResource<T>(FutureOr<T> Function() callback) {
_checkActive();
return _operationLock.withResource(() {
_checkActive();
assert(
_connection._pending == null,
'Previous operation ${_connection._pending} did not clean up.',
);
return Future(callback).whenComplete(() {
_connection._pending = null;
});
});
}
/// Sends a message to the server and waits for a response [T], gracefully
/// handling error messages that might come in instead.
Future<T> _sendAndWaitForQuery<T extends ServerMessage>(
ClientMessage send, {
StackTrace? stackTrace,
}) {
final trace = stackTrace ?? StackTrace.current;
return _withResource(() {
_connection._channel.sink.add(
AggregatedClientMessage([send, const SyncMessage()]),
);
final wait = _connection._pending = _WaitForMessage<T>(this, trace);
return wait.doneWithOperation.future.then((value) {
final effectiveResult =
wait.result ??
async.Result.error(StateError('Operation did not complete'), trace);
return effectiveResult.asFuture;
});
});
}
@override
bool get isOpen => !_sessionClosed && !_connection._isClosing;
@override
Future<void> get closed => _sessionClosedCompleter.future;
void _verifyStateBeforeQuery() {
if (_connection._isClosing || _sessionClosed) {
throw PgException(
'Attempting to execute query, but connection is not open.',
);
}
if (this == _connection && _connection._activeTransaction != null) {
throw PgException(
'Attempting to execute query on connection while inside a `runTx` call.',
);
}
}
@override
Future<Result> execute(
Object query, {
Object? parameters,
bool ignoreRows = false,
QueryMode? queryMode,
Duration? timeout,
}) async {
_verifyStateBeforeQuery();
final description = InternalQueryDescription.wrap(
query,
typeRegistry: _connection._settings.typeRegistry,
);
final variables = description.bindParameters(
parameters,
ignoreSuperfluous: _settings.ignoreSuperfluousParameters,
);
queryMode ??= _settings.queryMode;
final isSimple = queryMode == QueryMode.simple;
if (isSimple && variables.isNotEmpty) {
throw PgException(
'Parameterized queries are not supported when '
'using the Simple Query Protocol',
);
}
if (isSimple || (ignoreRows && variables.isEmpty)) {
_connection._queryCount++;
// Great, we can just run a simple query.
final controller = StreamController<ResultRow>();
final items = <ResultRow>[];
final querySubscription = _PgResultStreamSubscription.simpleQueryProtocol(
description.transformedSql,
this,
controller,
controller.stream.listen(items.add),
ignoreRows,
);
try {
return await querySubscription._waitForResult(
items: items,
timeout: timeout,
);
} finally {
await querySubscription.cancel();
}
} else {
// The simple query protocol does not support variables. So when we have
// parameters, we need an explicit prepare.
final prepared = await _prepare(description, variables);
try {
return await prepared.run(variables, timeout: timeout);
} finally {
await prepared.dispose();
}
}
}
@override
Future<Statement> prepare(Object query) async {
_verifyStateBeforeQuery();
return await _prepare(query);
}
Future<_PreparedStatement> _prepare(
Object query, [
List<TypedValue>? fallbackTypes,
]) async {
final stackTrace = StackTrace.current;
final trace = Trace.from(stackTrace);
final conn = _connection;
final name = 's/${conn._statementCounter++}';
final description = InternalQueryDescription.wrap(
query,
typeRegistry: _connection._settings.typeRegistry,
);
await _sendAndWaitForQuery<ParseCompleteMessage>(
ParseMessage(
description.transformedSql,
statementName: name,
typeOids: _mergeTypeOids(description.parameterTypes, fallbackTypes),
),
stackTrace: stackTrace,
);
return _PreparedStatement(description, name, this, trace);
}
}
class PgConnectionImplementation extends _PgSessionBase implements Connection {
static Future<PgConnectionImplementation> connect(
Endpoint endpoint, {
ConnectionSettings? connectionSettings,
@visibleForTesting
StreamTransformer<Uint8List, Uint8List>? incomingBytesTransformer,
}) async {
final settings = connectionSettings is ResolvedConnectionSettings
? connectionSettings
: ResolvedConnectionSettings(connectionSettings, null);
final codecContext = CodecContext(
connectionInfo: ConnectionInfo(),
// TODO: share this between pooled connections
databaseInfo: DatabaseInfo(),
encoding: settings.encoding,
typeRegistry: settings.typeRegistry,
);
var (channel, secure) = await _connect(
endpoint,
settings,
codecContext: codecContext,
incomingBytesTransformer: incomingBytesTransformer,
);
channel = _debugChannel(channel);
if (settings.transformer != null) {
channel = channel.transform(settings.transformer!);
}
final connection = PgConnectionImplementation._(
endpoint,
settings,
channel,
secure,
databaseInfo: codecContext.databaseInfo,
info: codecContext.connectionInfo,
);
await connection._startup();
if (connection._settings.onOpen != null) {
await connection._settings.onOpen!(connection);
}
return connection;
}
static StreamChannel<Message> _debugChannel(StreamChannel<Message> channel) {
if (!_debugLog) {
return channel;
}
final hash = channel.hashCode.abs().toRadixString(16);
return channel.transform(
StreamChannelTransformer(
StreamTransformer.fromHandlers(
handleData: (msg, sink) {
print('[$hash][in] $msg');
sink.add(msg);
},
),
async.StreamSinkTransformer.fromHandlers(
handleData: (msg, sink) {
print('[$hash][out] $msg');
sink.add(msg);
},
),
),
);
}
static Future<(StreamChannel<Message>, bool)> _connect(
Endpoint endpoint,
ResolvedConnectionSettings settings, {
required CodecContext codecContext,
StreamTransformer<Uint8List, Uint8List>? incomingBytesTransformer,
}) async {
final host = endpoint.host;
final port = endpoint.port;
var socket = await Socket.connect(
endpoint.isUnixSocket
? InternetAddress(host, type: InternetAddressType.unix)
: host,
port,
timeout: settings.connectTimeout,
);
final sslCompleter = Completer<int>();
// ignore: cancel_subscriptions
final subscription = socket.listen(
(data) {
if (sslCompleter.isCompleted) {
return;
}
if (data.length != 1) {
sslCompleter.completeError(
PgException(
'Could not initialize SSL connection, received unknown byte stream.',
),
);
return;
}
sslCompleter.complete(data.first);
},
onDone: () {
if (sslCompleter.isCompleted) {
return;
}
sslCompleter.completeError(
PgException(
'Could not initialize SSL connection, connection closed during handshake.',
),
);
},
onError: (e) {
if (sslCompleter.isCompleted) {
return;
}
sslCompleter.completeError(e);
},
);
Stream<Uint8List> adaptedStream;
var secure = false;
if (settings.sslMode != SslMode.disable) {
// Query if SSL is possible by sending a SSLRequest message
final byteBuffer = ByteData(8);
byteBuffer.setUint32(0, 8);
byteBuffer.setUint32(4, 80877103);
socket.add(byteBuffer.buffer.asUint8List());
final byte = await sslCompleter.future.timeout(settings.connectTimeout);
if (byte == $S) {
// SSL is supported, upgrade!
subscription.pause();
socket = await SecureSocket.secure(
socket,
context: settings.securityContext,
onBadCertificate: settings.sslMode.ignoreCertificateIssues
? (_) => true
: (c) => throw BadCertificateException(c),
).timeout(settings.connectTimeout);
secure = true;
// We can listen to the secured socket again, the existing subscription is
// ignored.
adaptedStream = socket;
} else {
// This server does not support SSL
throw PgException(
'Server does not support SSL, but it was required (default configuration). '
'To disable secure connections, use `ConnectionSettings(sslMode: SslMode.disable)`.',
);
}
} else {
// We've listened to the stream already and sockets are single-subscription
// streams. Expose it as a new stream.
adaptedStream = async.SubscriptionStream(subscription);
}
if (incomingBytesTransformer != null) {
adaptedStream = adaptedStream.transform(incomingBytesTransformer);
}
final outgoingSocket = async.StreamSinkExtensions(socket).transform<Uint8List>(
async.StreamSinkTransformer.fromHandlers(
handleDone: (out) {
// As per the stream channel's guarantees, closing the sink should close
// the channel in both directions.
socket.destroy();
return out.close();
},
),
);
return (
StreamChannel<List<int>>(
adaptedStream,
outgoingSocket,
).transform(messageTransformer(codecContext)),
secure,
);
}
final Endpoint _endpoint;
@override
final ResolvedConnectionSettings _settings;
final StreamChannel<Message> _channel;
final DatabaseInfo _databaseInfo;
@override
final ConnectionInfo info;
@internal
late final codecContext = CodecContext(
encoding: encoding,
databaseInfo: _databaseInfo,
connectionInfo: info,
typeRegistry: _settings.typeRegistry,
);
/// Whether [_channel] is backed by a TLS connection.
final bool _channelIsSecure;
late final StreamSubscription<Message> _serverMessages;
BackendKeyMessage? _backendKeyMessage;
bool _isClosing = false;
bool _socketIsBroken = false;
_PendingOperation? _pending;
// Errors happening while a transaction is active will roll back the
// transaction and should be reporte to the user.
_TransactionSession? _activeTransaction;
var _statementCounter = 0;
var _portalCounter = 0;
var _queryCount = 0;
late final _channels = _Channels(this);
@internal
int get queryCount => _queryCount;
@override
Channels get channels => _channels;
@override
PgConnectionImplementation get _connection => this;
PgConnectionImplementation._(
this._endpoint,
this._settings,
this._channel,
this._channelIsSecure, {
required DatabaseInfo databaseInfo,
required this.info,
}) : _databaseInfo = databaseInfo {
_serverMessages = _channel.stream.listen(
_handleMessage,
onDone: _socketClosed,
onError: (e, s) {
_close(true, PgException('Socket error: $e'), socketIsBroken: true);
},
);
}
Future<void> _startup() {
return _withResource(() {
final result = _pending = _AuthenticationProcedure(
this,
_channelIsSecure,
);
_channel.sink.add(
StartupMessage(
database: _endpoint.database,
timeZone: _settings.timeZone,
username: _endpoint.username,
replication: _settings.replicationMode,
applicationName: _settings.applicationName,
),
);
return result._done.future.timeout(_settings.connectTimeout);
});
}
Future<void> _socketClosed() async {
await _close(
true,
PgException(
'The underlying socket to Postgres has been closed unexpectedly.',
),
socketIsBroken: true,
);
}
Future<void> _handleMessage(Message message) async {
_serverMessages.pause();
try {
message as ServerMessage;
if (message is XLogDataLogicalMessage) {
final embedded = message.message;
if (embedded is RelationMessage) {
_databaseInfo.addRelationMessage(embedded);
}
}
if (message is ParameterStatusMessage) {
info.setParameter(message.name, message.value);
} else if (message is BackendKeyMessage) {
_backendKeyMessage = message;
} else if (message is NoticeMessage) {
// ignore for now
} else if (message is NotificationResponseMessage) {
_channels.deliverNotification(message);
} else if (message is ErrorResponseMessage) {
final exception = transformServerException(
buildExceptionFromErrorFields(message.fields),
);
// Close the connection in response to fatal errors or if we get them
// out of nowhere.
if (exception.willAbortConnection || _pending == null) {
_closeAfterError(exception);
} else {
_connection._activeTransaction?._transactionException = exception;
_pending!.handleError(exception);
}
} else if (_pending != null) {
await _pending!.handleMessage(message);
}
} finally {
_serverMessages.resume();
}
}
@override
Future<void> get closed => _channel.sink.done;
@override
Future<R> run<R>(
Future<R> Function(Session session) fn, {
SessionSettings? settings,
}) {
final session = _RegularSession(
this,
ResolvedSessionSettings(settings, _settings),
);
// Unlike runTx, this doesn't need any locks. An active transaction changes
// the state of the connection, this method does not. If methods requiring
// locks are called by [fn], these methods will aquire locks as needed.
return Future<R>(() => fn(session)).whenComplete(session._closeSession);
}
@override
Future<R> runTx<R>(
Future<R> Function(TxSession session) fn, {
TransactionSettings? settings,
}) {
final rsettings = ResolvedTransactionSettings(settings, _settings);
// Keep this database is locked while the transaction is active. We do that
// because on a protocol level, the entire connection is in a transaction.
// From a Dart point of view, methods called outside of the transaction
// should not be able to view data in the transaction though. So we avoid
// those outer calls while the transaction is active and resume them by
// returning the operation lock in the end.
return _operationLock.withResource(() async {
// The transaction has its own _operationLock, which means that it (and
// only it) can be used to run statements while it's active.
final transaction = _connection._activeTransaction = _TransactionSession(
this,
rsettings,
);
late String beginQuery;
if (rsettings.shouldExpandBegin) {
final sb = StringBuffer('BEGIN');
rsettings.expandBegin(sb);
sb.write(';');
beginQuery = sb.toString();
} else {
beginQuery = 'BEGIN;';
}
await transaction.execute(Sql(beginQuery), queryMode: QueryMode.simple);
try {
final result = await fn(transaction);
if (transaction.mayCommit) {
await transaction._sendAndMarkClosed('COMMIT;');
} else if (!transaction._sessionClosed) {
await transaction._sendAndMarkClosed('ROLLBACK;');
}
// If we have received an error while the transaction was active, it
// will always be rolled back.
if (transaction._transactionException case final PgException e) {
throw e;
}
return result;
} catch (e) {
if (!transaction._sessionClosed) {
try {
await transaction._sendAndMarkClosed('ROLLBACK;');
} catch (_) {
// checking the outer exception
if (e is PgException) {
// Ignore exception of rollback, as the earlier exception takes precedence.
} else {
// Do not ignore the exception here, it may be an implementation bug we are swallowing.
rethrow;
}
}
}
rethrow;
}
});
}
@override
Future<void> close({bool force = false}) async {
final ex = force ? PgException('Connection closed.') : null;
await _close(force, ex);
}
Future<void> _close(
bool interruptRunning,
PgException? cause, {
bool socketIsBroken = false,
}) async {
_socketIsBroken = _socketIsBroken || socketIsBroken;
if (!_isClosing) {
_isClosing = true;
try {
if (interruptRunning) {
_pending?.handleConnectionClosed(cause);
} else {
// Wait for the previous operation to complete by using the lock
await _operationLock.withResource(() {
if (!_socketIsBroken) {
_channel.sink.add(const TerminateMessage());
}
});
}
await Future.wait([_channel.sink.close(), _serverMessages.cancel()]);
_closeSession();
} catch (err) {
// error in _close(), silencing since the connection is no longer
// usable anyway
}
}
}
void _closeAfterError([PgException? cause]) {
_close(true, cause, socketIsBroken: cause?.willAbortConnection ?? false);
}
@internal
Future<void> cancelPendingStatement() async {
var (channel, _) = await _connect(
_endpoint,
_settings,
codecContext: codecContext,
);
if (_backendKeyMessage == null) {
throw PgException(
'Unable to cancel pending statement: no backend key available.',
);
}
channel = _debugChannel(channel);
channel.sink.add(
CancelRequestMessage(
processId: _backendKeyMessage!.processId,
secretKey: _backendKeyMessage!.secretKey,
),
);
// Waiting for the server to close connection.
await channel.stream.listen((_) {}).asFuture();
}
}
class _PreparedStatement extends Statement {
final InternalQueryDescription _description;
final String _name;
final _PgSessionBase _session;
/// Apparently, when we are in a transaction and using extended query mode,
/// one needs to close the portals to release the locks on tables.
/// This queue will collect the portal names to close and they will be closed
/// when the prepared statement is disposed or a run call completes.
///
/// See more in https://github.com/isoos/postgresql-dart/issues/390
Queue<String>? _portalsToClose;
final Trace _trace;
_PreparedStatement(this._description, this._name, this._session, this._trace);
_PgSessionBase get _effectiveSession =>
_session._connection._activeTransaction ?? _session;
@override
ResultStream bind(Object? parameters) {
return _BoundStatement(
this,
_description.bindParameters(
parameters,
ignoreSuperfluous:
_effectiveSession._settings.ignoreSuperfluousParameters,
),
);
}
@override
Future<Result> run(Object? parameters, {Duration? timeout}) async {
final stackTrace = StackTrace.current;
final trace = Trace.from(stackTrace);
_session._connection._queryCount++;
timeout ??= _session._settings.queryTimeout;
final items = <ResultRow>[];
final subscription = (bind(parameters) as _BoundStatement).listen(
items.add,
callerTrace: trace,
);
try {
return await (subscription as _PgResultStreamSubscription)._waitForResult(
items: items,
timeout: timeout,
);
} finally {
await subscription.cancel();
await _closePendingPortals(stackTrace: stackTrace);
}
}
@override
Future<void> dispose() async {
// Don't send a dispose message if the connection is already closed.
if (!_session._connection._isClosing) {
await _closePendingPortals();
await _session._sendAndWaitForQuery<CloseCompleteMessage>(
CloseMessage.statement(_name),
);
}
}
void _addPortalToClose(String portalName) {
_portalsToClose ??= Queue();
_portalsToClose!.add(portalName);
}
Future<void> _closePendingPortals({StackTrace? stackTrace}) async {
final list = _portalsToClose;
while (list != null && list.isNotEmpty) {
final portalName = list.removeFirst();
await _effectiveSession._sendAndWaitForQuery<CloseCompleteMessage>(
CloseMessage.portal(portalName),
stackTrace: stackTrace,
);
}
}
}
class _BoundStatement extends Stream<ResultRow> implements ResultStream {
final _PreparedStatement statement;
final List<TypedValue> parameters;
_BoundStatement(this.statement, this.parameters);
@override
ResultStreamSubscription listen(
void Function(ResultRow event)? onData, {
Function? onError,
void Function()? onDone,
bool? cancelOnError,
Trace? callerTrace,
}) {
final controller = StreamController<ResultRow>();
// ignore: cancel_subscriptions
final subscription = controller.stream.listen(
onData,
onError: onError,
onDone: onDone,
cancelOnError: cancelOnError,
);
return _PgResultStreamSubscription(
this,
controller,
subscription,
callerTrace: callerTrace,
);
}
}
class _PgResultStreamSubscription
implements ResultStreamSubscription, _PendingOperation {
@override
final _PgSessionBase session;
final StreamController<ResultRow> _controller;
final StreamSubscription<ResultRow> _source;
final bool ignoreRows;
final _affectedRows = Completer<int>();
int _affectedRowsSoFar = 0;
final _schema = Completer<ResultSchema>();
final _done = Completer<void>();
ResultSchema? _resultSchema;
_BoundStatement? _boundStatement;
@override
PgConnectionImplementation get connection => session._connection;
late final _portalName = 'p/${connection._portalCounter++}';
final Trace? _parentTrace;
final Trace _callerTrace;
_PgResultStreamSubscription(
_BoundStatement statement,
this._controller,
this._source, {
Trace? callerTrace,
}) : session = statement.statement._effectiveSession,
ignoreRows = false,
_boundStatement = statement,
_parentTrace = statement.statement._trace,
_callerTrace = callerTrace ?? Trace.current() {
_scheduleStatement(() async {
connection._pending = this;
final encodedFutures = <Future<EncodedValue?>>[];
final context = connection.codecContext;
for (final e in statement.parameters) {
if (e.isSqlNull) {
encodedFutures.add(Future.value(null));
continue;
}
final f = context.typeRegistry.encode(e, context);
encodedFutures.add(f);
}
final encodedValues = await Future.wait(encodedFutures);
connection._channel.sink.add(
AggregatedClientMessage([
BindMessage(
encodedValues,
portalName: _portalName,
statementName: statement.statement._name,
),
DescribeMessage.portal(portalName: _portalName),
ExecuteMessage(_portalName),
SyncMessage(),
]),
);
await _done.future;
});
}
_PgResultStreamSubscription.simpleQueryProtocol(
String sql,
this.session,
this._controller,
this._source,
this.ignoreRows, {
Trace? callerTrace,
void Function()? cleanup,
}) : _parentTrace = null,
_callerTrace = callerTrace ?? Trace.current() {
_scheduleStatement(() async {
connection._pending = this;
connection._channel.sink.add(QueryMessage(sql));
await _done.future;
cleanup?.call();
});
}
void _scheduleStatement(Future<void> Function() sendAndWait) async {
try {
await session._withResource(sendAndWait);
} catch (e, s) {
// _withResource can fail if the connection or the session is already
// closed. This error should be reported to the user!
if (!_done.isCompleted) {
_controller.addError(e, s);
await _completeQuery();
}
}
}
@override
Future<int> get affectedRows => _affectedRows.future;
@override
Future<ResultSchema> get schema => _schema.future;
Future<void> _completeQuery() async {
// Make sure the affectedRows and schema futures complete with something
// after the query is done, even if we didn't get a row description
// message.
if (!_affectedRows.isCompleted) {
_affectedRows.complete(_affectedRowsSoFar);
}
if (!_schema.isCompleted) {
_schema.complete(ResultSchema(const []));
}
_done.complete();
await _controller.close();
}
StackTrace _trace() => Chain([
Trace.current(1),
_callerTrace,
if (_parentTrace != null) _parentTrace,
]);
@override
void handleConnectionClosed(PgException? dueToException) {
if (dueToException != null) {
_controller.addError(dueToException, _trace());
}
_completeQuery();
}
@override
void handleError(PgException exception) {
_controller.addError(exception, _trace());
}
@override
Future<void> handleMessage(ServerMessage message) async {
switch (message) {
case BindCompleteMessage():
case NoDataMessage():
// Nothing to do!
break;
case RowDescriptionMessage():
final schema = _resultSchema = ResultSchema([
for (final field in message.fieldDescriptions)
ResultSchemaColumn(
typeOid: field.typeOid,
type: session._connection._settings.typeRegistry.resolveOid(
field.typeOid,
),
columnName: field.fieldName,
columnOid: field.columnOid,
tableOid: field.tableOid,
isBinaryEncoding: field.isBinaryEncoding,
),
]);
_schema.complete(schema);
case DataRowMessage():
if (!ignoreRows) {
final schema = _resultSchema!;
final columnCount = message.values.length;
final futures = <Future>[];
List<bool>? sqlNulls;
final context = session._connection.codecContext;
for (var i = 0; i < message.values.length; i++) {
final field = schema.columns[i];
final input = message.values[i];
if (input == null) {
sqlNulls ??= List<bool>.filled(columnCount, false);
sqlNulls[i] = true;
}
final futureValue = context.typeRegistry.decode(
EncodedValue(
input,
format: EncodingFormat.fromBinaryFlag(field.isBinaryEncoding),
typeOid: field.typeOid,
),
context,
);
futures.add(futureValue);
}
final values = await Future.wait(futures);
final row = ResultRow(
schema: schema,
values: values,
sqlNulls: sqlNulls,
);
_controller.add(row);
}
case CommandCompleteMessage():
// We can't complete _affectedRows directly after receiving the message
// since, if multiple statements are running in a single SQL string,
// we'll get this more than once.
_affectedRowsSoFar += message.rowsAffected;