-
-
Notifications
You must be signed in to change notification settings - Fork 472
/
output-flex.cpp
1566 lines (1334 loc) · 51 KB
/
output-flex.cpp
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-2021 by the osm2pgsql developer community.
* For a full list of authors see the git log.
*/
#include "expire-tiles.hpp"
#include "geom-transform.hpp"
#include "logging.hpp"
#include "lua-init.hpp"
#include "lua-utils.hpp"
#include "middle.hpp"
#include "options.hpp"
#include "osmtypes.hpp"
#include "output-flex.hpp"
#include "pgsql.hpp"
#include "reprojection.hpp"
#include "util.hpp"
#include "version.hpp"
#include "wkb.hpp"
#include <osmium/osm/types_from_string.hpp>
extern "C"
{
#include <lauxlib.h>
#include <lualib.h>
}
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
// Mutex used to coordinate access to Lua code
static 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.
#define TRAMPOLINE(func_name, lua_name) \
static 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_table, define_table)
TRAMPOLINE(app_get_bbox, get_bbox)
TRAMPOLINE(table_name, name)
TRAMPOLINE(table_schema, schema)
TRAMPOLINE(table_add_row, add_row)
TRAMPOLINE(table_columns, columns)
TRAMPOLINE(table_tostring, __tostring)
static char const osm2pgsql_table_name[] = "osm2pgsql.table";
static char const osm2pgsql_object_metatable[] = "osm2pgsql.object_metatable";
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 std::runtime_error{"osm2pgsql.{} must be a function."_format(name)};
}
static void push_osm_object_to_lua_stack(lua_State *lua_state,
osmium::OSMObject const &object,
bool with_attributes)
{
assert(lua_state);
/**
* Table will have 7 fields (id, version, timestamp, changeset, uid, user,
* tags) for all object types plus 2 (is_closed, nodes) for ways or 1
* (members) for relations.
*/
constexpr int const max_table_size = 9;
lua_createtable(lua_state, 0, max_table_size);
luaX_add_table_int(lua_state, "id", object.id());
if (with_attributes) {
if (object.version() != 0U) {
luaX_add_table_int(lua_state, "version", object.version());
} else {
// This is a workaround, because the middle will give us the
// attributes as pseudo-tags.
char const *const val = object.tags()["osm_version"];
if (val) {
luaX_add_table_int(lua_state, "version",
osmium::string_to_object_version(val));
}
}
if (object.timestamp().valid()) {
luaX_add_table_int(lua_state, "timestamp",
object.timestamp().seconds_since_epoch());
} else {
// This is a workaround, because the middle will give us the
// attributes as pseudo-tags.
char const *const val = object.tags()["osm_timestamp"];
if (val) {
auto const timestamp = osmium::Timestamp{val};
luaX_add_table_int(lua_state, "timestamp",
timestamp.seconds_since_epoch());
}
}
if (object.changeset() != 0U) {
luaX_add_table_int(lua_state, "changeset", object.changeset());
} else {
char const *const val = object.tags()["osm_changeset"];
// This is a workaround, because the middle will give us the
// attributes as pseudo-tags.
if (val) {
luaX_add_table_int(lua_state, "changeset",
osmium::string_to_changeset_id(val));
}
}
if (object.uid() != 0U) {
luaX_add_table_int(lua_state, "uid", object.uid());
} else {
// This is a workaround, because the middle will give us the
// attributes as pseudo-tags.
char const *const val = object.tags()["osm_uid"];
if (val) {
luaX_add_table_int(lua_state, "uid",
osmium::string_to_uid(val));
}
}
if (object.user()[0] != '\0') {
luaX_add_table_str(lua_state, "user", object.user());
} else {
// This is a workaround, because the middle will give us the
// attributes as pseudo-tags.
char const *const val = object.tags()["osm_user"];
if (val) {
luaX_add_table_str(lua_state, "user", val);
}
}
}
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.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[0]);
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_pushlightuserdata(lua_state, (void *)osm2pgsql_object_metatable);
lua_gettable(lua_state, LUA_REGISTRYINDEX);
lua_setmetatable(lua_state, -2);
}
static int sgn(double val) noexcept
{
if (val > 0) {
return 1;
}
if (val < 0) {
return -1;
}
return 0;
}
static void write_null(db_copy_mgr_t<db_deleter_by_type_and_id_t> *copy_mgr,
flex_table_column_t const &column)
{
if (column.not_null()) {
throw std::runtime_error{
"Can not add NULL to column '{}' declared NOT NULL."_format(
column.name())};
}
copy_mgr->add_null_column();
}
static void write_boolean(db_copy_mgr_t<db_deleter_by_type_and_id_t> *copy_mgr,
flex_table_column_t const &column, char const *str)
{
if ((std::strcmp(str, "yes") == 0) || (std::strcmp(str, "true") == 0) ||
std::strcmp(str, "1") == 0) {
copy_mgr->add_column(true);
return;
}
if ((std::strcmp(str, "no") == 0) || (std::strcmp(str, "false") == 0) ||
std::strcmp(str, "0") == 0) {
copy_mgr->add_column(false);
return;
}
write_null(copy_mgr, column);
}
static void
write_direction(db_copy_mgr_t<db_deleter_by_type_and_id_t> *copy_mgr,
flex_table_column_t const &column, char const *str)
{
if ((std::strcmp(str, "yes") == 0) || (std::strcmp(str, "1") == 0)) {
copy_mgr->add_column(1);
return;
}
if ((std::strcmp(str, "no") == 0) || (std::strcmp(str, "0") == 0)) {
copy_mgr->add_column(0);
return;
}
if (std::strcmp(str, "-1") == 0) {
copy_mgr->add_column(-1);
return;
}
write_null(copy_mgr, column);
}
template <typename T>
void write_integer(db_copy_mgr_t<db_deleter_by_type_and_id_t> *copy_mgr,
flex_table_column_t const &column, char const *str)
{
if (*str == '\0') {
write_null(copy_mgr, column);
return;
}
char *end = nullptr;
errno = 0;
auto const value = std::strtoll(str, &end, 10);
if (errno != 0 || *end != '\0') {
write_null(copy_mgr, column);
return;
}
if (value >= std::numeric_limits<T>::min() &&
value <= std::numeric_limits<T>::max()) {
copy_mgr->add_column(value);
return;
}
write_null(copy_mgr, column);
}
static void write_double(db_copy_mgr_t<db_deleter_by_type_and_id_t> *copy_mgr,
flex_table_column_t const &column, char const *str)
{
char *end = nullptr;
double const value = std::strtod(str, &end);
if (end && *end != '\0') {
write_null(copy_mgr, column);
return;
}
copy_mgr->add_column(value);
}
void output_flex_t::write_column(
db_copy_mgr_t<db_deleter_by_type_and_id_t> *copy_mgr,
flex_table_column_t const &column)
{
// If there is nothing on the Lua stack, then the Lua function add_row()
// was called without a table parameter. In that case this column will
// be set to NULL.
if (lua_gettop(lua_state()) == 0) {
write_null(copy_mgr, column);
return;
}
lua_getfield(lua_state(), -1, column.name().c_str());
int const ltype = lua_type(lua_state(), -1);
// Certain Lua types can never be added to the database
if (ltype == LUA_TFUNCTION || ltype == LUA_TUSERDATA ||
ltype == LUA_TTHREAD) {
throw std::runtime_error{
"Can not add Lua objects of type function, userdata, or thread."};
}
// A Lua nil value is always translated to a database NULL
if (ltype == LUA_TNIL) {
write_null(copy_mgr, column);
lua_pop(lua_state(), 1);
return;
}
if ((column.type() == table_column_type::sql) ||
(column.type() == table_column_type::text)) {
auto const *const str = lua_tolstring(lua_state(), -1, nullptr);
if (!str) {
throw std::runtime_error{
"Invalid type '{}' for text column."_format(
lua_typename(lua_state(), ltype))};
}
copy_mgr->add_column(str);
} else if (column.type() == table_column_type::boolean) {
switch (ltype) {
case LUA_TBOOLEAN:
copy_mgr->add_column(lua_toboolean(lua_state(), -1) != 0);
break;
case LUA_TNUMBER:
copy_mgr->add_column(lua_tonumber(lua_state(), -1) != 0);
break;
case LUA_TSTRING:
write_boolean(copy_mgr, column,
lua_tolstring(lua_state(), -1, nullptr));
break;
default:
throw std::runtime_error{
"Invalid type '{}' for boolean column."_format(
lua_typename(lua_state(), ltype))};
}
} else if (column.type() == table_column_type::int2) {
if (ltype == LUA_TNUMBER) {
int64_t const value = lua_tointeger(lua_state(), -1);
if (value >= std::numeric_limits<int16_t>::min() &&
value <= std::numeric_limits<int16_t>::max()) {
copy_mgr->add_column(value);
} else {
write_null(copy_mgr, column);
}
} else if (ltype == LUA_TSTRING) {
write_integer<int16_t>(copy_mgr, column,
lua_tolstring(lua_state(), -1, nullptr));
} else if (ltype == LUA_TBOOLEAN) {
copy_mgr->add_column(lua_toboolean(lua_state(), -1));
} else {
throw std::runtime_error{
"Invalid type '{}' for int2 column."_format(
lua_typename(lua_state(), ltype))};
}
} else if (column.type() == table_column_type::int4) {
if (ltype == LUA_TNUMBER) {
int64_t const value = lua_tointeger(lua_state(), -1);
if (value >= std::numeric_limits<int32_t>::min() &&
value <= std::numeric_limits<int32_t>::max()) {
copy_mgr->add_column(value);
} else {
write_null(copy_mgr, column);
}
} else if (ltype == LUA_TSTRING) {
write_integer<int32_t>(copy_mgr, column,
lua_tolstring(lua_state(), -1, nullptr));
} else if (ltype == LUA_TBOOLEAN) {
copy_mgr->add_column(lua_toboolean(lua_state(), -1));
} else {
throw std::runtime_error{
"Invalid type '{}' for int4 column."_format(
lua_typename(lua_state(), ltype))};
}
} else if (column.type() == table_column_type::int8) {
if (ltype == LUA_TNUMBER) {
copy_mgr->add_column(lua_tointeger(lua_state(), -1));
} else if (ltype == LUA_TSTRING) {
write_integer<int64_t>(copy_mgr, column,
lua_tolstring(lua_state(), -1, nullptr));
} else if (ltype == LUA_TBOOLEAN) {
copy_mgr->add_column(lua_toboolean(lua_state(), -1));
} else {
throw std::runtime_error{
"Invalid type '{}' for int8 column."_format(
lua_typename(lua_state(), ltype))};
}
} else if (column.type() == table_column_type::real) {
if (ltype == LUA_TNUMBER) {
copy_mgr->add_column(lua_tonumber(lua_state(), -1));
} else if (ltype == LUA_TSTRING) {
write_double(copy_mgr, column,
lua_tolstring(lua_state(), -1, nullptr));
} else {
throw std::runtime_error{
"Invalid type '{}' for real column."_format(
lua_typename(lua_state(), ltype))};
}
} else if (column.type() == table_column_type::hstore) {
if (ltype == LUA_TTABLE) {
copy_mgr->new_hash();
lua_pushnil(lua_state());
while (lua_next(lua_state(), -2) != 0) {
char const *const key = lua_tostring(lua_state(), -2);
char const *const val = lua_tostring(lua_state(), -1);
if (key == nullptr) {
int const ltype_key = lua_type(lua_state(), -2);
throw std::runtime_error{
"NULL key for hstore. Possibly this is due to"
" an incorrect data type '{}' as key."_format(
lua_typename(lua_state(), ltype_key))};
}
if (val == nullptr) {
int const ltype_value = lua_type(lua_state(), -1);
throw std::runtime_error{
"NULL value for hstore. Possibly this is due to"
" an incorrect data type '{}' for key '{}'."_format(
lua_typename(lua_state(), ltype_value), key)};
}
copy_mgr->add_hash_elem(key, val);
lua_pop(lua_state(), 1);
}
copy_mgr->finish_hash();
} else {
throw std::runtime_error{
"Invalid type '{}' for hstore column."_format(
lua_typename(lua_state(), ltype))};
}
} else if (column.type() == table_column_type::direction) {
switch (ltype) {
case LUA_TBOOLEAN:
copy_mgr->add_column(lua_toboolean(lua_state(), -1));
break;
case LUA_TNUMBER:
copy_mgr->add_column(sgn(lua_tonumber(lua_state(), -1)));
break;
case LUA_TSTRING:
write_direction(copy_mgr, column,
lua_tolstring(lua_state(), -1, nullptr));
break;
default:
throw std::runtime_error{
"Invalid type '{}' for direction column."_format(
lua_typename(lua_state(), ltype))};
}
} else {
throw std::runtime_error{
"Column type {} not implemented."_format(column.type())};
}
lua_pop(lua_state(), 1);
}
void output_flex_t::write_row(table_connection_t *table_connection,
osmium::item_type id_type, osmid_t id,
std::string const &geom, int srid)
{
assert(table_connection);
table_connection->new_line();
auto *copy_mgr = table_connection->copy_mgr();
for (auto const &column : table_connection->table()) {
if (column.create_only()) {
continue;
}
if (column.type() == table_column_type::id_type) {
copy_mgr->add_column(type_to_char(id_type));
} else if (column.type() == table_column_type::id_num) {
copy_mgr->add_column(id);
} else if (column.is_geometry_column()) {
assert(!geom.empty());
copy_mgr->add_hex_geom(geom);
} else if (column.type() == table_column_type::area) {
if (geom.empty()) {
write_null(copy_mgr, column);
} else {
// if srid of the area column is the same as for the geom column
double const area =
column.srid() == srid
? ewkb::parser_t(geom)
.get_area<osmium::geom::IdentityProjection>()
: ewkb::parser_t(geom).get_area<reprojection>(
reprojection::create_projection(srid).get());
copy_mgr->add_column(area);
}
} else {
write_column(copy_mgr, column);
}
}
copy_mgr->finish_line();
}
// Gets all way nodes from the middle the first time this is called.
std::size_t output_flex_t::get_way_nodes()
{
assert(m_context_way);
if (m_num_way_nodes == std::numeric_limits<std::size_t>::max()) {
m_num_way_nodes = m_mid->nodes_get_list(&m_context_way->nodes());
}
return m_num_way_nodes;
}
int output_flex_t::app_get_bbox()
{
if (m_calling_context != calling_context::process_node &&
m_calling_context != calling_context::process_way) {
throw std::runtime_error{"The function get_bbox() can only be called"
" from process_node() or process_way()."};
}
if (lua_gettop(lua_state()) > 1) {
throw std::runtime_error{"No parameter(s) needed for get_box()."};
}
if (m_context_node) {
lua_pushnumber(lua_state(), m_context_node->location().lon());
lua_pushnumber(lua_state(), m_context_node->location().lat());
lua_pushnumber(lua_state(), m_context_node->location().lon());
lua_pushnumber(lua_state(), m_context_node->location().lat());
return 4;
}
if (m_context_way) {
get_way_nodes();
auto const bbox = m_context_way->envelope();
if (bbox.valid()) {
lua_pushnumber(lua_state(), bbox.bottom_left().lon());
lua_pushnumber(lua_state(), bbox.bottom_left().lat());
lua_pushnumber(lua_state(), bbox.top_right().lon());
lua_pushnumber(lua_state(), bbox.top_right().lat());
return 4;
}
}
return 0;
}
static void check_name(std::string const &name, char const *in)
{
auto const pos = name.find_first_of("\"',.;$%&/()<>{}=?^*#");
if (pos == std::string::npos) {
return;
}
throw std::runtime_error{
"Special characters are not allowed in {} names: '{}'."_format(in,
name)};
}
flex_table_t &output_flex_t::create_flex_table()
{
std::string const table_name =
luaX_get_table_string(lua_state(), "name", -1, "The table");
check_name(table_name, "table");
auto const it = std::find_if(m_tables->cbegin(), m_tables->cend(),
[&table_name](flex_table_t const &table) {
return table.name() == table_name;
});
if (it != m_tables->cend()) {
throw std::runtime_error{
"Table with name '{}' already exists."_format(table_name)};
}
m_tables->emplace_back(table_name);
auto &new_table = m_tables->back();
lua_pop(lua_state(), 1);
// optional "schema" field
lua_getfield(lua_state(), -1, "schema");
if (lua_isstring(lua_state(), -1)) {
std::string const schema = lua_tostring(lua_state(), -1);
check_name(schema, "schema");
new_table.set_schema(schema);
}
lua_pop(lua_state(), 1);
// optional "data_tablespace" field
lua_getfield(lua_state(), -1, "data_tablespace");
if (lua_isstring(lua_state(), -1)) {
std::string const tablespace = lua_tostring(lua_state(), -1);
check_name(tablespace, "data_tablespace");
new_table.set_data_tablespace(tablespace);
}
lua_pop(lua_state(), 1);
// optional "index_tablespace" field
lua_getfield(lua_state(), -1, "index_tablespace");
if (lua_isstring(lua_state(), -1)) {
std::string const tablespace = lua_tostring(lua_state(), -1);
check_name(tablespace, "index_tablespace");
new_table.set_index_tablespace(tablespace);
}
lua_pop(lua_state(), 1);
return new_table;
}
void output_flex_t::setup_id_columns(flex_table_t *table)
{
assert(table);
lua_getfield(lua_state(), -1, "ids");
if (lua_type(lua_state(), -1) != LUA_TTABLE) {
log_warn("Table '{}' doesn't have an 'ids' column. Updates"
" and expire will not work!",
table->name());
lua_pop(lua_state(), 1); // ids
return;
}
std::string const type{
luaX_get_table_string(lua_state(), "type", -1, "The ids field")};
if (type == "node") {
table->set_id_type(osmium::item_type::node);
} else if (type == "way") {
table->set_id_type(osmium::item_type::way);
} else if (type == "relation") {
table->set_id_type(osmium::item_type::relation);
} else if (type == "area") {
table->set_id_type(osmium::item_type::area);
} else if (type == "any") {
table->set_id_type(osmium::item_type::undefined);
lua_getfield(lua_state(), -2, "type_column");
if (lua_isstring(lua_state(), -1)) {
std::string const column_name =
lua_tolstring(lua_state(), -1, nullptr);
check_name(column_name, "column");
auto &column = table->add_column(column_name, "id_type");
column.set_not_null();
} else if (!lua_isnil(lua_state(), -1)) {
throw std::runtime_error{"type_column must be a string or nil."};
}
lua_pop(lua_state(), 1); // type_column
} else {
throw std::runtime_error{"Unknown ids type: {}."_format(type)};
}
std::string const name =
luaX_get_table_string(lua_state(), "id_column", -2, "The ids field");
check_name(name, "column");
auto &column = table->add_column(name, "id_num");
column.set_not_null();
lua_pop(lua_state(), 3); // id_column, type, ids
}
void output_flex_t::setup_flex_table_columns(flex_table_t *table)
{
assert(table);
lua_getfield(lua_state(), -1, "columns");
if (lua_type(lua_state(), -1) != LUA_TTABLE) {
throw std::runtime_error{
"No columns defined for table '{}'."_format(table->name())};
}
std::size_t num_columns = 0;
lua_pushnil(lua_state());
while (lua_next(lua_state(), -2) != 0) {
if (!lua_isnumber(lua_state(), -2)) {
throw std::runtime_error{
"The 'columns' field must contain an array."};
}
if (!lua_istable(lua_state(), -1)) {
throw std::runtime_error{
"The entries in the 'columns' array must be tables."};
}
char const *const type =
luaX_get_table_string(lua_state(), "type", -1, "Column entry");
char const *const name =
luaX_get_table_string(lua_state(), "column", -2, "Column entry");
check_name(name, "column");
auto &column = table->add_column(name, type);
column.set_not_null(luaX_get_table_bool(lua_state(), "not_null", -3,
"Entry 'not_null'", false));
column.set_create_only(luaX_get_table_bool(
lua_state(), "create_only", -4, "Entry 'create_only'", false));
lua_getfield(lua_state(), -5, "projection");
if (!lua_isnil(lua_state(), -1)) {
if (column.is_geometry_column() ||
column.type() == table_column_type::area) {
column.set_projection(lua_tostring(lua_state(), -1));
} else {
throw std::runtime_error{
"Projection can only be set on geometry and area columns."};
}
}
// stack has: projection, create_only, not_null, column, type, table
lua_pop(lua_state(), 6);
++num_columns;
}
if (num_columns == 0) {
throw std::runtime_error{
"No columns defined for table '{}'."_format(table->name())};
}
}
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."};
}
luaL_checktype(lua_state(), 1, LUA_TTABLE);
auto &new_table = create_flex_table();
setup_id_columns(&new_table);
setup_flex_table_columns(&new_table);
lua_pushlightuserdata(lua_state(), (void *)(m_tables->size()));
luaL_getmetatable(lua_state(), osm2pgsql_table_name);
lua_setmetatable(lua_state(), -2);
return 1;
}
// Check that the first element on the Lua stack is an osm2pgsql.table
// parameter and return its internal table index.
static std::size_t table_idx_from_param(lua_State *lua_state)
{
void const *const user_data = lua_touserdata(lua_state, 1);
if (user_data == nullptr || !lua_getmetatable(lua_state, 1)) {
throw std::runtime_error{
"First parameter must be of type osm2pgsql.table."};
}
luaL_getmetatable(lua_state, osm2pgsql_table_name);
if (!lua_rawequal(lua_state, -1, -2)) {
throw std::runtime_error{
"First parameter must be of type osm2pgsql.table."};
}
lua_pop(lua_state, 2);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
return reinterpret_cast<uintptr_t>(user_data) - 1;
}
// Get the flex table that is as first parameter on the Lua stack.
flex_table_t const &output_flex_t::get_table_from_param()
{
if (lua_gettop(lua_state()) != 1) {
throw std::runtime_error{
"Need exactly one parameter of type osm2pgsql.table."};
}
auto const &table = m_tables->at(table_idx_from_param(lua_state()));
lua_remove(lua_state(), 1);
return table;
}
int output_flex_t::table_tostring()
{
auto const &table = get_table_from_param();
std::string const str{"osm2pgsql.table[{}]"_format(table.name())};
lua_pushstring(lua_state(), str.c_str());
return 1;
}
int output_flex_t::table_add_row()
{
if (m_disable_add_row) {
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 add_row() can only be called from the "
"process_node/way/relation() functions."};
}
// Params are the table object and an optional Lua table with the contents
// for the fields.
auto const num_params = lua_gettop(lua_state());
if (num_params < 1 || num_params > 2) {
throw std::runtime_error{
"Need two parameters: The osm2pgsql.table and the row data."};
}
auto &table_connection =
m_table_connections.at(table_idx_from_param(lua_state()));
auto const &table = table_connection.table();
// It there is a second parameter, it must be a Lua table.
if (num_params == 2) {
luaL_checktype(lua_state(), 2, LUA_TTABLE);
}
lua_remove(lua_state(), 1);
if (m_context_node) {
if (!table.matches_type(osmium::item_type::node)) {
throw std::runtime_error{
"Trying to add node to table '{}'."_format(table.name())};
}
add_row(&table_connection, *m_context_node);
} else if (m_context_way) {
if (!table.matches_type(osmium::item_type::way)) {
throw std::runtime_error{
"Trying to add way to table '{}'."_format(table.name())};
}
add_row(&table_connection, *m_context_way);
} else if (m_context_relation) {
if (!table.matches_type(osmium::item_type::relation)) {
throw std::runtime_error{
"Trying to add relation to table '{}'."_format(table.name())};
}
add_row(&table_connection, *m_context_relation);
}
return 0;
}
int output_flex_t::table_columns()
{
auto const &table = get_table_from_param();
lua_createtable(lua_state(), (int)table.num_columns(), 0);
int n = 0;
for (auto const &column : table) {
lua_pushinteger(lua_state(), ++n);
lua_newtable(lua_state());
luaX_add_table_str(lua_state(), "name", column.name().c_str());
luaX_add_table_str(lua_state(), "type", column.type_name().c_str());
luaX_add_table_str(lua_state(), "sql_type",
column.sql_type_name().c_str());
luaX_add_table_str(lua_state(), "sql_modifiers",
column.sql_modifiers().c_str());
luaX_add_table_bool(lua_state(), "not_null", column.not_null());
luaX_add_table_bool(lua_state(), "create_only", column.create_only());
lua_rawset(lua_state(), -3);
}
return 1;
}
int output_flex_t::table_name()
{
auto const &table = get_table_from_param();
lua_pushstring(lua_state(), table.name().c_str());
return 1;
}
int output_flex_t::table_schema()
{
auto const &table = get_table_from_param();
lua_pushstring(lua_state(), table.schema().c_str());
return 1;
}
static std::unique_ptr<geom_transform_t>
get_transform(lua_State *lua_state, flex_table_column_t const &column)
{
assert(lua_state);
assert(lua_gettop(lua_state) == 1);
std::unique_ptr<geom_transform_t> transform{};
lua_getfield(lua_state, -1, column.name().c_str());
int const ltype = lua_type(lua_state, -1);
if (ltype != LUA_TTABLE) {
lua_pop(lua_state, 1); // geom field
return transform;
}
lua_getfield(lua_state, -1, "create");
char const *create_type = lua_tostring(lua_state, -1);
if (create_type == nullptr) {
throw std::runtime_error{
"Missing geometry transformation for column '{}'."_format(
column.name())};
}
transform = create_geom_transform(create_type);
lua_pop(lua_state, 1); // 'create' field
init_geom_transform(transform.get(), lua_state);
if (!transform->is_compatible_with(column.type())) {
throw std::runtime_error{
"Geometry transformation is not compatible "
"with column type '{}'."_format(column.type_name())};
}
lua_pop(lua_state, 1); // geom field
return transform;
}
static geom_transform_t const *
get_default_transform(flex_table_column_t const &column,
osmium::item_type object_type)
{
static geom_transform_point_t const default_transform_node_to_point{};
static geom_transform_line_t const default_transform_way_to_line{};
static geom_transform_area_t const default_transform_way_to_area{};
switch (object_type) {
case osmium::item_type::node:
if (column.type() == table_column_type::point) {
return &default_transform_node_to_point;
}
break;
case osmium::item_type::way:
if (column.type() == table_column_type::linestring) {
return &default_transform_way_to_line;
}
if (column.type() == table_column_type::polygon) {
return &default_transform_way_to_area;
}
break;
default:
break;
}
throw std::runtime_error{
"Missing geometry transformation for column '{}'."_format(
column.name())};
}
geom::osmium_builder_t::wkbs_t
output_flex_t::run_transform(geom::osmium_builder_t *builder,
geom_transform_t const *transform,
table_column_type target_geom_type,
osmium::Node const &node)
{
return transform->run(builder, target_geom_type, node);
}
geom::osmium_builder_t::wkbs_t
output_flex_t::run_transform(geom::osmium_builder_t *builder,
geom_transform_t const *transform,
table_column_type target_geom_type,
osmium::Way const & /*way*/)
{
if (get_way_nodes() <= 1U) {
return {};
}
return transform->run(builder, target_geom_type, m_context_way);
}
geom::osmium_builder_t::wkbs_t
output_flex_t::run_transform(geom::osmium_builder_t *builder,
geom_transform_t const *transform,
table_column_type target_geom_type,
osmium::Relation const &relation)
{