-
Notifications
You must be signed in to change notification settings - Fork 34
/
ogr_fdw_deparse.c
729 lines (624 loc) · 16.6 KB
/
ogr_fdw_deparse.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
/*-------------------------------------------------------------------------
*
* ogr_fdw_deparse.c
* foreign-data wrapper for GIS data access.
*
* Copyright (c) 2014-2015, Paul Ramsey <[email protected]>
*
* Convert parse tree to a QueryExpression as described at
* http://gdal.org/ogr_sql.html
*-------------------------------------------------------------------------
*/
/*
* Local structures
*/
#include "ogr_fdw.h"
typedef struct OgrDeparseCtx
{
PlannerInfo* root; /* global planner state */
RelOptInfo* foreignrel; /* the foreign relation we are planning for */
StringInfo buf; /* output buffer to append to */
List** params_list; /* exprs that will become remote Params */
OgrFdwSpatialFilter* spatial_filter; /* spatial filter bounds and fieldnumber */
OgrFdwState* state; /* to convert local column names to OGR names */
} OgrDeparseCtx;
/* Local function signatures */
static bool ogrDeparseExpr(Expr* node, OgrDeparseCtx* context);
// static void ogrDeparseOpExpr(OpExpr* node, OgrDeparseCtx *context);
static void
setStringInfoLength(StringInfo str, int len)
{
str->len = len;
str->data[len] = '\0';
}
static void
stringInfoReverse(StringInfo str, unsigned int len)
{
if (str->len > len)
str->len -= len;
}
static char*
ogrStringFromDatum(Datum datum, Oid type)
{
StringInfoData result;
regproc typoutput;
HeapTuple tuple;
char* str, *p;
/* Special handling for boolean */
if (type == BOOLOID)
{
if (datum)
{
return "1=1";
}
else
{
return "1=0";
}
}
/* get the type's output function */
tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
if (!HeapTupleIsValid(tuple))
{
elog(ERROR, "cache lookup failed for type %u", type);
}
typoutput = ((Form_pg_type)GETSTRUCT(tuple))->typoutput;
ReleaseSysCache(tuple);
initStringInfo(&result);
/* Special handling to convert a geometry to a bbox needed here */
if (type == ogrGetGeometryOid())
{
elog(ERROR, "got a GEOMETRY!");
return NULL;
}
/* render the constant in OGR SQL */
switch (type)
{
case TEXTOID:
case DATEOID:
case TIMESTAMPOID:
case TIMESTAMPTZOID:
case CHAROID:
case BPCHAROID:
case VARCHAROID:
case NAMEOID:
str = DatumGetCString(OidFunctionCall1(typoutput, datum));
/* Don't return a zero length string, return an empty string */
if (str[0] == '\0')
{
return "''";
}
/* wrap string with ' */
appendStringInfoChar(&result, '\'');
for (p = str; *p; ++p)
{
/* Escape single quotes as doubled '' */
if (*p == '\'')
{
appendStringInfoChar(&result, '\'');
}
appendStringInfoChar(&result, *p);
}
appendStringInfoChar(&result, '\'');
break;
case INT8OID:
case INT2OID:
case INT4OID:
case OIDOID:
case FLOAT4OID:
case FLOAT8OID:
case NUMERICOID:
appendStringInfoString(&result, DatumGetCString(OidFunctionCall1(typoutput, datum)));
break;
default:
elog(DEBUG1, "could not convert type (%d) to OGR query form", type);
return NULL;
}
return result.data;
}
static bool
ogrDeparseConst(Const* constant, OgrDeparseCtx* context)
{
/* TODO: Can OGR do anythign w/ NULL? */
if (constant->constisnull)
{
appendStringInfoString(context->buf, "NULL");
}
/* Use geometry as a spatial filter? */
else if (constant->consttype == ogrGetGeometryOid())
{
/*
* For geometry we need to convert the gserialized constant into
* an OGRGeometry for the OGR spatial filter.
* For that, we can use the type's "send" function
* which takes in gserialized and spits out EWKB.
*/
Oid sendfunction;
bool typeIsVarlena;
Datum wkbdatum;
char* gser;
char* wkb;
char* wkt;
int wkb_size;
OGRGeometryH ogrgeom;
/*
* Given a type oid (geometry in this case),
* look up the "send" function that takes in
* serialized input and outputs the binary (WKB) form.
*/
getTypeBinaryOutputInfo(constant->consttype, &sendfunction, &typeIsVarlena);
wkbdatum = OidFunctionCall1(sendfunction, constant->constvalue);
/*
* Convert the WKB into an OGR geometry
*/
gser = DatumGetPointer(wkbdatum);
wkb = VARDATA(gser);
wkb_size = VARSIZE(gser) - VARHDRSZ;
OGR_G_CreateFromWkb((unsigned char*)wkb, NULL, &ogrgeom, wkb_size);
OGR_G_ExportToWkt(ogrgeom, &wkt);
elog(DEBUG1, "ogrDeparseConst got a geometry: %s", wkt);
free(wkt);
OGR_G_DestroyGeometry(ogrgeom);
/*
* geometry doesn't play a role in the deparsed SQL
*/
return false;
}
else
{
/* get a string representation of the value */
char* c = ogrStringFromDatum(constant->constvalue, constant->consttype);
if (c == NULL)
{
return false;
}
else
{
appendStringInfoString(context->buf, c);
}
}
return true;
}
static bool
ogrDeparseParam(Param* node, OgrDeparseCtx* context)
{
elog(DEBUG3, "got into ogrDeparseParam code");
return false;
}
static bool
ogrIsLegalVarName(const char* varname)
{
size_t len = strlen(varname);
int i;
for (i = 0; i < len; i++)
{
char c = varname[i];
/* First char must be a-zA-Z */
if (i == 0 && !((c >= 97 && c <= 122) || (c >= 65 && c <= 90)))
{
return false;
}
/* All other chars must be 0-9a-zA-Z_ */
if (!((c >= 97 && c <= 122) || (c >= 65 && c <= 90) || (c >= 48 && c <= 59) || (c == 96)))
{
return false;
}
}
return true;
}
static bool
ogrDeparseVarOgrColumn(const Var* node, const OgrDeparseCtx* context, OgrFdwColumn *col)
{
/* Var belongs to foreign table */
int i;
OgrFdwTable* table = context->state->table;
for (i = 0; i < table->ncols; i++)
{
if (table->cols[i].pgattnum == node->varattno)
{
*col = table->cols[i];
return true;
}
}
return false;
}
static const char *
ogrDeparseVarName(const Var* node, const OgrDeparseCtx* context)
{
/* Var belongs to foreign table */
OGRLayerH lyr = context->state->ogr.lyr;
OgrFdwColumn col;
if (ogrDeparseVarOgrColumn(node, context, &col))
{
const char* fldname = NULL;
if (col.ogrvariant == OGR_FID)
{
fldname = OGR_L_GetFIDColumn(lyr);
if (! fldname || strlen(fldname) == 0)
{
fldname = "fid";
}
}
else if (col.ogrvariant == OGR_FIELD)
{
OGRFeatureDefnH fd = OGR_L_GetLayerDefn(lyr);
OGRFieldDefnH fld = OGR_FD_GetFieldDefn(fd, col.ogrfldnum);
fldname = OGR_Fld_GetNameRef(fld);
}
if (fldname)
return fldname;
}
return NULL;
}
static bool
ogrDeparseVar(const Var* node, OgrDeparseCtx* context)
{
StringInfoData* buf = context->buf;
/* varno must not be any of OUTER_VAR, INNER_VAR and INDEX_VAR. */
Assert(!IS_SPECIAL_VARNO(node->varno));
if (node->varno == context->foreignrel->relid && node->varlevelsup == 0)
{
const char* fldname = ogrDeparseVarName(node, context);
if (fldname)
{
if (ogrIsLegalVarName(fldname))
{
appendStringInfoString(buf, fldname);
}
else
{
appendStringInfo(buf, "\"%s\"", fldname);
}
}
else
{
return false;
}
}
else
{
elog(ERROR, "got to param handling section of ogrDeparseVar");
return false;
}
return true;
}
static int
ogrOperatorCmpFunc(const void* a, const void* b)
{
return strcasecmp(*(const char**)a, *(const char**)b);
}
static bool
ogrOperatorIsSupported(const char* opname)
{
/* IMPORTANT */
/* This array MUST be in sorted order or the bsearch will fail */
static const char* ogrOperators[10] = { "!=", "&&", "<", "<=", "<>", "=", ">", ">=", "~~", "~~*" };
elog(DEBUG3, "ogrOperatorIsSupported got operator '%s'", opname);
return NULL != bsearch(&opname, ogrOperators, 10, sizeof(char*), ogrOperatorCmpFunc);
}
static bool ogrDeparseOpExprSpatial(OpExpr* node, OgrDeparseCtx* context)
{
Expr* r_arg = lfirst(list_head(node->args));
Expr* l_arg = lfirst(list_tail(node->args));
Expr* exprconst = NULL;
Const* constant = NULL;
Var* var = NULL;
OgrFdwColumn col;
OGRLayerH lyr;
OGRFeatureDefnH fdh;
OGRGeomFieldDefnH gfdh;
OGRGeometryH geom;
OGREnvelope env;
OGRErr err;
const char* fldname;
elog(DEBUG4, "%s:%d entered ogrDeparseOpExprSpatial", __FILE__, __LINE__);
/* We need a Geometry T_Const on one side and a T_Var */
/* column on the other side that is from the FDW relation */
/* Both of those implies and OGR spatial filter can be reasonably */
/* set. */
if (nodeTag(l_arg) == T_Var)
{
var = (Var*)l_arg;
exprconst = r_arg;
}
else if (nodeTag(r_arg) == T_Var)
{
var = (Var*)r_arg;
exprconst = l_arg;
}
else return false;
if (nodeTag(exprconst) == T_Const)
{
constant = (Const*)exprconst;
}
else return false;
/* Const isn't a geometry type? Done. */
if (constant->consttype != ogrGetGeometryOid() || constant->constisnull || constant->constbyval)
return false;
/* Var doesn't match an OGR field? Done. */
if (!ogrDeparseVarOgrColumn(var, context, &col))
return false;
/* Matched field isn't an OGR geometry? Done. */
if (col.ogrvariant != OGR_GEOMETRY)
return false;
lyr = context->state->ogr.lyr;
fdh = OGR_L_GetLayerDefn(lyr);
gfdh = OGR_FD_GetGeomFieldDefn(fdh, col.ogrfldnum);
fldname = OGR_GFld_GetNameRef(gfdh);
elog(DEBUG4, "%s:%d geometry fieldname '%s'", __FILE__, __LINE__, fldname);
err = pgDatumToOgrGeometry (constant->constvalue, col.pgsendfunc, &geom);
if (err != OGRERR_NONE)
return false;
elog(DEBUG4, "%s:%d geometry constant is %s", __FILE__, __LINE__, OGR_G_ExportToJson(geom));
OGR_G_GetEnvelope(geom, &env);
OGR_G_DestroyGeometry(geom);
context->spatial_filter = palloc(sizeof(OgrFdwSpatialFilter));
context->spatial_filter->minx = env.MinX;
context->spatial_filter->maxx = env.MaxX;
context->spatial_filter->miny = env.MinY;
context->spatial_filter->maxy = env.MaxY;
context->spatial_filter->ogrfldnum = col.ogrfldnum;
elog(DEBUG4, "%s:%d OGR spatial filter is (%f %f, %f %f)",
__FILE__, __LINE__,
env.MinX, env.MinY, env.MaxX, env.MaxY);
return false;
}
static bool
ogrDeparseOpExpr(OpExpr* node, OgrDeparseCtx* context)
{
StringInfo buf = context->buf;
HeapTuple tuple;
Form_pg_operator form;
char oprkind;
char* opname;
ListCell* arg;
bool result = true;
/* Retrieve information about the operator from system catalog. */
tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
if (!HeapTupleIsValid(tuple))
{
elog(ERROR, "cache lookup failed for operator %u", node->opno);
}
form = (Form_pg_operator) GETSTRUCT(tuple);
oprkind = form->oprkind;
opname = NameStr(form->oprname);
/* Don't deparse expressions we cannot support */
if (! ogrOperatorIsSupported(opname))
{
ReleaseSysCache(tuple);
return false;
}
/* Overlaps operator is special case: if one side is a */
/* constant (T_Const), and the other is a table column (T_Var), */
/* then we can pass it as a spatial filter to OGR */
if (strcmp("&&", opname) == 0)
{
ReleaseSysCache(tuple);
return ogrDeparseOpExprSpatial(node, context);
}
/* Sanity check. */
Assert((oprkind == 'r' && list_length(node->args) == 1) ||
(oprkind == 'l' && list_length(node->args) == 1) ||
(oprkind == 'b' && list_length(node->args) == 2));
/* Always parenthesize the operator expression. */
appendStringInfoChar(buf, '(');
/* Deparse left operand. */
if (oprkind == 'r' || oprkind == 'b')
{
arg = list_head(node->args);
/* recurse for nested operations */
result &= ogrDeparseExpr(lfirst(arg), context);
appendStringInfoChar(buf, ' ');
}
/* Special case, the 'LIKE' operator is converted to ~~ */
/* by PgSQL, so we have to convert it back here */
/* All OGR string comparisons are case insensitive, so we just */
/* use 'ILIKE' all the time. */
if (streq(opname, "~~") || streq(opname, "~~*"))
{
opname = "ILIKE";
}
/* Operator symbol */
appendStringInfoString(buf, opname);
/* Deparse right operand. */
if (oprkind == 'l' || oprkind == 'b')
{
arg = list_tail(node->args);
appendStringInfoChar(buf, ' ');
/* recurse for nested operations */
result &= ogrDeparseExpr(lfirst(arg), context);
}
appendStringInfoChar(buf, ')');
ReleaseSysCache(tuple);
return result;
}
static bool
ogrDeparseBoolExpr(BoolExpr* node, OgrDeparseCtx* context)
{
const char* op = NULL; /* keep compiler quiet */
ListCell* lc;
bool first = true;
bool result = true;
int len_save_all, len_save_part;
int boolop = node->boolop;
int result_total = 0;
StringInfo buf = context->buf;
switch (boolop)
{
case AND_EXPR:
op = "AND";
break;
case OR_EXPR:
op = "OR";
break;
/* OGR SQL cannot handle "NOT" */
case NOT_EXPR:
return false;
}
len_save_all = buf->len;
appendStringInfoChar(buf, '(');
foreach (lc, node->args)
{
len_save_part = buf->len;
/* Connect expressions and parenthesize each condition */
if (! first)
{
appendStringInfo(buf, " %s ", op);
}
/* Unparse the expression, if possible */
result = ogrDeparseExpr((Expr*) lfirst(lc), context);
result_total += result;
/* We can backtrack just this term for AND expressions */
if (boolop == AND_EXPR && ! result)
{
setStringInfoLength(buf, len_save_part);
}
/* We have to drop the whole thing if we can't get every part of an OR expression */
if (boolop == OR_EXPR && ! result)
{
break;
}
/* Don't flip the "first" bit until we get a good expression */
if (first && result)
{
first = false;
}
}
appendStringInfoChar(buf, ')');
/* We have to drop the whole thing if we can't get every part of an OR expression */
if (boolop == OR_EXPR && ! result)
{
setStringInfoLength(buf, len_save_all);
}
return result_total > 0;
}
static bool
ogrDeparseRelabelType(RelabelType* node, OgrDeparseCtx* context)
{
if (node->relabelformat != COERCE_IMPLICIT_CAST)
{
elog(WARNING, "Received a non-implicit relabel expression but did not handle it");
}
return ogrDeparseExpr(node->arg, context);
}
static bool
ogrDeparseNullTest(NullTest* node, OgrDeparseCtx* context)
{
StringInfo buf = context->buf;
/* Only push down simple "col IS NULL" tests */
if (nodeTag(node->arg) != T_Var)
return false;
appendStringInfoString(buf, "(");
if(!ogrDeparseVar((Var*)(node->arg), context))
{
stringInfoReverse(buf, 1);
return false;
}
if (node->nulltesttype == IS_NULL)
{
appendStringInfoString(buf, " IS NULL)");
}
else
{
appendStringInfoString(buf, " IS NOT NULL)");
}
return true;
}
static bool
ogrDeparseExpr(Expr* node, OgrDeparseCtx* context)
{
if (node == NULL)
{
return false;
}
switch (nodeTag(node))
{
case T_OpExpr:
return ogrDeparseOpExpr((OpExpr*) node, context);
case T_Const:
return ogrDeparseConst((Const*) node, context);
case T_Var:
return ogrDeparseVar((Var*) node, context);
case T_Param:
return ogrDeparseParam((Param*) node, context);
case T_BoolExpr:
/* Handle "OR" and "NOT" queries */
return ogrDeparseBoolExpr((BoolExpr*) node, context);
case T_NullTest:
/* Handle "IS NULL" queries */
return ogrDeparseNullTest((NullTest*) node, context);
case T_RelabelType:
return ogrDeparseRelabelType((RelabelType*) node, context);
case T_ScalarArrayOpExpr:
/* TODO: Handle this to support the "IN" operator */
elog(DEBUG2, "unsupported OGR FDW expression type, T_ScalarArrayOpExpr");
return false;
#if PG_VERSION_NUM < 120000
case T_ArrayRef:
elog(DEBUG2, "unsupported OGR FDW expression type, T_ArrayRef");
return false;
#else
case T_SubscriptingRef:
elog(DEBUG2, "unsupported OGR FDW expression type, T_SubscriptingRef");
return false;
#endif
case T_ArrayExpr:
elog(DEBUG2, "unsupported OGR FDW expression type, T_ArrayExpr");
return false;
case T_FuncExpr:
elog(DEBUG2, "unsupported OGR FDW expression type, T_FuncExpr");
return false;
case T_DistinctExpr:
elog(DEBUG2, "unsupported OGR FDW expression type, T_DistinctExpr");
return false;
default:
elog(DEBUG2, "unsupported OGR FDW expression type for deparse: %d", (int) nodeTag(node));
return false;
}
}
bool
ogrDeparse(StringInfo buf, PlannerInfo* root, RelOptInfo* foreignrel, List* exprs, OgrFdwState* state, List** params_list, OgrFdwSpatialFilter** sf)
{
OgrDeparseCtx context;
ListCell* lc;
bool first = true;
/* initialize result list to empty */
if (params_list)
{
*params_list = NIL;
}
/* Set up context struct for recursion */
memset(&context, 0, sizeof(OgrDeparseCtx));
context.buf = buf;
context.root = root;
context.foreignrel = foreignrel;
context.params_list = params_list;
context.state = state;
context.spatial_filter = NULL;
foreach (lc, exprs)
{
RestrictInfo* ri = (RestrictInfo*) lfirst(lc);
int len_save = buf->len;
bool result;
/* Connect expressions with "AND" and parenthesize each condition */
if (! first)
{
appendStringInfoString(buf, " AND ");
}
/* Unparse the expression, if possible */
result = ogrDeparseExpr(ri->clause, &context);
if (! result)
{
/* Couldn't unparse some portion of the expression, so rewind the stringinfo */
setStringInfoLength(buf, len_save);
}
/* Don't flip the "first" bit until we get a good expression */
if (first && result)
{
first = false;
}
}
if (context.spatial_filter)
*sf = context.spatial_filter;
return true;
}