-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnominatim_fdw.c
1716 lines (1424 loc) · 64.9 KB
/
nominatim_fdw.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
/**********************************************************************
*
* nominatim_fdw - PostgreSQL Nominatim Extension
*
* nominatim_fdw is free software: you can redistribute it and/or modify
* it under the terms of the MIT Licence.
*
* Copyright (C) 2024 University of Münster, Germany
* Written by Jim Jones <[email protected]>
*
**********************************************************************/
#include "postgres.h"
#include "fmgr.h"
#include "foreign/fdwapi.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/planmain.h"
#include "utils/rel.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/reloptions.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "foreign/foreign.h"
#include "commands/defrem.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pg_list.h"
#include "optimizer/pathnode.h"
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <utils/builtins.h>
#include <utils/array.h>
#include <commands/explain.h>
#include <libxml/tree.h>
#include <catalog/pg_collation.h>
#include <funcapi.h>
#include "lib/stringinfo.h"
#include <utils/lsyscache.h>
#include "utils/datetime.h"
#include "utils/timestamp.h"
#include "utils/formatting.h"
#include "catalog/pg_operator.h"
#include "utils/syscache.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_type.h"
#include "access/reloptions.h"
#include "catalog/pg_namespace.h"
#if PG_VERSION_NUM < 120000
#include "nodes/relation.h"
#include "optimizer/var.h"
#include "utils/tqual.h"
#else
#include "nodes/pathnodes.h"
#include "optimizer/optimizer.h"
#include "access/heapam.h"
#endif
#include "utils/date.h"
#include <utils/elog.h>
#include <access/tupdesc.h>
#define FDW_VERSION "1.0.0"
#define REQUEST_SUCCESS 0
#define REQUEST_FAIL -1
#define NOMINATIM_REQUEST_SEARCH "search"
#define NOMINATIM_REQUEST_REVERSE "reverse"
#define NOMINATIM_REQUEST_LOOKUP "lookup"
#define NOMINATIM_SERVER_OPTION_URL "url"
#define NOMINATIM_SERVER_OPTION_FORMAT "format"
#define NOMINATIM_SERVER_OPTION_CONNECTTIMEOUT "connect_timeout"
#define NOMINATIM_SERVER_OPTION_MAXCONNECTRETRY "max_connect_retry"
#define NOMINATIM_SERVER_OPTION_MAXREDIRECT "max_connect_redirect"
#define NOMINATIM_SERVER_OPTION_HTTP_PROXY "http_proxy"
#define NOMINATIM_SERVER_OPTION_HTTPS_PROXY "https_proxy"
#define NOMINATIM_SERVER_OPTION_PROXY_USER "proxy_user"
#define NOMINATIM_SERVER_OPTION_PROXY_USER_PASSWORD "proxy_user_password"
#define NOMINATIM_SERVER_OPTION_LANGUAGE "accept_language"
#define NOMINATIM_DEFAULT_CONNECTTIMEOUT 300
#define NOMINATIM_DEFAULT_MAXRETRY 3
#define NOMINATIM_DEFAULT_MAXREDIRECT 1
#define NOMINATIM_DEFAULT_FORMAT "xml"
#define NOMINATIM_DEFAULT_LANGUAGE "en-US,en;q=0.9"
PG_MODULE_MAGIC;
typedef struct NominatimFDWState
{
int numcols; /* Total number of columns in the foreign table. */
int rowcount; /* Number of rows currently returned to the client */
int pagesize; /* Total number of records retrieved from the SPARQL endpoint*/
int zoom; /* Level of detail required for the address. */
int limit; /* Limit the maximum number of returned results. */
int offset; /* */
char *request_type; /* one of: search, reverse or lookup*/
char *url; /* URL of the Nominatim endpoint */
char *osm_ids; /* a comma-separated list of OSM ids each prefixed with its type: N, W or R */
char *amenity; /* name and/or type of POI */
char *street; /* housenumber and streetname */
char *city; /* city */
char *county; /* county */
char *state; /* state */
char *country; /* country */
char *postalcode; /* postalcode */
char *proxy; /* Proxy for HTTP requests, if necessary. */
char *proxy_type; /* Proxy protocol (HTTPS, HTTP). */
char *proxy_user; /* User name for proxy authentication. */
char *proxy_user_password; /* Password for proxy authentication. */
char *custom_params; /* Custom parameters used to compose the request URL */
char *format; /* API result format. Only xml is currently supported! */
char *query; /* Free-form query string to search for */
char *layer; /* Comma-separated list of: address, poi, railway, natural, manmade*/
char *countrycodes; /* Comma-separated list of country codes */
char *feature_type; /* One of: country, state, city, settlement */
char *exclude_place_ids; /* Comma-separeted list of place ids */
char *viewbox; /* A bbox as in <x1>,<y1>,<x2>,<y2> */
char *polygon_type; /* One of: polygon_geojson, polygon_text, polygon_kml or polygon_svg*/
char *email; /* An e-mail address to identify the requests in the server */
char *accept_language; /* Preferred language order for showing search results */
bool dedupe; /* Remove duplicates? */
bool bounded; /* Exclude results outside the viewbox? */
bool request_redirect; /* Enables or disables URL redirecting. */
bool extratags; /* Include any additional information in the result that is available in the database? */
bool namedetails; /* Include a full list of names for the result? */
bool addressdetails; /* Include a breakdown of the address into elements? */
long request_max_redirect; /* Limit of how many times the URL redirection (jump) may occur. */
long connect_timeout; /* Timeout for SPARQL queries */
long max_retries; /* Number of re-try attemtps for failed SPARQL queries */
float8 lon; /* Longitude (x) */
float8 lat; /* Latitude (y) */
float8 polygon_threshold; /* Tolerance in degrees with which the geometry may differ from the original geometry */
xmlDocPtr xmldoc; /* XML document where the results from the request will be stored before parsing */
List *records; /* List of records retrieved from the server after parsing */
} NominatimFDWState;
struct NominatimFDWOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
bool optrequired; /* Flag mandatory options */
bool optfound; /* Flag whether options was specified by user */
} NomiatimFDWOption;
typedef struct NominatimRecord
{
char *timestamp;
char *attribution;
char *querystring;
char *polygon;
char *exclude_place_ids;
char *more_url;
char *place_id;
char *osm_type;
char *osm_id;
char *ref;
char *lat;
char *lon;
char *boundingbox;
char *place_rank;
char *address_rank;
char *display_rank;
char *display_name;
char *class;
char *type;
char *importance;
char *icon;
char *extratags;
char *addressdetails;
char *namedetails;
char *addressparts;
char *result;
} NominatimRecord;
struct string
{
char *ptr;
size_t len;
};
struct MemoryStruct
{
char *memory;
size_t size;
};
static struct NominatimFDWOption valid_options[] =
{
/* Foreign Servers */
{NOMINATIM_SERVER_OPTION_URL, ForeignServerRelationId, true, false},
{NOMINATIM_SERVER_OPTION_FORMAT, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_HTTP_PROXY, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_HTTPS_PROXY, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_PROXY_USER, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_PROXY_USER_PASSWORD, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_CONNECTTIMEOUT, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_MAXCONNECTRETRY, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_MAXREDIRECT, ForeignServerRelationId, false, false},
{NOMINATIM_SERVER_OPTION_LANGUAGE, ForeignServerRelationId, false, false},
/* EOList option */
{NULL, InvalidOid, false, false}};
extern Datum nominatim_fdw_handler(PG_FUNCTION_ARGS);
extern Datum nominatim_fdw_validator(PG_FUNCTION_ARGS);
extern Datum nominatim_fdw_version(PG_FUNCTION_ARGS);
extern Datum nominatim_fdw_search(PG_FUNCTION_ARGS);
extern Datum nominatim_fdw_reverse(PG_FUNCTION_ARGS);
extern Datum nominatim_fdw_lookup(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(nominatim_fdw_handler);
PG_FUNCTION_INFO_V1(nominatim_fdw_validator);
PG_FUNCTION_INFO_V1(nominatim_fdw_version);
PG_FUNCTION_INFO_V1(nominatim_fdw_search);
PG_FUNCTION_INFO_V1(nominatim_fdw_reverse);
PG_FUNCTION_INFO_V1(nominatim_fdw_lookup);
static void NominatimGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static void NominatimGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static ForeignScan *NominatimGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan);
static void NominatimBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *NominatimIterateForeignScan(ForeignScanState *node);
static void NominatimReScanForeignScan(ForeignScanState *node);
static void NominatimEndForeignScan(ForeignScanState *node);
static Datum CreateDatum(HeapTuple tuple, int pgtype, int pgtypemod, char *value);
static char *GetAttributeValue(Form_pg_attribute att, struct NominatimRecord *place);
static NominatimFDWState *InitSession(const char *srvname);
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp);
static size_t HeaderCallbackFunction(char *contents, size_t size, size_t nmemb, void *userp);
static void ParseNominatimSearchData(NominatimFDWState *state);
static void ParseNominatimReverseData(NominatimFDWState *state);
static int ExecuteRequest(NominatimFDWState *state);
static int CheckURL(char *url);
static bool IsPolygonTypeSupported(char *polygon_type);
static bool IsLayerValid(char *layer);
static void NominatimGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
}
static void NominatimGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
Path *path = (Path *)create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
baserel->rows, /* rows */
1, /* startup cost */
1 + baserel->rows, /* total cost */
NIL, /* no pathkeys */
NULL, /* no required outer relids */
NULL, /* no fdw_outerpath */
#if PG_VERSION_NUM >= 170000
NIL, /* no fdw_restrictinfo */
#endif /* PG_VERSION_NUM */
NULL); /* no fdw_private */
add_path(baserel, path);}
static ForeignScan *NominatimGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan)
{
List *fdw_private;
// NominatimFDWTable *opts = baserel->fdw_private;
NominatimFDWState *state = (NominatimFDWState *)palloc0(sizeof(NominatimFDWState));
fdw_private = list_make1(state);
scan_clauses = extract_actual_clauses(scan_clauses, false);
return make_foreignscan(tlist,
scan_clauses,
baserel->relid,
NIL, /* no expressions we will evaluate */
fdw_private, /* pass along our start and end */
NIL, /* no custom tlist; our scan tuple looks like tlist */
NIL, /* no quals we will recheck */
outer_plan);
}
static void NominatimBeginForeignScan(ForeignScanState *node, int eflags)
{
ForeignScan *fs = (ForeignScan *)node->ss.ps.plan;
NominatimFDWState *state = (NominatimFDWState *)linitial(fs->fdw_private);
if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
return;
node->fdw_state = (void *)state;
}
static TupleTableSlot *NominatimIterateForeignScan(ForeignScanState *node)
{
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
elog(DEBUG2, "%s called", __func__);
ExecClearTuple(slot);
return slot;
}
static void NominatimReScanForeignScan(ForeignScanState *node)
{
}
static void NominatimEndForeignScan(ForeignScanState *node)
{
}
Datum nominatim_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
fdwroutine->GetForeignRelSize = NominatimGetForeignRelSize;
fdwroutine->GetForeignPaths = NominatimGetForeignPaths;
fdwroutine->GetForeignPlan = NominatimGetForeignPlan;
fdwroutine->BeginForeignScan = NominatimBeginForeignScan;
fdwroutine->IterateForeignScan = NominatimIterateForeignScan;
fdwroutine->ReScanForeignScan = NominatimReScanForeignScan;
fdwroutine->EndForeignScan = NominatimEndForeignScan;
PG_RETURN_POINTER(fdwroutine);
}
Datum nominatim_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
ListCell *cell;
struct NominatimFDWOption *opt;
if (catalog == ForeignTableRelationId)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("FOREIGN TABLE not supported"),
errhint("The nominatim_fdw does not support FOREIGN TABLE mapping. Use the query functions instead.")));
/* Initialize found state to not found */
for (opt = valid_options; opt->optname; opt++)
opt->optfound = false;
foreach (cell, options_list)
{
DefElem *def = (DefElem *)lfirst(cell);
bool optfound = false;
for (opt = valid_options; opt->optname; opt++)
{
if (catalog == opt->optcontext && strcmp(opt->optname, def->defname) == 0)
{
/* Mark that this user option was found */
opt->optfound = optfound = true;
if (strlen(defGetString(def)) == 0)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("empty value in option '%s'", opt->optname)));
}
if (strcmp(opt->optname, NOMINATIM_SERVER_OPTION_URL) == 0 ||
strcmp(opt->optname, NOMINATIM_SERVER_OPTION_HTTP_PROXY) == 0 ||
strcmp(opt->optname, NOMINATIM_SERVER_OPTION_HTTPS_PROXY) == 0)
{
int return_code = CheckURL(defGetString(def));
if (return_code != REQUEST_SUCCESS)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid %s: '%s'", opt->optname, defGetString(def))));
}
}
if (strcmp(opt->optname, NOMINATIM_SERVER_OPTION_CONNECTTIMEOUT) == 0)
{
char *endptr;
char *timeout_str = defGetString(def);
long timeout_val = strtol(timeout_str, &endptr, 0);
if (timeout_str[0] == '\0' || *endptr != '\0' || timeout_val < 0)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid %s: '%s'", def->defname, timeout_str),
errhint("expected values are positive integers (timeout in seconds)")));
}
}
if (strcmp(opt->optname, NOMINATIM_SERVER_OPTION_MAXCONNECTRETRY) == 0 || strcmp(opt->optname, NOMINATIM_SERVER_OPTION_MAXREDIRECT) == 0)
{
char *endptr;
char *retry_str = defGetString(def);
long retry_val = strtol(retry_str, &endptr, 0);
if (retry_str[0] == '\0' || *endptr != '\0' || retry_val < 0)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE),
errmsg("invalid %s: '%s'", def->defname, retry_str),
errhint("expected values are positive integers")));
}
}
}
}
if (!optfound)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid rdf_fdw option '%s'", def->defname)));
}
}
for (opt = valid_options; opt->optname; opt++)
{
/* Required option for this catalog type is missing? */
if (catalog == opt->optcontext && opt->optrequired && !opt->optfound)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_DYNAMIC_PARAMETER_VALUE_NEEDED),
errmsg("required option '%s' is missing", opt->optname)));
}
}
PG_RETURN_VOID();
}
Datum nominatim_fdw_version(PG_FUNCTION_ARGS)
{
StringInfoData buffer;
initStringInfo(&buffer);
appendStringInfo(&buffer, "nominatim_fdw = %s,", FDW_VERSION);
appendStringInfo(&buffer, " libxml/%s", LIBXML_DOTTED_VERSION);
appendStringInfo(&buffer, " %s", curl_version());
PG_RETURN_TEXT_P(cstring_to_text(buffer.data));
}
/*
* nominatim_fdw_reverse
* ----------
* Reverse geocoding generates an address from a coordinate given as latitude
* and longitude.
*
* returns SETOF NominatimRecord
*/
Datum nominatim_fdw_reverse(PG_FUNCTION_ARGS)
{
text *srvname_text = PG_GETARG_TEXT_P(0);
float8 lon = PG_GETARG_FLOAT8(1);
float8 lat = PG_GETARG_FLOAT8(2);
int zoom = PG_GETARG_INT32(3);
text *layer = PG_GETARG_TEXT_P(4);
bool extratags = PG_GETARG_BOOL(5);
bool addressdetails = PG_GETARG_BOOL(6);
bool namedetails = PG_GETARG_BOOL(7);
text *polygon_text = PG_GETARG_TEXT_P(8);
text *language_text = PG_GETARG_TEXT_P(9);
FuncCallContext *funcctx;
TupleDesc tupdesc;
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
NominatimFDWState *state = InitSession(text_to_cstring(srvname_text));
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
if (language_text && strlen(text_to_cstring(language_text)) > 0)
state->accept_language = text_to_cstring(language_text);
state->lon = lon;
state->lat = lat;
state->zoom = zoom;
state->layer = strcmp(text_to_cstring(layer), "") == 0 ? NULL : text_to_cstring(layer);
state->request_type = NOMINATIM_REQUEST_REVERSE;
state->polygon_type = text_to_cstring(polygon_text);
state->extratags = extratags;
state->addressdetails = addressdetails;
state->namedetails = namedetails;
if(state->layer && !IsLayerValid(state->layer))
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_STRING_FORMAT),
errmsg("invalid layer '%s'", state->layer),
errhint("this parameter expects one of the following layers: address, poi, railway, natural, manmade")));
if (!IsPolygonTypeSupported(state->polygon_type))
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_STRING_FORMAT),
errmsg("invalid polygon type '%s'", state->polygon_type),
errhint("this parameter expects one of the following formats: polygon_geojson, polygon_kml, polygon_svg, polygon_text")));
elog(DEBUG1, "\n\n\t=== %s ===\n\tlon: '%f'\n\tlat: '%f'\n\tzoom: '%d'\n\tpolygon_type: '%s'\n\tlayer: '%s'\n", __func__,
state->lon,
state->lat,
state->zoom,
state->polygon_type,
state->layer);
ParseNominatimReverseData(state);
funcctx->user_fctx = state->records;
if (state->records)
funcctx->max_calls = state->records->length;
elog(DEBUG1, " %s: number of records retrieved = %ld ", __func__, funcctx->max_calls);
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context that cannot accept type record")));
tupdesc = BlessTupleDesc(tupdesc);
funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
if (funcctx->call_cntr < funcctx->max_calls)
{
Datum values[18];
bool nulls[18];
HeapTuple tuple;
Datum result;
NominatimRecord *place = (NominatimRecord *)list_nth((List *)funcctx->user_fctx, (int)funcctx->call_cntr);
memset(nulls, 0, sizeof(nulls));
for (size_t i = 0; i < funcctx->attinmeta->tupdesc->natts; i++)
{
Form_pg_attribute att = TupleDescAttr(funcctx->attinmeta->tupdesc, i);
char *value = GetAttributeValue(att, place);
if (value)
values[i] = CreateDatum(tuple, att->atttypid, att->atttypmod, value);
else
nulls[i] = true;
elog(DEBUG2, " %s = '%s'", NameStr(att->attname), value);
}
elog(DEBUG2, " %s: creating heap tuple", __func__);
tuple = heap_form_tuple(funcctx->attinmeta->tupdesc, values, nulls);
result = HeapTupleGetDatum(tuple);
SRF_RETURN_NEXT(funcctx, result);
}
else
{
SRF_RETURN_DONE(funcctx);
}
}
/*
* nominatim_fdw_search
* ----------
* Look up a location from a textual description or structured address.
*
* returns SETOF NominatimRecord
*/
Datum nominatim_fdw_search(PG_FUNCTION_ARGS)
{
text *srvname_text = PG_GETARG_TEXT_P(0);
text *query_text = PG_GETARG_TEXT_P(1);
text *amenity_text = PG_GETARG_TEXT_P(2);
text *street = PG_GETARG_TEXT_P(3);
text *city = PG_GETARG_TEXT_P(4);
text *county = PG_GETARG_TEXT_P(5);
text *tstate = PG_GETARG_TEXT_P(6);
text *country = PG_GETARG_TEXT_P(7);
text *postalcode = PG_GETARG_TEXT_P(8);
bool extratags = PG_GETARG_BOOL(9);
bool addressdetails = PG_GETARG_BOOL(10);
bool namedetails = PG_GETARG_BOOL(11);
text *polygon_text = PG_GETARG_TEXT_P(12);
text *language_text = PG_GETARG_TEXT_P(13);
text *countrycodes_text = PG_GETARG_TEXT_P(14);
text *layer_text = PG_GETARG_TEXT_P(15);
text *featuretype_text = PG_GETARG_TEXT_P(16);
text *excludeids_text = PG_GETARG_TEXT_P(17);
text *viewbox_text = PG_GETARG_TEXT_P(18);
bool bounded = PG_GETARG_BOOL(19);
float8 polygon_threshold = PG_GETARG_FLOAT8(20);
text *email_text = PG_GETARG_TEXT_P(21);
bool dedupe = PG_GETARG_BOOL(22);
int limit = PG_GETARG_INT32(23);
int offset = PG_GETARG_INT32(24);
FuncCallContext *funcctx;
TupleDesc tupdesc;
NominatimFDWState *state = (NominatimFDWState *)palloc0(sizeof(NominatimFDWState));
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
state = InitSession(text_to_cstring(srvname_text));
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
if (language_text && strlen(text_to_cstring(language_text)) > 0)
state->accept_language = text_to_cstring(language_text);
state->query = text_to_cstring(query_text);
state->amenity = text_to_cstring(amenity_text);
state->amenity = text_to_cstring(amenity_text);
state->street = text_to_cstring(street);
state->city = text_to_cstring(city);
state->county = text_to_cstring(county);
state->state = text_to_cstring(tstate);
state->country = text_to_cstring(country);
state->postalcode = text_to_cstring(postalcode);
state->polygon_type = text_to_cstring(polygon_text);
state->countrycodes = text_to_cstring(countrycodes_text);
state->layer = text_to_cstring(layer_text);
state->feature_type = text_to_cstring(featuretype_text);
state->exclude_place_ids = text_to_cstring(excludeids_text);
state->viewbox = text_to_cstring(viewbox_text);
state->bounded = bounded;
state->polygon_threshold = polygon_threshold;
state->email = text_to_cstring(email_text);
state->dedupe = dedupe;
state->extratags = extratags;
state->addressdetails = addressdetails;
state->namedetails = namedetails;
state->limit = limit;
state->offset = offset;
state->request_type = NOMINATIM_REQUEST_SEARCH;
if (state->amenity && strlen(state->amenity) > 0 &&
state->query && strlen(state->query) > 0)
ereport(ERROR, (errcode(ERRCODE_FDW_ERROR),
errmsg("bad request => structured query parameters (amenity, street, city, county, state, postalcode, country) cannot be used together with 'q' parameter")));
if ((strlen(state->amenity) == 0 && strlen(state->street) == 0 && strlen(state->city) == 0 && strlen(state->county) == 0 && strlen(state->state) == 0 && strlen(state->country) == 0 && strlen(state->postalcode) == 0) &&
strlen(state->query) == 0)
ereport(ERROR, (errcode(ERRCODE_FDW_ERROR),
errmsg("bad request => nothing to search for."),
errhint("a '%s' request requires either a 'q' (free form parameter) or one of the structured query parameteres (amenity, street, city, county, state, postalcode, country)", __func__)));
if(state->layer && !IsLayerValid(state->layer))
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_STRING_FORMAT),
errmsg("invalid layer '%s'", state->layer),
errhint("this parameter expects one of the following layers: address, poi, railway, natural, manmade")));
if (!IsPolygonTypeSupported(state->polygon_type))
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_STRING_FORMAT),
errmsg("invalid polygon type '%s'", state->polygon_type),
errhint("this parameter expects one of the following formats: polygon_geojson, polygon_kml, polygon_svg, polygon_text")));
elog(DEBUG1, "\n\n\t=== %s ===\n\tq:'%s'\n\tpolygon_type: '%s'\n", __func__,
state->query,
state->polygon_type);
ParseNominatimSearchData(state);
funcctx->user_fctx = state->records;
if (state->records)
funcctx->max_calls = state->records->length;
elog(DEBUG1, " %s: number of records retrieved = %ld ", __func__, funcctx->max_calls);
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context that cannot accept type record")));
tupdesc = BlessTupleDesc(tupdesc);
funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
if (funcctx->call_cntr < funcctx->max_calls)
{
Datum values[23];
bool nulls[23];
HeapTuple tuple;
Datum result;
NominatimRecord *place = (NominatimRecord *)list_nth((List *)funcctx->user_fctx, (int)funcctx->call_cntr);
memset(nulls, 0, sizeof(nulls));
for (size_t i = 0; i < funcctx->attinmeta->tupdesc->natts; i++)
{
Form_pg_attribute att = TupleDescAttr(funcctx->attinmeta->tupdesc, i);
char *value = GetAttributeValue(att, place);
if (value)
values[i] = CreateDatum(tuple, att->atttypid, att->atttypmod, value);
else
nulls[i] = true;
elog(DEBUG2, " %s = '%s'", NameStr(att->attname), value);
}
elog(DEBUG2, " %s: creating heap tuple", __func__);
tuple = heap_form_tuple(funcctx->attinmeta->tupdesc, values, nulls);
result = HeapTupleGetDatum(tuple);
SRF_RETURN_NEXT(funcctx, result);
}
else
{
SRF_RETURN_DONE(funcctx);
}
}
/*
* nominatim_fdw_lookup
* ----------
* Query the address and other details of one or multiple OSM objects like node,
* way or relation.
*
* returns SETOF NominatimRecord
*/
Datum nominatim_fdw_lookup(PG_FUNCTION_ARGS)
{
text *srvname_text = PG_GETARG_TEXT_P(0);
text *osm_ids_text = PG_GETARG_TEXT_P(1);
bool extratags = PG_GETARG_BOOL(2);
bool addressdetails = PG_GETARG_BOOL(3);
bool namedetails = PG_GETARG_BOOL(4);
text *polygon_text = PG_GETARG_TEXT_P(5);
text *language_text = PG_GETARG_TEXT_P(6);
text *countrycodes_text = PG_GETARG_TEXT_P(7);
text *layer_text = PG_GETARG_TEXT_P(8);
text *featuretype_text = PG_GETARG_TEXT_P(9);
text *excludeids_text = PG_GETARG_TEXT_P(10);
text *viewbox_text = PG_GETARG_TEXT_P(11);
bool bounded = PG_GETARG_BOOL(12);
float8 polygon_threshold = PG_GETARG_FLOAT8(13);
text *email_text = PG_GETARG_TEXT_P(14);
bool dedupe = PG_GETARG_BOOL(15);
FuncCallContext *funcctx;
TupleDesc tupdesc;
NominatimFDWState *state = (NominatimFDWState *)palloc0(sizeof(NominatimFDWState));
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
funcctx = SRF_FIRSTCALL_INIT();
state = InitSession(text_to_cstring(srvname_text));
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
if (language_text && strlen(text_to_cstring(language_text)) > 0)
state->accept_language = text_to_cstring(language_text);
state->osm_ids = text_to_cstring(osm_ids_text);
state->polygon_type = text_to_cstring(polygon_text);
state->countrycodes = text_to_cstring(countrycodes_text);
state->layer = text_to_cstring(layer_text);
state->feature_type = text_to_cstring(featuretype_text);
state->exclude_place_ids = text_to_cstring(excludeids_text);
state->viewbox = text_to_cstring(viewbox_text);
state->bounded = bounded;
state->polygon_threshold = polygon_threshold;
state->email = text_to_cstring(email_text);
state->dedupe = dedupe;
state->extratags = extratags;
state->addressdetails = addressdetails;
state->namedetails = namedetails;
state->request_type = NOMINATIM_REQUEST_LOOKUP;
if(state->layer && !IsLayerValid(state->layer))
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_STRING_FORMAT),
errmsg("invalid layer '%s'", state->layer),
errhint("this parameter expects one of the following layers: address, poi, railway, natural, manmade")));
if (!IsPolygonTypeSupported(state->polygon_type))
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_STRING_FORMAT),
errmsg("invalid polygon type '%s'", state->polygon_type),
errhint("this parameter expects one of the following formats: polygon_geojson, polygon_kml, polygon_svg, polygon_text")));
elog(DEBUG1, "\n\n\t=== %s ===\n\tosm_ids:'%s'\n\tpolygon_type: '%s'\n", __func__,
state->osm_ids,
state->polygon_type);
ParseNominatimSearchData(state);
funcctx->user_fctx = state->records;
if (state->records)
funcctx->max_calls = state->records->length;
elog(DEBUG1, " %s: number of records retrieved = %ld ", __func__, funcctx->max_calls);
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context that cannot accept type record")));
tupdesc = BlessTupleDesc(tupdesc);
funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
if (funcctx->call_cntr < funcctx->max_calls)
{
Datum values[23];
bool nulls[23];
HeapTuple tuple;
Datum result;
NominatimRecord *place = (NominatimRecord *)list_nth((List *)funcctx->user_fctx, (int)funcctx->call_cntr);
memset(nulls, 0, sizeof(nulls));
for (size_t i = 0; i < funcctx->attinmeta->tupdesc->natts; i++)
{
Form_pg_attribute att = TupleDescAttr(funcctx->attinmeta->tupdesc, i);
char *value = GetAttributeValue(att, place);
if (value)
values[i] = CreateDatum(tuple, att->atttypid, att->atttypmod, value);
else
nulls[i] = true;
elog(DEBUG2, " %s: %s = '%s'", __func__, NameStr(att->attname), value);
}
elog(DEBUG2, " %s: creating heap tuple", __func__);
tuple = heap_form_tuple(funcctx->attinmeta->tupdesc, values, nulls);
result = HeapTupleGetDatum(tuple);
SRF_RETURN_NEXT(funcctx, result);
}
else
{
SRF_RETURN_DONE(funcctx);
}
}
/*
* GetAttributeValue
* ----------
* Extracts the value of a given attribute and sets the correspondent property
* in the NominatimRecord struct. It returs NULL in case of no match.
*
* att: a Form_pg_attribute attribute
* place: a NominatimRecord variable
*
* returns SETOF NominatimRecord
*/
static char *GetAttributeValue(Form_pg_attribute att, struct NominatimRecord *place)
{
if (strcmp(NameStr(att->attname), "osm_id") == 0)
return place->osm_id;
else if (strcmp(NameStr(att->attname), "osm_type") == 0)
return place->osm_type;
else if (strcmp(NameStr(att->attname), "ref") == 0)
return place->ref;
else if (strcmp(NameStr(att->attname), "class") == 0)
return place->class;
else if (strcmp(NameStr(att->attname), "display_name") == 0)
return place->display_name;
else if (strcmp(NameStr(att->attname), "display_rank") == 0)
return place->display_rank;
else if (strcmp(att->attname.data, "place_id") == 0)
return place->place_id;
else if (strcmp(NameStr(att->attname), "place_rank") == 0)
return place->place_rank;
else if (strcmp(NameStr(att->attname), "address_rank") == 0)
return place->address_rank;
else if (strcmp(NameStr(att->attname), "lon") == 0)
return place->lon;
else if (strcmp(NameStr(att->attname), "lat") == 0)
return place->lat;
else if (strcmp(NameStr(att->attname), "boundingbox") == 0)
return place->boundingbox;
else if (strcmp(NameStr(att->attname), "importance") == 0)
return place->importance;
else if (strcmp(NameStr(att->attname), "icon") == 0)
return place->icon;
else if (strcmp(NameStr(att->attname), "extratags") == 0)
return place->extratags;
else if (strcmp(NameStr(att->attname), "timestamp") == 0)
return place->timestamp;
else if (strcmp(NameStr(att->attname), "attribution") == 0)
return place->attribution;
else if (strcmp(NameStr(att->attname), "querystring") == 0)
return place->querystring;
else if (strcmp(NameStr(att->attname), "polygon") == 0)
return place->polygon;
else if (strcmp(NameStr(att->attname), "exclude_place_ids") == 0)
return place->exclude_place_ids;
else if (strcmp(NameStr(att->attname), "more_url") == 0)
return place->more_url;
else if (strcmp(NameStr(att->attname), "addressdetails") == 0)
return place->addressdetails;
else if (strcmp(NameStr(att->attname), "namedetails") == 0)
return place->namedetails;
else if (strcmp(NameStr(att->attname), "result") == 0)
return place->result;
else if (strcmp(NameStr(att->attname), "addressparts") == 0)
return place->addressparts;
else
return NULL;
}
/*
* CreateDatum
* ----------
*
* Creates a Datum from a given value based on the postgres types and modifiers.
*
* tuple: a Heaptuple
* pgtype: postgres type
* pgtypemod: postgres type modifier
* value: value to be converted
*
* returns Datum
*/
static Datum CreateDatum(HeapTuple tuple, int pgtype, int pgtypmod, char *value)
{
regproc typinput;
tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(pgtype));
if (!HeapTupleIsValid(tuple))
{
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_DATA_TYPE),
errmsg("cache lookup failed for type %u (osm_id)", pgtype)));
}
typinput = ((Form_pg_type)GETSTRUCT(tuple))->typinput;
ReleaseSysCache(tuple);
if (pgtype == FLOAT4OID ||
pgtype == FLOAT8OID ||
pgtype == NUMERICOID ||
pgtype == TIMESTAMPOID ||
pgtype == TIMESTAMPTZOID ||
pgtype == VARCHAROID)
return OidFunctionCall3(
typinput,
CStringGetDatum(value),
ObjectIdGetDatum(InvalidOid),
Int32GetDatum(pgtypmod));
else
return OidFunctionCall1(typinput, CStringGetDatum(value));
}
/*
* InitSession
* ----------
*
* This function loads all session info from a specific foreign server data
* into a NominatimFDWState.
*
* srvname: foreign server's name
*
* returns NominatimFDWState with the loaded session values
*/
static NominatimFDWState *InitSession(const char *srvname)
{
NominatimFDWState *state = (NominatimFDWState *)palloc0(sizeof(NominatimFDWState));
ForeignServer *server = GetForeignServerByName(srvname, true);
state->request_redirect = 1L;
state->max_retries = NOMINATIM_DEFAULT_MAXRETRY;
state->request_max_redirect = NOMINATIM_DEFAULT_MAXREDIRECT;
state->accept_language = NOMINATIM_DEFAULT_LANGUAGE;
state->connect_timeout = NOMINATIM_DEFAULT_CONNECTTIMEOUT;
elog(DEBUG1, "%s called: '%s'", __func__, srvname);
if (server)
{
ListCell *cell;
foreach (cell, server->options)
{