Repository navigation
Expand file tree
/
Copy pathdbadmin.cpp
More file actions
2397 lines (2170 loc) · 103 KB
/
Copy pathdbadmin.cpp
File metadata and controls
2397 lines (2170 loc) · 103 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 "dbadmin.h"
#include <limits>
#include "dbids.h"
#include "dbcommon.h"
#include "dbstore.h"
#include "dbdecode.h"
#include "dbquery.h"
#include "dbusername.h"
#include "dbmeta.h"
#include "dbeditactivity.h"
#include "util.h"
#include "cppGzip/DecodeGzip.h"
#include "cppo5m/io.h"
#include <map>
#include <set>
#include <boost/filesystem.hpp>
#include <fstream>
#include <optional>
#include "dbjson.h"
using namespace std;
using namespace boost::filesystem;
bool ClearTable(pqxx::connection &c, pqxx::transaction_base *work, const string &tableName, std::string &errStr)
{
try
{
string deleteSql = "DELETE FROM "+ c.quote_name(tableName) + ";";
work->exec(deleteSql);
}
catch (const pqxx::sql_error &e)
{
errStr = e.what();
return false;
}
catch (const std::exception &e)
{
errStr = e.what();
return false;
}
return true;
}
bool ResetActiveTables(pqxx::connection &c, pqxx::transaction_base *work,
const string &tableActivePrefix,
const string &tableStaticPrefix,
std::string &errStr)
{
bool ok = ClearTable(c, work, tableActivePrefix + "livenodes", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "liveways", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "liverelations", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "oldnodes", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "oldways", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "oldrelations", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "nodeids", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "wayids", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "relationids", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "way_mems", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "relation_mems_n", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "relation_mems_w", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "relation_mems_r", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "nextids", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "changesets", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "usernames", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "edit_activity", errStr); if(!ok) return false;
ok = ClearTable(c, work, tableActivePrefix + "query_activity", errStr); if(!ok) return false;
for(const char *shapes : {"way_shapes", "relation_shapes"})
if(DbCheckTableExists(c, work, tableActivePrefix + shapes))
{
ok = ClearTable(c, work, tableActivePrefix + shapes, errStr);
if(!ok) return false;
}
map<string, int64_t> nextIdMap;
ok = GetNextObjectIds(c, work,
tableStaticPrefix,
nextIdMap,
errStr);
if(!ok) return false;
map<string, int64_t> emptyIdMap;
ok = UpdateNextObjectIds(c, work, tableActivePrefix, nextIdMap, emptyIdMap, errStr);
if(!ok) return false;
//Update next changeset and UIDs
ok = ResetChangesetUidCounts(c, work,
tableStaticPrefix, tableActivePrefix,
errStr);
if(!ok) return false;
return ok;
}
bool DbUpgradeTables0to11(pqxx::connection &c, pqxx::transaction_base *work,
int verbose,
const string &tablePrefix,
std::string &errStr)
{
string j = "JSONB";
string sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"oldnodes")+" (id BIGINT, changeset BIGINT, changeset_index SMALLINT, username TEXT, uid INTEGER, visible BOOLEAN, timestamp BIGINT, version INTEGER, tags "+j+", geom GEOMETRY(Point, 4326));";
bool ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"oldways")+" (id BIGINT, changeset BIGINT, changeset_index SMALLINT, username TEXT, uid INTEGER, visible BOOLEAN, timestamp BIGINT, version INTEGER, tags "+j+", members "+j+");";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"oldrelations")+" (id BIGINT, changeset BIGINT, changeset_index SMALLINT, username TEXT, uid INTEGER, visible BOOLEAN, timestamp BIGINT, version INTEGER, tags "+j+", members "+j+", memberroles "+j+");";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"livenodes")+" (id BIGINT, changeset BIGINT, changeset_index SMALLINT, username TEXT, uid INTEGER, timestamp BIGINT, version INTEGER, tags "+j+", geom GEOMETRY(Point, 4326));";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"liveways")+" (id BIGINT, changeset BIGINT, changeset_index SMALLINT, username TEXT, uid INTEGER, timestamp BIGINT, version INTEGER, tags "+j+", members "+j+");";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"liverelations")+" (id BIGINT, changeset BIGINT, changeset_index SMALLINT, username TEXT, uid INTEGER, timestamp BIGINT, version INTEGER, tags "+j+", members "+j+", memberroles "+j+");";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"nodeids")+" (id BIGINT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"wayids")+" (id BIGINT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"relationids")+" (id BIGINT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"way_mems")+" (id BIGINT, version INTEGER, index INTEGER, member BIGINT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"relation_mems_n")+" (id BIGINT, version INTEGER, index INTEGER, member BIGINT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"relation_mems_w")+" (id BIGINT, version INTEGER, index INTEGER, member BIGINT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"relation_mems_r")+" (id BIGINT, version INTEGER, index INTEGER, member BIGINT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"nextids")+" (id VARCHAR(16), maxid BIGINT, PRIMARY KEY(id));";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"meta")+" (key TEXT, value TEXT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DELETE FROM "+c.quote_name(tablePrefix+"meta")+" WHERE key = 'schema_version';";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "INSERT INTO "+c.quote_name(tablePrefix+"meta")+" (key, value) VALUES ('schema_version', '11');";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"changesets")+" (id BIGINT, username TEXT, uid INTEGER, tags "+j+", open_timestamp BIGINT, close_timestamp BIGINT, is_open BOOLEAN, geom GEOMETRY(Polygon, 4326), PRIMARY KEY(id));";
ok = DbExec(work, sql, errStr, nullptr, verbose);
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"usernames")+" (uid INTEGER, timestamp BIGINT, username TEXT);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
return ok;
}
static bool DbDefineVisibleViews(pqxx::connection &c, pqxx::transaction_base *work, int verbose,
const std::string &parentPrefix, const std::string &tablePrefix, bool distinct, std::string &errStr);
bool DbUpgradeTables11to12(pqxx::connection &c, pqxx::transaction_base *work,
int verbose,
const std::string &parentPrefix,
const std::string &tablePrefix,
std::string &errStr)
{
cout << "DbUpgradeTables11to12" << endl;
bool ok = true;
string sql;
sql = "ALTER TABLE "+c.quote_name(tablePrefix+"liveways")+" ADD COLUMN bbox GEOMETRY(Geometry, 4326);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "ALTER TABLE "+c.quote_name(tablePrefix+"liverelations")+" ADD COLUMN bbox GEOMETRY(Geometry, 4326);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
// As tables were then: rows compared to remove duplicates
return DbDefineVisibleViews(c, work, verbose, parentPrefix, tablePrefix, true, errStr);
}
bool DbUpgradeTables12to13(pqxx::connection &c, pqxx::transaction_base *work,
int verbose,
const std::string &parentPrefix,
const std::string &tablePrefix,
std::string &errStr)
{
cout << "DbUpgradeTables12to13" << endl;
bool ok = true;
string sql;
string ine = "IF NOT EXISTS ";
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"edit_activity")+" (id SERIAL PRIMARY KEY, changeset BIGINT, timestamp BIGINT, uid INTEGER, bbox GEOMETRY(Geometry, 4326), action VARCHAR(16), nodes INT, ways INT, relations INT, existing JSONB, updated JSONB, affectedparents JSONB, related JSONB);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE INDEX "+ine+c.quote_name(tablePrefix+"activity_ts")+" ON "+c.quote_name(tablePrefix+"edit_activity")+" (timestamp);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE TABLE IF NOT EXISTS "+c.quote_name(tablePrefix+"query_activity")+" (id SERIAL PRIMARY KEY, timestamp BIGINT, bbox GEOMETRY(Geometry, 4326), metrics JSONB);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "CREATE INDEX "+ine+c.quote_name(tablePrefix+"query_activity_ts")+" ON "+c.quote_name(tablePrefix+"query_activity")+" (timestamp);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "ALTER TABLE "+c.quote_name(tablePrefix+"changesets")+" ALTER COLUMN geom TYPE GEOMETRY(Geometry, 4326);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
return ok;
}
// Extracts store independent current states, not static/mod overlays.
bool DbCreateExtractTables(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const string &tablePrefix, string &errStr)
{
string metadata = c.quote_name(tablePrefix + "extracts");
string sql = "CREATE TABLE IF NOT EXISTS " + metadata +
" (id BIGSERIAL PRIMARY KEY, name TEXT, bbox GEOMETRY(Polygon, 4326) NOT NULL, "
"use_bbox_in_query BOOLEAN NOT NULL DEFAULT false, "
"performed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"edit_activity_id BIGINT CHECK (edit_activity_id >= 0), "
"atomic_edit_id BIGINT CHECK (atomic_edit_id >= 0), "
"auto_update BOOLEAN NOT NULL DEFAULT false, "
"update_url TEXT NOT NULL DEFAULT '');";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
// Columns added to schema 14 after it was first in use: whether the extract
// is to be kept up to date automatically, and the API to update it from,
// blank meaning this map. An extracts table made before then gains them here.
sql = "ALTER TABLE " + metadata +
" ADD COLUMN IF NOT EXISTS auto_update BOOLEAN NOT NULL DEFAULT false, "
"ADD COLUMN IF NOT EXISTS update_url TEXT NOT NULL DEFAULT '';";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
// Match live map object columns, adding extract_id to scope every object.
string common = " (extract_id BIGINT NOT NULL REFERENCES " + metadata +
"(id) ON DELETE CASCADE, id BIGINT NOT NULL, changeset BIGINT, "
"changeset_index SMALLINT, username TEXT, uid INTEGER, timestamp BIGINT, "
"version INTEGER NOT NULL, tags JSONB, ";
for(const char *type : {"node", "way", "relation"})
{
string kind(type);
string table = c.quote_name(tablePrefix + "extract_live" + kind + "s");
string columns;
if(kind == "node") columns = "geom GEOMETRY(Point, 4326)";
else if(kind == "way") columns = "members JSONB, bbox GEOMETRY(Geometry, 4326)";
else columns = "members JSONB, memberroles JSONB, bbox GEOMETRY(Geometry, 4326)";
sql = "CREATE TABLE IF NOT EXISTS " + table + common + columns +
", PRIMARY KEY (extract_id, id));";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "CREATE INDEX IF NOT EXISTS " + c.quote_name(tablePrefix + "extract_live" + kind + "s_gix") +
" ON " + table + " USING GIST (" + (kind == "node" ? "geom" : "bbox") + ");";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
// Keep reverse membership lookups within an extract. Do not require every
// relation member to exist: map queries do not return complete relations.
for(const char *suffix : {"way_mems", "relation_mems_n", "relation_mems_w", "relation_mems_r"})
{
string table = c.quote_name(tablePrefix + "extract_" + suffix);
string owner = string(suffix) == "way_mems" ? "way" : "relation";
sql = "CREATE TABLE IF NOT EXISTS " + table +
" (extract_id BIGINT NOT NULL, id BIGINT NOT NULL, version INTEGER NOT NULL, "
"index INTEGER NOT NULL, member BIGINT NOT NULL, PRIMARY KEY (extract_id, id, index), "
"FOREIGN KEY (extract_id, id) REFERENCES " +
c.quote_name(tablePrefix + "extract_live" + owner + "s") + "(extract_id, id) ON DELETE CASCADE);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "CREATE INDEX IF NOT EXISTS " + c.quote_name(tablePrefix + "extract_" + suffix + "_member_idx") +
" ON " + table + " (extract_id, member);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
return true;
}
bool DbDropExtractTables(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const string &tablePrefix, string &errStr)
{
for(const char *name : {"extract_way_mems", "extract_relation_mems_n", "extract_relation_mems_w",
"extract_relation_mems_r", "extract_livenodes", "extract_liveways", "extract_liverelations", "extracts"})
{
string sql = "DROP TABLE IF EXISTS " + c.quote_name(tablePrefix + name) + " CASCADE;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
return true;
}
// An index on each box column of edit_activity, as version 14 finds the
// records concerning an area with; or with enabled false, none.
static bool DbSetActivityBoxIndexes(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const string &tablePrefix, bool enabled, string &errStr)
{
for(const char *column : {"existing_bbox", "updated_bbox",
"affectedparents_before_bbox", "affectedparents_after_bbox", "relation_reach_bbox"})
{
string index = c.quote_name(tablePrefix + "activity_gix_" + column);
string sql = enabled ? "CREATE INDEX IF NOT EXISTS " + index + " ON " +
c.quote_name(tablePrefix + "edit_activity") + " USING GIST (" + column + ");" :
"DROP INDEX IF EXISTS " + index + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
return true;
}
// What schema 14 has gained since it was introduced. Every step leaves alone
// whatever is already there, so it both finishes an upgrade to version 14 and
// brings an older version 14 up to date.
bool DbAmendSchema14(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const string &tablePrefix, bool boxIndexes, string &errStr)
{
// related_parents: the relations holding an edit's related nodes. The four
// bbox columns: the boxes that go with the lists of existing, updated and
// affected parent objects, each a collection with one geometry for every
// object of its list. See EditActivity. Rows from before a column existed
// keep NULL there, meaning not recorded.
string box = " GEOMETRY(GeometryCollection, 4326)";
string sql = "ALTER TABLE " + c.quote_name(tablePrefix + "edit_activity") +
" ADD COLUMN IF NOT EXISTS related_parents JSONB,"
" ADD COLUMN IF NOT EXISTS existing_bbox" + box + ","
" ADD COLUMN IF NOT EXISTS updated_bbox" + box + ","
" ADD COLUMN IF NOT EXISTS affectedparents_before_bbox" + box + ","
" ADD COLUMN IF NOT EXISTS affectedparents_after_bbox" + box + ","
// Where an edited relation matters beyond its own box: the extent of
// the ways sharing its member nodes. NULL when there is nowhere more.
" ADD COLUMN IF NOT EXISTS relation_reach_bbox GEOMETRY(Polygon, 4326),"
// Four columns that schema 14 began with and nothing came to use: the
// lists of existing objects and these boxes say what they were for.
// The checks that tied them together go with them.
" DROP COLUMN IF EXISTS sync_before, DROP COLUMN IF EXISTS bbox_before,"
" DROP COLUMN IF EXISTS sync_after, DROP COLUMN IF EXISTS bbox_after,"
// The table's original box of a whole edit, which nothing ever filled in
" DROP COLUMN IF EXISTS bbox;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
// Finding the records of a changeset, as its change counts do, without
// reading the whole table
sql = "CREATE INDEX IF NOT EXISTS " + c.quote_name(tablePrefix + "activity_changeset") +
" ON " + c.quote_name(tablePrefix + "edit_activity") + " (changeset);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
// Finding the records that concern an area, which tests each of these.
// Version 15 has one index on the footprint in their place, so they are
// not made again for a map at 15.
if(boxIndexes && !DbSetActivityBoxIndexes(c, work, verbose, tablePrefix, true, errStr))
return false;
return DbCreateExtractTables(c, work, verbose, tablePrefix, errStr);
}
// The member tables, with the kind of object that owns each one's rows
static const char *MEMBER_TABLES[4][2] = {{"way_mems", "way"}, {"relation_mems_n", "relation"},
{"relation_mems_w", "relation"}, {"relation_mems_r", "relation"}};
// The views of the objects a table set shows: its own live objects, and its
// parent's except those it has taken over, or for a table set with no
// parent, its live objects alone. distinct says whether rows are also
// compared with each other to remove duplicates, as before version 15.
//
// The columns are named, as the table set's live table has them, rather
// than taken as *: a table set and its parent are brought from one schema
// version to the next one after the other, so while one is being changed
// they can have different columns. Defined again, a view shows what columns
// have been added since; a view's * would stand for the columns there were
// when it was made.
static bool DbDefineVisibleViews(pqxx::connection &c, pqxx::transaction_base *work, int verbose,
const std::string &parentPrefix, const std::string &tablePrefix, bool distinct, std::string &errStr)
{
for(const char *kind : {"node", "way", "relation"})
{
string view = c.quote_name(tablePrefix + "visible" + kind + "s");
string live = c.quote_name(tablePrefix + "live" + kind + "s");
string sql;
if(parentPrefix.empty())
sql = "CREATE OR REPLACE VIEW " + view + " AS SELECT * FROM " + live + ";";
else
{
string parent = c.quote_name(parentPrefix + "visible" + kind + "s");
string ids = c.quote_name(tablePrefix + kind + "ids");
pqxx::result r = work->exec("SELECT attname FROM pg_attribute WHERE attrelid = to_regclass(" +
work->quote(live) + ") AND attnum > 0 AND NOT attisdropped ORDER BY attnum");
string ownColumns, parentColumns;
for(pqxx::result::size_type i=0; i<r.size(); i++)
{
string column = c.quote_name(r[i][0].as<string>());
ownColumns += (i ? ", " : "") + column;
parentColumns += (i ? ", " : "") + parent + "." + column;
}
sql = "CREATE OR REPLACE VIEW " + view + " AS SELECT " + parentColumns + " FROM " + parent +
" LEFT JOIN " + ids + " ON " + ids + ".id = " + parent + ".id WHERE " + ids + ".id IS NULL " +
(distinct ? "UNION" : "UNION ALL") + " SELECT " + ownColumns + " FROM " + live + ";";
}
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
return true;
}
// The shapes an extract's boundary may have: a polygon, or from schema 15 a
// multipolygon too, such as a region with islands. Going back to a polygon
// column is refused while any extract has a multipolygon, which it could not
// hold.
static bool DbSetExtractBoundaryShapes(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &tablePrefix, bool multipolygons, std::string &errStr)
{
string name = tablePrefix + "extracts";
pqxx::result column = work->exec("SELECT format_type(a.atttypid, a.atttypmod) FROM pg_attribute a "
"WHERE a.attrelid = to_regclass(" + work->quote(c.quote_name(name)) + ") AND a.attname = 'bbox'");
if(column.empty()) return true; // No extract tables here
string table = c.quote_name(name);
string check = c.quote_name(tablePrefix + "extracts_bbox_shape");
string sql;
if(multipolygons)
{
if(column[0][0].as<string>() != "geometry(Geometry,4326)")
{
sql = "ALTER TABLE " + table + " ALTER COLUMN bbox TYPE GEOMETRY(Geometry, 4326);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
sql = "ALTER TABLE " + table + " DROP CONSTRAINT IF EXISTS " + check + ", ADD CONSTRAINT " + check +
" CHECK (GeometryType(bbox) IN ('POLYGON', 'MULTIPOLYGON'));";
return DbExec(work, sql, errStr, nullptr, verbose);
}
pqxx::result multi = work->exec("SELECT id FROM " + table + " WHERE GeometryType(bbox) <> 'POLYGON' ORDER BY id");
if(!multi.empty())
{
errStr = "Extracts " + multi[0][0].as<string>();
for(pqxx::result::size_type i = 1; i < multi.size() && i < 10; i++)
errStr += ", " + multi[i][0].as<string>();
errStr += string(multi.size() > 10 ? " and more" : "") + " in " + name + " have a multipolygon boundary, "
"which schema 14 cannot hold; delete them before going back to it";
return false;
}
sql = "ALTER TABLE " + table + " DROP CONSTRAINT IF EXISTS " + check + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "ALTER TABLE " + table + " ALTER COLUMN bbox TYPE GEOMETRY(Polygon, 4326);";
return DbExec(work, sql, errStr, nullptr, verbose);
}
// Edits announce themselves: when rows are added to edit_activity, PostgreSQL
// sends a notification on the channel <prefix>edits, with the highest edit
// activity ID and atomic edit ID added, as JSON. It goes out when the
// transaction commits, and not at all if it is rolled back, so whoever hears it
// can read the edits at once. Only connections listening at the time hear it;
// see notify/ in the parent project, which passes it on to clients.
static bool DbSetEditNotifications(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &tablePrefix, bool enabled, std::string &errStr)
{
string table = tablePrefix + "edit_activity";
if(work->exec("SELECT to_regclass(" + work->quote(c.quote_name(table)) + ")")[0][0].is_null())
return true; // No edit activity here
string function = c.quote_name(tablePrefix + "notify_edits");
string sql = "DROP TRIGGER IF EXISTS " + c.quote_name(tablePrefix + "notify_edits") + " ON " + c.quote_name(table) + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
if(!enabled)
{
sql = "DROP FUNCTION IF EXISTS " + function + "();";
return DbExec(work, sql, errStr, nullptr, verbose);
}
// Once for each statement, however many rows it adds: an upload adds
// several at a time
sql = "CREATE OR REPLACE FUNCTION " + function + "() RETURNS trigger LANGUAGE plpgsql AS $$\n"
"BEGIN\n"
" PERFORM pg_notify(" + work->quote(tablePrefix + "edits") + ", (SELECT json_build_object("
"'edit_activity_id', max(id), 'atomic_edit_id', max(atomic_edit_id))::text FROM added));\n"
" RETURN NULL;\n"
"END\n"
"$$;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "CREATE TRIGGER " + c.quote_name(tablePrefix + "notify_edits") + " AFTER INSERT ON " + c.quote_name(table) +
" REFERENCING NEW TABLE AS added FOR EACH STATEMENT EXECUTE FUNCTION " + function + "();";
return DbExec(work, sql, errStr, nullptr, verbose);
}
// The footprint of each edit activity record: the rectangle around all its
// boxes (the four collections and relation_reach_bbox), or the whole world
// when one of the collections was not recorded, as such a record may concern
// anywhere. It is worked out by PostgreSQL as each row is written, and has
// one GiST index together with the ID, so finding the records of a range of
// IDs that may concern an area is one index scan, in place of a test of each
// row against five columns. The exact test of the boxes follows, on the rows
// this finds. The footprint takes the place of the indexes on the separate
// boxes; with enabled false, they come back.
//
// btree_gist provides the ID's part of the index. It is a trusted extension,
// which the owner of the database may create.
static bool DbSetEditFootprint(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &tablePrefix, bool enabled, std::string &errStr)
{
string table = tablePrefix + "edit_activity";
if(work->exec("SELECT to_regclass(" + work->quote(c.quote_name(table)) + ")")[0][0].is_null())
return true; // No edit activity here
string sql;
if(!enabled)
{
// The index goes with the column
sql = "ALTER TABLE " + c.quote_name(table) + " DROP COLUMN IF EXISTS footprint;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
return DbSetActivityBoxIndexes(c, work, verbose, tablePrefix, true, errStr);
}
sql = "ALTER TABLE " + c.quote_name(table) + " ADD COLUMN IF NOT EXISTS footprint GEOMETRY(Geometry, 4326) "
"GENERATED ALWAYS AS (CASE WHEN existing_bbox IS NULL OR updated_bbox IS NULL "
"OR affectedparents_before_bbox IS NULL OR affectedparents_after_bbox IS NULL "
"THEN ST_MakeEnvelope(-180, -90, 180, 90, 4326) "
"ELSE ST_Envelope(ST_Collect(ARRAY[existing_bbox, updated_bbox, affectedparents_before_bbox, "
"affectedparents_after_bbox, relation_reach_bbox::geometry])) END) STORED;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "CREATE EXTENSION IF NOT EXISTS btree_gist;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "CREATE INDEX IF NOT EXISTS " + c.quote_name(tablePrefix + "activity_gix_footprint") +
" ON " + c.quote_name(table) + " USING GIST (id, footprint);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
return DbSetActivityBoxIndexes(c, work, verbose, tablePrefix, false, errStr);
}
// What schema 15 has gained since it was introduced, as for schema 14: every
// step leaves alone whatever is already there.
bool DbAmendSchema15(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &tablePrefix, std::string &errStr)
{
if(!DbSetExtractBoundaryShapes(c, work, verbose, tablePrefix, true, errStr)) return false;
if(!DbSetEditFootprint(c, work, verbose, tablePrefix, true, errStr)) return false;
return DbSetEditNotifications(c, work, verbose, tablePrefix, true, errStr);
}
// Version 15:
// - An extract's boundary may be a multipolygon as well as a polygon (see
// DbSetExtractBoundaryShapes), edits are announced with NOTIFY (see
// DbSetEditNotifications), and each edit activity record has a footprint,
// indexed with its ID (see DbSetEditFootprint), in place of an index on
// each of its boxes. These came after version 15 was first in use,
// so DbAmendSchema15 brings a map already at 15 up to date.
// - The member tables (way_mems, relation_mems_*) hold the members of the
// live version of each way and relation, and nothing else. Until now rows
// were added for every version stored and never removed, and nothing
// stopped the same row being added twice. Only the live version's rows
// are ever looked up; an old version's members remain in its history row.
// The tables are rebuilt here from the live tables, which are the
// authority, and given a primary key of (id, version, index).
// - The visible* views no longer compare whole rows to remove duplicates
// (UNION ALL in place of UNION): the two halves cannot overlap.
bool DbUpgradeTables14to15(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &parentPrefix, const std::string &tablePrefix, std::string &errStr)
{
for(const auto &entry : MEMBER_TABLES)
{
string suffix = entry[0], owner = entry[1];
string table = c.quote_name(tablePrefix + suffix);
string live = c.quote_name(tablePrefix + "live" + owner + "s");
string memberIndex = tablePrefix + suffix + "_mids";
bool hadIndex = !work->exec("SELECT to_regclass(" + work->quote(c.quote_name(memberIndex)) + ")")[0][0].is_null();
// Filling an empty table and indexing it afterwards is far quicker
// than deleting from a full one
string sql = "DROP INDEX IF EXISTS " + c.quote_name(memberIndex) + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "TRUNCATE " + table + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
if(owner == "way")
sql = "INSERT INTO " + table + " (id, version, index, member) SELECT o.id, o.version, "
"(m.ordinality-1)::integer, m.value::text::bigint FROM " + live +
" o CROSS JOIN LATERAL jsonb_array_elements(o.members) WITH ORDINALITY m;";
else
sql = "INSERT INTO " + table + " (id, version, index, member) SELECT o.id, o.version, "
"(m.ordinality-1)::integer, (m.value->>1)::bigint FROM " + live +
" o CROSS JOIN LATERAL jsonb_array_elements(o.members) WITH ORDINALITY m "
"WHERE m.value->>0 = " + work->quote(string(1, suffix.back()) == "n" ? string("node") :
(suffix.back() == 'w' ? string("way") : string("relation"))) + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "ALTER TABLE " + table + " ADD CONSTRAINT " + c.quote_name(tablePrefix + suffix + "_key") +
" PRIMARY KEY (id, version, index);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
if(hadIndex)
{
sql = "CREATE INDEX " + c.quote_name(memberIndex) + " ON " + table + " (member);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
}
return DbDefineVisibleViews(c, work, verbose, parentPrefix, tablePrefix, false, errStr);
}
// The member tables keep what they hold, which the earlier version reads
// just as well; only the key and the form of the views go back.
bool DbDowngradeTables15To14(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &parentPrefix, const std::string &tablePrefix, std::string &errStr)
{
if(!DbSetExtractBoundaryShapes(c, work, verbose, tablePrefix, false, errStr)) return false;
if(!DbSetEditNotifications(c, work, verbose, tablePrefix, false, errStr)) return false;
if(!DbSetEditFootprint(c, work, verbose, tablePrefix, false, errStr)) return false;
for(const auto &entry : MEMBER_TABLES)
{
string suffix = entry[0];
string sql = "ALTER TABLE " + c.quote_name(tablePrefix + suffix) + " DROP CONSTRAINT IF EXISTS " +
c.quote_name(tablePrefix + suffix + "_key") + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
for(const char *column : {"id", "version", "index"})
{
sql = "ALTER TABLE " + c.quote_name(tablePrefix + suffix) + " ALTER COLUMN " + column + " DROP NOT NULL;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
}
return DbDefineVisibleViews(c, work, verbose, parentPrefix, tablePrefix, true, errStr);
}
// Version 16: every version of every object records the atomic edit that
// made it, as atomic_edit_id in the live and history tables, the same ID as
// the edit's activity records. Versions from before this, the imported map
// in the static tables, and copies of versions the map already had (as an
// edit makes of the ways and relations holding what it changes) have NULL.
// The views of visible objects are defined again to show the column.
//
// A version in history also records the atomic edit that made it no longer
// current, as superseded_atomic_edit_id: the edit that made the next
// version, or deleted the object. A version of the parent's that a table set
// hides, from the first edit it makes to the object, is recorded the same
// way in the table set's ID tables (nodeids, wayids, relationids), as the
// parent's own tables (the imported map) are not written to. NULL means
// current, or replaced before version 16, or (in the ID tables) an object
// the table set made or only copied.
bool DbUpgradeTables15to16(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &parentPrefix, const std::string &tablePrefix, std::string &errStr)
{
for(const char *kind : {"node", "way", "relation"})
{
for(const char *table : {"live", "old"})
{
string sql = "ALTER TABLE " + c.quote_name(tablePrefix + table + kind + "s") +
" ADD COLUMN IF NOT EXISTS atomic_edit_id BIGINT;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
for(const char *table : {"old", ""})
{
string name = tablePrefix + table + kind + (table[0] ? "s" : "ids");
string sql = "ALTER TABLE " + c.quote_name(name) + " ADD COLUMN IF NOT EXISTS superseded_atomic_edit_id BIGINT;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
}
return DbDefineVisibleViews(c, work, verbose, parentPrefix, tablePrefix, false, errStr);
}
// The column goes, and with it the views showing it: this table set's, and
// those of any table set above it, whose own step defines them again (the
// table sets are taken from the static ones up).
bool DbDowngradeTables16To15(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const std::string &parentPrefix, const std::string &tablePrefix, std::string &errStr)
{
for(const char *kind : {"node", "way", "relation"})
{
for(const char *table : {"live", "old"})
{
string sql = "ALTER TABLE " + c.quote_name(tablePrefix + table + kind + "s") +
" DROP COLUMN IF EXISTS atomic_edit_id CASCADE;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
for(const char *table : {"old", ""})
{
string name = tablePrefix + table + kind + (table[0] ? "s" : "ids");
string sql = "ALTER TABLE " + c.quote_name(name) + " DROP COLUMN IF EXISTS superseded_atomic_edit_id;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
}
return DbDefineVisibleViews(c, work, verbose, parentPrefix, tablePrefix, false, errStr);
}
// Legacy rows remain ungrouped: timestamps cannot recover upload boundaries.
bool DbUpgradeTables13to14(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const string &tablePrefix, string &errStr)
{
string table = c.quote_name(tablePrefix + "edit_activity");
string sql = "CREATE SEQUENCE " + c.quote_name(tablePrefix + "atomic_edit_id_seq") + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "ALTER TABLE " + table + " ADD COLUMN atomic_edit_id BIGINT, ADD COLUMN block_index BIGINT, "
"ADD CHECK ((atomic_edit_id IS NULL AND block_index IS NULL) OR "
"(atomic_edit_id IS NOT NULL AND atomic_edit_id > 0 AND block_index IS NOT NULL AND block_index >= 0));";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "CREATE UNIQUE INDEX " + c.quote_name(tablePrefix + "activity_atomic_block") +
" ON " + table + " (atomic_edit_id, block_index);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
return DbAmendSchema14(c, work, verbose, tablePrefix, true, errStr);
}
bool DbDowngradeTables14To13(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const string &tablePrefix, string &errStr)
{
if(!DbDropExtractTables(c, work, verbose, tablePrefix, errStr)) return false;
string sql = "DROP INDEX IF EXISTS " + c.quote_name(tablePrefix + "activity_changeset") + ";";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
// The box indices go with their columns, below
sql = "ALTER TABLE " + c.quote_name(tablePrefix + "edit_activity") +
" DROP COLUMN IF EXISTS related_parents, DROP COLUMN IF EXISTS existing_bbox,"
" DROP COLUMN IF EXISTS updated_bbox, DROP COLUMN IF EXISTS affectedparents_before_bbox,"
" DROP COLUMN IF EXISTS affectedparents_after_bbox,"
" DROP COLUMN IF EXISTS relation_reach_bbox,"
" DROP COLUMN atomic_edit_id, DROP COLUMN block_index,"
" DROP COLUMN IF EXISTS sync_before, DROP COLUMN IF EXISTS bbox_before,"
" DROP COLUMN IF EXISTS sync_after, DROP COLUMN IF EXISTS bbox_after,"
// As the table had it before version 14
" ADD COLUMN IF NOT EXISTS bbox GEOMETRY(Geometry, 4326);";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
sql = "DROP SEQUENCE " + c.quote_name(tablePrefix + "atomic_edit_id_seq") + ";";
return DbExec(work, sql, errStr, nullptr, verbose);
}
bool DbDowngradeTables13To12(pqxx::connection &c, pqxx::transaction_base *work,
int verbose,
const string &tablePrefix,
std::string &errStr)
{
cout << "DbDowngradeTables13To12" << endl;
string sql;
bool ok = true;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"edit_activity")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"query_activity")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "ALTER TABLE "+c.quote_name(tablePrefix+"changesets")+" ALTER COLUMN geom TYPE GEOMETRY(Polygon, 4326);";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
return ok;
}
bool DbDowngradeTables12To11(pqxx::connection &c, pqxx::transaction_base *work,
int verbose,
const string &tablePrefix,
std::string &errStr)
{
cout << "DbDowngradeTables12To11" << endl;
string sql;
bool ok = true;
sql = "ALTER TABLE "+c.quote_name(tablePrefix+"liveways")+" DROP COLUMN bbox CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "ALTER TABLE "+c.quote_name(tablePrefix+"liverelations")+" DROP COLUMN bbox CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP VIEW IF EXISTS "+c.quote_name(tablePrefix+"visiblenodes")+" CASCADE";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP VIEW IF EXISTS "+c.quote_name(tablePrefix+"visibleways")+" CASCADE";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP VIEW IF EXISTS "+c.quote_name(tablePrefix+"visiblerelations")+" CASCADE";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
return ok;
}
bool DbDowngradeTables11To0(pqxx::connection &c, pqxx::transaction_base *work,
int verbose,
const string &tablePrefix,
std::string &errStr)
{
string sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"oldnodes")+" CASCADE;";
bool ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"oldways")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"oldrelations")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"livenodes")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"liveways")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"liverelations")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"nodeids")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"wayids")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"relationids")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"way_mems")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"relation_mems_n")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"relation_mems_w")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"relation_mems_r")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"nextids")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"meta")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose); if(!ok) return ok;
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"changesets")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose);
sql = "DROP TABLE IF EXISTS "+c.quote_name(tablePrefix+"usernames")+" CASCADE;";
ok = DbExec(work, sql, errStr, nullptr, verbose);
return ok;
}
bool DbDropMapTables(pqxx::connection &c, pqxx::transaction_base *work,
int verbose, const string &tablePrefix, string &errStr)
{
if(!DbDropExtractTables(c, work, verbose, tablePrefix, errStr)) return false;
// Use exact known names rather than prefix matching, which could remove
// unrelated tables. IF EXISTS supports partial or mismatched schemas.
for(const char *name : {"visiblenodes", "visibleways", "visiblerelations"})
{
string sql = "DROP VIEW IF EXISTS " + c.quote_name(tablePrefix + name) + " CASCADE;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
for(const char *name : {"way_shapes", "relation_shapes", "edit_activity", "query_activity", "oldnodes", "oldways",
"oldrelations", "livenodes", "liveways", "liverelations", "nodeids", "wayids",
"relationids", "way_mems", "relation_mems_n", "relation_mems_w",
"relation_mems_r", "nextids", "changesets", "usernames", "meta"})
{
string sql = "DROP TABLE IF EXISTS " + c.quote_name(tablePrefix + name) + " CASCADE;";
if(!DbExec(work, sql, errStr, nullptr, verbose)) return false;
}
string sql = "DROP SEQUENCE IF EXISTS " + c.quote_name(tablePrefix + "atomic_edit_id_seq") + ";";
return DbExec(work, sql, errStr, nullptr, verbose);
}
bool DbSetSchemaVersion(pqxx::connection &c, pqxx::transaction_base *work,
int verbose,
const std::string &parentPrefix,
const std::string &tablePrefix,
int targetVer, bool latest, std::string &errStr)
{
cout << "DbSetSchemaVersion " << parentPrefix << "," << tablePrefix << "," << targetVer << endl;
int schemaVersion = 0;
try
{
schemaVersion = std::stoi(DbGetMetaValue(c, work, "schema_version", tablePrefix, errStr));
}
catch (runtime_error &err) {}
cout << "Starting schema version" << schemaVersion << endl;
if(latest)
targetVer = MAP_SCHEMA_VERSION;
bool ok = true;
//Upgrading
if(schemaVersion == 0 and targetVer>schemaVersion)
{
ok = DbUpgradeTables0to11(c, work,
verbose,
tablePrefix,
errStr);
if(!ok) return false;
ok = DbSetMetaValue(c, work, "schema_version", to_string(11), tablePrefix, errStr);
if(!ok) return false;
schemaVersion = 11;
}
if(schemaVersion == 11 and targetVer>schemaVersion)
{
ok = DbUpgradeTables11to12(c, work,
verbose,
parentPrefix, tablePrefix,
errStr);
if(!ok) return false;
ok = DbSetMetaValue(c, work, "schema_version", to_string(12), tablePrefix, errStr);
if(!ok) return false;
schemaVersion = 12;
}
if(schemaVersion == 12 and targetVer>schemaVersion)
{
ok = DbUpgradeTables12to13(c, work,
verbose,
parentPrefix, tablePrefix,
errStr);
if(!ok) return false;
ok = DbSetMetaValue(c, work, "schema_version", to_string(13), tablePrefix, errStr);
if(!ok) return false;
schemaVersion = 13;
}
if(schemaVersion == 13 and targetVer > schemaVersion)
{
if(!DbUpgradeTables13to14(c, work, verbose, tablePrefix, errStr)) return false;
if(!DbSetMetaValue(c, work, "schema_version", "14", tablePrefix, errStr)) return false;
schemaVersion = 14;
}
if(schemaVersion >= 14 and targetVer >= schemaVersion)
{
// Schema 14 has gained columns since it was introduced. Every step of
// creating its extract tables leaves alone whatever is already there,
// so asking for the version a map already has, or a later one, brings
// an older version 14 up to date.
if(!DbAmendSchema14(c, work, verbose, tablePrefix, schemaVersion < 15, errStr)) return false;
}
if(schemaVersion == 14 and targetVer > schemaVersion)
{
if(!DbUpgradeTables14to15(c, work, verbose, parentPrefix, tablePrefix, errStr)) return false;
if(!DbSetMetaValue(c, work, "schema_version", "15", tablePrefix, errStr)) return false;
schemaVersion = 15;
}
if(schemaVersion >= 15 and targetVer >= schemaVersion)
{
// As for schema 14: what version 15 has gained since it was introduced
if(!DbAmendSchema15(c, work, verbose, tablePrefix, errStr)) return false;
}
if(schemaVersion == 15 and targetVer > schemaVersion)
{
if(!DbUpgradeTables15to16(c, work, verbose, parentPrefix, tablePrefix, errStr)) return false;
if(!DbSetMetaValue(c, work, "schema_version", "16", tablePrefix, errStr)) return false;
schemaVersion = 16;
}
//Downgrading
if(targetVer < 16 and schemaVersion == 16)
{
if(!DbDowngradeTables16To15(c, work, verbose, parentPrefix, tablePrefix, errStr)) return false;
if(!DbSetMetaValue(c, work, "schema_version", "15", tablePrefix, errStr)) return false;
schemaVersion = 15;
}
if(targetVer < 15 and schemaVersion == 15)
{
if(!DbDowngradeTables15To14(c, work, verbose, parentPrefix, tablePrefix, errStr)) return false;
if(!DbSetMetaValue(c, work, "schema_version", "14", tablePrefix, errStr)) return false;
schemaVersion = 14;
}
if(targetVer < 14 and schemaVersion == 14)
{
if(!DbDowngradeTables14To13(c, work, verbose, tablePrefix, errStr)) return false;
if(!DbSetMetaValue(c, work, "schema_version", "13", tablePrefix, errStr)) return false;
schemaVersion = 13;
}
if(targetVer < 13 and schemaVersion == 13)
{
ok = DbDowngradeTables13To12(c, work,
verbose,
tablePrefix,
errStr);
if(!ok) return false;
ok = DbSetMetaValue(c, work, "schema_version", to_string(12), tablePrefix, errStr);
if(!ok) return false;
schemaVersion = 12;
}
if(targetVer < 12 and schemaVersion == 12)
{
ok = DbDowngradeTables12To11(c, work,
verbose,
tablePrefix,
errStr);
if(!ok) return false;
ok = DbSetMetaValue(c, work, "schema_version", to_string(11), tablePrefix, errStr);
if(!ok) return false;
schemaVersion = 11;
}
if(targetVer < 11 and schemaVersion == 11)
{
ok = DbDowngradeTables11To0(c, work,
verbose,
tablePrefix,
errStr);
if(!ok) return false;
schemaVersion = 0;
}
return true;
}
// ************* Importing a map file straight into the tables *************
// Receives the objects of a map file and writes them to one set of map
// tables with COPY, which is the fast way into PostgreSQL. The data goes
// through the connection, so no files are written first and the database
// user need not be a superuser. The tables must have been created and
// should be empty.
//
// A connection carries one COPY at a time, while each object has rows for
// several tables, so rows are collected and written out a table at a time.
class MapTableImport : public IDataStreamHandler
{
public:
MapTableImport(pqxx::connection &c, pqxx::transaction_base *work, const string &tablePrefix, int verbose):
c(c), work(work), tablePrefix(tablePrefix), verbose(verbose), buffered(0), total(0)
{
for(int i=0; i<3; i++) lastId[i] = 0;
}
void StoreNode(const OsmNode &node) override
{
if(node.lat < -90.0 || node.lat > 90.0 || node.lon < -180.0 || node.lon > 180.0)
cerr << "Warning: node " << node.objId << " has invalid lat/lon: " << node.lat << "," << node.lon << endl;
ObjectRow row;
Common(node, 0, row);
stringstream ss;
ss.precision(9);
ss << "SRID=4326;POINT(" << fixed << node.lon << " " << node.lat << ")";
row.extra = ss.str();
Add(node, 0, row);
}
void StoreWay(const OsmWay &way) override
{
ObjectRow row;
Common(way, 1, row);
EncodeInt64Vec(way.refs, row.extra);
// Only the live version of an object has rows in the member tables
if(IsLive(way))
{
for(size_t i=0; i<way.refs.size(); i++)
members[0].push_back({way.objId, (int64_t)way.metaData.version, (int64_t)i, way.refs[i]});