forked from Emill/Npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayHandler.cs
More file actions
549 lines (487 loc) · 20 KB
/
ArrayHandler.cs
File metadata and controls
549 lines (487 loc) · 20 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
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 Npgsql.BackendMessages;
using NpgsqlTypes;
namespace Npgsql.TypeHandlers
{
/// <summary>
/// Base class for all type handlers which handle PostgreSQL arrays.
/// </summary>
/// <remarks>
/// http://www.postgresql.org/docs/current/static/arrays.html
/// </remarks>
internal abstract class ArrayHandler : TypeHandler<Array>
{
/// <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;
NpgsqlBuffer _buf;
NpgsqlParameter _parameter;
LengthCache _lengthCache;
FieldDescription _fieldDescription;
int _dimensions;
int[] _dimLengths, _indices;
int _index;
int _elementLen;
/// <summary>
/// The array currently being written
/// </summary>
bool _wroteElementLen;
#endregion
internal override Type GetFieldType(FieldDescription fieldDescription)
{
return typeof (Array);
}
internal override Type GetProviderSpecificFieldType(FieldDescription fieldDescription)
{
return typeof (Array);
}
internal abstract Type GetElementFieldType(FieldDescription fieldDescription);
internal abstract Type GetElementPsvType(FieldDescription fieldDescription);
/// <summary>
/// The type handler for the element that this array type holds
/// </summary>
internal TypeHandler ElementHandler { get; private set; }
protected ArrayHandler(TypeHandler elementHandler)
{
LowerBound = 1;
ElementHandler = elementHandler;
}
#region Read
protected void PrepareRead(NpgsqlBuffer buf, FieldDescription fieldDescription, int len)
{
Contract.Assert(_readState == ReadState.NeedPrepare);
if (_readState != ReadState.NeedPrepare) // Checks against recursion and bugs
throw new InvalidOperationException("Started reading a value before completing a previous value");
_buf = buf;
_fieldDescription = fieldDescription;
_elementLen = -1;
_readState = ReadState.ReadNothing;
}
protected bool Read<TElement>(out Array result)
{
switch (_readState)
{
case ReadState.ReadNothing:
if (_buf.ReadBytesLeft < 12)
{
result = null;
return false;
}
_dimensions = _buf.ReadInt32();
var hasNulls = _buf.ReadInt32(); // Not populated by PG?
var elementOID = _buf.ReadUInt32();
Contract.Assume(elementOID == ElementHandler.OID);
_dimLengths = new int[_dimensions];
if (_dimensions > 1) {
_indices = new int[_dimensions];
}
_index = 0;
goto case ReadState.ReadHeader;
case ReadState.ReadHeader:
if (_buf.ReadBytesLeft < _dimensions * 8) {
result = null;
return false;
}
for (var i = 0; i < _dimensions; i++)
{
_dimLengths[i] = _buf.ReadInt32();
_buf.ReadInt32(); // We don't care about the lower bounds
}
if (_dimensions == 0)
{
result = new TElement[0];
_readState = ReadState.NeedPrepare;
return true;
}
_readValue = Array.CreateInstance(typeof(TElement), _dimLengths);
_readState = ReadState.ReadingElements;
goto case ReadState.ReadingElements;
case ReadState.ReadingElements:
var completed = _readValue is TElement[]
? ReadElementsOneDimensional<TElement>()
: ReadElementsMultidimensional<TElement>();
if (!completed)
{
result = null;
return false;
}
result = _readValue;
_readValue = null;
_buf = 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<TElement>()
{
var array = (TElement[])_readValue;
for (; _index < array.Length; _index++)
{
TElement 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<TElement>()
{
while (true)
{
TElement 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<TElement>(out TElement element)
{
try
{
if (_elementLen == -1)
{
if (_buf.ReadBytesLeft < 4)
{
element = default(TElement);
return false;
}
_elementLen = _buf.ReadInt32();
if (_elementLen == -1)
{
// TODO: Nullables
element = default(TElement);
return true;
}
}
var asSimpleReader = ElementHandler as ISimpleTypeReader<TElement>;
if (asSimpleReader != null)
{
if (_buf.ReadBytesLeft < _elementLen)
{
element = default(TElement);
return false;
}
element = asSimpleReader.Read(_buf, _elementLen, _fieldDescription);
_elementLen = -1;
return true;
}
var asChunkingReader = ElementHandler as IChunkingTypeReader<TElement>;
if (asChunkingReader != null)
{
asChunkingReader.PrepareRead(_buf, _elementLen, _fieldDescription);
if (!asChunkingReader.Read(out element))
{
return false;
}
_elementLen = -1;
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 virtual void PrepareWrite(object value, NpgsqlBuffer 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");
_buf = buf;
_parameter = parameter;
_lengthCache = lengthCache;
var asArray = value as Array;
_writeValue = (IList)value;
_dimensions = asArray != null ? asArray.Rank : 1;
_index = 0;
_wroteElementLen = false;
_writeState = WriteState.WroteNothing;
}
public bool Write<TElement>(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 (_buf.WriteSpaceLeft < len) {
Contract.Assume(_buf.Size >= len, "Buffer too small for header");
return false;
}
_buf.WriteInt32(_dimensions);
_buf.WriteInt32(1); // HasNulls=1. Not actually used by the backend.
_buf.WriteInt32((int)ElementHandler.OID);
var asArray = _writeValue as Array;
if (asArray != null)
{
for (var i = 0; i < _dimensions; i++)
{
_buf.WriteInt32(asArray.GetLength(i));
_buf.WriteInt32(LowerBound); // We don't map .NET lower bounds to PG
}
}
else
{
_buf.WriteInt32(_writeValue.Count);
_buf.WriteInt32(LowerBound); // We don't map .NET lower bounds to PG
_enumerator = _writeValue.GetEnumerator();
}
var asGeneric = _writeValue as IList<TElement>;
_enumerator = asGeneric != null ? 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<TElement>;
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;
_buf = null;
_parameter = null;
_writeState = WriteState.NeedPrepare;
return true;
default:
throw PGUtil.ThrowIfReached();
}
}
bool WriteSingleElement(object element, ref DirectBuffer directBuf)
{
// TODO: Need generic version of this...
if (element == null || element is DBNull) {
if (_buf.WriteSpaceLeft < 4) {
return false;
}
_buf.WriteInt32(-1);
return true;
}
var asSimpleWriter = ElementHandler as ISimpleTypeWriter;
if (asSimpleWriter != null)
{
var elementLen = asSimpleWriter.ValidateAndGetLength(element);
if (_buf.WriteSpaceLeft < 4 + elementLen) { return false; }
_buf.WriteInt32(elementLen);
asSimpleWriter.Write(element, _buf);
return true;
}
var asChunkedWriter = ElementHandler as IChunkingTypeWriter;
if (asChunkedWriter != null)
{
if (!_wroteElementLen) {
if (_buf.WriteSpaceLeft < 4) {
return false;
}
_buf.WriteInt32(asChunkedWriter.ValidateAndGetLength(element, ref _lengthCache, _parameter));
asChunkedWriter.PrepareWrite(element, _buf, _lengthCache, _parameter);
_wroteElementLen = true;
}
if (!asChunkedWriter.Write(ref directBuf)) {
return false;
}
_wroteElementLen = false;
return true;
}
throw PGUtil.ThrowIfReached();
}
public int ValidateAndGetLength<TElement>(object value, ref LengthCache lengthCache, NpgsqlParameter parameter=null)
{
// Take care of single-dimensional arrays and generic IList<T>
var asGenericList = value as IList<TElement>;
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 != null ? 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(String.Format("Can't write type {0} as an array", value.GetType()));
}
int GetSingleElementLength(object element, ref LengthCache lengthCache, NpgsqlParameter parameter=null)
{
if (element == null || element is DBNull) {
return 0;
}
var asChunkingWriter = ElementHandler as IChunkingTypeWriter;
return asChunkingWriter != null
? asChunkingWriter.ValidateAndGetLength(element, ref lengthCache, parameter)
: ((ISimpleTypeWriter)ElementHandler).ValidateAndGetLength(element);
}
enum WriteState
{
NeedPrepare,
WroteNothing,
WritingElements,
Cleanup,
}
#endregion
}
/// <remarks>
/// http://www.postgresql.org/docs/current/static/arrays.html
/// </remarks>
/// <typeparam name="TElement">The .NET type contained as an element within this array</typeparam>
internal class ArrayHandler<TElement> : ArrayHandler,
IChunkingTypeReader<Array>, IChunkingTypeWriter
{
/// <summary>
/// The type of the elements contained within this array
/// </summary>
/// <param name="fieldDescription"></param>
internal override Type GetElementFieldType(FieldDescription fieldDescription)
{
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);
}
public ArrayHandler(TypeHandler elementHandler)
: base(elementHandler) { }
public void PrepareRead(NpgsqlBuffer buf, int len, FieldDescription fieldDescription)
{
base.PrepareRead(buf, fieldDescription, len);
}
public bool Read(out Array result)
{
return Read<TElement>(out result);
}
public int ValidateAndGetLength(object value, ref LengthCache lengthCache, NpgsqlParameter parameter=null)
{
return ValidateAndGetLength<TElement>(value, ref lengthCache, parameter);
}
public bool Write(ref DirectBuffer directBuf)
{
return Write<TElement>(ref directBuf);
}
}
/// <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 ReadPsvAsObject(DataRowMessage row, FieldDescription fieldDescription)
{
PrepareRead(row.Buffer, row.ColumnLen, fieldDescription);
Array result;
while (!Read<TPsv>(out result)) {
row.Buffer.ReadMore();
}
return result;
}
public ArrayHandlerWithPsv(TypeHandler elementHandler)
: base(elementHandler) {}
}
}