-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathogr_fdw.c
3339 lines (2914 loc) · 89.6 KB
/
ogr_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
/*-------------------------------------------------------------------------
*
* ogr_fdw.c
* foreign-data wrapper for GIS data access.
*
* Copyright (c) 2014-2015, Paul Ramsey <[email protected]>
*
*-------------------------------------------------------------------------
*/
/*
* PostgreSQL
*/
#include "postgres.h"
/*
* System
*/
#include <sys/stat.h>
#include <unistd.h>
/*
* Require PostgreSQL >= 9.3
*/
#if PG_VERSION_NUM < 90300
#error "OGR FDW requires PostgreSQL version 9.3 or higher"
#else
/*
* Definition of stringToQualifiedNameList
*/
#if PG_VERSION_NUM >= 100000
#include "utils/regproc.h"
#endif
/*
* Local structures
*/
#include "ogr_fdw.h"
PG_MODULE_MAGIC;
/*
* Describes the valid options for objects that use this wrapper.
*/
struct OgrFdwOption
{
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 */
};
#define OPT_DRIVER "format"
#define OPT_SOURCE "datasource"
#define OPT_LAYER "layer"
#define OPT_COLUMN "column_name"
#define OPT_CONFIG_OPTIONS "config_options"
#define OPT_OPEN_OPTIONS "open_options"
#define OPT_UPDATEABLE "updateable"
#define OPT_CHAR_ENCODING "character_encoding"
#define OGR_FDW_FRMT_INT64 "%lld"
#define OGR_FDW_CAST_INT64(x) (long long)(x)
/*
* Valid options for ogr_fdw.
* ForeignDataWrapperRelationId (no options)
* ForeignServerRelationId (CREATE SERVER options)
* UserMappingRelationId (CREATE USER MAPPING options)
* ForeignTableRelationId (CREATE FOREIGN TABLE options)
*
* {optname, optcontext, optrequired, optfound}
*/
static struct OgrFdwOption valid_options[] =
{
/* OGR column mapping */
{OPT_COLUMN, AttributeRelationId, false, false},
/* OGR datasource options */
{OPT_SOURCE, ForeignServerRelationId, true, false},
{OPT_DRIVER, ForeignServerRelationId, false, false},
{OPT_UPDATEABLE, ForeignServerRelationId, false, false},
{OPT_CONFIG_OPTIONS, ForeignServerRelationId, false, false},
{OPT_CHAR_ENCODING, ForeignServerRelationId, false, false},
#if GDAL_VERSION_MAJOR >= 2
{OPT_OPEN_OPTIONS, ForeignServerRelationId, false, false},
#endif
/* OGR layer options */
{OPT_LAYER, ForeignTableRelationId, true, false},
{OPT_UPDATEABLE, ForeignTableRelationId, false, false},
/* EOList marker */
{NULL, InvalidOid, false, false}
};
/*
* SQL functions
*/
extern Datum ogr_fdw_handler(PG_FUNCTION_ARGS);
extern Datum ogr_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(ogr_fdw_handler);
PG_FUNCTION_INFO_V1(ogr_fdw_validator);
void _PG_init(void);
/*
* FDW query callback routines
*/
static void ogrGetForeignRelSize(PlannerInfo* root,
RelOptInfo* baserel,
Oid foreigntableid);
static void ogrGetForeignPaths(PlannerInfo* root,
RelOptInfo* baserel,
Oid foreigntableid);
static ForeignScan* ogrGetForeignPlan(PlannerInfo* root,
RelOptInfo* baserel,
Oid foreigntableid,
ForeignPath* best_path,
List* tlist,
List* scan_clauses
#if PG_VERSION_NUM >= 90500
, Plan* outer_plan
#endif
);
static void ogrBeginForeignScan(ForeignScanState* node, int eflags);
static TupleTableSlot* ogrIterateForeignScan(ForeignScanState* node);
static void ogrReScanForeignScan(ForeignScanState* node);
static void ogrEndForeignScan(ForeignScanState* node);
/*
* FDW modify callback routines
*/
#if PG_VERSION_NUM >= 140000
static void ogrAddForeignUpdateTargets(PlannerInfo* planinfo,
unsigned int rte_index,
RangeTblEntry* target_rte,
Relation target_relation);
#else
static void ogrAddForeignUpdateTargets(Query* parsetree,
RangeTblEntry* target_rte,
Relation target_relation);
#endif
static void ogrBeginForeignModify(ModifyTableState* mtstate,
ResultRelInfo* rinfo,
List* fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot* ogrExecForeignInsert(EState* estate,
ResultRelInfo* rinfo,
TupleTableSlot* slot,
TupleTableSlot* planSlot);
static TupleTableSlot* ogrExecForeignUpdate(EState* estate,
ResultRelInfo* rinfo,
TupleTableSlot* slot,
TupleTableSlot* planSlot);
static TupleTableSlot* ogrExecForeignDelete(EState* estate,
ResultRelInfo* rinfo,
TupleTableSlot* slot,
TupleTableSlot* planSlot);
static void ogrEndForeignModify(EState* estate,
ResultRelInfo* rinfo);
static int ogrIsForeignRelUpdatable(Relation rel);
#if PG_VERSION_NUM >= 90500
static List* ogrImportForeignSchema(ImportForeignSchemaStmt* stmt, Oid serverOid);
#endif
/*
* Helper functions
*/
static OgrConnection ogrGetConnectionFromTable(Oid foreigntableid, OgrUpdateable updateable);
static void ogr_fdw_exit(int code, Datum arg);
static void ogrReadColumnData(OgrFdwState* state);
/* Global to hold GEOMETRYOID */
Oid GEOMETRYOID = InvalidOid;
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,1,0)
const char* const gdalErrorTypes[] =
{
"None",
"AppDefined",
"OutOfMemory",
"FileIO",
"OpenFailed",
"IllegalArg",
"NotSupported",
"AssertionFailed",
"NoWriteAccess",
"UserInterrupt",
"ObjectNull",
"HttpResponse",
"AWSBucketNotFound",
"AWSObjectNotFound",
"AWSAccessDenied",
"AWSInvalidCredentials",
"AWSSignatureDoesNotMatch"
};
/* In theory this function should be declared "static void CPL_STDCALL" */
/* since this is the official signature of error handler callbacks. */
/* That would be needed if both GDAL and ogr_fdw were compiled with Visual */
/* Studio, but with non-Visual Studio compilers, the macro expands to empty, */
/* so if both GDAL and ogr_fdw are compiled with gcc things are fine. In case */
/* of mixes, crashes may occur but there is no clean fix... So let this as a note */
/* in case of future issue... */
static void
ogrErrorHandler(CPLErr eErrClass, int err_no, const char* msg)
{
const char* gdalErrType = "unknown type";
if (err_no >= 0 && err_no <
(int)sizeof(gdalErrorTypes) / sizeof(gdalErrorTypes[0]))
{
gdalErrType = gdalErrorTypes[err_no];
}
switch (eErrClass)
{
case CE_None:
elog(NOTICE, "GDAL %s [%d] %s", gdalErrType, err_no, msg);
break;
case CE_Debug:
elog(DEBUG2, "GDAL %s [%d] %s", gdalErrType, err_no, msg);
break;
case CE_Warning:
elog(WARNING, "GDAL %s [%d] %s", gdalErrType, err_no, msg);
break;
case CE_Failure:
case CE_Fatal:
default:
elog(ERROR, "GDAL %s [%d] %s", gdalErrType, err_no, msg);
break;
}
return;
}
#endif /* GDAL 2.1.0+ */
void
_PG_init(void)
{
on_proc_exit(&ogr_fdw_exit, PointerGetDatum(NULL));
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,1,0)
/* Hook up the GDAL error handlers to PgSQL elog() */
CPLSetErrorHandler(ogrErrorHandler);
CPLSetCurrentErrorHandlerCatchDebug(true);
#endif
}
/*
* ogr_fdw_exit: Exit callback function.
*/
static void
ogr_fdw_exit(int code, Datum arg)
{
OGRCleanupAll();
}
/*
* Given extension oid, lookup installation namespace oid.
* This side steps search_path issues with
* TypenameGetTypid encountered in
* https://github.com/pramsey/pgsql-ogr-fdw/issues/263
*/
static Oid
get_extension_nsp_oid(Oid extOid)
{
Oid result;
SysScanDesc scandesc;
HeapTuple tuple;
ScanKeyData entry[1];
#if PG_VERSION_NUM < 120000
Relation rel = heap_open(ExtensionRelationId, AccessShareLock);
ScanKeyInit(&entry[0],
ObjectIdAttributeNumber,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(extOid));
#else
Relation rel = table_open(ExtensionRelationId, AccessShareLock);
ScanKeyInit(&entry[0],
Anum_pg_extension_oid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(extOid));
#endif /* PG_VERSION_NUM */
scandesc = systable_beginscan(rel, ExtensionOidIndexId, true,
NULL, 1, entry);
tuple = systable_getnext(scandesc);
/* We assume that there can be at most one matching tuple */
if (HeapTupleIsValid(tuple))
result = ((Form_pg_extension) GETSTRUCT(tuple))->extnamespace;
else
result = InvalidOid;
systable_endscan(scandesc);
#if PG_VERSION_NUM < 120000
heap_close(rel, AccessShareLock);
#else
table_close(rel, AccessShareLock);
#endif
return result;
}
/*
* Get the geometry OID (if postgis is
* installed) and cache it for quick lookup.
*/
Oid
ogrGetGeometryOid(void)
{
/* Is value not set yet? */
if (GEOMETRYOID == InvalidOid)
{
const char *extName = "postgis";
const char *typName = "geometry";
bool missing_ok = true;
Oid extOid, extNspOid, typOid;
/* Got postgis extension? */
extOid = get_extension_oid(extName, missing_ok);
if (!OidIsValid(extOid))
{
elog(DEBUG2, "%s: lookup of extension '%s' failed", __func__, extName);
GEOMETRYOID = BYTEAOID;
return GEOMETRYOID;
}
/* Got namespace for extension? */
extNspOid = get_extension_nsp_oid(extOid);
if (!OidIsValid(extNspOid))
{
elog(DEBUG2, "%s: lookup of namespace for '%s' (%u) failed", __func__, extName, extOid);
GEOMETRYOID = BYTEAOID;
return GEOMETRYOID;
}
/* Got geometry type in namespace? */
typOid = GetSysCacheOid2(TYPENAMENSP,
#if PG_VERSION_NUM >= 120000
Anum_pg_type_oid,
#endif
PointerGetDatum(typName),
ObjectIdGetDatum(extNspOid));
elog(DEBUG2, "%s: lookup of type id for '%s' got %u", __func__, typName, typOid);
/* Geometry type is good? */
if (OidIsValid(typOid) && get_typisdefined(typOid))
GEOMETRYOID = typOid;
else
GEOMETRYOID = BYTEAOID;
}
return GEOMETRYOID;
}
/*
* Foreign-data wrapper handler function: return a struct with pointers
* to my callback routines.
*/
Datum
ogr_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine* fdwroutine = makeNode(FdwRoutine);
/* Read support */
fdwroutine->GetForeignRelSize = ogrGetForeignRelSize;
fdwroutine->GetForeignPaths = ogrGetForeignPaths;
fdwroutine->GetForeignPlan = ogrGetForeignPlan;
fdwroutine->BeginForeignScan = ogrBeginForeignScan;
fdwroutine->IterateForeignScan = ogrIterateForeignScan;
fdwroutine->ReScanForeignScan = ogrReScanForeignScan;
fdwroutine->EndForeignScan = ogrEndForeignScan;
/* Write support */
fdwroutine->AddForeignUpdateTargets = ogrAddForeignUpdateTargets;
fdwroutine->BeginForeignModify = ogrBeginForeignModify;
fdwroutine->ExecForeignInsert = ogrExecForeignInsert;
fdwroutine->ExecForeignUpdate = ogrExecForeignUpdate;
fdwroutine->ExecForeignDelete = ogrExecForeignDelete;
fdwroutine->EndForeignModify = ogrEndForeignModify;
fdwroutine->IsForeignRelUpdatable = ogrIsForeignRelUpdatable;
#if PG_VERSION_NUM >= 90500
/* Support functions for IMPORT FOREIGN SCHEMA */
fdwroutine->ImportForeignSchema = ogrImportForeignSchema;
#endif
PG_RETURN_POINTER(fdwroutine);
}
/*
* When attempting a soft open (allowing for failure and retry),
* we might need to call the opening
* routines twice, so all the opening machinery is placed here
* for convenient re-calling.
*/
static OGRErr
ogrGetDataSourceAttempt(OgrConnection* ogr, bool bUpdateable, char** open_option_list)
{
GDALDriverH ogr_dr = NULL;
#if GDAL_VERSION_MAJOR >= 2
unsigned int open_flags = GDAL_OF_VECTOR;
if (bUpdateable)
{
open_flags |= GDAL_OF_UPDATE;
}
else
{
open_flags |= GDAL_OF_READONLY;
}
#endif
if (ogr->dr_str)
{
ogr_dr = GDALGetDriverByName(ogr->dr_str);
if (!ogr_dr)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("unable to find format \"%s\"", ogr->dr_str),
errhint("See the formats list at http://www.gdal.org/ogr_formats.html")));
}
#if GDAL_VERSION_MAJOR < 2
ogr->ds = OGR_Dr_Open(ogr_dr, ogr->ds_str, bUpdateable);
#else
{
char** driver_list = CSLAddString(NULL, ogr->dr_str);
ogr->ds = GDALOpenEx(ogr->ds_str, /* file/data source */
open_flags, /* open flags */
(const char* const*)driver_list, /* driver */
(const char* const*)open_option_list, /* open options */
NULL); /* sibling files */
CSLDestroy(driver_list);
}
#endif
}
/* No driver, try a blind open... */
else
{
#if GDAL_VERSION_MAJOR < 2
ogr->ds = OGROpen(ogr->ds_str, bUpdateable, &ogr_dr);
#else
ogr->ds = GDALOpenEx(ogr->ds_str,
open_flags,
NULL,
(const char* const*)open_option_list,
NULL);
#endif
}
return ogr->ds ? OGRERR_NONE : OGRERR_FAILURE;
}
/*
* Given a connection string and (optional) driver string, try to connect
* with appropriate error handling and reporting. Used in query startup,
* and in FDW options validation.
*/
static OGRErr
ogrGetDataSource(OgrConnection* ogr, OgrUpdateable updateable)
{
char** open_option_list = NULL;
bool bUpdateable = (updateable == OGR_UPDATEABLE_TRUE || updateable == OGR_UPDATEABLE_TRY);
OGRErr err;
/* Set the GDAL config options into the environment */
if (ogr->config_options)
{
char** option_iter;
char** option_list = CSLTokenizeString(ogr->config_options);
for (option_iter = option_list; option_iter && *option_iter; option_iter++)
{
char* key;
const char* value;
value = CPLParseNameValue(*option_iter, &key);
if (!(key && value))
{
elog(ERROR, "bad config option string '%s'", ogr->config_options);
}
elog(DEBUG1, "GDAL config option '%s' set to '%s'", key, value);
CPLSetConfigOption(key, value);
CPLFree(key);
}
CSLDestroy(option_list);
}
/* Parse the GDAL layer open options */
if (ogr->open_options)
{
open_option_list = CSLTokenizeString(ogr->open_options);
}
/* Cannot search for drivers if they aren't registered, */
/* but don't do registration if we already have drivers loaded */
if (GDALGetDriverCount() <= 0)
{
GDALAllRegister();
}
/* First attempt at connection */
err = ogrGetDataSourceAttempt(ogr, bUpdateable, open_option_list);
/* Failed on soft updateable attempt, try and fall back to readonly */
if ((!ogr->ds) && updateable == OGR_UPDATEABLE_TRY)
{
err = ogrGetDataSourceAttempt(ogr, false, open_option_list);
/* Succeeded with readonly connection */
if (ogr->ds)
{
ogr->ds_updateable = ogr->lyr_updateable = OGR_UPDATEABLE_FALSE;
}
}
/* Open failed, provide error hint if OGR gives us one. */
if (!ogr->ds)
{
const char* ogrerrmsg = CPLGetLastErrorMsg();
if (ogrerrmsg && !streq(ogrerrmsg, ""))
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("unable to connect to data source \"%s\"", ogr->ds_str),
errhint("%s", ogrerrmsg)));
}
else
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("unable to connect to data source \"%s\"", ogr->ds_str)));
}
}
CSLDestroy(open_option_list);
return err;
}
static bool
ogrCanReallyCountFast(const OgrConnection* con)
{
GDALDriverH dr = GDALGetDatasetDriver(con->ds);
const char* dr_str = GDALGetDriverShortName(dr);
if (streq(dr_str, "ESRI Shapefile") ||
streq(dr_str, "FileGDB") ||
streq(dr_str, "OpenFileGDB"))
{
return true;
}
return false;
}
static void
ogrEreportError(const char* errstr)
{
const char* ogrerrmsg = CPLGetLastErrorMsg();
if (ogrerrmsg && !streq(ogrerrmsg, ""))
{
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmsg("%s", errstr),
errhint("%s", ogrerrmsg)));
}
else
{
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmsg("%s", errstr)));
}
}
/*
* Make sure the datasource is cleaned up when we're done
* with a connection.
*/
static void
ogrFinishConnection(OgrConnection* ogr)
{
elog(DEBUG3, "%s: entered function", __func__);
if (ogr->lyr && OGR_L_SyncToDisk(ogr->lyr) != OGRERR_NONE)
{
elog(NOTICE, "failed to flush writes to OGR data source");
}
if (ogr->ds)
{
GDALClose(ogr->ds);
}
ogr->ds = NULL;
}
static OgrConnection
ogrGetConnectionFromServer(Oid foreignserverid, OgrUpdateable updateable)
{
ForeignServer* server;
OgrConnection ogr;
ListCell* cell;
OGRErr err;
elog(DEBUG3, "%s: entered function", __func__);
/* Null all values */
memset(&ogr, 0, sizeof(OgrConnection));
ogr.ds_updateable = OGR_UPDATEABLE_UNSET;
ogr.lyr_updateable = OGR_UPDATEABLE_UNSET;
server = GetForeignServer(foreignserverid);
foreach (cell, server->options)
{
DefElem* def = (DefElem*) lfirst(cell);
if (streq(def->defname, OPT_SOURCE))
{
ogr.ds_str = defGetString(def);
}
if (streq(def->defname, OPT_DRIVER))
{
ogr.dr_str = defGetString(def);
}
if (streq(def->defname, OPT_CONFIG_OPTIONS))
{
ogr.config_options = defGetString(def);
}
if (streq(def->defname, OPT_OPEN_OPTIONS))
{
ogr.open_options = defGetString(def);
}
if (streq(def->defname, OPT_CHAR_ENCODING))
{
ogr.char_encoding = pg_char_to_encoding(defGetString(def));
}
if (streq(def->defname, OPT_UPDATEABLE))
{
if (defGetBoolean(def))
{
ogr.ds_updateable = OGR_UPDATEABLE_TRUE;
}
else
{
ogr.ds_updateable = OGR_UPDATEABLE_FALSE;
/* Over-ride the open mode to favour user-defined mode */
updateable = OGR_UPDATEABLE_FALSE;
}
}
}
if (!ogr.ds_str)
{
elog(ERROR, "FDW table '%s' option is missing", OPT_SOURCE);
}
/*
* TODO: Connections happen twice for each query, having a
* connection pool will certainly make things faster.
*/
/* Connect! */
err = ogrGetDataSource(&ogr, updateable);
if (err == OGRERR_FAILURE)
{
elog(ERROR, "ogrGetDataSource failed");
}
return ogr;
}
/*
* Read the options (data source connection from server and
* layer name from table) from a foreign table and use them
* to connect to an OGR layer. Return a connection object that
* has handles for both the datasource and layer.
*/
static OgrConnection
ogrGetConnectionFromTable(Oid foreigntableid, OgrUpdateable updateable)
{
ForeignTable* table;
/* UserMapping *mapping; */
/* ForeignDataWrapper *wrapper; */
ListCell* cell;
OgrConnection ogr;
elog(DEBUG3, "%s: entered function", __func__);
/* Gather all data for the foreign table. */
table = GetForeignTable(foreigntableid);
/* mapping = GetUserMapping(GetUserId(), table->serverid); */
ogr = ogrGetConnectionFromServer(table->serverid, updateable);
elog(DEBUG3, "%s: ogr.ds_str = %s", __func__, ogr.ds_str);
foreach (cell, table->options)
{
DefElem* def = (DefElem*) lfirst(cell);
if (streq(def->defname, OPT_LAYER))
{
ogr.lyr_str = defGetString(def);
}
if (streq(def->defname, OPT_UPDATEABLE))
{
if (defGetBoolean(def))
{
if (ogr.ds_updateable == OGR_UPDATEABLE_FALSE)
{
ereport(ERROR, (
errcode(ERRCODE_FDW_ERROR),
errmsg("data source \"%s\" is not updateable", ogr.ds_str),
errhint("cannot set table '%s' option to true", OPT_UPDATEABLE)
));
}
ogr.lyr_updateable = OGR_UPDATEABLE_TRUE;
}
else
{
ogr.lyr_updateable = OGR_UPDATEABLE_FALSE;
}
}
}
if (!ogr.lyr_str)
{
elog(ERROR, "FDW table '%s' option is missing", OPT_LAYER);
}
elog(DEBUG3, "%s: ogr.lyr_str = %s", __func__, ogr.lyr_str);
/* Does the layer exist in the data source? */
ogr.lyr = GDALDatasetGetLayerByName(ogr.ds, ogr.lyr_str);
if (!ogr.lyr)
{
const char* ogrerr = CPLGetLastErrorMsg();
ereport(ERROR, (
errcode(ERRCODE_FDW_TABLE_NOT_FOUND),
errmsg("unable to connect to %s to \"%s\"", OPT_LAYER, ogr.lyr_str),
(ogrerr && ! streq(ogrerr, ""))
? errhint("%s", ogrerr)
: errhint("Does the layer exist?")
));
}
if (OGR_L_TestCapability(ogr.lyr, OLCStringsAsUTF8))
{
ogr.char_encoding = PG_UTF8;
}
return ogr;
}
/*
* Validate the options given to a FOREIGN DATA WRAPPER, SERVER,
* USER MAPPING or FOREIGN TABLE that uses ogr_fdw.
*
* Raise an ERROR if the option or its value is considered invalid.
*/
Datum
ogr_fdw_validator(PG_FUNCTION_ARGS)
{
List* options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
ListCell* cell;
struct OgrFdwOption* opt;
const char* source = NULL, *driver = NULL;
const char* config_options = NULL, *open_options = NULL;
OgrUpdateable updateable = OGR_UPDATEABLE_FALSE;
/* Initialize found state to not found */
for (opt = valid_options; opt->optname; opt++)
{
opt->optfound = false;
}
/*
* Check that only options supported by ogr_fdw, and allowed for the
* current object type, are given.
*/
foreach (cell, options_list)
{
DefElem* def = (DefElem*) lfirst(cell);
bool optfound = false;
for (opt = valid_options; opt->optname; opt++)
{
if (catalog == opt->optcontext && streq(opt->optname, def->defname))
{
/* Mark that this user option was found */
opt->optfound = optfound = true;
/* Store some options for testing later */
if (streq(opt->optname, OPT_SOURCE))
{
source = defGetString(def);
}
if (streq(opt->optname, OPT_DRIVER))
{
driver = defGetString(def);
}
if (streq(opt->optname, OPT_CONFIG_OPTIONS))
{
config_options = defGetString(def);
}
if (streq(opt->optname, OPT_OPEN_OPTIONS))
{
open_options = defGetString(def);
}
if (streq(opt->optname, OPT_UPDATEABLE))
{
if (defGetBoolean(def))
{
updateable = OGR_UPDATEABLE_TRY;
}
}
break;
}
}
if (!optfound)
{
/*
* Unknown option specified, complain about it. Provide a hint
* with list of valid options for the object.
*/
const struct OgrFdwOption* opt;
StringInfoData buf;
initStringInfo(&buf);
for (opt = valid_options; opt->optname; opt++)
{
if (catalog == opt->optcontext)
appendStringInfo(&buf, "%s%s", (buf.len > 0) ? ", " : "",
opt->optname);
}
ereport(ERROR, (
errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", def->defname),
buf.len > 0
? errhint("Valid options in this context are: %s", buf.data)
: errhint("There are no valid options in this context.")));
}
}
/* Check that all the mandatory options were found */
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)));
}
}
/* Make sure server connection can actually be established */
if (catalog == ForeignServerRelationId && source)
{
OgrConnection ogr;
OGRErr err;
ogr.ds_str = source;
ogr.dr_str = driver;
ogr.config_options = config_options;
ogr.open_options = open_options;
err = ogrGetDataSource(&ogr, updateable);
if (err == OGRERR_FAILURE)
{
elog(ERROR, "ogrGetDataSource failed");
}
if (ogr.ds)
{
GDALClose(ogr.ds);
}
}
PG_RETURN_VOID();
}
/*
* Initialize an OgrFdwPlanState on the heap.
*/
static OgrFdwState*
getOgrFdwState(Oid foreigntableid, OgrFdwStateType state_type)
{
OgrFdwState* state;
size_t size;
OgrUpdateable updateable = OGR_UPDATEABLE_FALSE;
switch (state_type)
{
case OGR_PLAN_STATE:
size = sizeof(OgrFdwPlanState);
updateable = OGR_UPDATEABLE_FALSE;
break;
case OGR_EXEC_STATE:
size = sizeof(OgrFdwExecState);
updateable = OGR_UPDATEABLE_FALSE;
break;
case OGR_MODIFY_STATE:
updateable = OGR_UPDATEABLE_TRUE;
size = sizeof(OgrFdwModifyState);
break;
default:
elog(ERROR, "invalid state type");
}
state = palloc0(size);
state->type = state_type;
/* Connect! */
state->ogr = ogrGetConnectionFromTable(foreigntableid, updateable);
state->foreigntableid = foreigntableid;
return state;
}
/*
* ogrGetForeignRelSize
* Obtain relation size estimates for a foreign table
*/
static void
ogrGetForeignRelSize(PlannerInfo* root,
RelOptInfo* baserel,
Oid foreigntableid)
{
/* Initialize the OGR connection */
OgrFdwState* state = (OgrFdwState*)getOgrFdwState(foreigntableid, OGR_PLAN_STATE);
OgrFdwPlanState* planstate = (OgrFdwPlanState*)state;
List* scan_clauses = baserel->baserestrictinfo;
elog(DEBUG3, "%s: entered function", __func__);
/* Set to NULL to clear the restriction clauses in OGR */
OGR_L_SetIgnoredFields(planstate->ogr.lyr, NULL);
OGR_L_SetSpatialFilter(planstate->ogr.lyr, NULL);
OGR_L_SetAttributeFilter(planstate->ogr.lyr, NULL);
/*
* The estimate number of rows returned must actually use restrictions.
* Since OGR can't really give us a fast count with restrictions on
* (usually involves a scan) and restrictions in the baserel mean we
* must punt row count estimates.
*/
/* TODO: calculate the row width based on the attribute types of the OGR table */
/*
* OGR asks drivers to honestly state if they can provide a fast
* row count, but too many drivers lie. We are only listing drivers
* we trust in ogrCanReallyCountFast()
*/
/* If we can quickly figure how many rows this layer has, then do so */
if (scan_clauses == NIL &&
OGR_L_TestCapability(planstate->ogr.lyr, OLCFastFeatureCount) == TRUE &&
ogrCanReallyCountFast(&(planstate->ogr)))
{
/* Count rows, but don't force a slow count */
int rows = OGR_L_GetFeatureCount(planstate->ogr.lyr, false);
/* Only use row count if return is valid (>0) */
if (rows >= 0)
{
planstate->nrows = rows;
baserel->rows = rows;
}
}
/* Save connection state for next calls */
baserel->fdw_private = (void*) planstate;
return;
}