-
-
Notifications
You must be signed in to change notification settings - Fork 477
Expand file tree
/
Copy pathoutput-flex.cpp
More file actions
1513 lines (1251 loc) · 47.8 KB
/
output-flex.cpp
File metadata and controls
1513 lines (1251 loc) · 47.8 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
/**
* SPDX-License-Identifier: GPL-2.0-or-later
*
* This file is part of osm2pgsql (https://osm2pgsql.org/).
*
* Copyright (C) 2006-2026 by the osm2pgsql developer community.
* For a full list of authors see the git log.
*/
#include "output-flex.hpp"
#include "db-copy.hpp"
#include "debug-output.hpp"
#include "expire-output.hpp"
#include "expire-tiles.hpp"
#include "flex-lua-expire-output.hpp"
#include "flex-lua-geom.hpp"
#include "flex-lua-index.hpp"
#include "flex-lua-locator.hpp"
#include "flex-lua-table.hpp"
#include "flex-write.hpp"
#include "format.hpp"
#include "geom-from-osm.hpp"
#include "logging.hpp"
#include "lua-init.hpp"
#include "lua-setup.hpp"
#include "lua-utils.hpp"
#include "middle.hpp"
#include "options.hpp"
#include "osmtypes.hpp"
#include "pgsql-capabilities.hpp"
#include "pgsql.hpp"
#include "projection.hpp"
#include "properties.hpp"
#include "reprojection.hpp"
#include "thread-pool.hpp"
#include "util.hpp"
#include "wkb.hpp"
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <mutex>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
namespace {
// Mutex used to coordinate access to Lua code
std::mutex lua_mutex;
// Lua can't call functions on C++ objects directly. This macro defines simple
// C "trampoline" functions which are called from Lua which get the current
// context (the output_flex_t object) and call the respective function on the
// context object.
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define TRAMPOLINE(func_name, lua_name) \
int lua_trampoline_##func_name(lua_State *lua_state) \
{ \
try { \
return static_cast<output_flex_t *>(luaX_get_context(lua_state)) \
->func_name(); \
} catch (std::exception const &e) { \
return luaL_error(lua_state, "Error in '" #lua_name "': %s\n", \
e.what()); \
} catch (...) { \
return luaL_error(lua_state, \
"Unknown error in '" #lua_name "'.\n"); \
} \
}
TRAMPOLINE(app_define_locator, define_locator)
TRAMPOLINE(app_define_table, define_table)
TRAMPOLINE(app_define_expire_output, define_expire_output)
TRAMPOLINE(app_get_bbox, get_bbox)
TRAMPOLINE(app_as_point, as_point)
TRAMPOLINE(app_as_linestring, as_linestring)
TRAMPOLINE(app_as_polygon, as_polygon)
TRAMPOLINE(app_as_multipoint, as_multipoint)
TRAMPOLINE(app_as_multilinestring, as_multilinestring)
TRAMPOLINE(app_as_multipolygon, as_multipolygon)
TRAMPOLINE(app_as_geometrycollection, as_geometrycollection)
} // anonymous namespace
TRAMPOLINE(table_insert, insert)
prepared_lua_function_t::prepared_lua_function_t(lua_State *lua_state,
calling_context context,
char const *name, int nresults)
{
int const index = lua_gettop(lua_state);
lua_getfield(lua_state, 1, name);
if (lua_type(lua_state, -1) == LUA_TFUNCTION) {
m_index = index;
m_name = name;
m_nresults = nresults;
m_calling_context = context;
return;
}
if (lua_type(lua_state, -1) == LUA_TNIL) {
return;
}
throw fmt_error("osm2pgsql.{} must be a function.", name);
}
namespace {
char const *const OSM2PGSQL_OSMOBJECT_CLASS = "osm2pgsql.OSMObject";
void push_osm_object_to_lua_stack(lua_State *lua_state,
osmium::OSMObject const &object)
{
assert(lua_state);
/**
* Table will always have at least 8 fields (id, type, tags, version,
* timestamp, changeset, uid, user). For ways there are 2 more (is_closed,
* nodes), for relations 1 more (members).
*/
constexpr int MAX_TABLE_SIZE = 10;
lua_createtable(lua_state, 0, MAX_TABLE_SIZE);
luaX_add_table_int(lua_state, "id", object.id());
luaX_add_table_str(lua_state, "type",
osmium::item_type_to_name(object.type()));
if (object.version() != 0U) {
luaX_add_table_int(lua_state, "version", object.version());
}
if (object.timestamp().valid()) {
luaX_add_table_int(lua_state, "timestamp",
object.timestamp().seconds_since_epoch());
}
if (object.changeset() != 0U) {
luaX_add_table_int(lua_state, "changeset", object.changeset());
}
if (object.uid() != 0U) {
luaX_add_table_int(lua_state, "uid", object.uid());
}
if (object.user()[0] != '\0') {
luaX_add_table_str(lua_state, "user", object.user());
}
if (!object.deleted()) {
if (object.type() == osmium::item_type::way) {
auto const &way = static_cast<osmium::Way const &>(object);
luaX_add_table_bool(lua_state, "is_closed",
!way.nodes().empty() && way.is_closed());
luaX_add_table_array(lua_state, "nodes", way.nodes(),
[&](osmium::NodeRef const &wn) {
lua_pushinteger(lua_state, wn.ref());
});
} else if (object.type() == osmium::item_type::relation) {
auto const &relation =
static_cast<osmium::Relation const &>(object);
luaX_add_table_array(
lua_state, "members", relation.members(),
[&](osmium::RelationMember const &member) {
lua_createtable(lua_state, 0, 3);
std::array<char, 2> tmp{"x"};
tmp[0] = osmium::item_type_to_char(member.type());
luaX_add_table_str(lua_state, "type", tmp.data());
luaX_add_table_int(lua_state, "ref", member.ref());
luaX_add_table_str(lua_state, "role", member.role());
});
}
lua_pushliteral(lua_state, "tags");
lua_createtable(lua_state, 0, (int)object.tags().size());
for (auto const &tag : object.tags()) {
luaX_add_table_str(lua_state, tag.key(), tag.value());
}
lua_rawset(lua_state, -3);
// Set the metatable of this object
lua_pushstring(lua_state, OSM2PGSQL_OSMOBJECT_CLASS);
lua_gettable(lua_state, LUA_REGISTRYINDEX);
lua_setmetatable(lua_state, -2);
}
}
/**
* Helper function to push the lon/lat of the specified location onto the
* Lua stack
*/
void push_location(lua_State *lua_state, osmium::Location location) noexcept
{
lua_pushnumber(lua_state, location.lon());
lua_pushnumber(lua_state, location.lat());
}
// Check that the first element on the Lua stack is a "type_name"
// parameter and return its internal index.
std::size_t idx_from_param(lua_State *lua_state, char const *type_name)
{
assert(lua_gettop(lua_state) >= 1);
void const *const user_data = lua_touserdata(lua_state, 1);
if (user_data == nullptr || !lua_getmetatable(lua_state, 1)) {
throw fmt_error("First parameter must be of type {}.", type_name);
}
luaL_getmetatable(lua_state, type_name);
if (!lua_rawequal(lua_state, -1, -2)) {
throw fmt_error("First parameter must be of type {}.", type_name);
}
lua_pop(lua_state, 2); // remove the two metatables
return *static_cast<std::size_t const *>(user_data);
}
template <typename CONTAINER>
typename CONTAINER::value_type &get_from_idx_param(lua_State *lua_state,
CONTAINER *container,
char const *type_name)
{
if (lua_gettop(lua_state) < 1) {
throw fmt_error("Argument #1 has to be of type {}.", type_name);
}
auto &item = container->at(idx_from_param(lua_state, type_name));
lua_remove(lua_state, 1);
return item;
}
std::size_t get_nodes(middle_query_t const &middle, osmium::Way *way)
{
constexpr std::size_t MAX_MISSING_NODES = 100;
static std::size_t count_missing_nodes = 0;
auto const count = middle.nodes_get_list(&way->nodes());
if (count_missing_nodes <= MAX_MISSING_NODES &&
count != way->nodes().size()) {
util::string_joiner_t id_list{','};
for (auto const &nr : way->nodes()) {
if (!nr.location().valid()) {
id_list.add(fmt::to_string(nr.ref()));
++count_missing_nodes;
}
}
log_debug("Missing nodes in way {}: {}", way->id(), id_list());
if (count_missing_nodes > MAX_MISSING_NODES) {
log_debug("Reported more than {} missing nodes, no further missing "
"nodes will be reported!",
MAX_MISSING_NODES);
}
}
return count;
}
void flush_tables(std::vector<table_connection_t> &table_connections)
{
for (auto &table : table_connections) {
table.flush();
}
}
void create_expire_tables(std::vector<expire_output_t> const &expire_outputs,
connection_params_t const &connection_params)
{
if (std::all_of(expire_outputs.cbegin(), expire_outputs.cend(),
[](auto const &expire_output) {
return expire_output.table().empty();
})) {
return;
}
pg_conn_t const connection{connection_params, "out.flex.expire"};
for (auto const &expire_output : expire_outputs) {
if (!expire_output.table().empty()) {
expire_output.create_output_table(connection);
}
}
}
void check_for_object(lua_State *lua_state, char const *const function_name)
{
// This is used to make sure we are printing warnings only once per
// function name.
static std::set<std::string> message_shown;
if (message_shown.count(function_name)) {
return;
}
int const num_params = lua_gettop(lua_state);
if (num_params == 0) {
log_warn("You should use the syntax 'object:{}()' (with the colon, not "
"a point) to call functions on the OSM object.",
function_name);
message_shown.emplace(function_name);
return;
}
if (lua_getmetatable(lua_state, 1)) {
luaL_getmetatable(lua_state, OSM2PGSQL_OSMOBJECT_CLASS);
if (lua_rawequal(lua_state, -1, -2)) {
lua_pop(lua_state, 2); // remove the two metatables
return;
}
lua_pop(lua_state, 2); // remove the two metatables
}
message_shown.emplace(function_name);
log_warn("First and only parameter for {0}() must be the OSM object. Call "
"it like this: 'object:{0}()'.",
function_name);
}
/**
* Expects a Lua (hash) table on the stack, reads the field with name of the
* 'type' parameter which must be either nil or a Lua (array) table, in which
* case all (integer) ids in that table are reads into the 'ids' out
* parameter.
*/
void get_object_ids(lua_State *lua_state, char const *const type, idlist_t *ids)
{
lua_getfield(lua_state, -1, type);
int const ltype = lua_type(lua_state, -1);
if (ltype == LUA_TNIL) {
lua_pop(lua_state, 1);
return;
}
if (ltype != LUA_TTABLE) {
lua_pop(lua_state, 1);
throw fmt_error(
"Table returned from select_relation_members() contains '{}' "
"field, but it isn't an array table.",
type);
}
if (!luaX_is_array(lua_state)) {
lua_pop(lua_state, 1);
throw fmt_error(
"Table returned from select_relation_members() contains '{}' "
"field, but it isn't an array table.",
type);
}
luaX_for_each(lua_state, [&]() {
osmid_t const id = lua_tointeger(lua_state, -1);
if (id == 0) {
throw fmt_error(
"Table returned from select_relation_members() contains "
"'{}' field, which must contain an array of non-zero "
"integer node ids.",
type);
}
ids->push_back(id);
});
lua_pop(lua_state, 1);
}
} // anonymous namespace
/**
* Helper function checking that Lua function "name" is called in the correct
* context and without parameters.
*/
void output_flex_t::check_context_and_state(char const *name,
char const *context, bool condition)
{
check_for_object(lua_state(), name);
if (condition) {
throw fmt_error(
"The function {}() can only be called (directly or indirectly) "
"from the process_[untagged]_{}() functions.",
name, context);
}
if (lua_gettop(lua_state()) > 1) {
throw fmt_error("No parameter(s) needed for {}().", name);
}
}
int output_flex_t::app_get_bbox()
{
check_context_and_state(
"get_bbox", "node/way/relation",
m_calling_context != calling_context::process_node &&
m_calling_context != calling_context::process_way &&
m_calling_context != calling_context::process_relation);
if (m_calling_context == calling_context::process_node) {
push_location(lua_state(), m_context_node->location());
push_location(lua_state(), m_context_node->location());
return 4;
}
if (m_calling_context == calling_context::process_way) {
m_way_cache.add_nodes(middle());
auto const bbox = m_way_cache.get().envelope();
if (bbox.valid()) {
push_location(lua_state(), bbox.bottom_left());
push_location(lua_state(), bbox.top_right());
return 4;
}
return 0;
}
if (m_calling_context == calling_context::process_relation) {
m_relation_cache.add_members(middle());
osmium::Box bbox;
// Bounding boxes of all the member nodes
for (auto const &node :
m_relation_cache.members_buffer().select<osmium::Node>()) {
bbox.extend(node.location());
}
// Bounding boxes of all the member ways
for (auto const &way :
m_relation_cache.members_buffer().select<osmium::Way>()) {
bbox.extend(way.nodes().envelope());
}
if (bbox.valid()) {
push_location(lua_state(), bbox.bottom_left());
push_location(lua_state(), bbox.top_right());
return 4;
}
}
return 0;
}
int output_flex_t::app_as_point()
{
check_for_object(lua_state(), "as_point");
if (m_calling_context == calling_context::process_node) {
if (lua_gettop(lua_state()) > 1) {
throw fmt_error("No parameter(s) needed for as_point().");
}
auto *geom = create_lua_geometry_object(lua_state());
geom::create_point(geom, *m_context_node);
return 1;
}
if (m_calling_context != calling_context::process_way) {
throw fmt_error(
"The function as_point() can only be called (directly "
"or indirectly) from the process_[untagged]_node/way() functions.");
}
if (lua_gettop(lua_state()) > 2) {
throw fmt_error("Too many arguments for function as_point()");
}
m_way_cache.add_nodes(middle());
auto const &nodes = m_way_cache.get().nodes();
int64_t n = 1; // get first node by default
if (lua_gettop(lua_state()) > 1) {
if (lua_type(lua_state(), 2) != LUA_TNUMBER) {
throw std::runtime_error{
"Argument #1 to 'as_point()' must be an integer."};
}
n = lua_tointeger(lua_state(), 2);
if (n < 0) { // negative index values count from the back
n += static_cast<int64_t>(nodes.size()) + 1;
}
}
auto *geom = create_lua_geometry_object(lua_state());
if (n > 0 && static_cast<std::size_t>(n) <= nodes.size()) {
geom::create_point(geom, nodes[n - 1].location());
} // fall through returning null geometry if 0 or too large or small
return 1;
}
int output_flex_t::app_as_linestring()
{
check_context_and_state("as_linestring", "way",
m_calling_context != calling_context::process_way);
m_way_cache.add_nodes(middle());
auto *geom = create_lua_geometry_object(lua_state());
geom::create_linestring(geom, m_way_cache.get());
return 1;
}
int output_flex_t::app_as_polygon()
{
check_context_and_state("as_polygon", "way",
m_calling_context != calling_context::process_way);
m_way_cache.add_nodes(middle());
auto *geom = create_lua_geometry_object(lua_state());
geom::create_polygon(geom, m_way_cache.get(), &m_area_buffer);
return 1;
}
int output_flex_t::app_as_multipoint()
{
check_context_and_state(
"as_multipoint", "node/relation",
m_calling_context != calling_context::process_node &&
m_calling_context != calling_context::process_relation);
auto *geom = create_lua_geometry_object(lua_state());
if (m_calling_context == calling_context::process_node) {
geom::create_point(geom, *m_context_node);
} else {
m_relation_cache.add_members(middle());
geom::create_multipoint(geom, m_relation_cache.members_buffer());
}
return 1;
}
int output_flex_t::app_as_multilinestring()
{
check_context_and_state("as_multilinestring", "way/relation",
m_calling_context != calling_context::process_way &&
m_calling_context !=
calling_context::process_relation);
if (m_calling_context == calling_context::process_way) {
m_way_cache.add_nodes(middle());
auto *geom = create_lua_geometry_object(lua_state());
geom::create_linestring(geom, m_way_cache.get());
return 1;
}
m_relation_cache.add_members(middle());
auto *geom = create_lua_geometry_object(lua_state());
geom::create_multilinestring(geom, m_relation_cache.members_buffer(),
false);
return 1;
}
int output_flex_t::app_as_multipolygon()
{
check_context_and_state("as_multipolygon", "way/relation",
m_calling_context != calling_context::process_way &&
m_calling_context !=
calling_context::process_relation);
if (m_calling_context == calling_context::process_way) {
m_way_cache.add_nodes(middle());
auto *geom = create_lua_geometry_object(lua_state());
geom::create_polygon(geom, m_way_cache.get(), &m_area_buffer);
return 1;
}
m_relation_cache.add_members(middle());
auto *geom = create_lua_geometry_object(lua_state());
geom::create_multipolygon(geom, m_relation_cache.get(),
m_relation_cache.members_buffer(),
&m_area_buffer);
return 1;
}
int output_flex_t::app_as_geometrycollection()
{
check_context_and_state("as_geometrycollection", "relation",
m_calling_context !=
calling_context::process_relation);
m_relation_cache.add_members(middle());
auto *geom = create_lua_geometry_object(lua_state());
geom::create_collection(geom, m_relation_cache.members_buffer());
return 1;
}
int output_flex_t::app_define_locator()
{
if (m_calling_context != calling_context::main) {
throw std::runtime_error{
"Locators have to be defined in the"
" main Lua code, not in any of the callbacks."};
}
return setup_flex_locator(lua_state(), m_locators.get());
}
int output_flex_t::app_define_table()
{
if (m_calling_context != calling_context::main) {
throw std::runtime_error{
"Database tables have to be defined in the"
" main Lua code, not in any of the callbacks."};
}
return setup_flex_table(lua_state(), m_tables.get(), m_expire_outputs.get(),
get_options()->dbschema,
get_options()->slim && !get_options()->droptemp,
get_options()->append);
}
int output_flex_t::app_define_expire_output()
{
if (m_calling_context != calling_context::main) {
throw std::runtime_error{
"Expire outputs have to be defined in the"
" main Lua code, not in any of the callbacks."};
}
return setup_flex_expire_output(lua_state(), get_options()->dbschema,
m_expire_outputs.get());
}
flex_table_t &output_flex_t::get_table_from_param()
{
return get_from_idx_param(lua_state(), m_tables.get(),
OSM2PGSQL_TABLE_CLASS);
}
expire_output_t &output_flex_t::get_expire_output_from_param()
{
return get_from_idx_param(lua_state(), m_expire_outputs.get(),
OSM2PGSQL_EXPIRE_OUTPUT_CLASS);
}
locator_t &output_flex_t::get_locator_from_param()
{
return get_from_idx_param(lua_state(), m_locators.get(),
OSM2PGSQL_LOCATOR_CLASS);
}
bool output_flex_t::way_cache_t::init(middle_query_t const &middle, osmid_t id)
{
m_buffer.clear();
m_num_way_nodes = std::numeric_limits<std::size_t>::max();
if (!middle.way_get(id, &m_buffer)) {
return false;
}
m_way = &m_buffer.get<osmium::Way>(0);
return true;
}
void output_flex_t::way_cache_t::init(osmium::Way *way)
{
m_buffer.clear();
m_num_way_nodes = std::numeric_limits<std::size_t>::max();
m_way = way;
}
std::size_t output_flex_t::way_cache_t::add_nodes(middle_query_t const &middle)
{
if (m_num_way_nodes == std::numeric_limits<std::size_t>::max()) {
m_num_way_nodes = get_nodes(middle, m_way);
}
return m_num_way_nodes;
}
bool output_flex_t::relation_cache_t::init(middle_query_t const &middle,
osmid_t id)
{
m_relation_buffer.clear();
m_members_buffer.clear();
if (!middle.relation_get(id, &m_relation_buffer)) {
return false;
}
m_relation = &m_relation_buffer.get<osmium::Relation>(0);
return true;
}
void output_flex_t::relation_cache_t::init(osmium::Relation const &relation)
{
m_relation_buffer.clear();
m_members_buffer.clear();
m_relation = &relation;
}
bool output_flex_t::relation_cache_t::add_members(middle_query_t const &middle)
{
if (members_buffer().committed() == 0) {
auto const num_members = middle.rel_members_get(
*m_relation, &m_members_buffer,
osmium::osm_entity_bits::node | osmium::osm_entity_bits::way);
if (num_members == 0) {
return false;
}
for (auto &node : m_members_buffer.select<osmium::Node>()) {
if (!node.location().valid()) {
node.set_location(middle.get_node_location(node.id()));
}
}
for (auto &way : m_members_buffer.select<osmium::Way>()) {
get_nodes(middle, &way);
}
}
return true;
}
osmium::OSMObject const &
output_flex_t::check_and_get_context_object(flex_table_t const &table)
{
if (m_calling_context == calling_context::process_node) {
if (!table.matches_type(osmium::item_type::node)) {
throw fmt_error("Trying to add node to table '{}'.", table.name());
}
return *m_context_node;
}
if (m_calling_context == calling_context::process_way) {
if (!table.matches_type(osmium::item_type::way)) {
throw fmt_error("Trying to add way to table '{}'.", table.name());
}
return m_way_cache.get();
}
assert(m_calling_context == calling_context::process_relation);
if (!table.matches_type(osmium::item_type::relation)) {
throw fmt_error("Trying to add relation to table '{}'.", table.name());
}
return m_relation_cache.get();
}
int output_flex_t::table_insert()
{
if (m_disable_insert) {
return 0;
}
if (m_calling_context != calling_context::process_node &&
m_calling_context != calling_context::process_way &&
m_calling_context != calling_context::process_relation) {
throw std::runtime_error{
"The function insert() can only be called from the "
"process_node/way/relation() functions."};
}
auto const num_params = lua_gettop(lua_state());
if (num_params != 2) {
throw std::runtime_error{
"Need two parameters: The osm2pgsql.Table and the row data."};
}
// The first parameter is the table object.
auto &table_connection = m_table_connections.at(
idx_from_param(lua_state(), OSM2PGSQL_TABLE_CLASS));
// The second parameter must be a Lua table with the contents for the
// fields.
luaL_checktype(lua_state(), 2, LUA_TTABLE);
lua_remove(lua_state(), 1);
auto const &table = table_connection.table();
auto const &object = check_and_get_context_object(table);
osmid_t const id = table.map_id(object.type(), object.id());
table_connection.new_line();
auto *copy_mgr = table_connection.copy_mgr();
try {
for (auto const &column : table_connection.table().columns()) {
if (column.create_only()) {
continue;
}
if (column.type() == table_column_type::id_type) {
copy_mgr->add_column(type_to_char(object.type()));
} else if (column.type() == table_column_type::id_num) {
copy_mgr->add_column(id);
} else {
flex_write_column(lua_state(), copy_mgr, column,
&m_expire_tiles, m_expire_outputs.get());
}
}
table_connection.increment_insert_counter();
} catch (not_null_exception_t const &e) {
copy_mgr->rollback_line();
lua_pushboolean(lua_state(), false);
lua_pushliteral(lua_state(), "null value in not null column.");
luaX_pushstring(lua_state(), e.column().name());
push_osm_object_to_lua_stack(lua_state(), object);
table_connection.increment_not_null_error_counter();
return 4;
}
copy_mgr->finish_line();
lua_pushboolean(lua_state(), true);
return 1;
}
void output_flex_t::call_lua_function(prepared_lua_function_t func)
{
lua_pushvalue(lua_state(), func.index());
if (luaX_pcall(lua_state(), 0, func.nresults())) {
throw fmt_error("Failed to execute Lua function 'osm2pgsql.{}': {}.",
func.name(), lua_tostring(lua_state(), -1));
}
}
void output_flex_t::call_lua_function(prepared_lua_function_t func,
osmium::OSMObject const &object)
{
m_calling_context = func.context();
lua_pushvalue(lua_state(), func.index()); // the function to call
push_osm_object_to_lua_stack(lua_state(), object); // the single argument
luaX_set_context(lua_state(), this);
if (luaX_pcall(lua_state(), 1, func.nresults())) {
throw fmt_error("Failed to execute Lua function 'osm2pgsql.{}': {}.",
func.name(), lua_tostring(lua_state(), -1));
}
m_calling_context = calling_context::main;
}
void output_flex_t::get_mutex_and_call_lua_function(
prepared_lua_function_t func)
{
std::lock_guard<std::mutex> const guard{lua_mutex};
call_lua_function(func);
}
void output_flex_t::get_mutex_and_call_lua_function(
prepared_lua_function_t func, osmium::OSMObject const &object)
{
std::lock_guard<std::mutex> const guard{lua_mutex};
call_lua_function(func, object);
}
void output_flex_t::pending_way(osmid_t id)
{
if (!m_process_way && !m_process_untagged_way) {
return;
}
if (!m_way_cache.init(middle(), id)) {
return;
}
way_delete(id);
auto const &func = m_way_cache.get().tags().empty() ? m_process_untagged_way
: m_process_way;
if (func) {
get_mutex_and_call_lua_function(func, m_way_cache.get());
}
}
void output_flex_t::select_relation_members()
{
if (!m_select_relation_members) {
return;
}
// We can not use get_mutex_and_call_lua_function() here, because we need
// the mutex to stick around as long as we are looking at the Lua stack.
std::lock_guard<std::mutex> const guard{lua_mutex};
call_lua_function(m_select_relation_members, m_relation_cache.get());
// If the function returned nil there is nothing to be marked.
if (lua_type(lua_state(), -1) == LUA_TNIL) {
lua_pop(lua_state(), 1); // return value (nil)
return;
}
if (lua_type(lua_state(), -1) != LUA_TTABLE) {
throw std::runtime_error{"select_relation_members() returned something "
"other than nil or a table."};
}
// We have established that we have a table...
// Get the 'nodes' and 'ways' fields...
get_object_ids(lua_state(), "nodes", m_stage2_node_ids.get());
get_object_ids(lua_state(), "ways", m_stage2_way_ids.get());
lua_pop(lua_state(), 1); // return value (a table)
}
void output_flex_t::select_relation_members(osmid_t id)
{
if (!m_select_relation_members) {
return;
}
if (!m_relation_cache.init(middle(), id)) {
return;
}
select_relation_members();
}
void output_flex_t::process_relation()
{
auto const &func = m_relation_cache.get().tags().empty()
? m_process_untagged_relation
: m_process_relation;
if (func) {
get_mutex_and_call_lua_function(func, m_relation_cache.get());
}
}
void output_flex_t::pending_relation(osmid_t id)
{
if (!m_process_relation && !m_process_untagged_relation &&
!m_select_relation_members) {
return;
}
if (!m_relation_cache.init(middle(), id)) {
return;
}
select_relation_members();
delete_from_tables(osmium::item_type::relation, id);
process_relation();
}
void output_flex_t::pending_relation_stage1c(osmid_t id)
{
if (!m_process_relation && !m_process_untagged_relation) {
return;
}
if (!m_relation_cache.init(middle(), id)) {
return;
}
m_disable_insert = true;
process_relation();
m_disable_insert = false;
}
void output_flex_t::sync()
{
for (auto &table : m_table_connections) {
table.sync();
}
}
void output_flex_t::after_nodes()
{
if (m_after_nodes) {
get_mutex_and_call_lua_function(m_after_nodes);
}
flush_tables(m_table_connections);
}
void output_flex_t::after_ways()
{
if (m_after_ways) {
get_mutex_and_call_lua_function(m_after_ways);
}
flush_tables(m_table_connections);
}
void output_flex_t::after_relations()
{
if (m_after_relations) {
get_mutex_and_call_lua_function(m_after_relations);
}
flush_tables(m_table_connections);