forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlRawCopyStream.cs
More file actions
385 lines (326 loc) · 12.2 KB
/
NpgsqlRawCopyStream.cs
File metadata and controls
385 lines (326 loc) · 12.2 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
#region License
// The PostgreSQL License
//
// Copyright (C) 2016 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
using Npgsql.BackendMessages;
using Npgsql.FrontendMessages;
#pragma warning disable 1591
namespace Npgsql
{
/// <summary>
/// Provides an API for a raw binary COPY operation, a high-performance data import/export mechanism to
/// a PostgreSQL table. Initiated by <see cref="NpgsqlConnection.BeginRawBinaryCopy"/>
/// </summary>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public class NpgsqlRawCopyStream : Stream, ICancelable
{
#region Fields and Properties
NpgsqlConnector _connector;
ReadBuffer _readBuf;
WriteBuffer _writeBuf;
bool _writingDataMsg;
int _leftToReadInDataMsg;
bool _isDisposed, _isConsumed;
readonly bool _canRead;
readonly bool _canWrite;
internal bool IsBinary { get; private set; }
public override bool CanWrite => _canWrite;
public override bool CanRead => _canRead;
/// <summary>
/// The copy binary format header signature
/// </summary>
internal static readonly byte[] BinarySignature =
{
(byte)'P',(byte)'G',(byte)'C',(byte)'O',(byte)'P',(byte)'Y',
(byte)'\n', 255, (byte)'\r', (byte)'\n', 0
};
#endregion
#region Constructor
internal NpgsqlRawCopyStream(NpgsqlConnector connector, string copyCommand)
{
_connector = connector;
_readBuf = connector.ReadBuffer;
_writeBuf = connector.WriteBuffer;
_connector.SendQuery(copyCommand);
var msg = _connector.ReadMessage(DataRowLoadingMode.NonSequential);
switch (msg.Code)
{
case BackendMessageCode.CopyInResponse:
var copyInResponse = (CopyInResponseMessage) msg;
IsBinary = copyInResponse.IsBinary;
_canWrite = true;
break;
case BackendMessageCode.CopyOutResponse:
var copyOutResponse = (CopyOutResponseMessage) msg;
IsBinary = copyOutResponse.IsBinary;
_canRead = true;
break;
default:
throw _connector.UnexpectedMessageReceived(msg.Code);
}
}
#endregion
#region Write
public override void Write(byte[] buffer, int offset, int count)
{
CheckDisposed();
if (!CanWrite)
throw new InvalidOperationException("Stream not open for writing");
if (count == 0) { return; }
EnsureDataMessage();
if (count <= _writeBuf.WriteSpaceLeft)
{
_writeBuf.WriteBytes(buffer, offset, count);
return;
}
try {
// Value is too big. Flush whatever is in the buffer, then write a new CopyData
// directly with the buffer.
Flush();
_writeBuf.WriteByte((byte)BackendMessageCode.CopyData);
_writeBuf.WriteInt32(count + 4);
_writeBuf.Flush();
_writeBuf.DirectWrite(buffer, offset, count);
EnsureDataMessage();
} catch {
_connector.Break();
Cleanup();
throw;
}
}
public override void Flush()
{
CheckDisposed();
if (!_writingDataMsg) { return; }
// Need to update the length for the CopyData about to be sent
var pos = _writeBuf.WritePosition;
_writeBuf.WritePosition = 1;
_writeBuf.WriteInt32(pos - 1);
_writeBuf.WritePosition = pos;
_writeBuf.Flush();
_writingDataMsg = false;
}
void EnsureDataMessage()
{
if (_writingDataMsg) { return; }
Contract.Assert(_writeBuf.WritePosition == 0);
_writeBuf.WriteByte((byte)BackendMessageCode.CopyData);
// Leave space for the message length
_writeBuf.WriteInt32(0);
_writingDataMsg = true;
}
#endregion
#region Read
public override int Read(byte[] buffer, int offset, int count)
{
CheckDisposed();
if (!CanRead)
throw new InvalidOperationException("Stream not open for reading");
if (_isConsumed) {
return 0;
}
if (_leftToReadInDataMsg == 0)
{
// We've consumed the current DataMessage (or haven't yet received the first),
// read the next message
var msg = _connector.ReadMessage(DataRowLoadingMode.NonSequential);
switch (msg.Code) {
case BackendMessageCode.CopyData:
_leftToReadInDataMsg = ((CopyDataMessage)msg).Length;
break;
case BackendMessageCode.CopyDone:
_connector.ReadExpecting<CommandCompleteMessage>();
_connector.ReadExpecting<ReadyForQueryMessage>();
_isConsumed = true;
return 0;
default:
throw _connector.UnexpectedMessageReceived(msg.Code);
}
}
Contract.Assume(_leftToReadInDataMsg > 0);
// If our buffer is empty, read in more. Otherwise return whatever is there, even if the
// user asked for more (normal socket behavior)
if (_readBuf.ReadBytesLeft == 0) {
_readBuf.ReadMore();
}
Contract.Assert(_readBuf.ReadBytesLeft > 0);
var maxCount = Math.Min(_readBuf.ReadBytesLeft, _leftToReadInDataMsg);
if (count > maxCount) {
count = maxCount;
}
_leftToReadInDataMsg -= count;
_readBuf.ReadBytes(buffer, offset, count);
return count;
}
#endregion
#region Cancel
/// <summary>
/// Cancels and terminates an ongoing operation. Any data already written will be discarded.
/// </summary>
public void Cancel()
{
CheckDisposed();
if (CanWrite)
{
_isDisposed = true;
_writeBuf.Clear();
_connector.SendMessage(new CopyFailMessage());
try
{
var msg = _connector.ReadMessage(DataRowLoadingMode.NonSequential);
// The CopyFail should immediately trigger an exception from the read above.
_connector.Break();
throw new NpgsqlException("Expected ErrorResponse when cancelling COPY but got: " + msg.Code);
}
catch (PostgresException e)
{
if (e.SqlState == "57014") { return; }
throw;
}
}
else
{
_connector.CancelRequest();
}
}
#endregion
#region Dispose
protected override void Dispose(bool disposing)
{
if (_isDisposed || !disposing) { return; }
if (CanWrite)
{
Flush();
_connector.SendMessage(CopyDoneMessage.Instance);
_connector.ReadExpecting<CommandCompleteMessage>();
_connector.ReadExpecting<ReadyForQueryMessage>();
}
else
{
if (!_isConsumed) {
if (_leftToReadInDataMsg > 0) {
_readBuf.Skip(_leftToReadInDataMsg);
}
_connector.SkipUntil(BackendMessageCode.ReadyForQuery);
}
}
_connector.CurrentCopyOperation = null;
_connector.EndUserAction();
Cleanup();
}
void Cleanup()
{
_connector = null;
_readBuf = null;
_writeBuf = null;
_isDisposed = true;
}
void CheckDisposed()
{
if (_isDisposed) {
throw new ObjectDisposedException(GetType().FullName, "The COPY operation has already ended.");
}
}
#endregion
#region Invariants
[ContractInvariantMethod]
void ObjectInvariants()
{
Contract.Invariant(_isDisposed || (_connector != null && _readBuf != null && _writeBuf != null));
Contract.Invariant(CanRead || CanWrite);
Contract.Invariant(_readBuf == null || _readBuf == _connector.ReadBuffer);
Contract.Invariant(_writeBuf == null || _writeBuf == _connector.WriteBuffer);
}
#endregion
#region Unsupported
public override bool CanSeek => false;
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
#endregion
}
/// <summary>
/// Writer for a text import, initiated by <see cref="NpgsqlConnection.BeginTextImport"/>.
/// </summary>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public class NpgsqlCopyTextWriter : StreamWriter, ICancelable
{
internal NpgsqlCopyTextWriter(NpgsqlRawCopyStream underlying) : base(underlying)
{
if (underlying.IsBinary)
throw new Exception("Can't use a binary copy stream for text writing");
Contract.EndContractBlock();
}
/// <summary>
/// Cancels and terminates an ongoing import. Any data already written will be discarded.
/// </summary>
public void Cancel()
{
((NpgsqlRawCopyStream)BaseStream).Cancel();
}
}
/// <summary>
/// Reader for a text export, initiated by <see cref="NpgsqlConnection.BeginTextExport"/>.
/// </summary>
/// <remarks>
/// See http://www.postgresql.org/docs/current/static/sql-copy.html.
/// </remarks>
public class NpgsqlCopyTextReader : StreamReader, ICancelable
{
internal NpgsqlCopyTextReader(NpgsqlRawCopyStream underlying) : base(underlying)
{
if (underlying.IsBinary)
throw new Exception("Can't use a binary copy stream for text reading");
Contract.EndContractBlock();
}
/// <summary>
/// Cancels and terminates an ongoing import.
/// </summary>
public void Cancel()
{
((NpgsqlRawCopyStream)BaseStream).Cancel();
}
}
}