-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathspatial_functions_scalar.cpp
More file actions
9649 lines (7909 loc) · 362 KB
/
spatial_functions_scalar.cpp
File metadata and controls
9649 lines (7909 loc) · 362 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
// Spatial
#include "spatial/modules/main/spatial_functions.hpp"
#include "spatial/geometry/geometry_serialization.hpp"
#include "spatial/geometry/vertex.hpp"
#include "spatial/geometry/sgl.hpp"
#include "spatial/spatial_types.hpp"
#include "spatial/util/binary_reader.hpp"
#include "spatial/util/function_builder.hpp"
#include "spatial/util/math.hpp"
// DuckDB
#include "duckdb/common/constants.hpp"
#include "duckdb/common/types/blob.hpp"
#include "duckdb/common/vector_operations/generic_executor.hpp"
#include "duckdb/execution/expression_executor.hpp"
#include "duckdb/planner/expression/bound_function_expression.hpp"
#include "duckdb/common/vector_operations/septenary_executor.hpp"
#include "duckdb/planner/expression/bound_constant_expression.hpp"
#include "spatial/util/distance_extract.hpp"
#include "spatial/util/knn_extract.hpp"
#include "spatial/spatial_settings.hpp"
// Extra
#include "yyjson.h"
namespace duckdb {
namespace {
//######################################################################################################################
// Util
//######################################################################################################################
//======================================================================================================================
// LocalState
//======================================================================================================================
class LocalState final : public FunctionLocalState {
public:
explicit LocalState(ClientContext &context) : arena(BufferAllocator::Get(context)), allocator(arena) {
}
static unique_ptr<FunctionLocalState> Init(ExpressionState &state, const BoundFunctionExpression &expr,
FunctionData *bind_data);
static LocalState &ResetAndGet(ExpressionState &state);
// De/Serialize geometries
void Deserialize(const string_t &blob, sgl::geometry &geom);
void Deserialize(const string_t &blob, sgl::prepared_geometry &geom);
sgl::geometry *DeserializeToHeap(const string_t &blob);
string_t Serialize(Vector &vector, const sgl::geometry &geom);
ArenaAllocator &GetArena() {
return arena;
}
GeometryAllocator &GetAllocator() {
return allocator;
}
private:
ArenaAllocator arena;
GeometryAllocator allocator;
};
unique_ptr<FunctionLocalState> LocalState::Init(ExpressionState &state, const BoundFunctionExpression &expr,
FunctionData *bind_data) {
return make_uniq_base<FunctionLocalState, LocalState>(state.GetContext());
}
LocalState &LocalState::ResetAndGet(ExpressionState &state) {
auto &local_state = ExecuteFunctionState::GetFunctionState(state)->Cast<LocalState>();
local_state.arena.Reset();
return local_state;
}
void LocalState::Deserialize(const string_t &blob, sgl::geometry &geom) {
Serde::Deserialize(geom, arena, blob.GetDataUnsafe(), blob.GetSize());
}
void LocalState::Deserialize(const string_t &blob, sgl::prepared_geometry &geom) {
Serde::DeserializePrepared(geom, arena, blob.GetDataUnsafe(), blob.GetSize());
}
sgl::geometry *LocalState::DeserializeToHeap(const string_t &blob) {
const auto mem = arena.AllocateAligned(sizeof(sgl::geometry));
const auto geom = new (mem) sgl::geometry();
Serde::Deserialize(*geom, arena, blob.GetDataUnsafe(), blob.GetSize());
return geom;
}
string_t LocalState::Serialize(Vector &vector, const sgl::geometry &geom) {
const auto size = Serde::GetRequiredSize(geom);
auto blob = StringVector::EmptyString(vector, size);
Serde::Serialize(geom, blob.GetDataWriteable(), size);
blob.Finalize();
return blob;
}
} // namespace
namespace {
//######################################################################################################################
// Functions
//######################################################################################################################
//======================================================================================================================
// ST_Affine
//======================================================================================================================
struct ST_Affine {
//------------------------------------------------------------------------------------------------------------------
// GEOMETRY
//------------------------------------------------------------------------------------------------------------------
static void Execute3D(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
auto &alloc = lstate.GetAllocator();
const auto row_count = args.size();
UnifiedVectorFormat geom_format;
args.data[0].ToUnifiedFormat(row_count, geom_format);
UnifiedVectorFormat matrix_elems[12];
idx_t matrix_idx[12];
for (idx_t i = 1; i < 13; i++) {
args.data[i].ToUnifiedFormat(row_count, matrix_elems[i - 1]);
}
for (idx_t out_idx = 0; out_idx < args.size(); out_idx++) {
// Reset the arena after every iteration, to avoid holding onto too much memory
lstate.GetArena().Reset();
const auto geom_idx = geom_format.sel->get_index(out_idx);
if (!geom_format.validity.RowIsValid(geom_idx)) {
FlatVector::SetNull(result, out_idx, true);
continue;
}
bool all_valid = true;
for (idx_t j = 0; j < 12; j++) {
matrix_idx[j] = matrix_elems[j].sel->get_index(out_idx);
all_valid = all_valid && matrix_elems[j].validity.RowIsValid(matrix_idx[j]);
}
if (!all_valid) {
FlatVector::SetNull(result, out_idx, true);
continue;
}
// Setup the matrix
auto matrix = sgl::affine_matrix::identity();
matrix.v[0] = UnifiedVectorFormat::GetData<double>(matrix_elems[0])[matrix_idx[0]]; // a
matrix.v[1] = UnifiedVectorFormat::GetData<double>(matrix_elems[1])[matrix_idx[1]]; // b
matrix.v[2] = UnifiedVectorFormat::GetData<double>(matrix_elems[2])[matrix_idx[2]]; // c
matrix.v[3] = UnifiedVectorFormat::GetData<double>(matrix_elems[9])[matrix_idx[9]]; // xoff
matrix.v[4] = UnifiedVectorFormat::GetData<double>(matrix_elems[3])[matrix_idx[3]]; // d
matrix.v[5] = UnifiedVectorFormat::GetData<double>(matrix_elems[4])[matrix_idx[4]]; // e
matrix.v[6] = UnifiedVectorFormat::GetData<double>(matrix_elems[5])[matrix_idx[5]]; // f
matrix.v[7] = UnifiedVectorFormat::GetData<double>(matrix_elems[10])[matrix_idx[10]]; // yoff
matrix.v[8] = UnifiedVectorFormat::GetData<double>(matrix_elems[6])[matrix_idx[6]]; // g
matrix.v[9] = UnifiedVectorFormat::GetData<double>(matrix_elems[7])[matrix_idx[7]]; // h
matrix.v[10] = UnifiedVectorFormat::GetData<double>(matrix_elems[8])[matrix_idx[8]]; // i
matrix.v[11] = UnifiedVectorFormat::GetData<double>(matrix_elems[11])[matrix_idx[11]]; // zoff
// Deserialize the geometry
auto geom_blob = UnifiedVectorFormat::GetData<string_t>(geom_format)[geom_idx];
sgl::geometry geom;
lstate.Deserialize(geom_blob, geom);
// Apply the transformation
sgl::ops::affine_transform(alloc, geom, matrix);
// Serialize the result
FlatVector::GetData<string_t>(result)[out_idx] = lstate.Serialize(result, geom);
}
if (row_count == 1) {
result.SetVectorType(VectorType::CONSTANT_VECTOR);
}
}
static void Execute2D(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
auto &alloc = lstate.GetAllocator();
SeptenaryExecutor::Execute<string_t, double, double, double, double, double, double, string_t>(
args, result,
[&](const string_t &geom_blob, const double a, const double b, const double d, const double e,
const double xoff, const double yoff) {
// Reset the arena after every iteration, to avoid holding onto too much memory
lstate.GetArena().Reset();
// Deserialize the geometry
sgl::geometry geom;
lstate.Deserialize(geom_blob, geom);
// Setup the matrix
auto matrix = sgl::affine_matrix::identity();
matrix.v[0] = a; // a
matrix.v[1] = b; // b
matrix.v[3] = xoff; // xoff
matrix.v[4] = d; // d
matrix.v[5] = e; // e
matrix.v[7] = yoff; // yoff
// Transform the geometry
sgl::ops::affine_transform(alloc, geom, matrix);
// Serialize the result
return lstate.Serialize(result, geom);
});
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_Affine", [](ScalarFunctionBuilder &func) {
// GEOMETRY (3D)
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("a", LogicalType::DOUBLE);
variant.AddParameter("b", LogicalType::DOUBLE);
variant.AddParameter("c", LogicalType::DOUBLE);
variant.AddParameter("d", LogicalType::DOUBLE);
variant.AddParameter("e", LogicalType::DOUBLE);
variant.AddParameter("f", LogicalType::DOUBLE);
variant.AddParameter("g", LogicalType::DOUBLE);
variant.AddParameter("h", LogicalType::DOUBLE);
variant.AddParameter("i", LogicalType::DOUBLE);
variant.AddParameter("xoff", LogicalType::DOUBLE);
variant.AddParameter("yoff", LogicalType::DOUBLE);
variant.AddParameter("zoff", LogicalType::DOUBLE);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetBind(GeoTypes::PropagateCRS);
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute3D);
});
// GEOMETRY (2D)
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("a", LogicalType::DOUBLE);
variant.AddParameter("b", LogicalType::DOUBLE);
variant.AddParameter("d", LogicalType::DOUBLE);
variant.AddParameter("e", LogicalType::DOUBLE);
variant.AddParameter("xoff", LogicalType::DOUBLE);
variant.AddParameter("yoff", LogicalType::DOUBLE);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetBind(GeoTypes::PropagateCRS);
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute2D);
});
func.SetDescription(R"(
Applies an affine transformation to a geometry.
For the 2D variant, the transformation matrix is defined as follows:
```
| a b xoff |
| d e yoff |
| 0 0 1 |
```
For the 3D variant, the transformation matrix is defined as follows:
```
| a b c xoff |
| d e f yoff |
| g h i zoff |
| 0 0 0 1 |
```
The transformation is applied to all vertices of the geometry.
)");
func.SetExample(R"(
-- Translate a point by (2, 3)
SELECT ST_Affine(ST_Point(1, 1),
1, 0, -- a, b
0, 1, -- d, e
2, 3); -- xoff, yoff
----
POINT (3 4)
-- Scale a geometry by factor 2 in X and Y
SELECT ST_Affine(ST_Point(1, 1),
2, 0, 0, -- a, b, c
0, 2, 0, -- d, e, f
0, 0, 1, -- g, h, i
0, 0, 0); -- xoff, yoff, zoff
----
POINT (2 2)
)");
func.SetTag("ext", "spatial");
func.SetTag("category", "property");
});
// Add helper macros
FunctionBuilder::RegisterMacro(loader, "ST_Scale", [](MacroFunctionBuilder &builder) {
builder.AddDefinition(
{"geom", "xs", "ys", "zs"}, "ST_Affine(geom, xs, 0, 0, 0, ys, 0, 0, 0, zs, 0, 0, 0)",
"Scales a geometry in X, Y and Z direction. This is a shorthand macro for calling ST_Affine.",
R"(
-- Scale a point by factor 2 in X and 3 in Y
SELECT ST_Scale(ST_Point(1, 1), 2, 3);
----
POINT (2 3)
-- Scale a 3D point
SELECT ST_Scale(
ST_GeomFromText('POINT Z(1 2 3)'),
2, 2, 2
);
----
POINT Z (2 4 6)
)");
builder.AddDefinition(
{"geom", "xs", "ys"}, "ST_Affine(geom, xs, 0, 0, 0, ys, 0, 0, 0, 1, 0, 0, 0)",
"Scales a geometry in X and Y direction. This is a shorthand macro for calling ST_Affine.");
});
FunctionBuilder::RegisterMacro(loader, "ST_Translate", [](MacroFunctionBuilder &builder) {
builder.AddDefinition(
{"geom", "dx", "dy", "dz"}, "ST_Affine(geom, 1, 0, dx, 0, 1, dy, 0, 0, 1, dz, 0, 0)",
"Translates a geometry in X, Y and Z direction. This is a shorthand macro for calling ST_Affine.",
R"(
-- Translate a point by (2, 3)
SELECT ST_Translate(ST_Point(1, 1), 2, 3);
----
POINT (3 4)
-- Translate a linestring
SELECT ST_Translate(
ST_GeomFromText('LINESTRING(0 0, 1 1)'),
5, -2
);
----
LINESTRING (5 -2, 6 -1)
)");
builder.AddDefinition(
{"geom", "dx", "dy"}, "ST_Affine(geom, 1, 0, dx, 0, 1, dy, 0, 0, 1, 0, 0, 0)",
"Translates a geometry in X and Y direction. This is a shorthand macro for calling ST_Affine.");
});
FunctionBuilder::RegisterMacro(loader, "ST_TransScale", [](MacroFunctionBuilder &builder) {
builder.AddDefinition({"geom", "dx", "dy", "xs", "ys"},
"ST_Affine(geom, xs, 0, 0, 0, ys, 0, 0, 0, 1, dx * xs, dy * ys, 0)",
"Translates and then scales a geometry in X and Y direction. This is a shorthand "
"macro for calling ST_Affine.",
R"(
-- Translate by (1, 2) then scale by (2, 3)
SELECT ST_TransScale(ST_Point(1, 1), 1, 2, 2, 3);
----
POINT (4 9)
)");
});
FunctionBuilder::RegisterMacro(loader, "ST_RotateX", [](MacroFunctionBuilder &builder) {
builder.AddDefinition(
{"geom", "radians"},
"ST_Affine(geom, 1, 0, 0, 0, COS(radians), -SIN(radians), 0, SIN(radians), COS(radians), 0, 0, 0)",
"Rotates a geometry around the X axis. This is a shorthand macro for calling ST_Affine.",
R"(
-- Rotate a 3D point 90 degrees (π/2 radians) around the X-axis
SELECT ST_RotateX(ST_GeomFromText('POINT Z(0 1 0)'), pi()/2);
----
POINT Z (0 0 1)
)");
});
FunctionBuilder::RegisterMacro(loader, "ST_RotateY", [](MacroFunctionBuilder &builder) {
builder.AddDefinition(
{"geom", "radians"},
"ST_Affine(geom, COS(radians), 0, SIN(radians), 0, 1, 0, -SIN(radians), 0, COS(radians), 0, 0, 0)",
"Rotates a geometry around the Y axis. This is a shorthand macro for calling ST_Affine.",
R"(
-- Rotate a 3D point 90 degrees (π/2 radians) around the Y-axis
SELECT ST_RotateY(ST_GeomFromText('POINT Z(1 0 0)'), pi()/2);
----
POINT Z (0 0 -1)
)");
});
FunctionBuilder::RegisterMacro(loader, "ST_RotateZ", [](MacroFunctionBuilder &builder) {
builder.AddDefinition(
{"geom", "radians"},
"ST_Affine(geom, COS(radians), -SIN(radians), 0, SIN(radians), COS(radians), 0, 0, 0, 1, 0, 0, 0)",
"Rotates a geometry around the Z axis. This is a shorthand macro for calling ST_Affine.",
R"(
-- Rotate a point 90 degrees (π/2 radians) around the Z-axis
SELECT ST_RotateZ(ST_Point(1, 0), pi()/2);
----
POINT (0 1)
)");
});
// Alias for ST_RotateZ
FunctionBuilder::RegisterMacro(loader, "ST_Rotate", [](MacroFunctionBuilder &builder) {
builder.AddDefinition({"geom", "radians"}, "ST_RotateZ(geom, radians)", "Alias of ST_RotateZ");
});
}
};
//======================================================================================================================
// ST_Area
//======================================================================================================================
struct ST_Area {
//------------------------------------------------------------------------------------------------------------------
// GEOMETRY
//------------------------------------------------------------------------------------------------------------------
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
UnaryExecutor::Execute<string_t, double>(args.data[0], result, args.size(), [&](const string_t &blob) {
sgl::geometry geom;
lstate.Deserialize(blob, geom);
return sgl::ops::get_area(geom);
});
}
//------------------------------------------------------------------------------------------------------------------
// POLYGON_2D
//------------------------------------------------------------------------------------------------------------------
static void PolygonAreaFunction(DataChunk &args, ExpressionState &state, Vector &result) {
D_ASSERT(args.data.size() == 1);
auto &input = args.data[0];
auto count = args.size();
auto &ring_vec = ListVector::GetEntry(input);
auto ring_entries = ListVector::GetData(ring_vec);
auto &coord_vec = ListVector::GetEntry(ring_vec);
auto &coord_vec_children = StructVector::GetEntries(coord_vec);
auto x_data = FlatVector::GetData<double>(*coord_vec_children[0]);
auto y_data = FlatVector::GetData<double>(*coord_vec_children[1]);
UnaryExecutor::Execute<list_entry_t, double>(input, result, count, [&](list_entry_t polygon) {
auto polygon_offset = polygon.offset;
auto polygon_length = polygon.length;
bool first = true;
double area = 0;
for (idx_t ring_idx = polygon_offset; ring_idx < polygon_offset + polygon_length; ring_idx++) {
auto ring = ring_entries[ring_idx];
auto ring_offset = ring.offset;
auto ring_length = ring.length;
double sum = 0;
for (idx_t coord_idx = ring_offset; coord_idx < ring_offset + ring_length - 1; coord_idx++) {
sum += (x_data[coord_idx] * y_data[coord_idx + 1]) - (x_data[coord_idx + 1] * y_data[coord_idx]);
}
sum = std::abs(sum);
if (first) {
// Add outer ring
area = sum * 0.5;
first = false;
} else {
// Subtract holes
area -= sum * 0.5;
}
}
return area;
});
if (count == 1) {
result.SetVectorType(VectorType::CONSTANT_VECTOR);
}
}
//------------------------------------------------------------------------------------------------------------------
// LINESTRING_2D
//------------------------------------------------------------------------------------------------------------------
static void LineStringAreaFunction(DataChunk &args, ExpressionState &state, Vector &result) {
auto input = args.data[0];
UnaryExecutor::Execute<list_entry_t, double>(input, result, args.size(), [](list_entry_t) { return 0; });
}
//------------------------------------------------------------------------------------------------------------------
// POINT_2D
//------------------------------------------------------------------------------------------------------------------
static void PointAreaFunction(DataChunk &args, ExpressionState &state, Vector &result) {
using POINT_TYPE = StructTypeBinary<double, double>;
using AREA_TYPE = PrimitiveType<double>;
GenericExecutor::ExecuteUnary<POINT_TYPE, AREA_TYPE>(args.data[0], result, args.size(),
[](POINT_TYPE) { return 0; });
}
//------------------------------------------------------------------------------------------------------------------
// BOX_2D
//------------------------------------------------------------------------------------------------------------------
static void BoxAreaFunction(DataChunk &args, ExpressionState &state, Vector &result) {
using BOX_TYPE = StructTypeQuaternary<double, double, double, double>;
using AREA_TYPE = PrimitiveType<double>;
GenericExecutor::ExecuteUnary<BOX_TYPE, AREA_TYPE>(args.data[0], result, args.size(), [&](BOX_TYPE &box) {
auto minx = box.a_val;
auto miny = box.b_val;
auto maxx = box.c_val;
auto maxy = box.d_val;
return AREA_TYPE {(maxx - minx) * (maxy - miny)};
});
}
//------------------------------------------------------------------------------------------------------------------
// Documentation
//------------------------------------------------------------------------------------------------------------------
static constexpr const char *DESCRIPTION = R"(
Compute the area of a geometry.
Returns `0.0` for any geometry that is not a `POLYGON`, `MULTIPOLYGON` or `GEOMETRYCOLLECTION` containing polygon
geometries.
The area is in the same units as the spatial reference system of the geometry.
The `POINT_2D` and `LINESTRING_2D` overloads of this function always return `0.0` but are included for completeness.
)";
static constexpr const char *EXAMPLE = R"(
SELECT ST_Area('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))'::GEOMETRY);
-- 1.0
)";
//------------------------------------------------------------------------------------------------------------------
// Register
//------------------------------------------------------------------------------------------------------------------
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_Area", [](ScalarFunctionBuilder &func) {
// GEOMETRY
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::DOUBLE);
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
// POLYGON_2D
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("polygon", GeoTypes::POLYGON_2D());
variant.SetReturnType(LogicalType::DOUBLE);
variant.SetFunction(PolygonAreaFunction);
});
// LINESTRING_2D
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("linestring", GeoTypes::LINESTRING_2D());
variant.SetReturnType(LogicalType::DOUBLE);
variant.SetFunction(LineStringAreaFunction);
});
// POINT_2D
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("point", GeoTypes::POINT_2D());
variant.SetReturnType(LogicalType::DOUBLE);
variant.SetFunction(PointAreaFunction);
});
// BOX_2D
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("box", GeoTypes::BOX_2D());
variant.SetReturnType(LogicalType::DOUBLE);
variant.SetFunction(BoxAreaFunction);
});
func.SetDescription(DESCRIPTION);
func.SetExample(EXAMPLE);
func.SetTag("ext", "spatial");
func.SetTag("category", "property");
});
}
};
//======================================================================================================================
// ST_AsGeoJSON
//======================================================================================================================
using namespace duckdb_yyjson_spatial;
class JSONAllocator {
// Stolen from the JSON extension :)
public:
explicit JSONAllocator(ArenaAllocator &allocator)
: allocator(allocator), yyjson_allocator({Allocate, Reallocate, Free, &allocator}) {
}
yyjson_alc *GetYYJSONAllocator() {
return &yyjson_allocator;
}
void Reset() {
allocator.Reset();
}
private:
static void *Allocate(void *ctx, size_t size) {
const auto alloc = static_cast<ArenaAllocator *>(ctx);
return alloc->AllocateAligned(size);
}
static void *Reallocate(void *ctx, void *ptr, size_t old_size, size_t size) {
const auto alloc = static_cast<ArenaAllocator *>(ctx);
return alloc->ReallocateAligned(data_ptr_cast(ptr), old_size, size);
}
static void Free(void *ctx, void *ptr) {
// NOP because ArenaAllocator can't free
}
ArenaAllocator &allocator;
yyjson_alc yyjson_allocator;
};
struct ST_AsGeoJSON {
//------------------------------------------------------------------------------------------------------------------
// JSON Formatting Functions
//------------------------------------------------------------------------------------------------------------------
// TODO: Move these into SGL at some point, make non-recursive
static void FormatCoord(const sgl::geometry *geom, yyjson_mut_doc *doc, yyjson_mut_val *obj) {
const auto vertex_type = geom->get_vertex_type();
const auto vertex_count = geom->get_vertex_count();
if (vertex_count == 0) {
// Make empty
const auto coord = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coord);
return;
}
// GeoJSON does not support M values, so we ignore them
switch (vertex_type) {
case sgl::vertex_type::XY:
case sgl::vertex_type::XYM: {
const auto coord = yyjson_mut_arr(doc);
const auto vert = geom->get_vertex_xy(0);
yyjson_mut_arr_add_real(doc, coord, vert.x);
yyjson_mut_arr_add_real(doc, coord, vert.y);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coord);
} break;
case sgl::vertex_type::XYZ:
case sgl::vertex_type::XYZM: {
const auto coord = yyjson_mut_arr(doc);
const auto vert = geom->get_vertex_xyzm(0);
yyjson_mut_arr_add_real(doc, coord, vert.x);
yyjson_mut_arr_add_real(doc, coord, vert.y);
yyjson_mut_arr_add_real(doc, coord, vert.z);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coord);
} break;
default:
D_ASSERT(false);
break;
}
}
static void FormatCoords(const sgl::geometry *geom, yyjson_mut_doc *doc, yyjson_mut_val *obj) {
const auto vertex_type = geom->get_vertex_type();
const auto vertex_count = geom->get_vertex_count();
// GeoJSON does not support M values, so we ignore them
switch (vertex_type) {
case sgl::vertex_type::XY:
case sgl::vertex_type::XYM: {
for (uint32_t i = 0; i < vertex_count; i++) {
const auto coord = yyjson_mut_arr(doc);
const auto vert = geom->get_vertex_xy(i);
yyjson_mut_arr_add_real(doc, coord, vert.x);
yyjson_mut_arr_add_real(doc, coord, vert.y);
yyjson_mut_arr_append(obj, coord);
}
} break;
case sgl::vertex_type::XYZ:
case sgl::vertex_type::XYZM: {
for (uint32_t i = 0; i < vertex_count; i++) {
const auto coord = yyjson_mut_arr(doc);
const auto vert = geom->get_vertex_xyzm(i);
yyjson_mut_arr_add_real(doc, coord, vert.x);
yyjson_mut_arr_add_real(doc, coord, vert.y);
yyjson_mut_arr_add_real(doc, coord, vert.z);
yyjson_mut_arr_append(obj, coord);
}
} break;
default:
D_ASSERT(false);
break;
}
}
static void FormatRecursive(const sgl::geometry *geom, yyjson_mut_doc *doc, yyjson_mut_val *obj) {
switch (geom->get_type()) {
case sgl::geometry_type::POINT: {
yyjson_mut_obj_add_str(doc, obj, "type", "Point");
FormatCoord(geom, doc, obj);
} break;
case sgl::geometry_type::LINESTRING: {
yyjson_mut_obj_add_str(doc, obj, "type", "LineString");
const auto coords = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coords);
FormatCoords(geom, doc, coords);
} break;
case sgl::geometry_type::POLYGON: {
yyjson_mut_obj_add_str(doc, obj, "type", "Polygon");
const auto coords = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coords);
const auto tail = geom->get_last_part();
auto head = tail;
if (head) {
do {
head = head->get_next();
const auto ring = yyjson_mut_arr(doc);
FormatCoords(head, doc, ring);
yyjson_mut_arr_append(coords, ring);
} while (head != tail);
}
} break;
case sgl::geometry_type::MULTI_POINT: {
yyjson_mut_obj_add_str(doc, obj, "type", "MultiPoint");
const auto coords = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coords);
const auto tail = geom->get_last_part();
auto head = tail;
if (head) {
do {
head = head->get_next();
FormatCoords(head, doc, coords);
} while (head != tail);
}
} break;
case sgl::geometry_type::MULTI_LINESTRING: {
yyjson_mut_obj_add_str(doc, obj, "type", "MultiLineString");
const auto coords = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coords);
const auto tail = geom->get_last_part();
auto head = tail;
if (head) {
do {
head = head->get_next();
const auto line = yyjson_mut_arr(doc);
FormatCoords(head, doc, line);
yyjson_mut_arr_append(coords, line);
} while (head != tail);
}
} break;
case sgl::geometry_type::MULTI_POLYGON: {
yyjson_mut_obj_add_str(doc, obj, "type", "MultiPolygon");
const auto coords = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc, obj, "coordinates", coords);
const auto tail = geom->get_last_part();
auto head = tail;
if (head) {
do {
head = head->get_next();
const auto poly = yyjson_mut_arr(doc);
const auto ring_tail = head->get_last_part();
auto ring_head = ring_tail;
if (ring_head) {
do {
ring_head = ring_head->get_next();
const auto ring = yyjson_mut_arr(doc);
FormatCoords(ring_head, doc, ring);
yyjson_mut_arr_append(poly, ring);
} while (ring_head != ring_tail);
}
yyjson_mut_arr_append(coords, poly);
} while (head != tail);
}
} break;
case sgl::geometry_type::GEOMETRY_COLLECTION: {
yyjson_mut_obj_add_str(doc, obj, "type", "GeometryCollection");
const auto geoms = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc, obj, "geometries", geoms);
const auto tail = geom->get_last_part();
auto head = tail;
if (head) {
do {
head = head->get_next();
const auto sub_geom = yyjson_mut_obj(doc);
FormatRecursive(head, doc, sub_geom);
yyjson_mut_arr_append(geoms, sub_geom);
} while (head != tail);
}
} break;
default:
D_ASSERT(false);
break;
}
}
//------------------------------------------------------------------------------------------------------------------
// GEOMETRY
//------------------------------------------------------------------------------------------------------------------
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
JSONAllocator allocator(lstate.GetArena());
UnaryExecutor::Execute<string_t, string_t>(args.data[0], result, args.size(), [&](string_t &blob) {
sgl::geometry geom;
lstate.Deserialize(blob, geom);
const auto doc = yyjson_mut_doc_new(allocator.GetYYJSONAllocator());
const auto obj = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, obj);
FormatRecursive(&geom, doc, obj);
size_t json_size = 0;
char *json_data = yyjson_mut_write_opts(doc, 0, allocator.GetYYJSONAllocator(), &json_size, nullptr);
// Because the arena allocator only resets after each pipeline invocation, we can safely just point into the
// arena here without needing to copy the data to the string heap with StringVector::AddString
return string_t {json_data, static_cast<uint32_t>(json_size)};
});
}
//------------------------------------------------------------------------------------------------------------------
// Documentation
//------------------------------------------------------------------------------------------------------------------
static constexpr auto DESCRIPTION = R"(
Returns the geometry as a GeoJSON fragment
This does not return a complete GeoJSON document, only the geometry fragment.
To construct a complete GeoJSON document or feature, look into using the DuckDB JSON extension in conjunction with this function.
This function supports geometries with Z values, but not M values. M values are ignored.
)";
static constexpr auto EXAMPLE = R"(
SELECT ST_AsGeoJSON('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))'::GEOMETRY);
----
{"type":"Polygon","coordinates":[[[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]]}
-- Convert a geometry into a full GeoJSON feature (requires the JSON extension to be loaded)
SELECT CAST({
type: 'Feature',
geometry: ST_AsGeoJSON(ST_Point(1, 2)),
properties: {
name: 'my_point'
}
} AS JSON);
----
{"type":"Feature","geometry":{"type":"Point","coordinates":[1.0, 2.0]},"properties":{"name":"my_point"}}
)";
//------------------------------------------------------------------------------------------------------------------
// Register
//------------------------------------------------------------------------------------------------------------------
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_AsGeoJSON", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::JSON());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription(DESCRIPTION);
func.SetExample(EXAMPLE);
func.SetTag("ext", "spatial");
func.SetTag("category", "conversion");
});
}
};
//======================================================================================================================
// ST_AsText
//======================================================================================================================
struct ST_AsText {
//------------------------------------------------------------------------------------------------------------------
// POINT_2D
//------------------------------------------------------------------------------------------------------------------
static void ExecutePoint(DataChunk &args, ExpressionState &state, Vector &result) {
D_ASSERT(args.data.size() == 1);
auto &input = args.data[0];
auto count = args.size();
CoreVectorOperations::Point2DToVarchar(input, result, count);
}
//------------------------------------------------------------------------------------------------------------------
// LINESTRING_2D
//------------------------------------------------------------------------------------------------------------------
// TODO: We want to format these to trim trailing zeros
static void ExecuteLineString(DataChunk &args, ExpressionState &state, Vector &result) {
D_ASSERT(args.data.size() == 1);
auto &input = args.data[0];
auto count = args.size();
CoreVectorOperations::LineString2DToVarchar(input, result, count);
}
//------------------------------------------------------------------------------------------------------------------
// POLYGON_2D
//------------------------------------------------------------------------------------------------------------------
// TODO: We want to format these to trim trailing zeros
static void ExecutePolygon(DataChunk &args, ExpressionState &state, Vector &result) {
D_ASSERT(args.data.size() == 1);
auto count = args.size();
auto &input = args.data[0];
CoreVectorOperations::Polygon2DToVarchar(input, result, count);
}
//------------------------------------------------------------------------------------------------------------------
// BOX_2D
//------------------------------------------------------------------------------------------------------------------
static void ExecuteBox(DataChunk &args, ExpressionState &state, Vector &result) {
D_ASSERT(args.data.size() == 1);
auto count = args.size();
auto &input = args.data[0];
CoreVectorOperations::Box2DToVarchar(input, result, count);
}
//------------------------------------------------------------------------------------------------------------------
// Documentation
//------------------------------------------------------------------------------------------------------------------
static constexpr const char *DESCRIPTION = R"(
Returns the geometry as a WKT string
)";
static constexpr const char *EXAMPLE = R"(
SELECT ST_MakeEnvelope(0, 0, 1, 1);
----
POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))
)";
//------------------------------------------------------------------------------------------------------------------
// Register
//------------------------------------------------------------------------------------------------------------------
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_AsText", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("point", GeoTypes::POINT_2D());
variant.SetReturnType(LogicalType::VARCHAR);
variant.SetFunction(ExecutePoint);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("linestring", GeoTypes::LINESTRING_2D());
variant.SetReturnType(LogicalType::VARCHAR);
variant.SetFunction(ExecuteLineString);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("polygon", GeoTypes::POLYGON_2D());
variant.SetReturnType(LogicalType::VARCHAR);
variant.SetFunction(ExecutePolygon);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("box", GeoTypes::BOX_2D());
variant.SetReturnType(LogicalType::VARCHAR);
variant.SetFunction(ExecuteBox);
});
func.SetDescription(DESCRIPTION);
func.SetExample(EXAMPLE);
func.SetTag("ext", "spatial");
func.SetTag("category", "conversion");
});
}
};
//======================================================================================================================
// ST_AsWKB