forked from osm2pgsql-dev/osm2pgsql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
middle-pgsql.c
1830 lines (1595 loc) · 60.6 KB
/
middle-pgsql.c
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
/* Implements the mid-layer processing for osm2pgsql
* using several PostgreSQL tables
*
* This layer stores data read in from the planet.osm file
* and is then read by the backend processing code to
* emit the final geometry-enabled output formats
*/
#include "config.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <time.h>
#include <errno.h>
#ifdef HAVE_PTHREAD
#include <pthread.h>
#endif
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_MMAP
#include <sys/mman.h>
#ifndef MAP_ANONYMOUS
#ifdef MAP_ANON
#define MAP_ANONYMOUS MAP_ANON
#endif
#endif
#endif
#include <libpq-fe.h>
#include "osmtypes.h"
#include "middle.h"
#include "middle-pgsql.h"
#include "output-pgsql.h"
#include "node-ram-cache.h"
#include "node-persistent-cache.h"
#include "pgsql.h"
struct progress_info {
time_t start;
time_t end;
int count;
int finished;
};
enum table_id {
t_node, t_way, t_rel
} ;
struct table_desc {
const char *name;
const char *start;
const char *create;
const char *create_index;
const char *prepare;
const char *prepare_intarray;
const char *copy;
const char *analyze;
const char *stop;
const char *array_indexes;
int copyMode; /* True if we are in copy mode */
int transactionMode; /* True if we are in an extended transaction */
PGconn *sql_conn;
};
static struct table_desc tables [] = {
{
/*table = t_node,*/
.name = "%p_nodes",
.start = "BEGIN;\n",
#ifdef FIXED_POINT
.create = "CREATE %m TABLE %p_nodes (id " POSTGRES_OSMID_TYPE " PRIMARY KEY {USING INDEX TABLESPACE %i}, lat int4 not null, lon int4 not null, tags text[]) {TABLESPACE %t};\n",
.prepare = "PREPARE insert_node (" POSTGRES_OSMID_TYPE ", int4, int4, text[]) AS INSERT INTO %p_nodes VALUES ($1,$2,$3,$4);\n"
#else
.create = "CREATE %m TABLE %p_nodes (id " POSTGRES_OSMID_TYPE " PRIMARY KEY {USING INDEX TABLESPACE %i}, lat double precision not null, lon double precision not null, tags text[]) {TABLESPACE %t};\n",
.prepare = "PREPARE insert_node (" POSTGRES_OSMID_TYPE ", double precision, double precision, text[]) AS INSERT INTO %p_nodes VALUES ($1,$2,$3,$4);\n"
#endif
"PREPARE get_node (" POSTGRES_OSMID_TYPE ") AS SELECT lat,lon,tags FROM %p_nodes WHERE id = $1 LIMIT 1;\n"
"PREPARE get_node_list(" POSTGRES_OSMID_TYPE "[]) AS SELECT id, lat, lon FROM %p_nodes WHERE id = ANY($1::" POSTGRES_OSMID_TYPE "[]);\n"
"PREPARE delete_node (" POSTGRES_OSMID_TYPE ") AS DELETE FROM %p_nodes WHERE id = $1;\n",
.copy = "COPY %p_nodes FROM STDIN;\n",
.analyze = "ANALYZE %p_nodes;\n",
.stop = "COMMIT;\n"
},
{
/*table = t_way,*/
.name = "%p_ways",
.start = "BEGIN;\n",
.create = "CREATE %m TABLE %p_ways (id " POSTGRES_OSMID_TYPE " PRIMARY KEY {USING INDEX TABLESPACE %i}, nodes " POSTGRES_OSMID_TYPE "[] not null, tags text[], pending boolean not null) {TABLESPACE %t};\n",
.create_index = "CREATE INDEX %p_ways_idx ON %p_ways (id) {TABLESPACE %i} WHERE pending;\n",
.array_indexes = "CREATE INDEX %p_ways_nodes ON %p_ways USING gin (nodes) {TABLESPACE %i};\n",
.prepare = "PREPARE insert_way (" POSTGRES_OSMID_TYPE ", " POSTGRES_OSMID_TYPE "[], text[], boolean) AS INSERT INTO %p_ways VALUES ($1,$2,$3,$4);\n"
"PREPARE get_way (" POSTGRES_OSMID_TYPE ") AS SELECT nodes, tags, array_upper(nodes,1) FROM %p_ways WHERE id = $1;\n"
"PREPARE get_way_list (" POSTGRES_OSMID_TYPE "[]) AS SELECT id, nodes, tags, array_upper(nodes,1) FROM %p_ways WHERE id = ANY($1::" POSTGRES_OSMID_TYPE "[]);\n"
"PREPARE way_done(" POSTGRES_OSMID_TYPE ") AS UPDATE %p_ways SET pending = false WHERE id = $1;\n"
"PREPARE pending_ways AS SELECT id FROM %p_ways WHERE pending;\n"
"PREPARE delete_way(" POSTGRES_OSMID_TYPE ") AS DELETE FROM %p_ways WHERE id = $1;\n",
.prepare_intarray = "PREPARE node_changed_mark(" POSTGRES_OSMID_TYPE ") AS UPDATE %p_ways SET pending = true WHERE nodes && ARRAY[$1] AND NOT pending;\n"
"PREPARE rel_delete_mark(" POSTGRES_OSMID_TYPE ") AS UPDATE %p_ways SET pending = true WHERE id IN (SELECT unnest(parts[way_off+1:rel_off]) FROM %p_rels WHERE id = $1) AND NOT pending;\n",
.copy = "COPY %p_ways FROM STDIN;\n",
.analyze = "ANALYZE %p_ways;\n",
.stop = "COMMIT;\n"
},
{
/*table = t_rel,*/
.name = "%p_rels",
.start = "BEGIN;\n",
.create = "CREATE %m TABLE %p_rels(id " POSTGRES_OSMID_TYPE " PRIMARY KEY {USING INDEX TABLESPACE %i}, way_off int2, rel_off int2, parts " POSTGRES_OSMID_TYPE "[], members text[], tags text[], pending boolean not null) {TABLESPACE %t};\n",
.create_index = "CREATE INDEX %p_rels_idx ON %p_rels (id) {TABLESPACE %i} WHERE pending;\n",
.array_indexes = "CREATE INDEX %p_rels_parts ON %p_rels USING gin (parts) {TABLESPACE %i};\n",
.prepare = "PREPARE insert_rel (" POSTGRES_OSMID_TYPE ", int2, int2, " POSTGRES_OSMID_TYPE "[], text[], text[]) AS INSERT INTO %p_rels VALUES ($1,$2,$3,$4,$5,$6,false);\n"
"PREPARE get_rel (" POSTGRES_OSMID_TYPE ") AS SELECT members, tags, array_upper(members,1)/2 FROM %p_rels WHERE id = $1;\n"
"PREPARE rel_done(" POSTGRES_OSMID_TYPE ") AS UPDATE %p_rels SET pending = false WHERE id = $1;\n"
"PREPARE pending_rels AS SELECT id FROM %p_rels WHERE pending;\n"
"PREPARE delete_rel(" POSTGRES_OSMID_TYPE ") AS DELETE FROM %p_rels WHERE id = $1;\n",
.prepare_intarray =
"PREPARE node_changed_mark(" POSTGRES_OSMID_TYPE ") AS UPDATE %p_rels SET pending = true WHERE parts && ARRAY[$1] AND parts[1:way_off] && ARRAY[$1] AND NOT pending;\n"
"PREPARE way_changed_mark(" POSTGRES_OSMID_TYPE ") AS UPDATE %p_rels SET pending = true WHERE parts && ARRAY[$1] AND parts[way_off+1:rel_off] && ARRAY[$1] AND NOT pending;\n"
"PREPARE rel_changed_mark(" POSTGRES_OSMID_TYPE ") AS UPDATE %p_rels SET pending = true WHERE parts && ARRAY[$1] AND parts[rel_off+1:array_length(parts,1)] && ARRAY[$1] AND NOT pending;\n",
.copy = "COPY %p_rels FROM STDIN;\n",
.analyze = "ANALYZE %p_rels;\n",
.stop = "COMMIT;\n"
}
};
static const int num_tables = sizeof(tables)/sizeof(tables[0]);
static struct table_desc *node_table = &tables[t_node];
static struct table_desc *way_table = &tables[t_way];
static struct table_desc *rel_table = &tables[t_rel];
static int Append;
const struct output_options *out_options;
#define HELPER_STATE_UNINITIALIZED -1
#define HELPER_STATE_FORKED -2
#define HELPER_STATE_RUNNING 0
#define HELPER_STATE_FINISHED 1
#define HELPER_STATE_CONNECTED 2
#define HELPER_STATE_FAILED 3
static int pgsql_connect(const struct output_options *options) {
int i;
/* We use a connection per table to enable the use of COPY */
for (i=0; i<num_tables; i++) {
PGconn *sql_conn;
sql_conn = PQconnectdb(options->conninfo);
/* Check to see that the backend connection was successfully made */
if (PQstatus(sql_conn) != CONNECTION_OK) {
fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(sql_conn));
return 1;
}
tables[i].sql_conn = sql_conn;
pgsql_exec(sql_conn, PGRES_COMMAND_OK, "SET synchronous_commit TO off;");
if (tables[i].prepare) {
pgsql_exec(sql_conn, PGRES_COMMAND_OK, "%s", tables[i].prepare);
}
if (tables[i].prepare_intarray) {
pgsql_exec(sql_conn, PGRES_COMMAND_OK, "%s", tables[i].prepare_intarray);
}
}
return 0;
}
static void pgsql_cleanup(void)
{
int i;
for (i=0; i<num_tables; i++) {
if (tables[i].sql_conn) {
PQfinish(tables[i].sql_conn);
tables[i].sql_conn = NULL;
}
}
}
char *pgsql_store_nodes(osmid_t *nds, int nd_count)
{
static char *buffer;
static int buflen;
char *ptr;
int i, first;
if( buflen <= nd_count * 10 )
{
buflen = ((nd_count * 10) | 4095) + 1; /* Round up to next page */
buffer = realloc( buffer, buflen );
}
_restart:
ptr = buffer;
first = 1;
*ptr++ = '{';
for( i=0; i<nd_count; i++ )
{
if( !first ) *ptr++ = ',';
ptr += sprintf(ptr, "%" PRIdOSMID, nds[i] );
if( (ptr-buffer) > (buflen-20) ) /* Almost overflowed? */
{
buflen <<= 1;
buffer = realloc( buffer, buflen );
goto _restart;
}
first = 0;
}
*ptr++ = '}';
*ptr++ = 0;
return buffer;
}
/* Special escape routine for escaping strings in array constants: double quote, backslash,newline, tab*/
static char *escape_tag( char *ptr, const char *in, int escape )
{
while( *in )
{
switch(*in)
{
case '"':
if( escape ) *ptr++ = '\\';
*ptr++ = '\\';
*ptr++ = '"';
break;
case '\\':
if( escape ) *ptr++ = '\\';
if( escape ) *ptr++ = '\\';
*ptr++ = '\\';
*ptr++ = '\\';
break;
case '\n':
if( escape ) *ptr++ = '\\';
*ptr++ = '\\';
*ptr++ = 'n';
break;
case '\r':
if( escape ) *ptr++ = '\\';
*ptr++ = '\\';
*ptr++ = 'r';
break;
case '\t':
if( escape ) *ptr++ = '\\';
*ptr++ = '\\';
*ptr++ = 't';
break;
default:
*ptr++ = *in;
break;
}
in++;
}
return ptr;
}
/* escape means we return '\N' for copy mode, otherwise we return just NULL */
char *pgsql_store_tags(struct keyval *tags, int escape)
{
static char *buffer;
static int buflen;
char *ptr;
struct keyval *i;
int first;
int countlist = countList(tags);
if( countlist == 0 )
{
if( escape )
return "\\N";
else
return NULL;
}
if( buflen <= countlist * 24 ) /* LE so 0 always matches */
{
buflen = ((countlist * 24) | 4095) + 1; /* Round up to next page */
buffer = realloc( buffer, buflen );
}
_restart:
ptr = buffer;
first = 1;
*ptr++ = '{';
/* The lists are circular, exit when we reach the head again */
for( i=tags->next; i->key; i = i->next )
{
int maxlen = (strlen(i->key) + strlen(i->value)) * 4;
if( (ptr+maxlen-buffer) > (buflen-20) ) /* Almost overflowed? */
{
buflen <<= 1;
buffer = realloc( buffer, buflen );
goto _restart;
}
if( !first ) *ptr++ = ',';
*ptr++ = '"';
ptr = escape_tag( ptr, i->key, escape );
*ptr++ = '"';
*ptr++ = ',';
*ptr++ = '"';
ptr = escape_tag( ptr, i->value, escape );
*ptr++ = '"';
first=0;
}
*ptr++ = '}';
*ptr++ = 0;
return buffer;
}
/* Decodes a portion of an array literal from postgres */
/* Argument should point to beginning of literal, on return points to delimiter */
static const char *decode_upto( const char *src, char *dst )
{
int quoted = (*src == '"');
if( quoted ) src++;
while( quoted ? (*src != '"') : (*src != ',' && *src != '}') )
{
if( *src == '\\' )
{
switch( src[1] )
{
case 'n': *dst++ = '\n'; break;
case 't': *dst++ = '\t'; break;
default: *dst++ = src[1]; break;
}
src+=2;
}
else
*dst++ = *src++;
}
if( quoted ) src++;
*dst = 0;
return src;
}
static void pgsql_parse_tags( const char *string, struct keyval *tags )
{
char key[1024];
char val[1024];
if( *string == '\0' )
return;
if( *string++ != '{' )
return;
while( *string != '}' )
{
string = decode_upto( string, key );
/* String points to the comma */
string++;
string = decode_upto( string, val );
/* String points to the comma or closing '}' */
addItem( tags, key, val, 0 );
if( *string == ',' )
string++;
}
}
/* Parses an array of integers */
static void pgsql_parse_nodes(const char *src, osmid_t *nds, int nd_count )
{
int count = 0;
const char *string = src;
if( *string++ != '{' )
return;
while( *string != '}' )
{
char *ptr;
nds[count] = strtoosmid( string, &ptr, 10 );
string = ptr;
if( *string == ',' )
string++;
count++;
}
if( count != nd_count )
{
fprintf( stderr, "parse_nodes problem: '%s' expected %d got %d\n", src, nd_count, count );
exit_nicely();
}
}
static int pgsql_endCopy( struct table_desc *table)
{
PGresult *res;
PGconn *sql_conn;
int stop;
/* Terminate any pending COPY */
if (table->copyMode) {
sql_conn = table->sql_conn;
stop = PQputCopyEnd(sql_conn, NULL);
if (stop != 1) {
fprintf(stderr, "COPY_END for %s failed: %s\n", table->copy, PQerrorMessage(sql_conn));
exit_nicely();
}
res = PQgetResult(sql_conn);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "COPY_END for %s failed: %s\n", table->copy, PQerrorMessage(sql_conn));
PQclear(res);
exit_nicely();
}
PQclear(res);
table->copyMode = 0;
}
return 0;
}
static int pgsql_nodes_set(osmid_t id, double lat, double lon, struct keyval *tags)
{
/* Four params: id, lat, lon, tags */
char *paramValues[4];
char *buffer;
if( node_table->copyMode )
{
char *tag_buf = pgsql_store_tags(tags,1);
int length = strlen(tag_buf) + 64;
buffer = alloca( length );
#ifdef FIXED_POINT
if( snprintf( buffer, length, "%" PRIdOSMID "\t%d\t%d\t%s\n", id, DOUBLE_TO_FIX(lat), DOUBLE_TO_FIX(lon), tag_buf ) > (length-10) )
{ fprintf( stderr, "buffer overflow node id %" PRIdOSMID "\n", id); return 1; }
#else
if( snprintf( buffer, length, "%" PRIdOSMID "\t%.10f\t%.10f\t%s\n", id, lat, lon, tag_buf ) > (length-10) )
{ fprintf( stderr, "buffer overflow node id %" PRIdOSMID "\n", id); return 1; }
#endif
return pgsql_CopyData(__FUNCTION__, node_table->sql_conn, buffer);
}
buffer = alloca(64);
paramValues[0] = buffer;
paramValues[1] = paramValues[0] + sprintf( paramValues[0], "%" PRIdOSMID, id ) + 1;
#ifdef FIXED_POINT
paramValues[2] = paramValues[1] + sprintf( paramValues[1], "%d", DOUBLE_TO_FIX(lat) ) + 1;
sprintf( paramValues[2], "%d", DOUBLE_TO_FIX(lon) );
#else
paramValues[2] = paramValues[1] + sprintf( paramValues[1], "%.10f", lat ) + 1;
sprintf( paramValues[2], "%.10f", lon );
#endif
paramValues[3] = pgsql_store_tags(tags,0);
pgsql_execPrepared(node_table->sql_conn, "insert_node", 4, (const char * const *)paramValues, PGRES_COMMAND_OK);
return 0;
}
static int middle_nodes_set(osmid_t id, double lat, double lon, struct keyval *tags) {
ram_cache_nodes_set( id, lat, lon, tags );
return (out_options->flat_node_cache_enabled) ? persistent_cache_nodes_set(id, lat, lon) : pgsql_nodes_set(id, lat, lon, tags);
}
#if 0
static int pgsql_nodes_get(struct osmNode *out, osmid_t id)
{
PGresult *res;
char tmp[16];
char const *paramValues[1];
PGconn *sql_conn = node_table->sql_conn;
/* Make sure we're out of copy mode */
pgsql_endCopy( node_table );
snprintf(tmp, sizeof(tmp), "%" PRIdOSMID, id);
paramValues[0] = tmp;
res = pgsql_execPrepared(sql_conn, "get_node", 1, paramValues, PGRES_TUPLES_OK);
if (PQntuples(res) != 1) {
PQclear(res);
return 1;
}
#ifdef FIXED_POINT
out->lat = FIX_TO_DOUBLE(strtol(PQgetvalue(res, 0, 0), NULL, 10));
out->lon = FIX_TO_DOUBLE(strtol(PQgetvalue(res, 0, 1), NULL, 10));
#else
out->lat = strtod(PQgetvalue(res, 0, 0), NULL);
out->lon = strtod(PQgetvalue(res, 0, 1), NULL);
#endif
PQclear(res);
return 0;
}
#endif
/* Currently not used
static int middle_nodes_get(struct osmNode *out, osmid_t id)
{
/ * Check cache first * /
if( ram_cache_nodes_get( out, id ) == 0 )
return 0;
return (out_options->flat_node_cache_enabled) ? persistent_cache_nodes_get(out, id) : pgsql_nodes_get(out, id);
}*/
/* This should be made more efficient by using an IN(ARRAY[]) construct */
static int pgsql_nodes_get_list(struct osmNode *nodes, osmid_t *ndids, int nd_count)
{
char tmp[16];
char *tmp2;
int count, countDB, countPG, i,j;
osmid_t *ndidspg;
struct osmNode *nodespg;
char const *paramValues[1];
PGresult *res;
PGconn *sql_conn = node_table->sql_conn;
count = 0; countDB = 0;
tmp2 = malloc(sizeof(char)*nd_count*16);
if (tmp2 == NULL) return 0; /*failed to allocate memory, return */
/* create a list of ids in tmp2 to query the database */
sprintf(tmp2, "{");
for( i=0; i<nd_count; i++ ) {
/* Check cache first */
if( ram_cache_nodes_get( &nodes[i], ndids[i]) == 0 ) {
count++;
continue;
}
countDB++;
/* Mark nodes as needing to be fetched from the DB */
nodes[i].lat = NAN;
nodes[i].lon = NAN;
snprintf(tmp, sizeof(tmp), "%" PRIdOSMID ",", ndids[i]);
strncat(tmp2, tmp, sizeof(char)*(nd_count*16 - 2));
}
tmp2[strlen(tmp2) - 1] = '}'; /* replace last , with } to complete list of ids*/
if (countDB == 0) {
free(tmp2);
return count; /* All ids where in cache, so nothing more to do */
}
pgsql_endCopy(node_table);
paramValues[0] = tmp2;
res = pgsql_execPrepared(sql_conn, "get_node_list", 1, paramValues, PGRES_TUPLES_OK);
countPG = PQntuples(res);
ndidspg = malloc(sizeof(osmid_t)*countPG);
nodespg = malloc(sizeof(struct osmNode)*countPG);
if ((ndidspg == NULL) || (nodespg == NULL)) {
free(tmp2);
free(ndidspg);
free(nodespg);
PQclear(res);
return 0;
}
for (i = 0; i < countPG; i++) {
ndidspg[i] = strtoosmid(PQgetvalue(res, i, 0), NULL, 10);
#ifdef FIXED_POINT
nodespg[i].lat = FIX_TO_DOUBLE(strtol(PQgetvalue(res, i, 1), NULL, 10));
nodespg[i].lon = FIX_TO_DOUBLE(strtol(PQgetvalue(res, i, 2), NULL, 10));
#else
nodespg[i].lat = strtod(PQgetvalue(res, i, 1), NULL);
nodespg[i].lon = strtod(PQgetvalue(res, i, 2), NULL);
#endif
}
/* The list of results coming back from the db is in a different order to the list of nodes in the way.
Match the results back to the way node list */
for (i=0; i<nd_count; i++ ) {
if ((isnan(nodes[i].lat)) || (isnan(nodes[i].lon))) {
/* TODO: implement an O(log(n)) algorithm to match node ids */
for (j = 0; j < countPG; j++) {
if (ndidspg[j] == ndids[i]) {
nodes[i].lat = nodespg[j].lat;
nodes[i].lon = nodespg[j].lon;
count++;
break;
}
}
}
}
/* If some of the nodes in the way don't exist, the returning list has holes.
As the rest of the code expects a continuous list, it needs to be re-compacted */
if (count != nd_count) {
j = 0;
for (i = 0; i < nd_count; i++) {
if ( !isnan(nodes[i].lat)) {
nodes[j].lat = nodes[i].lat;
nodes[j].lon = nodes[i].lon;
j++;
}
}
}
PQclear(res);
free(tmp2);
free(ndidspg);
free(nodespg);
return count;
}
static int middle_nodes_get_list(struct osmNode *nodes, osmid_t *ndids, int nd_count)
{
return (out_options->flat_node_cache_enabled) ? persistent_cache_nodes_get_list(nodes, ndids, nd_count) : pgsql_nodes_get_list(nodes, ndids, nd_count);
}
static int pgsql_nodes_delete(osmid_t osm_id)
{
char const *paramValues[1];
char buffer[64];
/* Make sure we're out of copy mode */
pgsql_endCopy( node_table );
sprintf( buffer, "%" PRIdOSMID, osm_id );
paramValues[0] = buffer;
pgsql_execPrepared(node_table->sql_conn, "delete_node", 1, paramValues, PGRES_COMMAND_OK );
return 0;
}
static int middle_nodes_delete(osmid_t osm_id)
{
return ((out_options->flat_node_cache_enabled) ? persistent_cache_nodes_set(osm_id, NAN, NAN) : pgsql_nodes_delete(osm_id));
}
static int pgsql_node_changed(osmid_t osm_id)
{
char const *paramValues[1];
char buffer[64];
/* Make sure we're out of copy mode */
pgsql_endCopy( way_table );
pgsql_endCopy( rel_table );
sprintf( buffer, "%" PRIdOSMID, osm_id );
paramValues[0] = buffer;
pgsql_execPrepared(way_table->sql_conn, "node_changed_mark", 1, paramValues, PGRES_COMMAND_OK );
pgsql_execPrepared(rel_table->sql_conn, "node_changed_mark", 1, paramValues, PGRES_COMMAND_OK );
return 0;
}
static int pgsql_ways_set(osmid_t way_id, osmid_t *nds, int nd_count, struct keyval *tags, int pending)
{
/* Three params: id, nodes, tags, pending */
char *paramValues[4];
char *buffer;
if( way_table->copyMode )
{
char *tag_buf = pgsql_store_tags(tags,1);
char *node_buf = pgsql_store_nodes(nds, nd_count);
int length = strlen(tag_buf) + strlen(node_buf) + 64;
buffer = alloca(length);
if( snprintf( buffer, length, "%" PRIdOSMID "\t%s\t%s\t%c\n",
way_id, node_buf, tag_buf, pending?'t':'f' ) > (length-10) )
{ fprintf( stderr, "buffer overflow way id %" PRIdOSMID "\n", way_id); return 1; }
return pgsql_CopyData(__FUNCTION__, way_table->sql_conn, buffer);
}
buffer = alloca(64);
paramValues[0] = buffer;
paramValues[3] = paramValues[0] + sprintf( paramValues[0], "%" PRIdOSMID, way_id ) + 1;
sprintf( paramValues[3], "%c", pending?'t':'f' );
paramValues[1] = pgsql_store_nodes(nds, nd_count);
paramValues[2] = pgsql_store_tags(tags,0);
pgsql_execPrepared(way_table->sql_conn, "insert_way", 4, (const char * const *)paramValues, PGRES_COMMAND_OK);
return 0;
}
/* Caller is responsible for freeing nodesptr & resetList(tags) */
static int pgsql_ways_get(osmid_t id, struct keyval *tags, struct osmNode **nodes_ptr, int *count_ptr)
{
PGresult *res;
char tmp[16];
char const *paramValues[1];
PGconn *sql_conn = way_table->sql_conn;
int num_nodes;
osmid_t *list;
/* Make sure we're out of copy mode */
pgsql_endCopy( way_table );
snprintf(tmp, sizeof(tmp), "%" PRIdOSMID, id);
paramValues[0] = tmp;
res = pgsql_execPrepared(sql_conn, "get_way", 1, paramValues, PGRES_TUPLES_OK);
if (PQntuples(res) != 1) {
PQclear(res);
return 1;
}
pgsql_parse_tags( PQgetvalue(res, 0, 1), tags );
num_nodes = strtol(PQgetvalue(res, 0, 2), NULL, 10);
list = alloca(sizeof(osmid_t)*num_nodes );
*nodes_ptr = malloc(sizeof(struct osmNode) * num_nodes);
pgsql_parse_nodes( PQgetvalue(res, 0, 0), list, num_nodes);
*count_ptr = out_options->flat_node_cache_enabled ?
persistent_cache_nodes_get_list(*nodes_ptr, list, num_nodes) :
pgsql_nodes_get_list( *nodes_ptr, list, num_nodes);
PQclear(res);
return 0;
}
static int pgsql_ways_get_list(osmid_t *ids, int way_count, osmid_t **way_ids, struct keyval *tags, struct osmNode **nodes_ptr, int *count_ptr) {
char tmp[16];
char *tmp2;
int count, countPG, i, j;
osmid_t *wayidspg;
char const *paramValues[1];
int num_nodes;
osmid_t *list;
PGresult *res;
PGconn *sql_conn = way_table->sql_conn;
*way_ids = malloc( sizeof(osmid_t) * (way_count + 1));
if (way_count == 0) return 0;
tmp2 = malloc(sizeof(char)*way_count*16);
if (tmp2 == NULL) return 0; /*failed to allocate memory, return */
/* create a list of ids in tmp2 to query the database */
sprintf(tmp2, "{");
for( i=0; i<way_count; i++ ) {
snprintf(tmp, sizeof(tmp), "%" PRIdOSMID ",", ids[i]);
strncat(tmp2,tmp, sizeof(char)*(way_count*16 - 2));
}
tmp2[strlen(tmp2) - 1] = '}'; /* replace last , with } to complete list of ids*/
pgsql_endCopy(way_table);
paramValues[0] = tmp2;
res = pgsql_execPrepared(sql_conn, "get_way_list", 1, paramValues, PGRES_TUPLES_OK);
countPG = PQntuples(res);
wayidspg = malloc(sizeof(osmid_t)*countPG);
if (wayidspg == NULL) return 0; /*failed to allocate memory, return */
for (i = 0; i < countPG; i++) {
wayidspg[i] = strtoosmid(PQgetvalue(res, i, 0), NULL, 10);
}
/* Match the list of ways coming from postgres in a different order
back to the list of ways given by the caller */
count = 0;
initList(&(tags[count]));
for (i = 0; i < way_count; i++) {
for (j = 0; j < countPG; j++) {
if (ids[i] == wayidspg[j]) {
(*way_ids)[count] = ids[i];
pgsql_parse_tags( PQgetvalue(res, j, 2), &(tags[count]) );
num_nodes = strtol(PQgetvalue(res, j, 3), NULL, 10);
list = alloca(sizeof(osmid_t)*num_nodes );
nodes_ptr[count] = malloc(sizeof(struct osmNode) * num_nodes);
pgsql_parse_nodes( PQgetvalue(res, j, 1), list, num_nodes);
count_ptr[count] = out_options->flat_node_cache_enabled ?
persistent_cache_nodes_get_list(nodes_ptr[count], list, num_nodes) :
pgsql_nodes_get_list( nodes_ptr[count], list, num_nodes);
count++;
initList(&(tags[count]));
}
}
}
PQclear(res);
free(tmp2);
free(wayidspg);
return count;
}
static int pgsql_ways_done(osmid_t id)
{
char tmp[16];
char const *paramValues[1];
PGconn *sql_conn = way_table->sql_conn;
/* Make sure we're out of copy mode */
pgsql_endCopy( way_table );
snprintf(tmp, sizeof(tmp), "%" PRIdOSMID, id);
paramValues[0] = tmp;
pgsql_execPrepared(sql_conn, "way_done", 1, paramValues, PGRES_COMMAND_OK);
return 0;
}
static int pgsql_ways_delete(osmid_t osm_id)
{
char const *paramValues[1];
char buffer[64];
/* Make sure we're out of copy mode */
pgsql_endCopy( way_table );
sprintf( buffer, "%" PRIdOSMID, osm_id );
paramValues[0] = buffer;
pgsql_execPrepared(way_table->sql_conn, "delete_way", 1, paramValues, PGRES_COMMAND_OK );
return 0;
}
static void pgsql_iterate_ways(int (*callback)(osmid_t id, struct keyval *tags, struct osmNode *nodes, int count, int exists))
{
int noProcs = out_options->num_procs;
int pid = 0;
PGresult *res_ways;
int i, p, count = 0;
/* The flag we pass to indicate that the way in question might exist already in the database */
int exists = Append;
time_t start, end;
time(&start);
#if HAVE_MMAP
struct progress_info *info = 0;
if(noProcs > 1) {
info = mmap(0, sizeof(struct progress_info)*noProcs, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
info[0].finished = HELPER_STATE_CONNECTED;
for (i = 1; i < noProcs; i++) {
info[i].finished = HELPER_STATE_UNINITIALIZED; /* Register that the process was not yet initialised; */
}
}
#endif
fprintf(stderr, "\nGoing over pending ways...\n");
/* Make sure we're out of copy mode */
pgsql_endCopy( way_table );
if (out_options->flat_node_cache_enabled) shutdown_node_persistent_cache();
res_ways = pgsql_execPrepared(way_table->sql_conn, "pending_ways", 0, NULL, PGRES_TUPLES_OK);
fprintf(stderr, "\t%i ways are pending\n", PQntuples(res_ways));
/**
* To speed up processing of pending ways, fork noProcs worker processes
* each of which independently goes through an equal subset of the pending ways array
*/
fprintf(stderr, "\nUsing %i helper-processes\n", noProcs);
#ifdef HAVE_FORK
for (p = 1; p < noProcs; p++) {
pid=fork();
if (pid==0) {
#if HAVE_MMAP
info[p].finished = HELPER_STATE_FORKED;
#endif
break;
}
if (pid==-1) {
#if HAVE_MMAP
info[p].finished = HELPER_STATE_FAILED;
fprintf(stderr,"WARNING: Failed to fork helper process %i: %s. Trying to recover.\n", p, strerror(errno));
#else
fprintf(stderr,"ERROR: Failed to fork helper process %i: %s. Can't recover!\n", p, strerror(errno));
exit_nicely();
#endif
}
}
#endif
if ((pid == 0) && (noProcs > 1)) {
/* After forking, need to reconnect to the postgresql db */
if ((pgsql_connect(out_options) != 0) || (out_options->out->connect(out_options, 1) != 0)) {
#if HAVE_MMAP
info[p].finished = HELPER_STATE_FAILED;
#else
fprintf(stderr,"\n\n!!!FATAL: Helper process failed, but can't compensate. Your DB will be broken and corrupt!!!!\n\n");
#endif
exit_nicely();
};
} else {
p = 0;
}
if (out_options->flat_node_cache_enabled) init_node_persistent_cache(out_options,1); /* at this point we always want to be in append mode, to not delete and recreate the node cache file */
/* Only start an extended transaction on the ways table,
* which should cover the bulk of the update statements.
* The nodes table should not be written to in this phase.
* The relations table can't be wrapped in an extended
* transaction, as with prallel processing it may deadlock.
* Updating a way will trigger an update of the pending status
* on connected relations. This should not be as many updates,
* so in combination with the synchronous_comit = off it should be fine.
*
*/
if (tables[t_way].start) {
pgsql_endCopy(&tables[t_way]);
pgsql_exec(tables[t_way].sql_conn, PGRES_COMMAND_OK, "%s", tables[t_way].start);
tables[t_way].transactionMode = 1;
}
#if HAVE_MMAP
if (noProcs > 1) {
info[p].finished = HELPER_STATE_CONNECTED;
/* Syncronize all processes to make sure they have all run through the initialisation steps */
int all_processes_initialised = 0;
while (all_processes_initialised == 0) {
all_processes_initialised = 1;
for (i = 0; i < noProcs; i++) {
if (info[i].finished < 0) {
all_processes_initialised = 0;
sleep(1);
}
}
}
/* As we process the pending ways in steps of noProcs,
we need to make sure that all processes correctly forked
and have connected to the db. Otherwise we need to readjust
the step size of going through the pending ways array */
int noProcsTmp = noProcs;
int pTmp = p;
for (i = 0; i < noProcs; i++) {
if (info[i].finished == HELPER_STATE_FAILED) {
noProcsTmp--;
if (i < p) pTmp--;
}
}
info[p].finished = HELPER_STATE_RUNNING;
p = pTmp; /* reset the process number to account for failed processes */
/* As we have potentially changed the process number assignment,
we need to synchronize on all processes having performed the reassignment
as otherwise multiple process might have the same number and overwrite
the info fields incorrectly.
*/
all_processes_initialised = 0;
while (all_processes_initialised == 0) {
all_processes_initialised = 1;
for (i = 0; i < noProcs; i++) {
if (info[i].finished == HELPER_STATE_CONNECTED) {
/* Process is connected, but hasn't performed the re-assignment of p. */
all_processes_initialised = 0;
sleep(1);
break;
}
}
}
noProcs = noProcsTmp;
}
#endif
/* some spaces at end, so that processings outputs get cleaned if already existing */
fprintf(stderr, "\rHelper process %i out of %i initialised \n", p, noProcs);
/* Use a stride length of the number of worker processes,
starting with an offset for each worker process p */
for (i = p; i < PQntuples(res_ways); i+= noProcs) {
osmid_t id = strtoosmid(PQgetvalue(res_ways, i, 0), NULL, 10);
struct keyval tags;
struct osmNode *nodes;
int nd_count;
if (count++ %1000 == 0) {
time(&end);
#if HAVE_MMAP
if(info)
{
double rate = 0;
int n, total = 0, finished = 0;
struct progress_info f;
f.start = start;
f.end = end;
f.count = count;
f.finished = HELPER_STATE_RUNNING;
info[p] = f;
for(n = 0; n < noProcs; ++n)
{
f = info[n];
total += f.count;
finished += f.finished;
if(f.end > f.start)
rate += (double)f.count / (double)(f.end - f.start);