forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeoJSONHandler.cs
More file actions
782 lines (633 loc) · 30.4 KB
/
GeoJSONHandler.cs
File metadata and controls
782 lines (633 loc) · 30.4 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
using System;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using GeoJSON.Net;
using GeoJSON.Net.CoordinateReferenceSystem;
using GeoJSON.Net.Geometry;
using Npgsql.BackendMessages;
using Npgsql.TypeHandling;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace Npgsql.GeoJSON
{
[Flags]
public enum GeoJSONOptions
{
None = 0,
BoundingBox = 1,
ShortCRS = 2,
LongCRS = 4
}
public sealed class GeoJSONHandlerFactory : NpgsqlTypeHandlerFactory<GeoJSONObject>
{
readonly GeoJSONOptions _options;
public GeoJSONHandlerFactory(GeoJSONOptions options = GeoJSONOptions.None)
=> _options = options;
static readonly ConcurrentDictionary<string, CrsMap> s_crsMaps = new ConcurrentDictionary<string, CrsMap>();
protected override NpgsqlTypeHandler<GeoJSONObject> Create(NpgsqlConnection conn)
{
var crsMap = (_options & (GeoJSONOptions.ShortCRS | GeoJSONOptions.LongCRS)) == GeoJSONOptions.None
? default : s_crsMaps.GetOrAdd(conn.ConnectionString, _ =>
{
var builder = new CrsMapBuilder();
using (var cmd = new NpgsqlCommand(
"SELECT min(srid), max(srid), auth_name " +
"FROM(SELECT srid, auth_name, srid - rank() OVER(ORDER BY srid) AS range " +
"FROM spatial_ref_sys) AS s GROUP BY range, auth_name ORDER BY 1;", conn))
using (var reader = cmd.ExecuteReader())
while (reader.Read())
{
builder.Add(new CrsMapEntry(
reader.GetInt32(0),
reader.GetInt32(1),
reader.GetString(2)));
}
return builder.Build();
});
return new GeoJsonHandler(_options, crsMap);
}
}
sealed class GeoJsonHandler : NpgsqlTypeHandler<GeoJSONObject>,
INpgsqlTypeHandler<Point>, INpgsqlTypeHandler<MultiPoint>,
INpgsqlTypeHandler<Polygon>, INpgsqlTypeHandler<MultiPolygon>,
INpgsqlTypeHandler<LineString>, INpgsqlTypeHandler<MultiLineString>,
INpgsqlTypeHandler<GeometryCollection>,
INpgsqlTypeHandler<IGeoJSONObject>,
INpgsqlTypeHandler<IGeometryObject>
{
readonly GeoJSONOptions _options;
readonly CrsMap _crsMap;
NamedCRS _lastCrs;
int _lastSrid;
internal GeoJsonHandler(GeoJSONOptions options, CrsMap crsMap)
{
_options = options;
_crsMap = crsMap;
}
GeoJSONOptions CrsType => _options & (GeoJSONOptions.ShortCRS | GeoJSONOptions.LongCRS);
bool BoundingBox => (_options & GeoJSONOptions.BoundingBox) != 0;
static bool HasSrid(EwkbGeometryType type)
=> (type & EwkbGeometryType.HasSrid) != 0;
static bool HasZ(EwkbGeometryType type)
=> (type & EwkbGeometryType.HasZ) != 0;
static bool HasM(EwkbGeometryType type)
=> (type & EwkbGeometryType.HasM) != 0;
static bool HasZ(IPosition coordinates)
=> coordinates.Altitude.HasValue;
const int SizeOfLength = sizeof(int);
const int SizeOfHeader = sizeof(byte) + sizeof(EwkbGeometryType);
const int SizeOfHeaderWithLength = SizeOfHeader + SizeOfLength;
const int SizeOfPoint2D = 2 * sizeof(double);
const int SizeOfPoint3D = 3 * sizeof(double);
static int SizeOfPoint(bool hasZ)
=> hasZ ? SizeOfPoint3D : SizeOfPoint2D;
static int SizeOfPoint(EwkbGeometryType type)
{
var size = SizeOfPoint2D;
if (HasZ(type))
size += sizeof(double);
if (HasM(type))
size += sizeof(double);
return size;
}
#region Throw
static Exception UnknownPostGisType()
=> throw new InvalidOperationException("Invalid PostGIS type");
static Exception AllOrNoneCoordiantesMustHaveZ(NpgsqlParameter parameter, string typeName)
=> throw new ArgumentException($"The Z coordinate must be specified for all or none elements of {typeName} in the {parameter.ParameterName} parameter", parameter.ParameterName);
#endregion
#region Read
public override ValueTask<GeoJSONObject> Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription = null)
=> ReadGeometry(buf, async);
async ValueTask<Point> INpgsqlTypeHandler<Point>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (Point)await ReadGeometry(buf, async);
async ValueTask<LineString> INpgsqlTypeHandler<LineString>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (LineString)await ReadGeometry(buf, async);
async ValueTask<Polygon> INpgsqlTypeHandler<Polygon>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (Polygon)await ReadGeometry(buf, async);
async ValueTask<MultiPoint> INpgsqlTypeHandler<MultiPoint>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (MultiPoint)await ReadGeometry(buf, async);
async ValueTask<MultiLineString> INpgsqlTypeHandler<MultiLineString>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (MultiLineString)await ReadGeometry(buf, async);
async ValueTask<MultiPolygon> INpgsqlTypeHandler<MultiPolygon>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (MultiPolygon)await ReadGeometry(buf, async);
async ValueTask<GeometryCollection> INpgsqlTypeHandler<GeometryCollection>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (GeometryCollection)await ReadGeometry(buf, async);
async ValueTask<IGeoJSONObject> INpgsqlTypeHandler<IGeoJSONObject>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> await ReadGeometry(buf, async);
async ValueTask<IGeometryObject> INpgsqlTypeHandler<IGeometryObject>.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription)
=> (IGeometryObject)await ReadGeometry(buf, async);
async ValueTask<GeoJSONObject> ReadGeometry(NpgsqlReadBuffer buf, bool async)
{
var boundingBox = BoundingBox ? new BoundingBoxBuilder() : null;
var geometry = await ReadGeometryCore(buf, async, boundingBox);
geometry.BoundingBoxes = boundingBox?.Build();
return geometry;
}
async ValueTask<GeoJSONObject> ReadGeometryCore(NpgsqlReadBuffer buf, bool async, BoundingBoxBuilder boundingBox)
{
await buf.Ensure(SizeOfHeader, async);
var littleEndian = buf.ReadByte() > 0;
var type = (EwkbGeometryType)buf.ReadUInt32(littleEndian);
GeoJSONObject geometry;
NamedCRS crs = null;
if (HasSrid(type))
{
await buf.Ensure(4, async);
crs = GetCrs(buf.ReadInt32(littleEndian));
}
switch (type & EwkbGeometryType.BaseType)
{
case EwkbGeometryType.Point:
{
await buf.Ensure(SizeOfPoint(type), async);
var position = ReadPosition(buf, type, littleEndian);
boundingBox?.Accumulate(position);
geometry = new Point(position);
break;
}
case EwkbGeometryType.LineString:
{
await buf.Ensure(SizeOfLength, async);
var coordinates = new Position[buf.ReadInt32(littleEndian)];
for (var i = 0; i < coordinates.Length; ++i)
{
await buf.Ensure(SizeOfPoint(type), async);
var position = ReadPosition(buf, type, littleEndian);
boundingBox?.Accumulate(position);
coordinates[i] = position;
}
geometry = new LineString(coordinates);
break;
}
case EwkbGeometryType.Polygon:
{
await buf.Ensure(SizeOfLength, async);
var lines = new LineString[buf.ReadInt32(littleEndian)];
for (var i = 0; i < lines.Length; ++i)
{
var coordinates = new Position[buf.ReadInt32(littleEndian)];
for (var j = 0; j < coordinates.Length; ++j)
{
await buf.Ensure(SizeOfPoint(type), async);
var position = ReadPosition(buf, type, littleEndian);
boundingBox?.Accumulate(position);
coordinates[j] = position;
}
lines[i] = new LineString(coordinates);
}
geometry = new Polygon(lines);
break;
}
case EwkbGeometryType.MultiPoint:
{
await buf.Ensure(SizeOfLength, async);
var points = new Point[buf.ReadInt32(littleEndian)];
for (var i = 0; i < points.Length; ++i)
{
await buf.Ensure(SizeOfHeader + SizeOfPoint(type), async);
await buf.Skip(SizeOfHeader, async);
var position = ReadPosition(buf, type, littleEndian);
boundingBox?.Accumulate(position);
points[i] = new Point(position);
}
geometry = new MultiPoint(points);
break;
}
case EwkbGeometryType.MultiLineString:
{
await buf.Ensure(SizeOfLength, async);
var lines = new LineString[buf.ReadInt32(littleEndian)];
for (var i = 0; i < lines.Length; ++i)
{
await buf.Ensure(SizeOfHeaderWithLength, async);
await buf.Skip(SizeOfHeader, async);
var coordinates = new Position[buf.ReadInt32(littleEndian)];
for (var j = 0; j < coordinates.Length; ++j)
{
await buf.Ensure(SizeOfPoint(type), async);
var position = ReadPosition(buf, type, littleEndian);
boundingBox?.Accumulate(position);
coordinates[j] = position;
}
lines[i] = new LineString(coordinates);
}
geometry = new MultiLineString(lines);
break;
}
case EwkbGeometryType.MultiPolygon:
{
await buf.Ensure(SizeOfLength, async);
var polygons = new Polygon[buf.ReadInt32(littleEndian)];
for (var i = 0; i < polygons.Length; ++i)
{
await buf.Ensure(SizeOfHeaderWithLength, async);
await buf.Skip(SizeOfHeader, async);
var lines = new LineString[buf.ReadInt32(littleEndian)];
for (var j = 0; j < lines.Length; ++j)
{
var coordinates = new Position[buf.ReadInt32(littleEndian)];
for (var k = 0; k < coordinates.Length; ++k)
{
await buf.Ensure(SizeOfPoint(type), async);
var position = ReadPosition(buf, type, littleEndian);
boundingBox?.Accumulate(position);
coordinates[k] = position;
}
lines[j] = new LineString(coordinates);
}
polygons[i] = new Polygon(lines);
}
geometry = new MultiPolygon(polygons);
break;
}
case EwkbGeometryType.GeometryCollection:
{
await buf.Ensure(SizeOfLength, async);
var elements = new IGeometryObject[buf.ReadInt32(littleEndian)];
for (var i = 0; i < elements.Length; ++i)
elements[i] = (IGeometryObject)await ReadGeometryCore(buf, async, boundingBox);
geometry = new GeometryCollection(elements);
break;
}
default:
throw new NpgsqlSafeReadException(UnknownPostGisType());
}
geometry.CRS = crs;
return geometry;
}
static Position ReadPosition(NpgsqlReadBuffer buf, EwkbGeometryType type, bool littleEndian)
{
var position = new Position(
longitude: buf.ReadDouble(littleEndian),
latitude: buf.ReadDouble(littleEndian),
altitude: HasZ(type) ? buf.ReadDouble() : (double?)null);
if (HasM(type)) buf.ReadDouble(littleEndian);
return position;
}
#endregion
#region Write
public override int ValidateAndGetLength(GeoJSONObject value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
switch (value.Type)
{
case GeoJSONObjectType.Point:
return ValidateAndGetLength((Point)value, ref lengthCache, parameter);
case GeoJSONObjectType.LineString:
return ValidateAndGetLength((LineString)value, ref lengthCache, parameter);
case GeoJSONObjectType.Polygon:
return ValidateAndGetLength((Polygon)value, ref lengthCache, parameter);
case GeoJSONObjectType.MultiPoint:
return ValidateAndGetLength((MultiPoint)value, ref lengthCache, parameter);
case GeoJSONObjectType.MultiLineString:
return ValidateAndGetLength((MultiLineString)value, ref lengthCache, parameter);
case GeoJSONObjectType.MultiPolygon:
return ValidateAndGetLength((MultiPolygon)value, ref lengthCache, parameter);
case GeoJSONObjectType.GeometryCollection:
return ValidateAndGetLength((GeometryCollection)value, ref lengthCache, parameter);
default:
throw UnknownPostGisType();
}
}
public int ValidateAndGetLength(Point value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
var length = SizeOfHeader + SizeOfPoint(HasZ(value.Coordinates));
if (GetSrid(value.CRS) != 0)
length += sizeof(int);
return length;
}
public int ValidateAndGetLength(LineString value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
var coordinates = value.Coordinates;
if (NotValid(coordinates, out var hasZ))
throw AllOrNoneCoordiantesMustHaveZ(parameter, nameof(LineString));
var length = SizeOfHeaderWithLength + coordinates.Count * SizeOfPoint(hasZ);
if (GetSrid(value.CRS) != 0)
length += sizeof(int);
return length;
}
public int ValidateAndGetLength(Polygon value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
var lines = value.Coordinates;
var length = SizeOfHeaderWithLength + SizeOfLength * lines.Count;
if (GetSrid(value.CRS) != 0)
length += sizeof(int);
var hasZ = false;
for (var i = 0; i < lines.Count; ++i)
{
var coordinates = lines[i].Coordinates;
if (NotValid(coordinates, out var lineHasZ))
throw AllOrNoneCoordiantesMustHaveZ(parameter, nameof(Polygon));
if (hasZ != lineHasZ)
{
if (i == 0) hasZ = lineHasZ;
else throw AllOrNoneCoordiantesMustHaveZ(parameter, nameof(LineString));
}
length += coordinates.Count * SizeOfPoint(hasZ);
}
return length;
}
static bool NotValid(ReadOnlyCollection<IPosition> coordinates, out bool hasZ)
{
if (coordinates.Count == 0)
hasZ = false;
else
{
hasZ = HasZ(coordinates[0]);
for (var i = 1; i < coordinates.Count; ++i)
if (HasZ(coordinates[i]) != hasZ) return true;
}
return false;
}
public int ValidateAndGetLength(MultiPoint value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
var length = SizeOfHeaderWithLength;
if (GetSrid(value.CRS) != 0)
length += sizeof(int);
var coordinates = value.Coordinates;
for (var i = 0; i < coordinates.Count; ++i)
length += ValidateAndGetLength(coordinates[i], ref lengthCache, parameter);
return length;
}
public int ValidateAndGetLength(MultiLineString value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
var length = SizeOfHeaderWithLength;
if (GetSrid(value.CRS) != 0)
length += sizeof(int);
var coordinates = value.Coordinates;
for (var i = 0; i < coordinates.Count; ++i)
length += ValidateAndGetLength(coordinates[i], ref lengthCache, parameter);
return length;
}
public int ValidateAndGetLength(MultiPolygon value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
var length = SizeOfHeaderWithLength;
if (GetSrid(value.CRS) != 0)
length += sizeof(int);
var coordinates = value.Coordinates;
for (var i = 0; i < coordinates.Count; ++i)
length += ValidateAndGetLength(coordinates[i], ref lengthCache, parameter);
return length;
}
public int ValidateAndGetLength(GeometryCollection value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
{
var length = SizeOfHeaderWithLength;
if (GetSrid(value.CRS) != 0)
length += sizeof(int);
var geometries = value.Geometries;
for (var i = 0; i < geometries.Count; ++i)
length += ValidateAndGetLength((GeoJSONObject)geometries[i], ref lengthCache, parameter);
return length;
}
int INpgsqlTypeHandler<IGeoJSONObject>.ValidateAndGetLength(IGeoJSONObject value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
=> ValidateAndGetLength((GeoJSONObject)value, ref lengthCache, parameter);
int INpgsqlTypeHandler<IGeometryObject>.ValidateAndGetLength(IGeometryObject value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
=> ValidateAndGetLength((GeoJSONObject)value, ref lengthCache, parameter);
public override Task Write(GeoJSONObject value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
switch (value.Type)
{
case GeoJSONObjectType.Point:
return Write((Point)value, buf, lengthCache, parameter, async);
case GeoJSONObjectType.LineString:
return Write((LineString)value, buf, lengthCache, parameter, async);
case GeoJSONObjectType.Polygon:
return Write((Polygon)value, buf, lengthCache, parameter, async);
case GeoJSONObjectType.MultiPoint:
return Write((MultiPoint)value, buf, lengthCache, parameter, async);
case GeoJSONObjectType.MultiLineString:
return Write((MultiLineString)value, buf, lengthCache, parameter, async);
case GeoJSONObjectType.MultiPolygon:
return Write((MultiPolygon)value, buf, lengthCache, parameter, async);
case GeoJSONObjectType.GeometryCollection:
return Write((GeometryCollection)value, buf, lengthCache, parameter, async);
default:
throw UnknownPostGisType();
}
}
public async Task Write(Point value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
var type = EwkbGeometryType.Point;
var size = SizeOfHeader;
var srid = GetSrid(value.CRS);
if (srid != 0)
{
size += sizeof(int);
type |= EwkbGeometryType.HasSrid;
}
if (buf.WriteSpaceLeft < size)
await buf.Flush(async);
buf.WriteByte(0); // Most significant byte first
buf.WriteInt32((int)type);
if (srid != 0)
buf.WriteInt32(srid);
await WritePosition(value.Coordinates, buf, async);
}
public async Task Write(LineString value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
var type = EwkbGeometryType.LineString;
var size = SizeOfHeader;
var srid = GetSrid(value.CRS);
if (srid != 0)
{
size += sizeof(int);
type |= EwkbGeometryType.HasSrid;
}
if (buf.WriteSpaceLeft < size)
await buf.Flush(async);
var coordinates = value.Coordinates;
buf.WriteByte(0); // Most significant byte first
buf.WriteInt32((int)type);
buf.WriteInt32(coordinates.Count);
if (srid != 0)
buf.WriteInt32(srid);
for (var i = 0; i < coordinates.Count; ++i)
await WritePosition(coordinates[i], buf, async);
}
public async Task Write(Polygon value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
var type = EwkbGeometryType.Polygon;
var size = SizeOfHeader;
var srid = GetSrid(value.CRS);
if (srid != 0)
{
size += sizeof(int);
type |= EwkbGeometryType.HasSrid;
}
if (buf.WriteSpaceLeft < size)
await buf.Flush(async);
var lines = value.Coordinates;
buf.WriteByte(0); // Most significant byte first
buf.WriteInt32((int)type);
buf.WriteInt32(lines.Count);
if (srid != 0)
buf.WriteInt32(srid);
for (var i = 0; i < lines.Count; ++i)
{
if (buf.WriteSpaceLeft < 4)
await buf.Flush(async);
var coordinates = lines[i].Coordinates;
buf.WriteInt32(coordinates.Count);
for (var j = 0; j < coordinates.Count; ++j)
await WritePosition(coordinates[j], buf, async);
}
}
public async Task Write(MultiPoint value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
var type = EwkbGeometryType.MultiPoint;
var size = SizeOfHeader;
var srid = GetSrid(value.CRS);
if (srid != 0)
{
size += sizeof(int);
type |= EwkbGeometryType.HasSrid;
}
if (buf.WriteSpaceLeft < size)
await buf.Flush(async);
var coordinates = value.Coordinates;
buf.WriteByte(0); // Most significant byte first
buf.WriteInt32((int)type);
buf.WriteInt32(coordinates.Count);
if (srid != 0)
buf.WriteInt32(srid);
for (var i = 0; i < coordinates.Count; ++i)
await Write(coordinates[i], buf, lengthCache, parameter, async);
}
public async Task Write(MultiLineString value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
var type = EwkbGeometryType.MultiLineString;
var size = SizeOfHeader;
var srid = GetSrid(value.CRS);
if (srid != 0)
{
size += sizeof(int);
type |= EwkbGeometryType.HasSrid;
}
if (buf.WriteSpaceLeft < size)
await buf.Flush(async);
var coordinates = value.Coordinates;
buf.WriteByte(0); // Most significant byte first
buf.WriteInt32((int)type);
buf.WriteInt32(coordinates.Count);
if (srid != 0)
buf.WriteInt32(srid);
for (var i = 0; i < coordinates.Count; ++i)
await Write(coordinates[i], buf, lengthCache, parameter, async);
}
public async Task Write(MultiPolygon value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
var type = EwkbGeometryType.MultiPolygon;
var size = SizeOfHeader;
var srid = GetSrid(value.CRS);
if (srid != 0)
{
size += sizeof(int);
type |= EwkbGeometryType.HasSrid;
}
if (buf.WriteSpaceLeft < size)
await buf.Flush(async);
var coordinates = value.Coordinates;
buf.WriteByte(0); // Most significant byte first
buf.WriteInt32((int)type);
buf.WriteInt32(coordinates.Count);
if (srid != 0)
buf.WriteInt32(srid);
for (var i = 0; i < coordinates.Count; ++i)
await Write(coordinates[i], buf, lengthCache, parameter, async);
}
public async Task Write(GeometryCollection value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
{
var type = EwkbGeometryType.GeometryCollection;
var size = SizeOfHeader;
var srid = GetSrid(value.CRS);
if (srid != 0)
{
size += sizeof(int);
type |= EwkbGeometryType.HasSrid;
}
if (buf.WriteSpaceLeft < size)
await buf.Flush(async);
var geometries = value.Geometries;
buf.WriteByte(0); // Most significant byte first
buf.WriteInt32((int)type);
buf.WriteInt32(geometries.Count);
if (srid != 0)
buf.WriteInt32(srid);
for (var i = 0; i < geometries.Count; ++i)
await Write((GeoJSONObject)geometries[i], buf, lengthCache, parameter, async);
}
Task INpgsqlTypeHandler<IGeoJSONObject>.Write(IGeoJSONObject value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
=> Write((GeoJSONObject)value, buf, lengthCache, parameter, async);
Task INpgsqlTypeHandler<IGeometryObject>.Write(IGeometryObject value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
=> Write((GeoJSONObject)value, buf, lengthCache, parameter, async);
static async Task WritePosition(IPosition coordinate, NpgsqlWriteBuffer buf, bool async)
{
var altitude = coordinate.Altitude;
if (buf.WriteSpaceLeft < SizeOfPoint(altitude.HasValue))
await buf.Flush(async);
buf.WriteDouble(coordinate.Longitude);
buf.WriteDouble(coordinate.Latitude);
if (altitude.HasValue)
buf.WriteDouble(altitude.Value);
}
#endregion
#region Crs
NamedCRS GetCrs(int srid)
{
var crsType = CrsType;
if (crsType == GeoJSONOptions.None)
return null;
if (_lastSrid == srid && _lastCrs != null)
return _lastCrs;
var authority = _crsMap.GetAuthority(srid);
if (authority == null)
throw new NpgsqlSafeReadException(new InvalidOperationException($"SRID {srid} unknown in spatial_ref_sys table"));
_lastCrs = new NamedCRS(crsType == GeoJSONOptions.LongCRS
? "urn:ogc:def:crs:" + authority + "::" + srid : authority + ":" + srid);
_lastSrid = srid;
return _lastCrs;
}
static int GetSrid(ICRSObject crs)
{
if (crs == null || crs is UnspecifiedCRS)
return 0;
var namedCrs = crs as NamedCRS;
if (namedCrs == null)
throw new NotSupportedException("The LinkedCRS class isn't supported");
if (namedCrs.Properties.TryGetValue("name", out var value) && value != null)
{
var name = value.ToString();
if (string.Equals(name, "urn:ogc:def:crs:OGC::CRS84", StringComparison.Ordinal))
return 4326;
var index = name.LastIndexOf(':');
if (index != -1 && int.TryParse(name.Substring(index + 1), out var srid))
return srid;
throw new FormatException("The specified CRS isn't properly named");
}
return 0;
}
#endregion
}
/// <summary>
/// Represents the identifier of the Well Known Binary representation of a geographical feature specified by the OGC.
/// http://portal.opengeospatial.org/files/?artifact_id=13227 Chapter 6.3.2.7
/// </summary>
[Flags]
enum EwkbGeometryType : uint
{
// Types
Point = 1,
LineString = 2,
Polygon = 3,
MultiPoint = 4,
MultiLineString = 5,
MultiPolygon = 6,
GeometryCollection = 7,
// Masks
BaseType = Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon | GeometryCollection,
// Flags
HasSrid = 0x20000000,
HasM = 0x40000000,
HasZ = 0x80000000
}
}