forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlCopySerializer.cs
More file actions
481 lines (430 loc) · 10.9 KB
/
NpgsqlCopySerializer.cs
File metadata and controls
481 lines (430 loc) · 10.9 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
// Npgsql.NpgsqlCopySerializer.cs
//
// Author:
// Kalle Hallivuori <kato@iki.fi>
//
// Copyright (C) 2007 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// 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.
using System;
using System.IO;
using System.Text;
namespace Npgsql
{
/// <summary>
/// Writes given objects into a stream for PostgreSQL COPY in default copy format (not CSV or BINARY).
/// </summary>
public class NpgsqlCopySerializer
{
private static readonly Encoding ENCODING_UTF8 = Encoding.UTF8;
public static String DEFAULT_DELIMITER = "\t",
DEFAULT_SEPARATOR = "\n",
DEFAULT_NULL = "\\N",
DEFAULT_ESCAPE = "\\",
DEFAULT_QUOTE = "\"";
public static int DEFAULT_BUFFER_SIZE = 8192;
private readonly NpgsqlConnector _context;
private Stream _toStream;
private String _delimiter = DEFAULT_DELIMITER,
_escape = DEFAULT_ESCAPE,
_separator = DEFAULT_SEPARATOR,
_null = DEFAULT_NULL;
private byte[] _delimiterBytes = null, _escapeBytes = null, _separatorBytes = null, _nullBytes = null;
private byte[][] _escapeSequenceBytes = null;
private String[] _stringsToEscape = null;
private byte[] _sendBuffer = null;
private int _sendBufferAt = 0, _lastFieldEndAt = 0, _lastRowEndAt = 0, _atField = 0;
public NpgsqlCopySerializer(NpgsqlConnection conn)
{
_context = conn.Connector;
}
public bool IsActive
{
get { return _toStream != null && _context.Mediator.CopyStream == _toStream && _context.CurrentState is NpgsqlCopyInState; }
}
public Stream ToStream
{
get
{
if (_toStream == null)
{
_toStream = _context.Mediator.CopyStream;
}
return _toStream;
}
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change stream of an active " + this);
}
_toStream = value;
}
}
public String Delimiter
{
get { return _delimiter; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change delimiter of an active " + this);
}
_delimiter = value ?? DEFAULT_DELIMITER;
_delimiterBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] DelimiterBytes
{
get
{
if (_delimiterBytes == null)
{
_delimiterBytes = ENCODING_UTF8.GetBytes(_delimiter);
}
return _delimiterBytes;
}
}
public String Separator
{
get { return _separator; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change separator of an active " + this);
}
_separator = value ?? DEFAULT_SEPARATOR;
_separatorBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] SeparatorBytes
{
get
{
if (_separatorBytes == null)
{
_separatorBytes = ENCODING_UTF8.GetBytes(_separator);
}
return _separatorBytes;
}
}
public String Escape
{
get { return _escape; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change escape symbol of an active " + this);
}
_escape = value ?? DEFAULT_ESCAPE;
_escapeBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] EscapeBytes
{
get
{
if (_escapeBytes == null)
{
_escapeBytes = ENCODING_UTF8.GetBytes(_escape);
}
return _escapeBytes;
}
}
public String Null
{
get { return _null; }
set
{
if (IsActive)
{
throw new NpgsqlException("Do not change null symbol of an active " + this);
}
_null = value ?? DEFAULT_NULL;
_nullBytes = null;
_stringsToEscape = null;
_escapeSequenceBytes = null;
}
}
private byte[] NullBytes
{
get
{
if (_nullBytes == null)
{
_nullBytes = ENCODING_UTF8.GetBytes(_null);
}
return _nullBytes;
}
}
public Int32 BufferSize
{
get { return _sendBuffer != null ? _sendBuffer.Length : DEFAULT_BUFFER_SIZE; }
set
{
byte[] _newBuffer = new byte[value];
if (_sendBuffer != null)
{
for (int i = 0; i < _sendBufferAt; i++)
{
_newBuffer[i] = _sendBuffer[i];
}
}
_sendBuffer = _newBuffer;
}
}
public void Flush()
{
if (_sendBufferAt > 0)
{
ToStream.Write(_sendBuffer, 0, _sendBufferAt);
ToStream.Flush();
}
_sendBufferAt = 0;
_lastRowEndAt = 0;
_lastFieldEndAt = 0;
}
public void FlushRows()
{
if (_lastRowEndAt > 0)
{
ToStream.Write(_sendBuffer, 0, _lastRowEndAt);
ToStream.Flush();
int len = _sendBufferAt - _lastRowEndAt;
for (int i = 0; i < len; i++)
{
_sendBuffer[i] = _sendBuffer[_lastRowEndAt + i];
}
_lastFieldEndAt -= _lastRowEndAt;
_sendBufferAt -= _lastRowEndAt;
_lastRowEndAt = 0;
}
}
public void FlushFields()
{
if (_lastFieldEndAt > 0)
{
ToStream.Write(_sendBuffer, 0, _lastFieldEndAt);
ToStream.Flush();
int len = _sendBufferAt - _lastFieldEndAt;
for (int i = 0; i < len; i++)
{
_sendBuffer[i] = _sendBuffer[_lastFieldEndAt + i];
}
_lastRowEndAt -= _lastFieldEndAt;
_sendBufferAt -= _lastFieldEndAt;
_lastFieldEndAt = 0;
}
}
public void Close()
{
if (_atField > 0)
{
EndRow();
}
Flush();
ToStream.Close();
}
protected int SpaceInBuffer
{
get { return BufferSize - _sendBufferAt; }
}
protected String[] StringsToEscape
{
get
{
if (_stringsToEscape == null)
{
_stringsToEscape = new String[] {Delimiter, Separator, Escape, "\r", "\n"};
}
return _stringsToEscape;
}
}
protected byte[][] EscapeSequenceBytes
{
get
{
if (_escapeSequenceBytes == null)
{
_escapeSequenceBytes = new byte[StringsToEscape.Length][];
for (int i = 0; i < StringsToEscape.Length; i++)
{
_escapeSequenceBytes[i] = EscapeSequenceFor(StringsToEscape[i].ToCharArray(0, 1)[0]);
}
}
return _escapeSequenceBytes;
}
}
private static readonly byte[] esc_t = new byte[] {(byte) 't'};
private static readonly byte[] esc_n = new byte[] {(byte) 'n'};
private static readonly byte[] esc_r = new byte[] {(byte) 'r'};
private static readonly byte[] esc_b = new byte[] {(byte) 'b'};
private static readonly byte[] esc_f = new byte[] {(byte) 'f'};
private static readonly byte[] esc_v = new byte[] {(byte) 'v'};
protected static byte[] EscapeSequenceFor(char c)
{
return
c == '\t'
? esc_t
: c == '\n'
? esc_n
: c == '\r'
? esc_r
: c == '\b'
? esc_b
: c == '\f'
? esc_f
: c == '\v'
? esc_v
: (c < 32 || c > 127)
? new byte[] {(byte) ('0' + ((c/64) & 7)), (byte) ('0' + ((c/8) & 7)), (byte) ('0' + (c & 7))}
: new byte[] {(byte) c};
}
protected void MakeRoomForBytes(int len)
{
if (_sendBuffer == null)
{
_sendBuffer = new byte[BufferSize];
}
if (len >= SpaceInBuffer)
{
FlushRows();
if (len >= SpaceInBuffer)
{
FlushFields();
if (len >= SpaceInBuffer)
{
BufferSize = len;
}
}
}
}
protected void AddBytes(byte[] bytes)
{
MakeRoomForBytes(bytes.Length);
for (int i = 0; i < bytes.Length; i++)
{
_sendBuffer[_sendBufferAt++] = bytes[i];
}
}
public void EndRow()
{
if (_context != null)
{
while (_atField < _context.CurrentState.CopyFormat.FieldCount)
{
AddNull();
}
}
if (_context == null || ! _context.CurrentState.CopyFormat.IsBinary)
{
AddBytes(SeparatorBytes);
}
_lastRowEndAt = _sendBufferAt;
_atField = 0;
}
protected void PrefixField()
{
if (_atField > 0)
{
if (_atField >= _context.CurrentState.CopyFormat.FieldCount)
{
throw new NpgsqlException("Tried to add too many fields to a copy record with " + _atField + " fields");
}
AddBytes(DelimiterBytes);
}
}
protected void FieldAdded()
{
_lastFieldEndAt = _sendBufferAt;
_atField++;
}
public void AddNull()
{
PrefixField();
AddBytes(NullBytes);
FieldAdded();
}
public void AddString(String fieldValue)
{
PrefixField();
int bufferedUpto = 0;
while (bufferedUpto < fieldValue.Length)
{
int escapeAt = fieldValue.Length;
byte[] escapeSequence = null;
// choose closest instance of strings to escape in fieldValue
for (int eachEscapeable = 0; eachEscapeable < StringsToEscape.Length; eachEscapeable++)
{
int i = fieldValue.IndexOf(StringsToEscape[eachEscapeable], bufferedUpto);
if (i > -1 && i < escapeAt)
{
escapeAt = i;
escapeSequence = EscapeSequenceBytes[eachEscapeable];
}
}
// some, possibly all of fieldValue string does not require escaping and can be buffered for output
if (escapeAt > bufferedUpto)
{
int encodedLength = ENCODING_UTF8.GetByteCount(fieldValue.ToCharArray(bufferedUpto, escapeAt));
MakeRoomForBytes(encodedLength);
_sendBufferAt += ENCODING_UTF8.GetBytes(fieldValue, bufferedUpto, escapeAt, _sendBuffer, _sendBufferAt);
bufferedUpto = escapeAt;
}
// now buffer the escape sequence for output
if (escapeSequence != null)
{
AddBytes(EscapeBytes);
AddBytes(escapeSequence);
bufferedUpto++;
}
}
FieldAdded();
}
public void AddInt32(Int32 fieldValue)
{
AddString(string.Format("{0}", fieldValue));
}
public void AddInt64(Int64 fieldValue)
{
AddString(string.Format("{0}", fieldValue));
}
public void AddNumber(double fieldValue)
{
AddString(string.Format("{0}", fieldValue));
}
public void AddBool(bool fieldValue)
{
AddString(fieldValue ? "TRUE" : "FALSE");
}
public void AddDateTime(DateTime fieldValue)
{
AddString(string.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}", fieldValue.Year, fieldValue.Month, fieldValue.Day, fieldValue.Hour, fieldValue.Minute, fieldValue.Second, fieldValue.Millisecond));
}
}
}