-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathNpgsqlTypes.cs
More file actions
616 lines (505 loc) · 18.9 KB
/
NpgsqlTypes.cs
File metadata and controls
616 lines (505 loc) · 18.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
#pragma warning disable 1591
// ReSharper disable once CheckNamespace
namespace NpgsqlTypes;
/// <summary>
/// Represents a PostgreSQL point type.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/static/datatype-geometric.html
/// </remarks>
public struct NpgsqlPoint(double x, double y) : IEquatable<NpgsqlPoint>
{
public double X { get; set; } = x;
public double Y { get; set; } = y;
// ReSharper disable CompareOfFloatsByEqualityOperator
public bool Equals(NpgsqlPoint other) => X == other.X && Y == other.Y;
// ReSharper restore CompareOfFloatsByEqualityOperator
public override bool Equals(object? obj)
=> obj is NpgsqlPoint point && Equals(point);
public static bool operator ==(NpgsqlPoint x, NpgsqlPoint y) => x.Equals(y);
public static bool operator !=(NpgsqlPoint x, NpgsqlPoint y) => !(x == y);
public override int GetHashCode()
=> HashCode.Combine(X, Y);
public override string ToString()
=> string.Format(CultureInfo.InvariantCulture, "({0},{1})", X, Y);
public void Deconstruct(out double x, out double y) => (x, y) = (X, Y);
}
/// <summary>
/// Represents a PostgreSQL line type.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/static/datatype-geometric.html
/// </remarks>
public struct NpgsqlLine(double a, double b, double c) : IEquatable<NpgsqlLine>
{
public double A { get; set; } = a;
public double B { get; set; } = b;
public double C { get; set; } = c;
public override string ToString()
=> string.Format(CultureInfo.InvariantCulture, "{{{0},{1},{2}}}", A, B, C);
public override int GetHashCode()
=> HashCode.Combine(A, B, C);
public bool Equals(NpgsqlLine other)
=> A == other.A && B == other.B && C == other.C;
public override bool Equals(object? obj)
=> obj is NpgsqlLine line && Equals(line);
public static bool operator ==(NpgsqlLine x, NpgsqlLine y) => x.Equals(y);
public static bool operator !=(NpgsqlLine x, NpgsqlLine y) => !(x == y);
public void Deconstruct(out double a, out double b, out double c) => (a, b, c) = (A, B, C);
}
/// <summary>
/// Represents a PostgreSQL Line Segment type.
/// </summary>
public struct NpgsqlLSeg : IEquatable<NpgsqlLSeg>
{
public NpgsqlPoint Start { get; set; }
public NpgsqlPoint End { get; set; }
public NpgsqlLSeg(NpgsqlPoint start, NpgsqlPoint end)
: this()
{
Start = start;
End = end;
}
public NpgsqlLSeg(double startx, double starty, double endx, double endy) : this()
{
Start = new NpgsqlPoint(startx, starty);
End = new NpgsqlPoint(endx, endy);
}
public override string ToString()
=> string.Format(CultureInfo.InvariantCulture, "[{0},{1}]", Start, End);
public override int GetHashCode()
=> HashCode.Combine(Start.X, Start.Y, End.X, End.Y);
public bool Equals(NpgsqlLSeg other)
=> Start == other.Start && End == other.End;
public override bool Equals(object? obj)
=> obj is NpgsqlLSeg seg && Equals(seg);
public static bool operator ==(NpgsqlLSeg x, NpgsqlLSeg y) => x.Equals(y);
public static bool operator !=(NpgsqlLSeg x, NpgsqlLSeg y) => !(x == y);
public void Deconstruct(out NpgsqlPoint start, out NpgsqlPoint end) => (start, end) = (Start, End);
}
/// <summary>
/// Represents a PostgreSQL box type.
/// </summary>
/// <remarks>
/// See https://www.postgresql.org/docs/current/static/datatype-geometric.html
/// </remarks>
public struct NpgsqlBox : IEquatable<NpgsqlBox>
{
NpgsqlPoint _upperRight;
public NpgsqlPoint UpperRight
{
get => _upperRight;
set
{
_upperRight = value;
NormalizeBox();
}
}
NpgsqlPoint _lowerLeft;
public NpgsqlPoint LowerLeft
{
get => _lowerLeft;
set
{
_lowerLeft = value;
NormalizeBox();
}
}
public NpgsqlBox(NpgsqlPoint upperRight, NpgsqlPoint lowerLeft) : this()
{
_upperRight = upperRight;
_lowerLeft = lowerLeft;
NormalizeBox();
}
public NpgsqlBox(double top, double right, double bottom, double left)
: this(new NpgsqlPoint(right, top), new NpgsqlPoint(left, bottom)) { }
public double Left => LowerLeft.X;
public double Right => UpperRight.X;
public double Bottom => LowerLeft.Y;
public double Top => UpperRight.Y;
public double Width => Right - Left;
public double Height => Top - Bottom;
public bool IsEmpty => Width == 0 || Height == 0;
public bool Equals(NpgsqlBox other)
=> UpperRight == other.UpperRight && LowerLeft == other.LowerLeft;
public override bool Equals(object? obj)
=> obj is NpgsqlBox box && Equals(box);
public static bool operator ==(NpgsqlBox x, NpgsqlBox y) => x.Equals(y);
public static bool operator !=(NpgsqlBox x, NpgsqlBox y) => !(x == y);
public override string ToString()
=> string.Format(CultureInfo.InvariantCulture, "{0},{1}", UpperRight, LowerLeft);
public override int GetHashCode()
=> HashCode.Combine(Top, Right, Bottom, LowerLeft);
// Swaps corners for isomorphic boxes, to mirror postgres behavior.
// See: https://github.com/postgres/postgres/blob/af2324fabf0020e464b0268be9ef03e8f46ed84b/src/backend/utils/adt/geo_ops.c#L435-L447
void NormalizeBox()
{
if (_upperRight.X < _lowerLeft.X)
(_upperRight.X, _lowerLeft.X) = (_lowerLeft.X, _upperRight.X);
if (_upperRight.Y < _lowerLeft.Y)
(_upperRight.Y, _lowerLeft.Y) = (_lowerLeft.Y, _upperRight.Y);
}
public void Deconstruct(out NpgsqlPoint lowerLeft, out NpgsqlPoint upperRight)
{
lowerLeft = LowerLeft;
upperRight = UpperRight;
}
public void Deconstruct(out double left, out double right, out double bottom, out double top)
{
left = Left;
right = Right;
bottom = Bottom;
top = Top;
}
public void Deconstruct(out double left, out double right, out double bottom, out double top, out double width, out double height)
{
left = Left;
right = Right;
bottom = Bottom;
top = Top;
width = Width;
height = Height;
}
}
/// <summary>
/// Represents a PostgreSQL Path type.
/// </summary>
public struct NpgsqlPath : IList<NpgsqlPoint>, IEquatable<NpgsqlPath>
{
List<NpgsqlPoint> _points;
List<NpgsqlPoint> Points => _points ??= [];
public bool Open { get; set; }
public NpgsqlPath()
=> _points = [];
public NpgsqlPath(IEnumerable<NpgsqlPoint> points, bool open)
{
_points = [..points];
Open = open;
}
public NpgsqlPath(IEnumerable<NpgsqlPoint> points) : this(points, false) {}
public NpgsqlPath(params NpgsqlPoint[] points) : this(points, false) {}
public NpgsqlPath(bool open) : this()
{
_points = [];
Open = open;
}
public NpgsqlPath(int capacity, bool open) : this()
{
_points = new List<NpgsqlPoint>(capacity);
Open = open;
}
public NpgsqlPath(int capacity) : this(capacity, false) {}
public NpgsqlPoint this[int index]
{
get => Points[index];
set => Points[index] = value;
}
public int Capacity => Points.Capacity;
public int Count => _points?.Count ?? 0;
public bool IsReadOnly => false;
public int IndexOf(NpgsqlPoint item) => Points.IndexOf(item);
public void Insert(int index, NpgsqlPoint item) => Points.Insert(index, item);
public void RemoveAt(int index) => Points.RemoveAt(index);
public void Add(NpgsqlPoint item) => Points.Add(item);
public void Clear() => Points.Clear();
public bool Contains(NpgsqlPoint item) => Points.Contains(item);
public void CopyTo(NpgsqlPoint[] array, int arrayIndex) => Points.CopyTo(array, arrayIndex);
public bool Remove(NpgsqlPoint item) => Points.Remove(item);
public IEnumerator<NpgsqlPoint> GetEnumerator() => Points.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public bool Equals(NpgsqlPath other)
{
if (Open != other.Open || Count != other.Count)
return false;
if (ReferenceEquals(_points, other._points))//Short cut for shallow copies.
return true;
for (var i = 0; i != Count; ++i)
if (this[i] != other[i])
return false;
return true;
}
public override bool Equals(object? obj)
=> obj is NpgsqlPath path && Equals(path);
public static bool operator ==(NpgsqlPath x, NpgsqlPath y) => x.Equals(y);
public static bool operator !=(NpgsqlPath x, NpgsqlPath y) => !(x == y);
public override int GetHashCode()
{
var hashCode = new HashCode();
hashCode.Add(Open);
foreach (var point in this)
{
hashCode.Add(point.X);
hashCode.Add(point.Y);
}
return hashCode.ToHashCode();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(Open ? '[' : '(');
int i;
for (i = 0; i < Count; i++)
{
var p = _points[i];
sb.AppendFormat(CultureInfo.InvariantCulture, "({0},{1})", p.X, p.Y);
if (i < _points.Count - 1)
sb.Append(',');
}
sb.Append(Open ? ']' : ')');
return sb.ToString();
}
}
/// <summary>
/// Represents a PostgreSQL Polygon type.
/// </summary>
public struct NpgsqlPolygon : IList<NpgsqlPoint>, IEquatable<NpgsqlPolygon>
{
List<NpgsqlPoint> _points;
List<NpgsqlPoint> Points => _points ??= [];
public NpgsqlPolygon()
=> _points = [];
public NpgsqlPolygon(IEnumerable<NpgsqlPoint> points)
=> _points = [..points];
public NpgsqlPolygon(params NpgsqlPoint[] points) : this((IEnumerable<NpgsqlPoint>) points) {}
public NpgsqlPolygon(int capacity)
=> _points = new List<NpgsqlPoint>(capacity);
public NpgsqlPoint this[int index]
{
get => Points[index];
set => Points[index] = value;
}
public int Capacity => Points.Capacity;
public int Count => _points?.Count ?? 0;
public bool IsReadOnly => false;
public int IndexOf(NpgsqlPoint item) => Points.IndexOf(item);
public void Insert(int index, NpgsqlPoint item) => Points.Insert(index, item);
public void RemoveAt(int index) => Points.RemoveAt(index);
public void Add(NpgsqlPoint item) => Points.Add(item);
public void Clear() => Points.Clear();
public bool Contains(NpgsqlPoint item) => Points.Contains(item);
public void CopyTo(NpgsqlPoint[] array, int arrayIndex) => Points.CopyTo(array, arrayIndex);
public bool Remove(NpgsqlPoint item) => Points.Remove(item);
public IEnumerator<NpgsqlPoint> GetEnumerator() => Points.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public bool Equals(NpgsqlPolygon other)
{
if (Count != other.Count)
return false;
if (ReferenceEquals(_points, other._points))
return true;
for (var i = 0; i != Count; ++i)
if (this[i] != other[i])
return false;
return true;
}
public override bool Equals(object? obj)
=> obj is NpgsqlPolygon polygon && Equals(polygon);
public static bool operator ==(NpgsqlPolygon x, NpgsqlPolygon y) => x.Equals(y);
public static bool operator !=(NpgsqlPolygon x, NpgsqlPolygon y) => !(x == y);
public override int GetHashCode()
{
var hashCode = new HashCode();
foreach (var point in this)
{
hashCode.Add(point.X);
hashCode.Add(point.Y);
}
return hashCode.ToHashCode();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append('(');
int i;
for (i = 0; i < Count; i++)
{
var p = _points[i];
sb.AppendFormat(CultureInfo.InvariantCulture, "({0},{1})", p.X, p.Y);
if (i < _points.Count - 1) {
sb.Append(",");
}
}
sb.Append(')');
return sb.ToString();
}
}
/// <summary>
/// Represents a PostgreSQL Circle type.
/// </summary>
public struct NpgsqlCircle(double x, double y, double radius) : IEquatable<NpgsqlCircle>
{
public double X { get; set; } = x;
public double Y { get; set; } = y;
public double Radius { get; set; } = radius;
public NpgsqlCircle(NpgsqlPoint center, double radius)
: this(center.X, center.Y, radius)
{
}
public NpgsqlPoint Center
{
get => new(X, Y);
set => (X, Y) = (value.X, value.Y);
}
// ReSharper disable CompareOfFloatsByEqualityOperator
public bool Equals(NpgsqlCircle other)
=> X == other.X && Y == other.Y && Radius == other.Radius;
// ReSharper restore CompareOfFloatsByEqualityOperator
public override bool Equals(object? obj)
=> obj is NpgsqlCircle circle && Equals(circle);
public override string ToString()
=> string.Format(CultureInfo.InvariantCulture, "<({0},{1}),{2}>", X, Y, Radius);
public static bool operator ==(NpgsqlCircle x, NpgsqlCircle y) => x.Equals(y);
public static bool operator !=(NpgsqlCircle x, NpgsqlCircle y) => !(x == y);
public override int GetHashCode()
=> HashCode.Combine(X, Y, Radius);
public void Deconstruct(out double x, out double y, out double radius)
{
x = X;
y = Y;
radius = Radius;
}
public void Deconstruct(out NpgsqlPoint center, out double radius)
{
center = Center;
radius = Radius;
}
}
/// <summary>
/// Represents a PostgreSQL inet type, which is a combination of an IPAddress and a subnet mask.
/// </summary>
/// <remarks>
/// https://www.postgresql.org/docs/current/static/datatype-net-types.html
/// </remarks>
public readonly record struct NpgsqlInet
{
public IPAddress Address { get; }
public byte Netmask { get; }
public NpgsqlInet(IPAddress address, byte netmask)
{
CheckAddressFamily(address);
Address = address;
Netmask = netmask;
}
public NpgsqlInet(IPAddress address)
: this(address, (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128))
{
}
public NpgsqlInet(string addr)
{
switch (addr.Split('/'))
{
case { Length: 2 } segments:
(Address, Netmask) = (IPAddress.Parse(segments[0]), byte.Parse(segments[1]));
break;
case { Length: 1 } segments:
var ipAddr = IPAddress.Parse(segments[0]);
CheckAddressFamily(ipAddr);
(Address, Netmask) = (
ipAddr,
ipAddr.AddressFamily == AddressFamily.InterNetworkV6 ? (byte)128 : (byte)32);
break;
default:
throw new FormatException("Invalid number of parts in CIDR specification");
}
}
public override string ToString()
=> (Address?.AddressFamily == AddressFamily.InterNetwork && Netmask == 32) ||
(Address?.AddressFamily == AddressFamily.InterNetworkV6 && Netmask == 128)
? Address.ToString()
: $"{Address}/{Netmask}";
public static explicit operator IPAddress(NpgsqlInet inet)
=> inet.Address;
public static implicit operator NpgsqlInet(IPAddress ip)
=> new(ip);
public static implicit operator NpgsqlInet(IPNetwork cidr)
=> new(
cidr.BaseAddress,
cidr.PrefixLength <= byte.MaxValue
? (byte)cidr.PrefixLength
: throw new ArgumentOutOfRangeException(nameof(cidr), "IPNetwork.PrefixLength is too large to fit in a byte"));
public void Deconstruct(out IPAddress address, out byte netmask)
{
address = Address;
netmask = Netmask;
}
static void CheckAddressFamily(IPAddress address)
{
if (address.AddressFamily != AddressFamily.InterNetwork && address.AddressFamily != AddressFamily.InterNetworkV6)
throw new ArgumentException("Only IPAddress of InterNetwork or InterNetworkV6 address families are accepted", nameof(address));
}
}
/// <summary>
/// Represents a PostgreSQL cidr type.
/// </summary>
/// <remarks>
/// https://www.postgresql.org/docs/current/static/datatype-net-types.html
/// </remarks>
[Obsolete("Use .NET IPNetwork instead of NpgsqlCidr to map to PostgreSQL cidr")]
public readonly record struct NpgsqlCidr
{
public IPAddress Address { get; }
public byte Netmask { get; }
public NpgsqlCidr(IPAddress address, byte netmask)
{
if (address.AddressFamily != AddressFamily.InterNetwork && address.AddressFamily != AddressFamily.InterNetworkV6)
throw new ArgumentException("Only IPAddress of InterNetwork or InterNetworkV6 address families are accepted", nameof(address));
Address = address;
Netmask = netmask;
}
public NpgsqlCidr(string addr)
=> (Address, Netmask) = addr.Split('/') switch
{
{ Length: 2 } segments => (IPAddress.Parse(segments[0]), byte.Parse(segments[1])),
{ Length: 1 } => throw new FormatException("Missing netmask"),
_ => throw new FormatException("Invalid number of parts in CIDR specification")
};
public static implicit operator NpgsqlInet(NpgsqlCidr cidr)
=> new(cidr.Address, cidr.Netmask);
public static explicit operator IPAddress(NpgsqlCidr cidr)
=> cidr.Address;
public override string ToString()
=> $"{Address}/{Netmask}";
public void Deconstruct(out IPAddress address, out byte netmask)
{
address = Address;
netmask = Netmask;
}
}
/// <summary>
/// Represents a PostgreSQL tid value
/// </summary>
/// <remarks>
/// https://www.postgresql.org/docs/current/static/datatype-oid.html
/// </remarks>
public readonly struct NpgsqlTid(uint blockNumber, ushort offsetNumber) : IEquatable<NpgsqlTid>
{
/// <summary>
/// Block number
/// </summary>
public uint BlockNumber { get; } = blockNumber;
/// <summary>
/// Tuple index within block
/// </summary>
public ushort OffsetNumber { get; } = offsetNumber;
public bool Equals(NpgsqlTid other)
=> BlockNumber == other.BlockNumber && OffsetNumber == other.OffsetNumber;
public override bool Equals(object? o)
=> o is NpgsqlTid tid && Equals(tid);
public override int GetHashCode() => (int)BlockNumber ^ OffsetNumber;
public static bool operator ==(NpgsqlTid left, NpgsqlTid right) => left.Equals(right);
public static bool operator !=(NpgsqlTid left, NpgsqlTid right) => !(left == right);
public override string ToString() => $"({BlockNumber},{OffsetNumber})";
public void Deconstruct(out uint blockNumber, out ushort offsetNumber)
{
blockNumber = BlockNumber;
offsetNumber = OffsetNumber;
}
}
#pragma warning restore 1591