-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathgeos_module.cpp
More file actions
3196 lines (2596 loc) · 117 KB
/
geos_module.cpp
File metadata and controls
3196 lines (2596 loc) · 117 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
#include "spatial/modules/geos/geos_module.hpp"
#include "spatial/modules/geos/geos_geometry.hpp"
#include "spatial/modules/geos/geos_serde.hpp"
#include "spatial/spatial_types.hpp"
#include "spatial/util/function_builder.hpp"
#include "duckdb/common/vector_operations/senary_executor.hpp"
#include "duckdb/common/vector_operations/generic_executor.hpp"
#include "duckdb/planner/expression/bound_constant_expression.hpp"
#include "duckdb/planner/expression/bound_function_expression.hpp"
#include "spatial/geometry/geometry_serialization.hpp"
#include "spatial/geometry/sgl.hpp"
namespace duckdb {
//------------------------------------------------------------------------------
// Local State
//------------------------------------------------------------------------------
namespace {
class LocalState final : public FunctionLocalState {
public:
static unique_ptr<FunctionLocalState> Init(ExpressionState &state, const BoundFunctionExpression &expr,
FunctionData *bind_data) {
return make_uniq<LocalState>(state.GetContext());
}
static LocalState &ResetAndGet(ExpressionState &state) {
auto &local_state = ExecuteFunctionState::GetFunctionState(state)->Cast<LocalState>();
local_state.arena.Reset();
return local_state;
}
ArenaAllocator &GetArena() {
return arena;
}
GEOSContextHandle_t GetContext() const {
return ctx;
}
GeosGeometry Deserialize(const string_t &blob);
string_t Serialize(Vector &result, const GeosGeometry &geom) const;
// Most GEOS functions do not use an arena, so just use the default allocator
explicit LocalState(ClientContext &context) : arena(BufferAllocator::Get(context)) {
ctx = GEOS_init_r();
GEOSContext_setErrorMessageHandler_r(
ctx, [](const char *message, void *) { throw InvalidInputException(message); }, nullptr);
}
~LocalState() override {
GEOS_finish_r(ctx);
}
private:
ArenaAllocator arena;
GEOSContextHandle_t ctx;
};
string_t LocalState::Serialize(Vector &result, const GeosGeometry &geom) const {
// Get the size of the serialized geometry
const auto raw = geom.get_raw();
const auto size = GeosSerde::GetRequiredSize(ctx, raw);
// Allocate a blob of the correct size
auto blob = StringVector::EmptyString(result, size);
const auto ptr = blob.GetDataWriteable();
// Serialize the geometry into the blob
GeosSerde::Serialize(ctx, raw, ptr, size);
// Finalize and return the blob
blob.Finalize();
return blob;
}
GeosGeometry LocalState::Deserialize(const string_t &blob) {
const auto blob_ptr = blob.GetData();
const auto blob_len = blob.GetSize();
const auto geom = GeosSerde::Deserialize(ctx, arena, blob_ptr, blob_len);
if (geom == nullptr) {
throw InvalidInputException("Could not deserialize geometry");
}
return GeosGeometry(ctx, geom);
}
} // namespace
//------------------------------------------------------------------------------
// Base Functions
//------------------------------------------------------------------------------
namespace {
template <class IMPL, class RETURN_TYPE = bool>
class SymmetricPreparedBinaryFunction {
public:
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
auto &lhs_vec = args.data[0];
auto &rhs_vec = args.data[1];
const auto lhs_is_const =
lhs_vec.GetVectorType() == VectorType::CONSTANT_VECTOR && !ConstantVector::IsNull(lhs_vec);
const auto rhs_is_const =
rhs_vec.GetVectorType() == VectorType::CONSTANT_VECTOR && !ConstantVector::IsNull(rhs_vec);
if (lhs_is_const && rhs_is_const) {
// Both are const, just execute once
result.SetVectorType(VectorType::CONSTANT_VECTOR);
const auto &lhs_blob = ConstantVector::GetData<string_t>(lhs_vec)[0];
const auto &rhs_blob = ConstantVector::GetData<string_t>(rhs_vec)[0];
const auto lhs_geom = lstate.Deserialize(lhs_blob);
const auto rhs_geom = lstate.Deserialize(rhs_blob);
ConstantVector::GetData<RETURN_TYPE>(result)[0] = IMPL::ExecutePredicateNormal(lhs_geom, rhs_geom);
} else if (lhs_is_const != rhs_is_const) {
// One of the two is const, prepare the const one and execute on the non-const one
auto &const_vec = lhs_is_const ? lhs_vec : rhs_vec;
auto &probe_vec = lhs_is_const ? rhs_vec : lhs_vec;
const auto &const_blob = ConstantVector::GetData<string_t>(const_vec)[0];
const auto const_geom = lstate.Deserialize(const_blob);
const auto const_prep = const_geom.get_prepared();
UnaryExecutor::Execute<string_t, RETURN_TYPE>(
probe_vec, result, args.size(), [&](const string_t &probe_blob) {
const auto probe_geom = lstate.Deserialize(probe_blob);
return IMPL::ExecutePredicatePrepared(const_prep, probe_geom);
});
} else {
// Both are non-const, just execute normally
BinaryExecutor::Execute<string_t, string_t, RETURN_TYPE>(
lhs_vec, rhs_vec, result, args.size(), [&](const string_t &lhs_blob, const string_t &rhs_blob) {
const auto lhs = lstate.Deserialize(lhs_blob);
const auto rhs = lstate.Deserialize(rhs_blob);
return IMPL::ExecutePredicateNormal(lhs, rhs);
});
}
}
};
template <class IMPL, class RETURN_TYPE = bool>
class AsymmetricPreparedBinaryFunction {
public:
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
auto &lhs_vec = args.data[0];
auto &rhs_vec = args.data[1];
const auto lhs_is_const =
lhs_vec.GetVectorType() == VectorType::CONSTANT_VECTOR && !ConstantVector::IsNull(lhs_vec);
const auto rhs_is_const =
rhs_vec.GetVectorType() == VectorType::CONSTANT_VECTOR && !ConstantVector::IsNull(rhs_vec);
if (lhs_is_const && rhs_is_const) {
// Both are const, just execute once
result.SetVectorType(VectorType::CONSTANT_VECTOR);
const auto &lhs_blob = ConstantVector::GetData<string_t>(lhs_vec)[0];
const auto &rhs_blob = ConstantVector::GetData<string_t>(rhs_vec)[0];
const auto lhs_geom = lstate.Deserialize(lhs_blob);
const auto rhs_geom = lstate.Deserialize(rhs_blob);
ConstantVector::GetData<RETURN_TYPE>(result)[0] = IMPL::ExecutePredicateNormal(lhs_geom, rhs_geom);
} else if (lhs_is_const) {
// Prepare the left const and run on the non-const right
// Because this predicate is not symmetric, we can't just swap the two, so we only prepare the left
const auto lhs_blob = ConstantVector::GetData<string_t>(lhs_vec)[0];
const auto lhs_geom = lstate.Deserialize(lhs_blob);
const auto lhs_prep = lhs_geom.get_prepared();
UnaryExecutor::Execute<string_t, RETURN_TYPE>(rhs_vec, result, args.size(), [&](const string_t &rhs_blob) {
const auto rhs_geom = lstate.Deserialize(rhs_blob);
return IMPL::ExecutePredicatePrepared(lhs_prep, rhs_geom);
});
} else {
// Both are non-const, just execute normally
BinaryExecutor::Execute<string_t, string_t, RETURN_TYPE>(
lhs_vec, rhs_vec, result, args.size(), [&](const string_t &lhs_blob, const string_t &rhs_blob) {
const auto lhs = lstate.Deserialize(lhs_blob);
const auto rhs = lstate.Deserialize(rhs_blob);
return IMPL::ExecutePredicateNormal(lhs, rhs);
});
}
}
};
} // namespace
//------------------------------------------------------------------------------
// Functions
//------------------------------------------------------------------------------
namespace {
//======================================================================================================================
// ST_AsMVTGeom
//======================================================================================================================
struct ST_AsMVTGeom {
//------------------------------------------------------------------------------------------------------------------
// Bind
//------------------------------------------------------------------------------------------------------------------
struct BindData final : FunctionData {
int32_t extent = 4096;
int32_t buffer = 256;
bool clip = true;
unique_ptr<FunctionData> Copy() const override {
auto result = make_uniq<BindData>();
result->extent = extent;
result->buffer = buffer;
result->clip = clip;
return std::move(result);
}
bool Equals(const FunctionData &other_p) const override {
auto &other = other_p.Cast<BindData>();
return extent == other.extent && buffer == other.buffer && clip == other.clip;
}
};
static unique_ptr<FunctionData> Bind(ClientContext &context, ScalarFunction &bound_function,
vector<unique_ptr<Expression>> &arguments) {
auto result = make_uniq<BindData>();
// Extract parameters
auto folded_extent = false;
auto folded_buffer = false;
auto folded_clip = false;
if (arguments.size() >= 3) {
auto &extent_expr = arguments[2];
if (extent_expr->IsFoldable()) {
auto extent_val = ExpressionExecutor::EvaluateScalar(context, *extent_expr);
result->extent = extent_val.GetValue<int32_t>();
folded_extent = true;
} else {
throw InvalidInputException("ST_AsMVTGeom: \"tile_extent\" must be a constant");
}
}
if (arguments.size() >= 4) {
auto &buffer_expr = arguments[3];
if (buffer_expr->IsFoldable()) {
auto buffer_val = ExpressionExecutor::EvaluateScalar(context, *buffer_expr);
result->buffer = buffer_val.GetValue<int32_t>();
folded_buffer = true;
} else {
throw InvalidInputException("ST_AsMVTGeom: \"buffer\" must be a constant");
}
}
if (arguments.size() == 5) {
auto &clip_geom_expr = arguments[4];
if (clip_geom_expr->IsFoldable()) {
auto clip_geom_val = ExpressionExecutor::EvaluateScalar(context, *clip_geom_expr);
result->clip = clip_geom_val.GetValue<bool>();
folded_clip = true;
} else {
throw InvalidInputException("ST_AsMVTGeom: \"clip_geom\" must be a constant");
}
}
// Erase back to front
if (folded_clip) {
Function::EraseArgument(bound_function, arguments, 4);
}
if (folded_buffer) {
Function::EraseArgument(bound_function, arguments, 3);
}
if (folded_extent) {
Function::EraseArgument(bound_function, arguments, 2);
}
return std::move(result);
}
//------------------------------------------------------------------------------------------------------------------
// Execute
//------------------------------------------------------------------------------------------------------------------
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
// Bind data
const auto &func_expr = state.expr.Cast<BoundFunctionExpression>();
const auto &bind_data = func_expr.bind_info->Cast<BindData>();
// Local state
auto &lstate = LocalState::ResetAndGet(state);
UnifiedVectorFormat geom_format;
UnifiedVectorFormat bbox_format;
UnifiedVectorFormat minx_format;
UnifiedVectorFormat miny_format;
UnifiedVectorFormat maxx_format;
UnifiedVectorFormat maxy_format;
args.data[0].ToUnifiedFormat(args.size(), geom_format);
args.data[1].ToUnifiedFormat(args.size(), bbox_format);
const auto &bbox_parts = StructVector::GetEntries(args.data[1]);
bbox_parts[0]->ToUnifiedFormat(args.size(), minx_format);
bbox_parts[1]->ToUnifiedFormat(args.size(), miny_format);
bbox_parts[2]->ToUnifiedFormat(args.size(), maxx_format);
bbox_parts[3]->ToUnifiedFormat(args.size(), maxy_format);
const auto geom_data = UnifiedVectorFormat::GetData<string_t>(geom_format);
const auto minx_data = UnifiedVectorFormat::GetData<double>(minx_format);
const auto miny_data = UnifiedVectorFormat::GetData<double>(miny_format);
const auto maxx_data = UnifiedVectorFormat::GetData<double>(maxx_format);
const auto maxy_data = UnifiedVectorFormat::GetData<double>(maxy_format);
const auto res_data = FlatVector::GetData<string_t>(result);
for (idx_t out_idx = 0; out_idx < args.size(); out_idx++) {
const auto geom_idx = geom_format.sel->get_index(out_idx);
const auto bbox_idx = bbox_format.sel->get_index(out_idx);
const auto minx_idx = minx_format.sel->get_index(bbox_idx);
const auto miny_idx = miny_format.sel->get_index(bbox_idx);
const auto maxx_idx = maxx_format.sel->get_index(bbox_idx);
const auto maxy_idx = maxy_format.sel->get_index(bbox_idx);
if (!geom_format.validity.RowIsValid(geom_idx) || !bbox_format.validity.RowIsValid(bbox_idx) ||
!minx_format.validity.RowIsValid(minx_idx) || !miny_format.validity.RowIsValid(miny_idx) ||
!maxx_format.validity.RowIsValid(maxx_idx) || !maxy_format.validity.RowIsValid(maxy_idx)) {
FlatVector::SetNull(result, out_idx, true);
}
const auto &blob = geom_data[geom_idx];
auto geom = lstate.Deserialize(blob);
// Compute bounds
const auto extent = bind_data.extent;
const auto minx = minx_data[minx_idx];
const auto miny = miny_data[miny_idx];
const auto maxx = maxx_data[maxx_idx];
const auto maxy = maxy_data[maxy_idx];
const auto tile_w = maxx - minx;
const auto tile_h = maxy - miny;
if (tile_w <= 0 || tile_h <= 0) {
throw InvalidInputException("ST_AsMVTGeom: tile width and height must be positive");
}
// Note: Y-axis is flipped in MVT coordinate system
const auto scale_x = extent / tile_w;
const auto scale_y = -(extent / tile_h);
// Create transformation: translate to origin, then scale to tile extent
const double affine_matrix[6] = {
scale_x, // a: x scale
0.0, // b: x skew
0.0, // c: y skew
scale_y, // d: y scale (negative for flip)
-minx * scale_x, // e: x translation
-maxy * scale_y // f: y translation (with flip adjustment)
};
// Apply transformation
const auto transformed = geom.get_transformed(affine_matrix);
// Snap to grid (round coordinates to integers)
auto snapped = transformed.get_gridded(1.0);
// Should we clip? if not, return the snapped geometry
if (!bind_data.clip) {
// But first orient in place
snapped.orient_polygons(true);
res_data[out_idx] = lstate.Serialize(result, snapped);
continue;
}
// Apply buffer and clip if specified
const auto clip_minx = -bind_data.buffer;
const auto clip_miny = -bind_data.buffer;
const auto clip_maxx = extent + bind_data.buffer;
const auto clip_maxy = extent + bind_data.buffer;
const auto clipped = snapped.get_clipped(clip_minx, clip_miny, clip_maxx, clip_maxy);
if (clipped.is_empty()) {
FlatVector::SetNull(result, out_idx, true);
continue;
}
// Snap again to clean up any potential issues from clipping
auto cleaned_clipped = clipped.get_gridded(1.0);
// Also orient the polygons in place
cleaned_clipped.orient_polygons(true);
res_data[out_idx] = lstate.Serialize(result, cleaned_clipped);
}
}
//------------------------------------------------------------------------------------------------------------------
// Register
//------------------------------------------------------------------------------------------------------------------
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_AsMVTGeom", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("bounds", GeoTypes::BOX_2D());
variant.AddParameter("extent", LogicalType::BIGINT);
variant.AddParameter("buffer", LogicalType::BIGINT);
variant.AddParameter("clip_geom", LogicalType::BOOLEAN);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
variant.SetBind(Bind);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("bounds", GeoTypes::BOX_2D());
variant.AddParameter("extent", LogicalType::BIGINT);
variant.AddParameter("buffer", LogicalType::BIGINT);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
variant.SetBind(Bind);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("bounds", GeoTypes::BOX_2D());
variant.AddParameter("extent", LogicalType::BIGINT);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
variant.SetBind(Bind);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("bounds", GeoTypes::BOX_2D());
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
variant.SetBind(Bind);
});
func.SetDescription(R"(
Transform and clip geometry to a tile boundary
See "ST_AsMVT" for more details)");
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_Boundary {
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
UnaryExecutor::ExecuteWithNulls<string_t, string_t>(
args.data[0], result, args.size(), [&](const string_t &geom_blob, ValidityMask &mask, idx_t row_idx) {
const auto geom = lstate.Deserialize(geom_blob);
if (geom.type() == GEOS_GEOMETRYCOLLECTION) {
mask.SetInvalid(row_idx);
return string_t {};
}
const auto boundary = geom.get_boundary();
return lstate.Serialize(result, boundary);
});
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_Boundary", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription("Returns the \"boundary\" of a geometry");
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_Buffer {
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
BinaryExecutor::Execute<string_t, double, string_t>(args.data[0], args.data[1], result, args.size(),
[&](const string_t &blob, double radius) {
const auto geom = lstate.Deserialize(blob);
const auto buffer = geom.get_buffer(radius, 8);
return lstate.Serialize(result, buffer);
});
}
static void ExecuteWithSegments(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
TernaryExecutor::Execute<string_t, double, int32_t, string_t>(
args.data[0], args.data[1], args.data[2], result, args.size(),
[&](const string_t &blob, double radius, int32_t segments) {
const auto geom = lstate.Deserialize(blob);
const auto buffer = geom.get_buffer(radius, segments);
return lstate.Serialize(result, buffer);
});
}
template <class T>
static T TryParseStringArgument(const char *name, const vector<string> &keys, const vector<T> &values,
const string_t &arg) {
D_ASSERT(keys.size() == values.size());
for (idx_t i = 0; i < keys.size(); i++) {
if (StringUtil::CIEquals(keys[i], arg.GetString())) {
return values[i];
}
}
auto candidates = StringUtil::Join(keys, ", ");
throw InvalidInputException("Unknown %s: '%s', accepted inputs: %s", name, arg.GetString().c_str(),
candidates.c_str());
}
static void ExecuteWithStyle(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
SenaryExecutor::Execute<string_t, double, int32_t, string_t, string_t, double, string_t>(
args, result,
[&](const string_t &blob, double radius, int32_t segments, const string_t &cap_style_str,
const string_t &join_style_str, double mitre_limit) {
const auto geom = lstate.Deserialize(blob);
const auto cap_style = TryParseStringArgument<GEOSBufCapStyles>(
"cap style", {"CAP_ROUND", "CAP_FLAT", "CAP_SQUARE"},
{GEOSBUF_CAP_ROUND, GEOSBUF_CAP_FLAT, GEOSBUF_CAP_SQUARE}, cap_style_str);
const auto join_style = TryParseStringArgument<GEOSBufJoinStyles>(
"join style", {"JOIN_ROUND", "JOIN_MITRE", "JOIN_BEVEL"},
{GEOSBUF_JOIN_ROUND, GEOSBUF_JOIN_MITRE, GEOSBUF_JOIN_BEVEL}, join_style_str);
const auto buffer = geom.get_buffer_style(radius, segments, cap_style, join_style, mitre_limit);
return lstate.Serialize(result, buffer);
});
}
static constexpr auto DESCRIPTION = R"(
Returns a buffer around the input geometry at the target distance
`geom` is the input geometry.
`distance` is the target distance for the buffer, using the same units as the input geometry.
`num_triangles` represents how many triangles that will be produced to approximate a quarter circle. The larger the number, the smoother the resulting geometry. The default value is 8.
`cap_style` must be one of "CAP_ROUND", "CAP_FLAT", "CAP_SQUARE". This parameter is case-insensitive.
`join_style` must be one of "JOIN_ROUND", "JOIN_MITRE", "JOIN_BEVEL". This parameter is case-insensitive.
`mitre_limit` only applies when `join_style` is "JOIN_MITRE". It is the ratio of the distance from the corner to the mitre point to the corner radius. The default value is 1.0.
This is a planar operation and will not take into account the curvature of the earth.
)";
static constexpr auto EXAMPLE = "";
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_Buffer", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("distance", LogicalType::DOUBLE);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("distance", LogicalType::DOUBLE);
variant.AddParameter("num_triangles", LogicalType::INTEGER);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(ExecuteWithSegments);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("distance", LogicalType::DOUBLE);
variant.AddParameter("num_triangles", LogicalType::INTEGER);
variant.AddParameter("cap_style", LogicalType::VARCHAR);
variant.AddParameter("join_style", LogicalType::VARCHAR);
variant.AddParameter("mitre_limit", LogicalType::DOUBLE);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(ExecuteWithStyle);
});
func.SetDescription(DESCRIPTION);
func.SetExample(EXAMPLE);
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_BuildArea {
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
UnaryExecutor::Execute<string_t, string_t>(args.data[0], result, args.size(), [&](const string_t &geom_blob) {
const auto geom = lstate.Deserialize(geom_blob);
const auto area = geom.get_built_area();
return lstate.Serialize(result, area);
});
}
static constexpr auto DESCRIPTION = R"(
Creates a polygonal geometry by attempting to "fill in" the input geometry.
Unlike ST_Polygonize, this function does not fill in holes.)";
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_BuildArea", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription(DESCRIPTION);
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_Contains : AsymmetricPreparedBinaryFunction<ST_Contains> {
static bool ExecutePredicateNormal(const GeosGeometry &lhs, const GeosGeometry &rhs) {
return lhs.contains(rhs);
}
static bool ExecutePredicatePrepared(const PreparedGeosGeometry &lhs, const GeosGeometry &rhs) {
return lhs.contains(rhs);
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_Contains", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom1", LogicalType::GEOMETRY());
variant.AddParameter("geom2", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::BOOLEAN);
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription(R"(
Returns true if the first geometry contains the second geometry
In contrast to `ST_ContainsProperly`, this function will also return true if `geom2` is contained strictly on the boundary of `geom1`.
A geometry always `ST_Contains` itself, but does not `ST_ContainsProperly` itself.
)");
func.SetTag("ext", "spatial");
func.SetTag("category", "relation");
});
}
};
struct ST_ContainsProperly : AsymmetricPreparedBinaryFunction<ST_ContainsProperly> {
static bool ExecutePredicateNormal(const GeosGeometry &lhs, const GeosGeometry &rhs) {
// We have no choice but to prepare the left geometry
const auto lhs_prep = lhs.get_prepared();
return lhs_prep.contains_properly(rhs);
}
static bool ExecutePredicatePrepared(const PreparedGeosGeometry &lhs, const GeosGeometry &rhs) {
return lhs.contains_properly(rhs);
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_ContainsProperly", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom1", LogicalType::GEOMETRY());
variant.AddParameter("geom2", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::BOOLEAN);
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription(R"(
Returns true if the first geometry \"properly\" contains the second geometry
In contrast to `ST_Contains`, this function does not return true if `geom2` is contained strictly on the boundary of `geom1`.
A geometry always `ST_Contains` itself, but does not `ST_ContainsProperly` itself.
)");
func.SetTag("ext", "spatial");
func.SetTag("category", "relation");
});
}
};
struct ST_WithinProperly : AsymmetricPreparedBinaryFunction<ST_WithinProperly> {
static bool ExecutePredicateNormal(const GeosGeometry &lhs, const GeosGeometry &rhs) {
// We have no choice but to prepare the right geometry
const auto rhs_prep = rhs.get_prepared();
return rhs_prep.contains_properly(lhs);
}
static bool ExecutePredicatePrepared(const PreparedGeosGeometry &lhs, const GeosGeometry &rhs) {
return lhs.contains_properly(rhs);
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_WithinProperly", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom1", LogicalType::GEOMETRY());
variant.AddParameter("geom2", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::BOOLEAN);
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription(R"(
Returns true if the first geometry \"properly\" is contained by the second geometry
This function functions the same as `ST_ContainsProperly`, but the arguments are swapped.
)");
func.SetTag("ext", "spatial");
func.SetTag("category", "relation");
});
}
};
struct ST_ConcaveHull {
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
TernaryExecutor::Execute<string_t, double, bool, string_t>(
args.data[0], args.data[1], args.data[2], result, args.size(),
[&](const string_t &geom_blob, const double ratio, const bool allowHoles) {
const auto geom = lstate.Deserialize(geom_blob);
const auto hull = geom.get_concave_hull(ratio, allowHoles);
return lstate.Serialize(result, hull);
});
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_ConcaveHull", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.AddParameter("ratio", LogicalType::DOUBLE);
variant.AddParameter("allowHoles", LogicalType::BOOLEAN);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription(
"Returns the 'concave' hull of the input geometry, containing all of the source input's points, and "
"which can be used to create polygons from points. The ratio parameter dictates the level of "
"concavity; 1.0 returns the convex hull; and 0 indicates to return the most concave hull possible. Set "
"allowHoles to a non-zero value to allow output containing holes.");
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_ConvexHull {
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
UnaryExecutor::Execute<string_t, string_t>(args.data[0], result, args.size(), [&](const string_t &geom_blob) {
const auto geom = lstate.Deserialize(geom_blob);
const auto hull = geom.get_convex_hull();
return lstate.Serialize(result, hull);
});
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_ConvexHull", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geom", LogicalType::GEOMETRY());
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.SetDescription("Returns the convex hull enclosing the geometry");
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_CoverageInvalidEdges {
static unique_ptr<FunctionData> Bind(ClientContext &context, ScalarFunction &bound_function,
vector<unique_ptr<Expression>> &arguments) {
// Set the default value for the tolerance parameter
if (arguments.size() == 1) {
arguments.push_back(make_uniq_base<Expression, BoundConstantExpression>(Value::DOUBLE(0)));
}
return nullptr;
}
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
UnifiedVectorFormat format;
auto &list_vec = args.data[0];
auto &item_vec = ListVector::GetEntry(list_vec);
item_vec.ToUnifiedFormat(ListVector::GetListSize(list_vec), format);
// Collection to hold the working set of geometries
GeosCollection collection(lstate.GetContext());
BinaryExecutor::ExecuteWithNulls<list_entry_t, double, string_t>(
list_vec, args.data[1], result, args.size(),
[&](const list_entry_t &list, double tolerance, ValidityMask &mask, idx_t row_idx) {
// Reset the collection
collection.clear();
collection.reserve(list.length);
const auto offset = list.offset;
const auto length = list.length;
// Collect all geometries in the list into the collection
for (idx_t i = offset; i < offset + length; i++) {
const auto mapped_idx = format.sel->get_index(i);
if (!format.validity.RowIsValid(mapped_idx)) {
continue;
}
const auto &geom_blob = UnifiedVectorFormat::GetData<string_t>(format)[mapped_idx];
auto geom = lstate.Deserialize(geom_blob);
collection.add(std::move(geom));
}
// Now make a geometrycollection and get the invalid edges
const auto geometry_col = collection.get_collection();
const auto invalid = geometry_col.get_coverage_invalid_edges(tolerance);
if (invalid.is_empty()) {
mask.SetInvalid(row_idx);
return string_t {};
}
return lstate.Serialize(result, invalid);
});
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_CoverageInvalidEdges", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geoms", LogicalType::LIST(LogicalType::GEOMETRY()));
variant.AddParameter("tolerance", LogicalType::DOUBLE);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geoms", LogicalType::LIST(LogicalType::GEOMETRY()));
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetBind(Bind);
variant.SetFunction(Execute);
});
func.SetDescription(R"(
Returns the invalid edges in a polygonal coverage, which are edges that are not shared by two polygons.
Returns NULL if the input is not a polygonal coverage, or if the input is valid.
Tolerance is 0 by default.
)");
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_CoverageSimplify {
static unique_ptr<FunctionData> Bind(ClientContext &context, ScalarFunction &bound_function,
vector<unique_ptr<Expression>> &arguments) {
// Set the default value for the simplify_boundary parameter
if (arguments.size() == 2) {
arguments.push_back(make_uniq_base<Expression, BoundConstantExpression>(Value::BOOLEAN(true)));
}
return nullptr;
}
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);
UnifiedVectorFormat format;
auto &list_vec = args.data[0];
auto &item_vec = ListVector::GetEntry(list_vec);
item_vec.ToUnifiedFormat(ListVector::GetListSize(list_vec), format);
// Collection to hold the working set of geometries
GeosCollection collection(lstate.GetContext());
TernaryExecutor::Execute<list_entry_t, double, bool, string_t>(
list_vec, args.data[1], args.data[2], result, args.size(),
[&](const list_entry_t &list, double tolerance, bool simplify_boundary) {
// Reset the collection
collection.clear();
collection.reserve(list.length);
const auto offset = list.offset;
const auto length = list.length;
// Collect all geometries in the list into the collection
for (idx_t i = offset; i < offset + length; i++) {
const auto mapped_idx = format.sel->get_index(i);
if (!format.validity.RowIsValid(mapped_idx)) {
continue;
}
const auto &geom_blob = UnifiedVectorFormat::GetData<string_t>(format)[mapped_idx];
auto geom = lstate.Deserialize(geom_blob);
collection.add(std::move(geom));
}
// Now make a geometrycollection and simplify
const auto geometry_col = collection.get_collection();
const auto simplified = geometry_col.get_coverage_simplified(tolerance, !simplify_boundary);
return lstate.Serialize(result, simplified);
});
}
static void Register(ExtensionLoader &loader) {
FunctionBuilder::RegisterScalar(loader, "ST_CoverageSimplify", [](ScalarFunctionBuilder &func) {
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geoms", LogicalType::LIST(LogicalType::GEOMETRY()));
variant.AddParameter("tolerance", LogicalType::DOUBLE);
variant.AddParameter("simplify_boundary", LogicalType::BOOLEAN);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetFunction(Execute);
});
func.AddVariant([](ScalarFunctionVariantBuilder &variant) {
variant.AddParameter("geoms", LogicalType::LIST(LogicalType::GEOMETRY()));
variant.AddParameter("tolerance", LogicalType::DOUBLE);
variant.SetReturnType(LogicalType::GEOMETRY());
variant.SetInit(LocalState::Init);
variant.SetBind(Bind);
variant.SetFunction(Execute);
});
func.SetDescription(R"(
Simplify the edges in a polygonal coverage, preserving the coverange by ensuring that the there are no seams between the resulting simplified polygons.
By default, the boundary of the coverage is also simplified, but this can be controlled with the optional third 'simplify_boundary' parameter.
)");
func.SetTag("ext", "spatial");
func.SetTag("category", "construction");
});
}
};
struct ST_CoverageUnion {
static void Execute(DataChunk &args, ExpressionState &state, Vector &result) {
auto &lstate = LocalState::ResetAndGet(state);