-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProtocol.Types.cs
More file actions
1015 lines (965 loc) · 44.9 KB
/
Protocol.Types.cs
File metadata and controls
1015 lines (965 loc) · 44.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
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
/*
* Copyright 2017 Stanislav Muhametsin. All rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using CBAM.SQL.Implementation;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UtilPack;
using TStaticTypeCacheValue = System.Collections.Generic.IDictionary<System.String, CBAM.SQL.PostgreSQL.PgSQLTypeDatabaseData>;
using TStaticTypeCache = System.Collections.Generic.IDictionary<System.Version, System.Collections.Generic.IDictionary<System.String, CBAM.SQL.PostgreSQL.PgSQLTypeDatabaseData>>;
using TextBackendSizeInfo = UtilPack.EitherOr<System.ValueTuple<System.Int32, System.Object>, System.String>;
using TypeFunctionalityInfo = System.ValueTuple<System.ValueTuple<System.Type, CBAM.SQL.PostgreSQL.PgSQLTypeFunctionality>, System.Boolean>;
using CBAM.SQL.PostgreSQL;
namespace CBAM.SQL.PostgreSQL.Implementation
{
using TSyncTextualSizeInfo = ValueTuple<Int32, String>;
internal sealed partial class PostgreSQLProtocol
{
private static readonly TStaticTypeCache _StaticTypeCache;
private static readonly IDictionary<String, TypeFunctionalityInfo> _DefaultTypes;
static PostgreSQLProtocol()
{
var typeInfo = PostgreSQLProtocol.CreateDefaultTypesInfos()
.ToDictionary( tInfo => tInfo.Item1, tInfo => tInfo );
_DefaultTypes = new Dictionary<String, TypeFunctionalityInfo>()
{
{ "text", (typeInfo[typeof(String)], true) },
{ "void", (typeInfo[typeof(String)], false) },
{ "char", (typeInfo[typeof(String)], false) },
{ "varchar", (typeInfo[typeof(String)], false) },
{ "bool", (typeInfo[typeof(Boolean)], true) },
{ "int2", (typeInfo[typeof(Int16)], true) },
{ "int4", (typeInfo[typeof(Int32)], true) },
{ "int8", (typeInfo[typeof(Int64)], true) },
{ "oid", (typeInfo[typeof(Int32)], false) },
{ "float4", (typeInfo[typeof(Single)], true) },
{ "float8", (typeInfo[typeof(Double)], true) },
{ "numeric", (typeInfo[typeof(Decimal)], true) },
//{ "inet", typeof(PgSQLInternetAddress) },
//{ "macaddr", typeof(PgSQLMacAddress) },
{ "money", (typeInfo[typeof(Decimal)], false) },
{ "uuid", (typeInfo[typeof(Guid)], true) },
{ "xml", (typeInfo[typeof(System.Xml.Linq.XElement)], true) },
{ "interval", (typeInfo[typeof(PgSQLInterval)], true) },
{ "date", (typeInfo[typeof(PgSQLDate)], true) },
{ "time", (typeInfo[typeof(PgSQLTime)], true) },
{ "timetz", (typeInfo[typeof(PgSQLTimeTZ)], true) },
{ "timestamp", (typeInfo[typeof(PgSQLTimestamp)], true) },
{ "timestamptz", (typeInfo[typeof(PgSQLTimestampTZ)], true) },
{ "abstime", (typeInfo[typeof(PgSQLTimestampTZ)], false) },
{ "bytea", (typeInfo[typeof(Byte[])], true) }
};
_StaticTypeCache = new Dictionary<Version, TStaticTypeCacheValue>();
}
private async Task ReadTypesFromServer( Boolean force, CancellationToken token )
{
var serverVersion = this._serverVersion;
var typeCache = _StaticTypeCache;
if ( force || !typeCache.TryGetValue( serverVersion, out TStaticTypeCacheValue types ) )
{
this.CurrentCancellationToken = token;
try
{
types = await this.TypeRegistry.ReadTypeDataFromServer( _DefaultTypes.Keys );
}
finally
{
this.ResetCancellationToken();
}
lock ( typeCache )
{
typeCache[serverVersion] = types;
}
}
this.TypeRegistry.AssignTypeData(
types,
tName => _DefaultTypes[tName].Item1.Item1,
tuple =>
{
var valTuple = _DefaultTypes[tuple.DBTypeName];
return new TypeFunctionalityCreationResult( valTuple.Item1.Item2, valTuple.Item2 );
} );
}
private static IEnumerable<(Type, PgSQLTypeFunctionality)> CreateDefaultTypesInfos()
{
// Assumes that string is non-empty
Boolean ArrayElementStringNeedsQuotesSingleDelimiter( PgSQLTypeDatabaseData boundData, String value )
{
Boolean needsQuotes = false;
var delimChar = boundData.ArrayDelimiter[0];
for ( var i = 0; i < value.Length && !needsQuotes; ++i )
{
var c = value[i];
switch ( c )
{
case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_START:
case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_END:
case PgSQLTypeFunctionalityForArrays.ESCAPE:
case PgSQLTypeFunctionalityForArrays.QUOTE:
needsQuotes = true;
break;
default:
if ( c == delimChar || Char.IsWhiteSpace( c ) )
{
needsQuotes = true;
}
break;
}
}
return needsQuotes;
}
Boolean ArrayElementStringNeedsQuotesMultiDelimiter( PgSQLTypeDatabaseData boundData, String value )
{
var needsQuotes = value.IndexOf( boundData.ArrayDelimiter ) >= 0;
if ( !needsQuotes )
{
for ( var i = 0; i < value.Length && !needsQuotes; ++i )
{
var c = value[i];
switch ( c )
{
case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_START:
case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_END:
case PgSQLTypeFunctionalityForArrays.ESCAPE:
case PgSQLTypeFunctionalityForArrays.QUOTE:
needsQuotes = true;
break;
default:
if ( Char.IsWhiteSpace( c ) )
{
needsQuotes = true;
}
break;
}
}
}
return needsQuotes;
}
Int32 CalculateArrayElementStringSizeSingleDelimiter( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, String value )
{
var asciiByteSize = encoding.BytesPerASCIICharacter;
var retVal = 2 * asciiByteSize + encoding.Encoding.GetByteCount( value );
var delimChar = boundData.ArrayDelimiter[0];
for ( var i = 0; i < value.Length; ++i )
{
var c = value[i];
switch ( c )
{
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_START:
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_END:
case PgSQLTypeFunctionalityForArrays.ESCAPE:
case PgSQLTypeFunctionalityForArrays.QUOTE:
retVal += asciiByteSize;
break;
//default:
// if ( delimChar == c || Char.IsWhiteSpace( c ) )
// {
// retVal += asciiByteSize;
// }
// break;
}
}
return retVal;
}
Int32 CalculateArrayElementStringSizeMultiDelimiter( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, String value )
{
var asciiByteSize = encoding.BytesPerASCIICharacter;
var retVal = 2 * asciiByteSize + encoding.Encoding.GetByteCount( value ) + asciiByteSize * value.CountOccurrances( boundData.ArrayDelimiter, StringComparison.Ordinal );
for ( var i = 0; i < value.Length; ++i )
{
var c = value[i];
switch ( c )
{
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_START:
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_END:
case PgSQLTypeFunctionalityForArrays.ESCAPE:
case PgSQLTypeFunctionalityForArrays.QUOTE:
retVal += asciiByteSize;
break;
//default:
// if ( Char.IsWhiteSpace( c ) )
// {
// retVal += asciiByteSize;
// }
// break;
}
}
return retVal;
}
void WriteArrayElementStringSingleDelimiter( PgSQLTypeDatabaseData boundData, BackendABIHelper helper, Byte[] array, String value, ref Int32 offset )
{
var prevIdx = 0;
var delimChar = boundData.ArrayDelimiter[0];
var encoding = helper.Encoding.Encoding;
for ( var i = 0; i < value.Length; ++i )
{
var c = value[i];
switch ( c )
{
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_START:
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_END:
case PgSQLTypeFunctionalityForArrays.ESCAPE:
case PgSQLTypeFunctionalityForArrays.QUOTE:
offset += encoding.GetBytes( value, prevIdx, i - prevIdx, array, offset );
helper.Encoding.WriteASCIIByte( array, ref offset, (Byte) PgSQLTypeFunctionalityForArrays.ESCAPE );
prevIdx = i;
break;
default:
//if ( delimChar == c || Char.IsWhiteSpace( c ) )
//{
// arrayIdx += encoding.GetBytes( value, prevIdx, i - prevIdx, array, arrayIdx );
// helper.Encoding.WriteASCIIByte( array, ref arrayIdx, (Byte) PgSQLTypeFunctionalityForArrays.ESCAPE );
// prevIdx = i;
//}
break;
}
}
// Last chunk
offset += encoding.GetBytes( value, prevIdx, value.Length - prevIdx, array, offset );
}
void WriteArrayElementStringMultiDelimiter( PgSQLTypeDatabaseData boundData, BackendABIHelper helper, Byte[] array, String value, ref Int32 offset )
{
var prevIdx = 0;
var encoding = helper.Encoding.Encoding;
var delimCharStart = boundData.ArrayDelimiter[0];
var delimCharEnd = boundData.ArrayDelimiter[1];
for ( var i = 0; i < value.Length; ++i )
{
var c = value[i];
switch ( c )
{
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_START:
//case (Char) PgSQLTypeFunctionalityForArrays.ARRAY_END:
case PgSQLTypeFunctionalityForArrays.ESCAPE:
case PgSQLTypeFunctionalityForArrays.QUOTE:
offset += encoding.GetBytes( value, prevIdx, i - prevIdx, array, offset );
helper.Encoding.WriteASCIIByte( array, ref offset, (Byte) PgSQLTypeFunctionalityForArrays.ESCAPE );
prevIdx = i;
break;
//default:
// var isDelimStart = c == delimCharStart && i < value.Length - 1 && value[i + 1] == delimCharEnd;
// if ( isDelimStart || Char.IsWhiteSpace( c ) )
// {
// arrayIdx += encoding.GetBytes( value, prevIdx, i - prevIdx, array, arrayIdx );
// helper.Encoding.WriteASCIIByte( array, ref arrayIdx, (Byte) PgSQLTypeFunctionalityForArrays.ESCAPE );
// prevIdx = i;
// if ( isDelimStart )
// {
// ++i;
// }
// }
// break;
}
}
// Last chunk
offset += encoding.GetBytes( value, prevIdx, value.Length - prevIdx, array, offset );
}
// String
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return args.GetStringWithPool( array, offset, count );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return args.GetStringWithPool( array, offset, count );
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, String value, Boolean isArrayElement ) =>
{
EitherOr<Int32, String> retVal;
if ( isArrayElement )
{
// From https://www.postgresql.org/docs/current/static/arrays.html :
// The array output routine will put double quotes around element values if they are empty strings, contain curly braces, delimiter characters, double quotes, backslashes, or white space, or match the word NULL.
// Assumes that value is non-empty
var isNullString = String.Equals( value, "null", StringComparison.OrdinalIgnoreCase );
var isSingleDelimiter = boundData.ArrayDelimiter.Length == 1;
if (
value.Length == 0
|| isNullString
|| ( isSingleDelimiter ? ArrayElementStringNeedsQuotesSingleDelimiter( boundData, value ) : ArrayElementStringNeedsQuotesMultiDelimiter( boundData, value ) )
)
{
retVal = isNullString ?
6 * encoding.BytesPerASCIICharacter :
( isSingleDelimiter ?
CalculateArrayElementStringSizeSingleDelimiter( boundData, encoding, value ) :
CalculateArrayElementStringSizeMultiDelimiter( boundData, encoding, value )
);
}
else
{
// We can serialize without quotes
retVal = value;
}
}
else
{
retVal = value;
}
return retVal;
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, String value, Boolean isArrayElement ) =>
{
return encoding.Encoding.GetByteCount( value );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, String value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
if ( sizeInfo.Item2 == null )
{
// Because of how text format size is calculated, and because we are handling string type, we will come here *only* when we are serializing array element, *and* it has data to be escaped.
// Write starting quote
args.Encoding.WriteASCIIByte( array, ref offset, (Byte) PgSQLTypeFunctionalityForArrays.QUOTE );
// Write content, and escape any double quotes and backslashes
if ( boundData.ArrayDelimiter.Length == 1 )
{
WriteArrayElementStringSingleDelimiter( boundData, args, array, value, ref offset );
}
else
{
WriteArrayElementStringMultiDelimiter( boundData, args, array, value, ref offset );
}
// Write ending quote
args.Encoding.WriteASCIIByte( array, ref offset, (Byte) PgSQLTypeFunctionalityForArrays.QUOTE );
}
else
{
offset += args.Encoding.Encoding.GetBytes( value, 0, value.Length, array, offset );
}
System.Diagnostics.Debug.Assert( offset == sizeInfo.Item1 );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, String value, Int32 sizeInfo, Boolean isArrayElement ) =>
{
args.Encoding.Encoding.GetBytes( value, 0, value.Length, array, offset );
},
null,
null
);
// Boolean
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
Byte b;
return count > 0
&& (
( b = args.Encoding.ReadASCIIByte( array, ref offset ) ) == 'T'
|| b == 't'
);
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return count > 0 && array[offset] != 0;
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Boolean value, Boolean isArrayElement ) =>
{
return encoding.BytesPerASCIICharacter;
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Boolean value, Boolean isArrayElement ) =>
{
return 1;
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Boolean value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
args.Encoding.WriteASCIIByte( array, ref offset, (Byte) ( value ? 't' : 'f' ) );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Boolean value, Int32 sizeInfo, Boolean isArrayElement ) =>
{
array[offset] = (Byte) ( value ? 1 : 0 );
},
null,
null
);
// Int16
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return (Int16) args.Encoding.ParseInt32Textual( array, ref offset, (count / args.Encoding.BytesPerASCIICharacter, true) );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return array.ReadInt16BEFromBytes( ref offset );
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Int16 value, Boolean isArrayElement ) =>
{
return encoding.GetTextualIntegerRepresentationSize( value );
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Int16 value, Boolean isArrayElement ) =>
{
return sizeof( Int16 );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int16 value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
args.Encoding.WriteIntegerTextual( array, ref offset, value );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int16 value, Int32 sizeInfo, Boolean isArrayElement ) =>
{
array.WriteInt16BEToBytes( ref offset, value );
},
null,
null
);
// Int32
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return args.Encoding.ParseInt32Textual( array, ref offset, (count / args.Encoding.BytesPerASCIICharacter, true) );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return array.ReadInt32BEFromBytes( ref offset );
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Int32 value, Boolean isArrayElement ) =>
{
return encoding.GetTextualIntegerRepresentationSize( value );
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Int32 value, Boolean isArrayElement ) =>
{
return sizeof( Int32 );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
args.Encoding.WriteIntegerTextual( array, ref offset, value );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 value, Int32 sizeInfo, Boolean isArrayElement ) =>
{
array.WriteInt32BEToBytes( ref offset, value );
},
null,
null
);
// Int64
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return args.Encoding.ParseInt64Textual( array, ref offset, (count / args.Encoding.BytesPerASCIICharacter, true) );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return array.ReadInt64BEFromBytes( ref offset );
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Int64 value, Boolean isArrayElement ) =>
{
return encoding.GetTextualIntegerRepresentationSize( value );
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Int64 value, Boolean isArrayElement ) =>
{
return sizeof( Int64 );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int64 value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
args.Encoding.WriteIntegerTextual( array, ref offset, value );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int64 value, Int32 sizeInfo, Boolean isArrayElement ) =>
{
array.WriteInt64BEToBytes( ref offset, value );
},
null,
null
);
// Unfortunately, parsing real numbers (single, double, decimal) directly from byte array containing the string is quite a bit more complicated than integers,
// so right now we have to allocate a new string and parse it.
// It's a bit of a performance killer, so maybe should be fixed one day.
// Single
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return Single.Parse( args.GetStringWithPool( array, offset, count ), CommonPgSQLTypeFunctionalityInfo.NumberFormat );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return array.ReadSingleBEFromBytes( ref offset );
},
null,
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Single value, Boolean isArrayElement ) =>
{
return sizeof( Single );
},
null,
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Single value, Int32 sizeInfo, Boolean isArrayElement ) =>
{
array.WriteSingleBEToBytes( ref offset, value );
},
null,
null
);
// Double
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return Double.Parse( args.GetStringWithPool( array, offset, count ), CommonPgSQLTypeFunctionalityInfo.NumberFormat );
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return array.ReadDoubleBEFromBytes( ref offset );
},
null,
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Double value, Boolean isArrayElement ) =>
{
return sizeof( Double );
},
null,
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Double value, Int32 sizeInfo, Boolean isArrayElement ) =>
{
array.WriteDoubleBEToBytes( ref offset, value );
},
null,
null
);
// Decimal
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return Decimal.Parse( args.GetStringWithPool( array, offset, count ), CommonPgSQLTypeFunctionalityInfo.NumberFormat );
},
null,
null,
null,
null,
null,
null,
null
);
// Guid
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return Guid.Parse( args.GetStringWithPool( array, offset, count ) );
},
null,
null,
null,
null,
null,
null,
null
);
// Xml
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
// If there would be "LoadAsync" in XEelement, we could use new PgSQLTypeUnboundInfo constructor directly.
using ( var mStream = new System.IO.MemoryStream( array, offset, count, false ) )
{
return System.Xml.Linq.XElement.Load( mStream );
}
},
null,
null,
null,
null,
null,
null,
null
);
// PgSQLInterval
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
// TODO interval parsing without string allocation (PgSQLInterval.Load(Stream stream))
// Or PgSQLInterval.ParseBinaryText
return PgSQLInterval.Parse( args.GetStringWithPool( array, offset, count ) );
},
null,
// TODO interval string writing without string allocation
null,
null,
null,
null,
( PgSQLTypeDatabaseData dbData, PgSQLInterval pgSQLObject, Type targetType ) =>
{
return (TimeSpan) pgSQLObject;
},
( PgSQLTypeDatabaseData dbData, Object systemObject ) =>
{
return (TimeSpan) systemObject;
}
);
// PgSQLDate
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return PgSQLDate.ParseBinaryText( args.Encoding, array, ref offset, count );
},
null,
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, PgSQLDate value, Boolean isArrayElement ) =>
{
var retVal = value.GetTextByteCount( encoding );
if ( isArrayElement && value.NeedsQuotingInArrayElement() )
{
// The " BC" substring contains whitespace, so we must put quotes around this
retVal += 2 * encoding.BytesPerASCIICharacter;
}
return retVal;
},
null,
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, PgSQLDate value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
value.WriteBytesAndPossiblyQuote( args.Encoding, array, ref offset, isArrayElement && value.NeedsQuotingInArrayElement(), ( PgSQLDate v, IEncodingInfo e, Byte[] a, ref Int32 i ) => v.WriteTextBytes( e, a, ref i ) );
},
null,
( PgSQLTypeDatabaseData dbData, PgSQLDate pgSQLObject, Type targetType ) =>
{
return (DateTime) pgSQLObject;
},
( PgSQLTypeDatabaseData dbData, Object systemObject ) =>
{
return (PgSQLDate) (DateTime) systemObject;
}
);
// PgSQLTime
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return PgSQLTime.ParseBinaryText( args.Encoding, array, ref offset, count );
},
null,
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, PgSQLTime value, Boolean isArrayElement ) =>
{
return value.GetTextByteCount( encoding );
},
null,
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, PgSQLTime value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
value.WriteTextBytes( args.Encoding, array, ref offset );
},
null,
( PgSQLTypeDatabaseData dbData, PgSQLTime pgSQLObject, Type targetType ) =>
{
if ( typeof( DateTime ).Equals( targetType ) )
{
return (DateTime) pgSQLObject;
}
else if ( typeof( TimeSpan ).Equals( targetType ) )
{
return (TimeSpan) pgSQLObject;
}
else if ( typeof( PgSQLInterval ).Equals( targetType ) )
{
return (PgSQLInterval) pgSQLObject;
}
else
{
throw new InvalidCastException( "Can't cast time " + pgSQLObject + " to " + targetType + "." );
}
},
( PgSQLTypeDatabaseData dbData, Object systemObject ) =>
{
var tt = systemObject.GetType();
if ( typeof( DateTime ).Equals( tt ) )
{
return (PgSQLTime) (DateTime) systemObject;
}
else if ( typeof( TimeSpan ).Equals( tt ) )
{
return (PgSQLTime) (TimeSpan) systemObject;
}
else if ( typeof( PgSQLInterval ).Equals( tt ) )
{
return (PgSQLTime) (PgSQLInterval) systemObject;
}
else
{
throw new InvalidCastException( "Can't cast object " + systemObject + " to time." );
}
}
);
// PgSQLTimeTZ
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return PgSQLTimeTZ.ParseBinaryText( args.Encoding, array, ref offset, count );
},
null,
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, PgSQLTimeTZ value, Boolean isArrayElement ) =>
{
return value.GetTextByteCount( encoding );
},
null,
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, PgSQLTimeTZ value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
value.WriteTextBytes( args.Encoding, array, ref offset );
},
null,
( PgSQLTypeDatabaseData dbData, PgSQLTimeTZ pgSQLObject, Type targetType ) =>
{
if ( typeof( DateTime ).Equals( targetType ) )
{
return (DateTime) pgSQLObject;
}
else if ( typeof( TimeSpan ).Equals( targetType ) )
{
return (TimeSpan) pgSQLObject;
}
else
{
throw new InvalidCastException( "Can't cast time " + pgSQLObject + " to " + targetType + "." );
}
},
( PgSQLTypeDatabaseData dbData, Object systemObject ) =>
{
var tt = systemObject.GetType();
if ( typeof( DateTime ).Equals( tt ) )
{
return (PgSQLTimeTZ) (DateTime) systemObject;
}
else if ( typeof( TimeSpan ).Equals( tt ) )
{
return (PgSQLTimeTZ) (TimeSpan) systemObject;
}
else
{
throw new InvalidCastException( "Can't cast object " + systemObject + " to time with time zone." );
}
}
);
// PgSQLTimestamp
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return PgSQLTimestamp.ParseBinaryText( args.Encoding, array, ref offset, count );
},
null,
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, PgSQLTimestamp value, Boolean isArrayElement ) =>
{
var retVal = value.GetTextByteCount( encoding );
if ( isArrayElement && value.NeedsQuotingInArrayElement() )
{
// There will be a space -> the value must be quoted
retVal += 2 * encoding.BytesPerASCIICharacter;
}
return retVal;
},
null,
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, PgSQLTimestamp value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
value.WriteBytesAndPossiblyQuote( args.Encoding, array, ref offset, isArrayElement && value.NeedsQuotingInArrayElement(), ( PgSQLTimestamp v, IEncodingInfo e, Byte[] a, ref Int32 i ) => v.WriteTextBytes( e, a, ref i ) );
},
null,
( PgSQLTypeDatabaseData dbData, PgSQLTimestamp pgSQLObject, Type targetType ) =>
{
if ( typeof( DateTime ).Equals( targetType ) )
{
return (DateTime) pgSQLObject;
}
else
{
throw new InvalidCastException( "Can't cast time " + pgSQLObject + " to " + targetType + "." );
}
},
( PgSQLTypeDatabaseData dbData, Object systemObject ) =>
{
var tt = systemObject.GetType();
if ( typeof( DateTime ).Equals( tt ) )
{
return (PgSQLTimestamp) (DateTime) systemObject;
}
else
{
throw new InvalidCastException( "Can't cast object " + systemObject + " to timestamp." );
}
}
);
// PgSQLTimestampTZ
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
return PgSQLTimestampTZ.ParseBinaryText( args.Encoding, array, ref offset, count );
},
null,
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, PgSQLTimestampTZ value, Boolean isArrayElement ) =>
{
var retVal = value.GetTextByteCount( encoding );
if ( isArrayElement && value.NeedsQuotingInArrayElement() )
{
retVal += 2 * encoding.BytesPerASCIICharacter;
}
return retVal;
},
null,
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, PgSQLTimestampTZ value, TSyncTextualSizeInfo sizeInfo, Boolean isArrayElement ) =>
{
value.WriteBytesAndPossiblyQuote( args.Encoding, array, ref offset, isArrayElement && value.NeedsQuotingInArrayElement(), ( PgSQLTimestampTZ v, IEncodingInfo e, Byte[] a, ref Int32 i ) => v.WriteTextBytes( e, a, ref i ) );
},
null,
( PgSQLTypeDatabaseData dbData, PgSQLTimestampTZ pgSQLObject, Type targetType ) =>
{
if ( typeof( DateTime ).Equals( targetType ) )
{
return (DateTime) pgSQLObject;
}
else if ( typeof( DateTimeOffset ).Equals( targetType ) )
{
return (DateTimeOffset) pgSQLObject;
}
else
{
throw new InvalidCastException( "Can't cast time " + pgSQLObject + " to " + targetType + "." );
}
},
( PgSQLTypeDatabaseData dbData, Object systemObject ) =>
{
var tt = systemObject.GetType();
if ( typeof( DateTime ).Equals( tt ) )
{
return (PgSQLTimestampTZ) (DateTime) systemObject;
}
else if ( typeof( DateTimeOffset ).Equals( tt ) )
{
return (PgSQLTimestampTZ) (DateTimeOffset) systemObject;
}
else
{
throw new InvalidCastException( "Can't cast object " + systemObject + " to timestamp with time zone." );
}
}
);
// Byte[]
yield return CreateSingleBodyInfoWithType(
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
// Byte[] textual format is "\x<hex decimal pairs>"
var encoding = args.Encoding;
Byte[] retVal;
if ( count > 2
&& encoding.ReadASCIIByte( array, ref offset ) == '\\'
&& encoding.ReadASCIIByte( array, ref offset ) == 'x'
)
{
var len = ( count - offset ) / encoding.BytesPerASCIICharacter / 2;
retVal = new Byte[len];
for ( var i = 0; i < len; ++i )
{
retVal[i] = encoding.ReadHexDecimal( array, ref offset );
}
}
else
{
throw new PgSQLException( "Bytea strings must start with \"\\x\"." );
}
return retVal;
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Int32 count ) =>
{
// Binary format is just raw byte array
var retVal = new Byte[count];
Array.Copy( array, offset, retVal, 0, count );
return retVal;
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Byte[] value, Boolean isArrayElement ) =>
{
// Text size is 2 ASCII bytes + 2 ASCII bytes per each actual byte
var retVal = ( 2 + 2 * value.Length ) * encoding.BytesPerASCIICharacter;
if ( isArrayElement )
{
// Always need quotation since there is a '\\' character
retVal += 2 * encoding.BytesPerASCIICharacter;
}
return retVal;
},
( PgSQLTypeDatabaseData boundData, IEncodingInfo encoding, Byte[] value, Boolean isArrayElement ) =>
{
// Binary size is same as array size
return value.Length;
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Byte[] value, TSyncTextualSizeInfo additionalInfoFromSize, Boolean isArrayElement ) =>
{
// Write all text to array
var encoding = args.Encoding;
if ( isArrayElement )
{
encoding.WriteASCIIByte( array, ref offset, (Byte) PgSQLTypeFunctionalityForArrays.QUOTE );
}
encoding
.WriteASCIIByte( array, ref offset, (Byte) '\\' )
.WriteASCIIByte( array, ref offset, (Byte) 'x' );
foreach ( var b in value )
{
encoding.WriteHexDecimal( array, ref offset, b );
}
if ( isArrayElement )
{
encoding.WriteASCIIByte( array, ref offset, (Byte) PgSQLTypeFunctionalityForArrays.QUOTE );
}
},
( PgSQLTypeDatabaseData boundData, BackendABIHelper args, Byte[] array, Int32 offset, Byte[] value, Int32 additionalInfoFromSize, Boolean isArrayElement ) =>
{
// Just copy array
Array.Copy( value, 0, array, offset, value.Length );
},
null,
null
);
}
private static (Type Type, DefaultPgSQLTypeFunctionality<TValue> Functionality) CreateSingleBodyInfoWithType<TValue>(
ReadFromBackendSync<TValue> text2CLR,
ReadFromBackendSync<TValue> binary2CLR,
CalculateBackendSize<TValue, EitherOr<Int32, String>> textSize,
CalculateBackendSize<TValue, Int32> clr2BinarySize,
WriteToBackendSync<TValue, TSyncTextualSizeInfo> clr2Text,
WriteToBackendSync<TValue, Int32> clr2Binary,
ChangePgSQLToSystem<TValue> pgSQL2System,
ChangeSystemToPgSQL<TValue> system2PgSQL
)
{
return (typeof( TValue ), DefaultPgSQLTypeFunctionality<TValue>.CreateSingleBodyUnboundInfo( text2CLR, binary2CLR, textSize, clr2BinarySize, clr2Text, clr2Binary, pgSQL2System, system2PgSQL ));
}
}
}
public static partial class E_CBAM
{
internal static Boolean NeedsQuotingInArrayElement( this PgSQLDate date )
{
// Values with year less than 0 will be prefixed with " BC" suffix, thus requiring quoting
return date.Year < 0;
}
internal static Boolean NeedsQuotingInArrayElement( this PgSQLTimestamp timestamp )
{
// Anything other than "Infinity" and "-Infinity" will need quoting since there will be a space
return timestamp.IsFinite;
}
internal static Boolean NeedsQuotingInArrayElement( this PgSQLTimestampTZ timestamp )
{
// Anything other than "Infinity" and "-Infinity" will need quoting since there will be a space
return timestamp.IsFinite;
}
internal delegate void WriteTextBytes<T>( T value, IEncodingInfo encoding, Byte[] array, ref Int32 idx );
internal static void WriteBytesAndPossiblyQuote<T>(
this T value,
IEncodingInfo encoding,
Byte[] array,
ref Int32 index,