forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayHandler.cs
More file actions
576 lines (513 loc) · 21.6 KB
/
ArrayHandler.cs
File metadata and controls
576 lines (513 loc) · 21.6 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
#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;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using JetBrains.Annotations;
using Npgsql.BackendMessages;
using NpgsqlTypes;
namespace Npgsql.TypeHandlers
{
internal abstract class ArrayHandler : ChunkingTypeHandler<Array>
{
internal ArrayHandler(IBackendType backendType) : base(backendType) {}
internal abstract Type GetElementFieldType(FieldDescription fieldDescription = null);
internal abstract Type GetElementPsvType(FieldDescription fieldDescription = null);
}
/// <summary>
/// Base class for all type handlers which handle PostgreSQL arrays.
/// </summary>
/// <remarks>
/// http://www.postgresql.org/docs/current/static/arrays.html
/// </remarks>
internal class ArrayHandler<TElement> : ArrayHandler
{
/// <summary>
/// The lower bound value sent to the backend when writing arrays. Normally 1 (the PG default) but
/// is 0 for OIDVector.
/// </summary>
protected int LowerBound { get; set; }
#region State
Array _readValue;
IList _writeValue;
ReadState _readState;
WriteState _writeState;
IEnumerator _enumerator;
ReadBuffer _readBuf;
WriteBuffer _writeBuf;
LengthCache _lengthCache;
FieldDescription _fieldDescription;
int _dimensions;
int[] _dimLengths, _indices;
int _index;
int _elementLen;
bool _wroteElementLen;
bool _preparedRead;
#endregion
internal override Type GetFieldType(FieldDescription fieldDescription)
{
return typeof (Array);
}
internal override Type GetProviderSpecificFieldType(FieldDescription fieldDescription)
{
return typeof (Array);
}
/// <summary>
/// The type of the elements contained within this array
/// </summary>
/// <param name="fieldDescription"></param>
internal override Type GetElementFieldType(FieldDescription fieldDescription = null)
{
return typeof(TElement);
}
/// <summary>
/// The provider-specific type of the elements contained within this array,
/// </summary>
/// <param name="fieldDescription"></param>
internal override Type GetElementPsvType(FieldDescription fieldDescription)
{
return typeof(TElement);
}
/// <summary>
/// The type handler for the element that this array type holds
/// </summary>
protected internal TypeHandler ElementHandler { get; protected set; }
public ArrayHandler(IBackendType backendType, TypeHandler elementHandler, int lowerBound) : base(backendType)
{
LowerBound = lowerBound;
ElementHandler = elementHandler;
}
public ArrayHandler(IBackendType backendType, TypeHandler elementHandler)
: this(backendType, elementHandler, 1) {}
#region Read
public override void PrepareRead(ReadBuffer buf, int len, FieldDescription fieldDescription = null)
{
Contract.Assert(_readState == ReadState.NeedPrepare);
if (_readState != ReadState.NeedPrepare) // Checks against recursion and bugs
throw PGUtil.ThrowIfReached("Started reading a value before completing a previous value");
_readBuf = buf;
_fieldDescription = fieldDescription;
_elementLen = -1;
_readState = ReadState.ReadNothing;
_preparedRead = false;
}
public override bool Read(out Array result)
{
return Read<TElement>(out result);
}
protected bool Read<TElement2>([CanBeNull] out Array result)
{
switch (_readState)
{
case ReadState.ReadNothing:
if (_readBuf.ReadBytesLeft < 12)
{
result = null;
return false;
}
_dimensions = _readBuf.ReadInt32();
_readBuf.ReadInt32(); // Has nulls. Not populated by PG?
_readBuf.ReadUInt32();
// The following should hold but fails in test CopyTests.ReadBitString
//var elementOID = _readBuf.ReadUInt32();
//Contract.Assume(elementOID == ElementHandler.BackendType.OID);
_dimLengths = new int[_dimensions];
if (_dimensions > 1) {
_indices = new int[_dimensions];
}
_index = 0;
_readState = ReadState.ReadHeader;
goto case ReadState.ReadHeader;
case ReadState.ReadHeader:
if (_readBuf.ReadBytesLeft < _dimensions * 8) {
result = null;
return false;
}
for (var i = 0; i < _dimensions; i++)
{
_dimLengths[i] = _readBuf.ReadInt32();
_readBuf.ReadInt32(); // We don't care about the lower bounds
}
if (_dimensions == 0)
{
result = new TElement2[0];
_readState = ReadState.NeedPrepare;
return true;
}
_readValue = Array.CreateInstance(typeof(TElement2), _dimLengths);
_readState = ReadState.ReadingElements;
goto case ReadState.ReadingElements;
case ReadState.ReadingElements:
var completed = _readValue is TElement2[]
? ReadElementsOneDimensional<TElement2>()
: ReadElementsMultidimensional<TElement2>();
if (!completed)
{
result = null;
return false;
}
result = _readValue;
_readValue = null;
_readBuf = null;
_fieldDescription = null;
_readState = ReadState.NeedPrepare;
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Optimized population for one-dimensional arrays without boxing/unboxing
/// </summary>
bool ReadElementsOneDimensional<TElement2>()
{
var array = (TElement2[])_readValue;
for (; _index < array.Length; _index++)
{
TElement2 element;
if (!ReadSingleElement(out element)) { return false; }
array[_index] = element;
}
return true;
}
/// <summary>
/// Recursively populates an array from PB binary data representation.
/// </summary>
bool ReadElementsMultidimensional<TElement2>()
{
while (true)
{
TElement2 element;
if (!ReadSingleElement(out element)) { return false; }
_readValue.SetValue(element, _indices);
if (!MoveNextInMultidimensional()) { return true; }
}
}
bool MoveNextInMultidimensional()
{
_indices[_dimensions - 1]++;
for (var dim = _dimensions - 1; dim >= 0; dim--) {
if (_indices[dim] <= _readValue.GetUpperBound(dim)) {
continue;
}
if (dim == 0) {
return false;
}
for (var j = dim; j < _dimensions; j++)
_indices[j] = _readValue.GetLowerBound(j);
_indices[dim - 1]++;
}
return true;
}
bool ReadSingleElement<TElement2>(out TElement2 element)
{
try
{
if (_elementLen == -1)
{
if (_readBuf.ReadBytesLeft < 4)
{
element = default(TElement2);
return false;
}
_elementLen = _readBuf.ReadInt32();
if (_elementLen == -1)
{
// TODO: Nullables
element = default(TElement2);
return true;
}
}
var asSimpleReader = ElementHandler as ISimpleTypeHandler<TElement2>;
if (asSimpleReader != null)
{
if (_readBuf.ReadBytesLeft < _elementLen)
{
element = default(TElement2);
return false;
}
element = asSimpleReader.Read(_readBuf, _elementLen, _fieldDescription);
_elementLen = -1;
return true;
}
var asChunkingReader = ElementHandler as IChunkingTypeHandler<TElement2>;
if (asChunkingReader != null)
{
if (!_preparedRead)
{
asChunkingReader.PrepareRead(_readBuf, _elementLen, _fieldDescription);
_preparedRead = true;
}
if (!asChunkingReader.Read(out element))
{
return false;
}
_elementLen = -1;
_preparedRead = false;
return true;
}
throw PGUtil.ThrowIfReached();
}
catch (SafeReadException e)
{
// TODO: Implement safe reading for array: read all values to the end, only then raise the
// SafeReadException. For now, translate the safe exception to an unsafe one to break the connector.
throw e.InnerException;
}
}
enum ReadState
{
NeedPrepare,
ReadNothing,
ReadHeader,
ReadingElements,
}
#endregion
#region Write
public override void PrepareWrite(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter=null)
{
Contract.Assert(_readState == ReadState.NeedPrepare);
if (_writeState != WriteState.NeedPrepare) // Checks against recursion and bugs
throw new InvalidOperationException("Started reading a value before completing a previous value");
_writeBuf = buf;
_lengthCache = lengthCache;
var asArray = value as Array;
_writeValue = (IList)value;
_dimensions = asArray?.Rank ?? 1;
_index = 0;
_wroteElementLen = false;
_writeState = WriteState.WroteNothing;
}
public override bool Write(ref DirectBuffer directBuf)
{
return Write<TElement>(ref directBuf);
}
public bool Write<TElement2>(ref DirectBuffer directBuf)
{
switch (_writeState)
{
case WriteState.WroteNothing:
var len =
4 + // ndim
4 + // has_nulls
4 + // element_oid
_dimensions * 8; // dim (4) + lBound (4)
if (_writeBuf.WriteSpaceLeft < len) {
Contract.Assume(_writeBuf.UsableSize >= len, "Buffer too small for header");
return false;
}
_writeBuf.WriteInt32(_dimensions);
_writeBuf.WriteInt32(1); // HasNulls=1. Not actually used by the backend.
_writeBuf.WriteUInt32(ElementHandler.BackendType.OID);
var asArray = _writeValue as Array;
if (asArray != null)
{
for (var i = 0; i < _dimensions; i++)
{
_writeBuf.WriteInt32(asArray.GetLength(i));
_writeBuf.WriteInt32(LowerBound); // We don't map .NET lower bounds to PG
}
}
else
{
_writeBuf.WriteInt32(_writeValue.Count);
_writeBuf.WriteInt32(LowerBound); // We don't map .NET lower bounds to PG
_enumerator = _writeValue.GetEnumerator();
}
var asGeneric = _writeValue as IList<TElement2>;
_enumerator = asGeneric?.GetEnumerator() ?? _writeValue.GetEnumerator();
if (!_enumerator.MoveNext()) {
goto case WriteState.Cleanup;
}
_writeState = WriteState.WritingElements;
goto case WriteState.WritingElements;
case WriteState.WritingElements:
var genericEnumerator = _enumerator as IEnumerator<TElement2>;
if (genericEnumerator != null)
{
// TODO: Actually call the element writer generically...!
do
{
if (!WriteSingleElement(genericEnumerator.Current, ref directBuf)) { return false; }
} while (genericEnumerator.MoveNext());
}
else
{
do {
if (!WriteSingleElement(_enumerator.Current, ref directBuf)) { return false; }
} while (_enumerator.MoveNext());
}
goto case WriteState.Cleanup;
case WriteState.Cleanup:
_writeValue = null;
_writeBuf = null;
_writeState = WriteState.NeedPrepare;
return true;
default:
throw PGUtil.ThrowIfReached();
}
}
bool WriteSingleElement([CanBeNull] object element, ref DirectBuffer directBuf)
{
// TODO: Need generic version of this...
if (element == null || element is DBNull) {
if (_writeBuf.WriteSpaceLeft < 4) {
return false;
}
_writeBuf.WriteInt32(-1);
return true;
}
var asSimpleWriter = ElementHandler as ISimpleTypeHandler;
if (asSimpleWriter != null)
{
var elementLen = asSimpleWriter.ValidateAndGetLength(element, null);
if (_writeBuf.WriteSpaceLeft < 4 + elementLen) { return false; }
_writeBuf.WriteInt32(elementLen);
asSimpleWriter.Write(element, _writeBuf, null);
return true;
}
var asChunkedWriter = ElementHandler as IChunkingTypeHandler;
if (asChunkedWriter != null)
{
if (!_wroteElementLen) {
if (_writeBuf.WriteSpaceLeft < 4) {
return false;
}
_writeBuf.WriteInt32(asChunkedWriter.ValidateAndGetLength(element, ref _lengthCache, null));
asChunkedWriter.PrepareWrite(element, _writeBuf, _lengthCache, null);
_wroteElementLen = true;
}
if (!asChunkedWriter.Write(ref directBuf)) {
return false;
}
_wroteElementLen = false;
return true;
}
throw PGUtil.ThrowIfReached();
}
public override int ValidateAndGetLength(object value, ref LengthCache lengthCache, NpgsqlParameter parameter = null)
{
return ValidateAndGetLength<TElement>(value, ref lengthCache, parameter);
}
public int ValidateAndGetLength<TElement2>(object value, ref LengthCache lengthCache, NpgsqlParameter parameter=null)
{
// Take care of single-dimensional arrays and generic IList<T>
var asGenericList = value as IList<TElement2>;
if (asGenericList != null)
{
if (lengthCache == null) {
lengthCache = new LengthCache(1);
}
if (lengthCache.IsPopulated) {
return lengthCache.Get();
}
// Leave empty slot for the entire array length, and go ahead an populate the element slots
var pos = lengthCache.Position;
lengthCache.Set(0);
var lengthCache2 = lengthCache;
var len = 12 + (1 * 8) + asGenericList.Sum(e => 4 + GetSingleElementLength(e, ref lengthCache2, parameter));
lengthCache = lengthCache2;
return lengthCache.Lengths[pos] = len;
}
// Take care of multi-dimensional arrays and non-generic IList, we have no choice but to do
// boxing/unboxing
var asNonGenericList = value as IList;
if (asNonGenericList != null)
{
if (lengthCache == null) {
lengthCache = new LengthCache(1);
}
if (lengthCache.IsPopulated) {
return lengthCache.Get();
}
var asMultidimensional = value as Array;
var dimensions = asMultidimensional?.Rank ?? 1;
// Leave empty slot for the entire array length, and go ahead an populate the element slots
var pos = lengthCache.Position;
lengthCache.Set(0);
var lengthCache2 = lengthCache;
var len = 12 + (dimensions * 8) + asNonGenericList.Cast<object>().Sum(element => 4 + GetSingleElementLength(element, ref lengthCache2, parameter));
lengthCache = lengthCache2;
lengthCache.Lengths[pos] = len;
return len;
}
throw new InvalidCastException($"Can't write type {value.GetType()} as an array of {typeof (TElement2)}");
}
int GetSingleElementLength([CanBeNull] object element, ref LengthCache lengthCache, NpgsqlParameter parameter=null)
{
if (element == null || element is DBNull) {
return 0;
}
var asChunkingWriter = ElementHandler as IChunkingTypeHandler;
try
{
return asChunkingWriter?.ValidateAndGetLength(element, ref lengthCache, parameter) ??
((ISimpleTypeHandler) ElementHandler).ValidateAndGetLength(element, null);
}
catch (Exception e)
{
throw new Exception("While trying to write an array, one of its elements failed validation. You may be trying to mix types in a non-generic IList, or to write a jagged array.", e);
}
}
enum WriteState
{
NeedPrepare,
WroteNothing,
WritingElements,
Cleanup,
}
#endregion
}
/// <remarks>
/// http://www.postgresql.org/docs/current/static/arrays.html
/// </remarks>
/// <typeparam name="TNormal">The .NET type contained as an element within this array</typeparam>
/// <typeparam name="TPsv">The .NET provider-specific type contained as an element within this array</typeparam>
internal class ArrayHandlerWithPsv<TNormal, TPsv> : ArrayHandler<TNormal>, ITypeHandlerWithPsv
{
/// <summary>
/// The provider-specific type of the elements contained within this array,
/// </summary>
/// <param name="fieldDescription"></param>
internal override Type GetElementPsvType(FieldDescription fieldDescription)
{
return typeof(TPsv);
}
internal override object ReadPsvAsObjectFully(DataRowMessage row, FieldDescription fieldDescription)
{
PrepareRead(row.Buffer, row.ColumnLen, fieldDescription);
Array result;
while (!Read<TPsv>(out result)) {
row.Buffer.ReadMore();
}
return result;
}
public ArrayHandlerWithPsv(IBackendType backendType, TypeHandler elementHandler)
: base(backendType, elementHandler) {}
}
}