Repository navigation
Expand file tree
/
Copy pathpgmap.cpp
More file actions
2791 lines (2472 loc) · 94.8 KB
/
Copy pathpgmap.cpp
File metadata and controls
2791 lines (2472 loc) · 94.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
#include "pgmap.h"
#include <functional>
#include "dbquery.h"
#include "dbextract.h"
#include "dbprepared.h"
#include "dbids.h"
#include "dbadmin.h"
#include "dbdecode.h"
#include "dbreplicate.h"
#include "dbstore.h"
#include "dbdump.h"
#include "dbfilters.h"
#include "dbchangeset.h"
#include "dbmeta.h"
#include "osmfile.h"
#include "dbcommon.h"
#include "dboverpass.h"
#include "util.h"
#include "cppo5m/model.h"
#include <algorithm>
#include <cmath>
using namespace std;
PgMapError::PgMapError()
{
}
PgMapError::PgMapError(const string &connection)
{
this->errStr = connection;
}
PgMapError::PgMapError(const PgMapError &obj)
{
this->errStr = obj.errStr;
}
PgMapError::~PgMapError()
{
}
// **********************************************
bool LockMap(std::shared_ptr<pqxx::transaction_base> work, const std::string &prefix, const std::string &accessMode, std::string &errStr)
{
try
{
//It is important resources are locked in a consistent order to avoid deadlock
//Also, lock everything in one command to get a consistent view of the data.
string sql = "LOCK TABLE "+prefix+ "oldnodes";
sql += ","+prefix+ "oldways";
sql += ","+prefix+ "oldrelations";
sql += ","+prefix+ "livenodes";
sql += ","+prefix+ "liveways";
sql += ","+prefix+ "liverelations";
sql += ","+prefix+ "nodeids";
sql += ","+prefix+ "wayids";
sql += ","+prefix+ "relationids";
sql += ","+prefix+ "way_mems";
sql += ","+prefix+ "relation_mems_n";
sql += ","+prefix+ "relation_mems_w";
sql += ","+prefix+ "relation_mems_r";
sql += ","+prefix+ "nextids";
sql += ","+prefix+ "changesets";
sql += ","+prefix+ "meta";
sql += ","+prefix+ "usernames";
sql += ","+prefix+ "query_activity";
sql += ","+prefix+ "edit_activity";
sql += " IN "+accessMode+" MODE;";
work->exec(sql);
}
catch (const pqxx::sql_error &e)
{
stringstream ss;
ss << e.what() << " (" << e.query() << ")";
errStr = ss.str();
return false;
}
catch (const std::exception &e)
{
errStr = e.what();
return false;
}
return true;
}
// **********************************************
PgChangeset::PgChangeset()
{
objId = 0;
uid = 0;
open_timestamp = 0;
close_timestamp = 0;
is_open = true; bbox_set = false;
x1 = 0.0; y1 = 0.0; x2 = 0.0; y2 = 0.0;
created_count = 0; modified_count = 0; deleted_count = 0;
}
PgChangeset::PgChangeset(const PgChangeset &obj)
{
*this = obj;
}
PgChangeset::~PgChangeset()
{
}
PgChangeset& PgChangeset::operator=(const PgChangeset &obj)
{
objId = obj.objId;
uid = obj.uid;
open_timestamp = obj.open_timestamp;
close_timestamp = obj.close_timestamp;
username = obj.username;
tags = obj.tags;
is_open = obj.is_open;
bbox_set = obj.bbox_set;
x1 = obj.x1; y1 = obj.y1; x2 = obj.x2; y2 = obj.y2;
created_count = obj.created_count;
modified_count = obj.modified_count;
deleted_count = obj.deleted_count;
return *this;
}
// **********************************************
PgMapQuery::PgMapQuery(const string &tableStaticPrefixIn,
const string &tableActivePrefixIn,
shared_ptr<pqxx::connection> &db,
std::shared_ptr<class PgWork> sharedWorkIn,
class DbUsernameLookup &dbUsernameLookupIn):
sharedWork(sharedWorkIn),
dbUsernameLookup(dbUsernameLookupIn)
{
mapQueryActive = false;
dbconn = db;
tableStaticPrefix = tableStaticPrefixIn;
tableActivePrefix = tableActivePrefixIn;
useBboxInQuery = 0;
}
PgMapQuery::~PgMapQuery()
{
this->Reset();
}
PgMapQuery& PgMapQuery::operator=(const PgMapQuery&)
{
return *this;
}
int PgMapQuery::StartCommon(const vector<double> &bbox, int64_t timestamp, std::shared_ptr<IDataStreamHandler> &enc)
{
/**
\param area being queried
\param timestamp the timestamp right now (0 if we don't care about logging accurate query times)
\param enc output object to receive the query result
*/
this->mapQueryEnc = enc;
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
//Check if bbox data has been enabled for ways and relations
string errStrNative;
string useBboxInQueryStr;
try
{
useBboxInQueryStr = DbGetMetaValue(*dbconn, work.get(),
"useBboxInQuery",
this->tableActivePrefix,
errStrNative);
}
catch(runtime_error &err)
{
}
this->useBboxInQuery = atoi(useBboxInQueryStr.c_str()) == 1;
string errStr;
bool ok = DbInsertQueryActivity(*dbconn, work.get(), this->tableActivePrefix,
timestamp,
bbox,
errStr,
0);
if (!ok)
cout << errStr << endl;
return 0;
}
void PgMapQuery::SetAtomicEditId(int64_t atomicEditIdIn)
{
if(mapQueryActive)
throw runtime_error("Query already active");
if(atomicEditIdIn < 0)
throw invalid_argument("Atomic edit ID must not be negative");
this->atomicEditId = atomicEditIdIn;
}
int PgMapQuery::Start(const vector<double> &bbox, int64_t timestamp, std::shared_ptr<IDataStreamHandler> &enc)
{
if(mapQueryActive)
throw runtime_error("Query already active");
if(dbconn.get() == NULL)
throw runtime_error("DB pointer not set for PgMapQuery");
if(bbox.size() != 4)
throw invalid_argument("bbox must have four values");
mapQueryActive = true;
this->mapQueryPhase = 0;
this->mapQueryBbox = bbox;
return this->StartCommon(bbox, timestamp, enc);
}
int PgMapQuery::Start(const std::string &wkt, int64_t timestamp, std::shared_ptr<IDataStreamHandler> &enc)
{
if(mapQueryActive)
throw runtime_error("Query already active");
if(dbconn.get() == NULL)
throw runtime_error("DB pointer not set for PgMapQuery");
mapQueryActive = true;
this->mapQueryPhase = 0;
this->mapQueryWkt = wkt;
// The rectangle around it, for the bounds of what is written
this->mapQueryWktBounds.clear();
{
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work) throw runtime_error("Transaction has been deleted");
pqxx::result r = work->exec("SELECT ST_XMin(g), ST_YMin(g), ST_XMax(g), ST_YMax(g) FROM "
"(SELECT ST_GeomFromText(" + work->quote(wkt) + ", 4326) AS g) area");
if(!r[0][0].is_null())
for(int i=0; i<4; i++) this->mapQueryWktBounds.push_back(r[0][i].as<double>());
}
std::vector<double> emptyBbox;
return this->StartCommon(emptyBbox, timestamp, enc);
}
// The temporary tables one map query keeps its selection in. They belong to
// the session and go when its transaction ends.
static const char *MAP_QUERY_SEEDS = "pgmap_mapquery_seeds";
static const char *MAP_QUERY_WAYS = "pgmap_mapquery_ways";
static const char *MAP_QUERY_EXTRA = "pgmap_mapquery_extra";
static const char *MAP_QUERY_CHANGED = "pgmap_mapquery_changed";
static void DropMapQueryTables(pqxx::transaction_base *work)
{
for(const char *name : {MAP_QUERY_SEEDS, MAP_QUERY_WAYS, MAP_QUERY_EXTRA, MAP_QUERY_CHANGED})
work->exec(string("DROP TABLE IF EXISTS ") + name);
}
void PgMapQuery::SelectObjects()
{
/*
* The selection is worked out in the database, which then only has to be
* read from. The rule is:
* 1. the nodes inside the area,
* 2. the ways having one of those nodes or, on a map that uses stored
* boxes (useBboxInQuery), the ways whose box meets the area,
* 3. the other nodes of those ways,
* 4. the relations having any of those nodes or ways as a member or,
* with stored boxes, the relations whose box meets the area.
* DbUpdateExtract follows the same rule for a stored extract.
*
* Each kind of object is read from the static tables and from the active
* ones, a static object being passed over when the active tables have
* taken it over (its ID is then in their *ids table). That is what the
* visible* views do, without their removal of duplicates, which has
* nothing to remove.
*
* The map as it was after an atomic edit (SetAtomicEditId) is the map as
* it is with the edits since undone. The edit activity records since say
* which objects those edits changed, and in their lists of existing
* objects, the version each had before: the version before the first
* edit since that changed an object is its version then, and an object
* with none was made since. Every other object is as it was then, and is
* found as now; the changed ones are found among their versions then, by
* ID and version, in the live and history tables of every layer. So the
* work grows with the edits since, not with the history of the map.
* Stored boxes are of current shapes, so ways and relations are found
* through their members, as without useBboxInQuery.
*/
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
pqxx::connection &c = *dbconn;
// Static baseline, then the active overlay
vector<pair<string,string> > layers;
if(!tableStaticPrefix.empty() && tableStaticPrefix != tableActivePrefix)
layers.push_back({tableStaticPrefix, tableActivePrefix});
layers.push_back({tableActivePrefix, ""});
auto suppressed = [&](const string &exclude, const string &kind) {
if(exclude.empty()) return string("true");
return "NOT EXISTS (SELECT 1 FROM " + c.quote_name(exclude + kind + "ids") + " x WHERE x.id=o.id)";
};
// Rows of one kind of object from every layer, each layer's chosen by a
// FROM clause naming its live table as o
auto fromLayers = [&](const string &kind, const string &columns,
std::function<string(const string &)> choose) {
string sql;
for(const auto &layer : layers)
{
if(!sql.empty()) sql += " UNION ALL ";
sql += "SELECT " + columns + " FROM " + c.quote_name(layer.first + "live" + kind + "s") + " o " +
choose(layer.first) + " AND " + suppressed(layer.second, kind);
}
return sql;
};
string area;
if(this->mapQueryBbox.size() == 4)
{
stringstream ss;
ss.precision(9);
ss << fixed << "ST_MakeEnvelope(" << mapQueryBbox[0] << "," << mapQueryBbox[1] << ","
<< mapQueryBbox[2] << "," << mapQueryBbox[3] << ", 4326)";
area = ss.str();
}
else
area = "ST_GeomFromText(" + c.quote(this->mapQueryWkt) + ", 4326)";
// What is in a polygon, not just in the rectangle around it. For a
// rectangle the two are the same, and && alone is quicker.
bool polygon = this->mapQueryBbox.size() != 4;
auto within = [&](const string &column) {
return polygon ? "ST_Intersects(" + column + ", " + area + ")" : column + " && " + area;
};
DropMapQueryTables(work.get());
const bool past = this->atomicEditId > 0;
const bool byBoxes = this->useBboxInQuery && !past;
// What is read of an object of each kind, which the live and history
// tables both have
auto objectColumns = [](const string &kind) {
string columns = "o.id, o.changeset, o.username, o.uid, o.timestamp, o.version, o.tags";
if(kind == "node") return columns + ", o.geom";
if(kind == "way") return columns + ", o.members";
return columns + ", o.members, o.memberroles";
};
auto readColumns = [&](const string &kind) {
return kind == "node" ? objectColumns(kind) + ", ST_X(o.geom) AS lon, ST_Y(o.geom) AS lat" : objectColumns(kind);
};
if(past)
{
// The objects changed since, each with its version then, or NULL if made since
string activity = c.quote_name(tableActivePrefix + "edit_activity");
work->exec(string("CREATE TEMP TABLE ") + MAP_QUERY_CHANGED + " ON COMMIT DROP AS "
"SELECT DISTINCT ON (u.value->>0, (u.value->>1)::bigint) u.value->>0 AS kind, (u.value->>1)::bigint AS id, "
"(SELECT (x.value->>2)::bigint FROM jsonb_array_elements(a.existing) x "
"WHERE x.value->>0 = u.value->>0 AND x.value->>1 = u.value->>1 LIMIT 1) AS version "
"FROM " + activity + " a CROSS JOIN LATERAL jsonb_array_elements(a.updated) u "
"WHERE a.atomic_edit_id > " + to_string(this->atomicEditId) + " "
"ORDER BY u.value->>0, (u.value->>1)::bigint, a.atomic_edit_id, a.block_index");
}
// Rows of one kind of object as the map has them, or had them after the
// atomic edit: those unchanged since, chosen from each layer by choose as
// fromLayers does, and the versions then of those changed since, chosen
// by changed, a condition on o. A version can be in more than one layer
// (a static one the active tables copied), which is read once.
auto rowsOf = [&](const string &kind, std::function<string(const string &)> choose, const string &changed) {
// Columns named, not *, so that what is not sent, such as a shape kept
// for map renderers, is not read
if(!past)
return fromLayers(kind, readColumns(kind), choose);
string kindValue = c.quote(kind);
string sql = fromLayers(kind, readColumns(kind), [&](const string &prefix) {
return choose(prefix) + " AND NOT EXISTS (SELECT 1 FROM " + MAP_QUERY_CHANGED +
" ch WHERE ch.kind=" + kindValue + " AND ch.id=o.id)"; });
string versions;
int rank = 0;
for(auto layer = layers.rbegin(); layer != layers.rend(); ++layer)
for(const char *table : {"live", "old"})
{
if(!versions.empty()) versions += " UNION ALL ";
versions += "SELECT " + to_string(rank++) + " AS rank, " + objectColumns(kind) + " FROM " +
c.quote_name(layer->first + table + kind + "s") + " o JOIN " + MAP_QUERY_CHANGED +
" ch ON ch.kind=" + kindValue + " AND ch.id=o.id AND ch.version=o.version" +
(string(table) == "old" ? " WHERE o.visible" : "");
}
return sql + " UNION ALL (SELECT DISTINCT ON (o.id) " + readColumns(kind) + " FROM (" + versions +
") o WHERE " + changed + " ORDER BY o.id, o.rank)";
};
// The tables of nodes and ways hold whole rows, which are then written
// out from them. Holding only IDs and reading the objects again by ID was
// tried and measured: it was 10 to 15% slower on large areas, and more on
// small ones, since each object is then looked up twice.
// 1. Nodes in the area
work->exec(string("CREATE TEMP TABLE ") + MAP_QUERY_SEEDS + " ON COMMIT DROP AS " +
rowsOf("node", [&](const string &) { return "WHERE " + within("o.geom"); }, within("o.geom")));
// 2. Ways. The member tables are of live versions, which are the versions
// then of the ways unchanged since; a way's own list of members is read
// for its version then.
if(!byBoxes)
work->exec(string("CREATE TEMP TABLE ") + MAP_QUERY_WAYS + " ON COMMIT DROP AS " +
rowsOf("way", [&](const string &prefix) {
return "JOIN (SELECT DISTINCT m.id, m.version FROM " + c.quote_name(prefix + "way_mems") +
" m JOIN " + MAP_QUERY_SEEDS + " s ON m.member=s.id) w ON o.id=w.id AND o.version=w.version WHERE true"; },
string("EXISTS (SELECT 1 FROM jsonb_array_elements(o.members) m JOIN ") + MAP_QUERY_SEEDS +
" s ON s.id = m.value::text::bigint)"));
else
work->exec(string("CREATE TEMP TABLE ") + MAP_QUERY_WAYS + " ON COMMIT DROP AS " +
fromLayers("way", readColumns("way"), [&](const string &) { return "WHERE " + within("o.bbox"); }));
// 3. Nodes of those ways that are outside the area
work->exec(string("CREATE TEMP TABLE ") + MAP_QUERY_EXTRA + " ON COMMIT DROP AS "
"SELECT DISTINCT member.value::text::bigint AS id FROM " + MAP_QUERY_WAYS +
" w CROSS JOIN LATERAL jsonb_array_elements(w.members) member"
" EXCEPT SELECT id FROM " + MAP_QUERY_SEEDS);
this->extraNodesSql = rowsOf("node", [&](const string &) {
return string("JOIN ") + MAP_QUERY_EXTRA + " s ON o.id=s.id WHERE true"; },
string("o.id IN (SELECT id FROM ") + MAP_QUERY_EXTRA + ")");
// 4. Relations
if(!byBoxes)
this->relationsSql = rowsOf("relation", [&](const string &prefix) {
string holders;
for(const char *selected : {MAP_QUERY_SEEDS, MAP_QUERY_EXTRA})
holders += "SELECT m.id, m.version FROM " + c.quote_name(prefix + "relation_mems_n") +
" m JOIN " + selected + " s ON m.member=s.id UNION ";
holders += "SELECT m.id, m.version FROM " + c.quote_name(prefix + "relation_mems_w") +
" m JOIN " + MAP_QUERY_WAYS + " s ON m.member=s.id";
return "JOIN (" + holders + ") r ON o.id=r.id AND o.version=r.version WHERE true"; },
string("EXISTS (SELECT 1 FROM jsonb_array_elements(o.members) m WHERE "
"(m.value->>0 = 'node' AND (m.value->>1)::bigint IN (SELECT id FROM ") + MAP_QUERY_SEEDS +
" UNION ALL SELECT id FROM " + MAP_QUERY_EXTRA + ")) OR "
"(m.value->>0 = 'way' AND (m.value->>1)::bigint IN (SELECT id FROM " + MAP_QUERY_WAYS + ")))");
else
// A relation's box may be two, either side of the antimeridian, which
// the index sees as one round the world: what && finds is checked
this->relationsSql = fromLayers("relation", readColumns("relation"), [&](const string &) {
return "WHERE " + within("o.bbox") + (polygon ? "" : " AND ST_Intersects(o.bbox, " + area + ")"); });
}
int PgMapQuery::Continue()
{
if(!mapQueryActive)
throw runtime_error("Query not active");
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
// Each call does one step, so that the caller can pass on what has been
// written so far: the header, the selection, then a batch of objects at a time.
if(this->mapQueryPhase == 0)
{
this->mapQueryEnc->StoreIsDiff(false);
if(this->mapQueryBbox.size() == 4)
this->mapQueryEnc->StoreBounds(Bounds(this->mapQueryBbox[0], this->mapQueryBbox[1], this->mapQueryBbox[2], this->mapQueryBbox[3]));
else if(this->mapQueryWktBounds.size() == 4)
this->mapQueryEnc->StoreBounds(Bounds(this->mapQueryWktBounds[0], this->mapQueryWktBounds[1],
this->mapQueryWktBounds[2], this->mapQueryWktBounds[3]));
this->mapQueryPhase = 1;
return 0;
}
if(this->mapQueryPhase == 1)
{
this->SelectObjects();
cursor.reset(new pqxx::icursorstream(*work, string("SELECT * FROM ") + MAP_QUERY_SEEDS, "mapquerynodes", 1000));
this->mapQueryPhase = 2;
return 0;
}
if(this->mapQueryPhase == 2)
{
//Nodes in the area
int ret = NodeResultsToEncoder(*cursor, this->dbUsernameLookup, this->mapQueryEnc);
if(ret > 0) return 0;
if(ret < 0) return -1;
cursor.reset(new pqxx::icursorstream(*work, this->extraNodesSql, "mapqueryextranodes", 1000));
this->mapQueryPhase = 3;
return 0;
}
if(this->mapQueryPhase == 3)
{
//Nodes that complete the ways
int ret = NodeResultsToEncoder(*cursor, this->dbUsernameLookup, this->mapQueryEnc);
if(ret > 0) return 0;
if(ret < 0) return -1;
this->mapQueryEnc->Reset();
cursor.reset(new pqxx::icursorstream(*work, string("SELECT * FROM ") + MAP_QUERY_WAYS, "mapqueryways", 1000));
this->mapQueryPhase = 4;
return 0;
}
if(this->mapQueryPhase == 4)
{
int ret = WayResultsToEncoder(*cursor, this->dbUsernameLookup, this->mapQueryEnc);
if(ret > 0) return 0;
if(ret < 0) return -1;
this->mapQueryEnc->Reset();
cursor.reset(new pqxx::icursorstream(*work, this->relationsSql, "mapqueryrelations", 1000));
this->mapQueryPhase = 5;
return 0;
}
if(this->mapQueryPhase == 5)
{
std::set<int64_t> skipIds;
RelationResultsToEncoder(*cursor, this->dbUsernameLookup, skipIds, this->mapQueryEnc);
cursor.reset();
DropMapQueryTables(work.get());
this->mapQueryPhase = 6;
return 0;
}
if(this->mapQueryPhase == 6)
{
this->mapQueryEnc->Finish();
this->Reset();
return 1; // All done!
}
return -1;
}
void PgMapQuery::Reset()
{
this->mapQueryPhase = 0;
this->mapQueryActive = false;
this->mapQueryEnc.reset();
this->mapQueryBbox.clear();
this->mapQueryWkt.clear();
this->mapQueryWktBounds.clear();
this->cursor.reset();
this->extraNodesSql.clear();
this->relationsSql.clear();
this->atomicEditId = 0;
}
// *********************************************
PgTransaction::PgTransaction(shared_ptr<pqxx::connection> dbconnIn,
const string &tableStaticPrefixIn,
const string &tableActivePrefixIn,
std::shared_ptr<class PgWork> sharedWorkIn,
const std::string &shareMode):
PgCommon(dbconnIn, tableStaticPrefixIn, tableActivePrefixIn, sharedWorkIn, shareMode)
{
string errStr;
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
bool ok = LockMap(work, this->tableStaticPrefix, this->shareMode, errStr);
if(!ok)
throw runtime_error(errStr);
ok = LockMap(work, this->tableActivePrefix, this->shareMode, errStr);
if(!ok)
throw runtime_error(errStr);
}
PgTransaction::~PgTransaction()
{
this->sharedWork->work.reset();
this->sharedWork.reset();
}
shared_ptr<class PgMapQuery> PgTransaction::GetQueryMgr()
{
if(this->shareMode != "ACCESS SHARE" && this->shareMode != "EXCLUSIVE")
throw runtime_error("Database must be locked in ACCESS SHARE or EXCLUSIVE mode");
shared_ptr<class PgMapQuery> out(new class PgMapQuery(tableStaticPrefix, tableActivePrefix,
this->dbconn, this->sharedWork, this->dbUsernameLookup));
return out;
}
void PgTransaction::GetObjectsById(const std::string &type, const std::set<int64_t> &objectIds,
std::shared_ptr<IDataStreamHandler> out)
{
if(this->shareMode != "ACCESS SHARE" && this->shareMode != "EXCLUSIVE")
throw runtime_error("Database must be locked in ACCESS SHARE or EXCLUSIVE mode");
if(objectIds.size()==0)
return;
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
std::set<int64_t>::const_iterator it = objectIds.begin();
while(it != objectIds.end())
GetVisibleObjectsById(*dbconn, work.get(), this->dbUsernameLookup,
this->tableActivePrefix, type, objectIds,
it, 1000, out);
}
void PgTransaction::GetFullObjectById(const std::string &type, int64_t objectId,
std::shared_ptr<IDataStreamHandler> out)
{
if(this->shareMode != "ACCESS SHARE" && this->shareMode != "EXCLUSIVE")
throw runtime_error("Database must be locked in ACCESS SHARE or EXCLUSIVE mode");
if(type == "node")
throw invalid_argument("Cannot get full object for nodes");
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
//Get main object
std::shared_ptr<class OsmData> outData(new class OsmData());
std::set<int64_t> objectIds;
objectIds.insert(objectId);
this->GetObjectsById(type, objectIds, outData);
//Get members of main object
if(type == "way")
{
if (outData->ways.size() != 1)
return; //Unexpected number of objects in intermediate result
class OsmWay &mainWay = outData->ways[0];
std::set<int64_t> memberNodes;
for(size_t i=0; i<mainWay.refs.size(); i++)
memberNodes.insert(mainWay.refs[i]);
this->GetObjectsById("node", memberNodes, outData);
}
else if(type == "relation")
{
if (outData->relations.size() != 1)
return; //Unexpected number of objects in intermediate result
class OsmRelation &mainRelation = outData->relations[0];
std::set<int64_t> memberNodes, memberWays, memberRelations;
for(const RelationMember &member : mainRelation.members)
{
if(member.type == ObjectType::Node)
memberNodes.insert(member.ref);
else if(member.type == ObjectType::Way)
memberWays.insert(member.ref);
else if(member.type == ObjectType::Relation)
memberRelations.insert(member.ref);
}
std::shared_ptr<class OsmData> memberWayObjs(new class OsmData());
this->GetObjectsById("node", memberNodes, outData);
this->GetObjectsById("way", memberWays, memberWayObjs);
this->GetObjectsById("relation", memberRelations, outData);
memberWayObjs->StreamTo(*outData.get());
std::set<int64_t> memberNodes2;
for(size_t i=0; i<memberWayObjs->ways.size(); i++)
for(size_t j=0; j<memberWayObjs->ways[i].refs.size(); j++)
memberNodes2.insert(memberWayObjs->ways[i].refs[j]);
this->GetObjectsById("node", memberNodes2, outData);
}
else
throw invalid_argument("Known object type");
outData->StreamTo(*out.get());
}
void PgTransaction::GetObjectsByIdVer(const std::string &type, const std::set<std::pair<int64_t, int64_t> > &objectIdVers,
std::shared_ptr<IDataStreamHandler> out)
{
if(this->shareMode != "ACCESS SHARE" && this->shareMode != "EXCLUSIVE")
throw runtime_error("Database must be locked in ACCESS SHARE or EXCLUSIVE mode");
if(objectIdVers.size()==0)
return;
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
//Query all tables that might contain object of this id and version
std::set<std::pair<int64_t, int64_t> >::const_iterator it = objectIdVers.begin();
while(it != objectIdVers.end())
DbGetObjectsByIdVer(*dbconn, work.get(), this->dbUsernameLookup,
this->tableStaticPrefix, type, "old", objectIdVers,
it, 1000, out);
it = objectIdVers.begin();
while(it != objectIdVers.end())
DbGetObjectsByIdVer(*dbconn, work.get(), this->dbUsernameLookup,
this->tableStaticPrefix, type, "live", objectIdVers,
it, 1000, out);
it = objectIdVers.begin();
while(it != objectIdVers.end())
DbGetObjectsByIdVer(*dbconn, work.get(), this->dbUsernameLookup,
this->tableActivePrefix, type, "old", objectIdVers,
it, 1000, out);
it = objectIdVers.begin();
while(it != objectIdVers.end())
DbGetObjectsByIdVer(*dbconn, work.get(), this->dbUsernameLookup,
this->tableActivePrefix, type, "live", objectIdVers,
it, 1000, out);
}
void PgTransaction::GetObjectsHistoryById(const std::string &type, const std::set<int64_t> &objectIds,
std::shared_ptr<IDataStreamHandler> out)
{
if(this->shareMode != "ACCESS SHARE" && this->shareMode != "EXCLUSIVE")
throw runtime_error("Database must be locked in ACCESS SHARE or EXCLUSIVE mode");
if(objectIds.size()==0)
return;
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
//Query all tables that might contain object of this id and version
std::set<int64_t>::const_iterator it = objectIds.begin();
while(it != objectIds.end())
DbGetObjectsHistoryById(*dbconn, work.get(), this->dbUsernameLookup,
this->tableStaticPrefix, type, "old", objectIds,
it, 1000, out);
it = objectIds.begin();
while(it != objectIds.end())
DbGetObjectsHistoryById(*dbconn, work.get(), this->dbUsernameLookup,
this->tableStaticPrefix, type, "live", objectIds,
it, 1000, out);
it = objectIds.begin();
while(it != objectIds.end())
DbGetObjectsHistoryById(*dbconn, work.get(), this->dbUsernameLookup,
this->tableActivePrefix, type, "old", objectIds,
it, 1000, out);
it = objectIds.begin();
while(it != objectIds.end())
DbGetObjectsHistoryById(*dbconn, work.get(), this->dbUsernameLookup,
this->tableActivePrefix, type, "live", objectIds,
it, 1000, out);
}
bool PgTransaction::StoreObjects(class OsmData &data,
std::map<int64_t, int64_t> &createdNodeIds,
std::map<int64_t, int64_t> &createdWayIds,
std::map<int64_t, int64_t> &createdRelationIds,
bool saveToStaticTables,
class PgMapError &errStr,
bool asEdit)
{
std::string nativeErrStr;
if(this->shareMode != "EXCLUSIVE")
throw runtime_error("Database must be locked in EXCLUSIVE mode");
if(atoi(this->GetMetaValue("readonly", errStr).c_str()) == 1)
{
errStr.errStr = "Database is in READ ONLY mode";
return false;
}
string tablePrefix = this->tableActivePrefix;
if(saveToStaticTables)
tablePrefix = this->tableStaticPrefix;
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
// The static tables hold the imported map, which no atomic edit made
int64_t atomicEditId = asEdit && !saveToStaticTables ? this->Recorder(work.get()).AtomicEditId() : 0;
bool ok = ::StoreObjects(*dbconn, work.get(), tablePrefix, data, createdNodeIds, createdWayIds, createdRelationIds,
nativeErrStr, atomicEditId);
errStr.errStr = nativeErrStr;
return ok;
}
int PgTransaction::UpdateObjectBboxesById(
const std::string &objType,
const std::set<int64_t> &objectIds, int verbose,
bool saveToStaticTables,
class PgMapError &errStr)
{
std::string nativeErrStr;
if(this->shareMode != "EXCLUSIVE")
throw runtime_error("Database must be locked in EXCLUSIVE mode");
if(atoi(this->GetMetaValue("readonly", errStr).c_str()) == 1)
{
errStr.errStr = "Database is in READ ONLY mode";
return false;
}
string tablePrefix = this->tableActivePrefix;
if(saveToStaticTables)
tablePrefix = this->tableStaticPrefix;
std::shared_ptr<pqxx::transaction_base> work(this->sharedWork->work);
if(!work)
throw runtime_error("Transaction has been deleted");
int ok = 1;
if(objType == "way")
ok = ::UpdateWayBboxesById(*dbconn, work.get(),
objectIds,
verbose,
tablePrefix,
nativeErrStr);
else if (objType == "relation")
{
ok = ::UpdateRelationBboxesById(*dbconn, work.get(),
objectIds,
verbose,
tablePrefix,
nativeErrStr);
}
errStr.errStr = nativeErrStr;
return ok;
}
// A streaming database sink: object contents remain in PostgreSQL, not OsmData.
// The query and destination writes use the same repeatable-read transaction.
class ExtractDatabaseWriter : public IDataStreamHandler
{
pqxx::connection &connection;
pqxx::transaction_base &work;
string prefix;
int64_t extractId;
void CopyObject(const string &kind, int64_t id)
{
string columns = "id, changeset, changeset_index, username, uid, timestamp, version, tags";
if(kind == "node") columns += ", geom";
else if(kind == "way") columns += ", members, bbox";
else columns += ", members, memberroles, bbox";
string destination = connection.quote_name(prefix + "extract_live" + kind + "s");
string source = connection.quote_name(prefix + "visible" + kind + "s");
work.exec("INSERT INTO " + destination + " (extract_id, " + columns + ") SELECT " +
to_string(extractId) + ", " + columns + " FROM " + source + " WHERE id=" +
to_string(id) + " ON CONFLICT (extract_id, id) DO NOTHING");
}
// types, when given, selects the members whose type starts with the
// letter ending the table suffix.
void Membership(const string &suffix, int64_t id, int64_t version,
const vector<int64_t> &refs, const vector<ObjectType> *types = nullptr)
{
// Bound each SQL batch even for unusually large ways or relations.
for(size_t start = 0; start < refs.size(); start += 1000)
{
string sql = "INSERT INTO " + connection.quote_name(prefix + "extract_" + suffix) +
" (extract_id, id, version, index, member) VALUES ";
bool any = false;
for(size_t i = start; i < refs.size() && i < start + 1000; ++i)
{
if(types && suffix.back() != ObjectTypeName((*types)[i])[0]) continue;
if(any) sql += ",";
any = true;
sql += "(" + to_string(extractId) + "," + to_string(id) + "," +
to_string(version) + "," + to_string(i) + "," + to_string(refs[i]) + ")";
}
if(any) work.exec(sql + " ON CONFLICT (extract_id, id, index) DO NOTHING");
}
}
public:
ExtractDatabaseWriter(pqxx::connection &c, pqxx::transaction_base &w,
const string &p, int64_t id): connection(c), work(w), prefix(p), extractId(id) {}
void StoreNode(const OsmNode &node) override
{
CopyObject("node", node.objId);
}
void StoreWay(const OsmWay &way) override
{
CopyObject("way", way.objId);
Membership("way_mems", way.objId, way.metaData.version, way.refs);
}
void StoreRelation(const OsmRelation &relation) override
{
vector<int64_t> refs;
vector<ObjectType> types;
for(const RelationMember &member : relation.members)
{
refs.push_back(member.ref);
types.push_back(member.type);
}
CopyObject("relation", relation.objId);
for(const char *suffix : {"relation_mems_n", "relation_mems_w", "relation_mems_r"})
Membership(suffix, relation.objId, relation.metaData.version, refs, &types);
}
};
void PgTransaction::LockExtractTables(const string &accessMode)
{
if(accessMode != "ACCESS SHARE" && accessMode != "EXCLUSIVE")
throw invalid_argument("Unsupported extract lock mode");
auto work = sharedWork->work;
if(!work) throw runtime_error("Transaction has been deleted");
// The constructor acquires static then active main-map locks first.
// Every extract operation must use this same table order, in one statement,
// before accessing any extract metadata, objects or membership rows.
string sql = "LOCK TABLE ";
bool first = true;
for(const char *name : {"extracts", "extract_livenodes", "extract_liveways",
"extract_liverelations", "extract_way_mems", "extract_relation_mems_n",
"extract_relation_mems_w", "extract_relation_mems_r"})
{
if(!first) sql += ",";
first = false;
sql += dbconn->quote_name(tableActivePrefix + name);
}
work->exec(sql + " IN " + accessMode + " MODE;");
// Locks are owned by the transaction and released at commit or abort.
}
int64_t PgTransaction::SaveExtract(const vector<double> &bbox, const string &name)
{
if(bbox.size() != 4) throw invalid_argument("Bbox must have four coordinates");
for(double value : bbox)
if(!std::isfinite(value)) throw invalid_argument("Bbox coordinates must be finite");
if(bbox[0] < -180 || bbox[2] > 180 || bbox[1] < -90 || bbox[3] > 90 ||
bbox[0] >= bbox[2] || bbox[1] >= bbox[3])
throw invalid_argument("Bbox must be a nonempty longitude/latitude rectangle");
auto work = sharedWork->work;
if(!work) throw runtime_error("Transaction has been deleted");
string envelope = "ST_MakeEnvelope(";
for(size_t i=0; i<4; ++i) envelope += work->quote(bbox[i]) + ",";
envelope += "4326)";
return SaveExtractArea(envelope, bbox, "", name);
}
int64_t PgTransaction::SaveExtractWkt(const string &wkt, const string &name)
{
if(shareMode != "ACCESS SHARE" && shareMode != "EXCLUSIVE")
throw runtime_error("Map must be locked while creating an extract");
auto work = sharedWork->work;
if(!work) throw runtime_error("Transaction has been deleted");
string boundary = DbCheckExtractBoundary(*work, wkt);
return SaveExtractArea("ST_GeomFromText(" + work->quote(boundary) + ", 4326)", vector<double>(), boundary, name);
}
std::string PgTransaction::BufferExtractBoundary(const string &wkt, double bufferMetres)
{
auto work = sharedWork->work;
if(!work) throw runtime_error("Transaction has been deleted");
return DbBufferExtractBoundary(*work, wkt, bufferMetres);
}
int64_t PgTransaction::SaveExtractArea(const string &areaSql, const vector<double> &bbox,
const string &wkt, const string &name)
{
if(shareMode != "ACCESS SHARE" && shareMode != "EXCLUSIVE")
throw runtime_error("Map must be locked while creating an extract");
LockExtractTables("EXCLUSIVE");
auto work = sharedWork->work;
if(!work) throw runtime_error("Transaction has been deleted");
// Capture both cursors from the same snapshot as the map query. No later
// commits can advance these checkpoints beyond the contents being extracted.
string activity = dbconn->quote_name(tableActivePrefix + "edit_activity");
auto checkpoint = work->exec("SELECT COALESCE(max(id),0), COALESCE(max(atomic_edit_id),0) FROM " + activity);
auto mode = work->exec("SELECT value FROM " + dbconn->quote_name(tableActivePrefix + "meta") +
" WHERE key='useBboxInQuery'");
bool bboxMode = !mode.empty() && atoi(mode[0][0].as<string>().c_str()) == 1;
string sql = "INSERT INTO " + dbconn->quote_name(tableActivePrefix + "extracts") +
" (name, bbox, use_bbox_in_query, performed_at, edit_activity_id, atomic_edit_id) VALUES (" +
work->quote(name) + "," + areaSql + "," + (bboxMode ? "true" : "false") +
",CURRENT_TIMESTAMP," + checkpoint[0][0].as<string>() + "," +
checkpoint[0][1].as<string>() + ") RETURNING id";
int64_t id = work->exec(sql)[0][0].as<int64_t>();
shared_ptr<IDataStreamHandler> sink = make_shared<ExtractDatabaseWriter>(*dbconn, *work, tableActivePrefix, id);
auto query = GetQueryMgr();
int status = wkt.empty() ? query->Start(bbox, time(nullptr), sink) : query->Start(wkt, time(nullptr), sink);
while(status == 0) status = query->Continue();
if(status < 0) throw runtime_error("Extract map query failed");
return id;
}
std::map<std::string, std::string> PgTransaction::GetExtractHeaderAttribs(int64_t extractId, const string &name,
const string &publicUrl)
{
std::vector<ExtractInfo> extracts, selected;
this->ListExtracts(extracts);
for(const ExtractInfo &info : extracts)
if(extractId ? info.extractId == extractId : info.name == name)
selected.push_back(info);
TagMap attribs;
if(selected.size() != 1)
return attribs; // Not found or ambiguous is reported by the export itself
const ExtractInfo &info = selected[0];
// The IDs an extract is current to are its stored checkpoint, not the
// map's latest: the extract may be waiting for an update
if(info.editActivityId >= 0 && info.atomicEditId >= 0)
{
attribs["edit_activity_id"] = std::to_string(info.editActivityId);
attribs["atomic_edit_id"] = std::to_string(info.atomicEditId);
}
if(info.rectangular)
{
string bbox;
for(size_t i = 0; i < info.bbox.size(); i++)
bbox += (i ? "," : "") + ShortestDouble(info.bbox[i]);
attribs["bbox"] = bbox;
}
else
attribs["boundary"] = info.boundaryWkt;
// An extract kept up from another server follows that server's edits, and