-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathvops_fdw.c
1557 lines (1393 loc) · 46.7 KB
/
vops_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
/*-------------------------------------------------------------------------
*
* postgres_fdw.c
* Foreign-data wrapper for remote PostgreSQL servers
*
* Portions Copyright (c) 2012-2017, PostgreSQL Global Development Group
*
* IDENTIFICATION
* contrib/postgres_fdw/postgres_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "vops_fdw.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/reloptions.h"
#include "catalog/pg_class.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "commands/extension.h"
#include "foreign/fdwapi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/cost.h"
#include "optimizer/clauses.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/plancat.h"
#if PG_VERSION_NUM>=140000
#include "optimizer/prep.h"
#endif
#include "optimizer/restrictinfo.h"
#if PG_VERSION_NUM>=120000
#include "access/table.h"
#include "nodes/primnodes.h"
#include "optimizer/optimizer.h"
#else
#include "optimizer/var.h"
#endif
#include "optimizer/tlist.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/sampling.h"
#include "utils/selfuncs.h"
#include "executor/spi.h"
#include "vops.h"
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
* These items are indexed with the enum FdwScanPrivateIndex, so an item
* can be fetched with list_nth(). For example, to get the SELECT statement:
* sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
*/
enum FdwScanPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwScanPrivateSelectSql,
/* Integer list of attribute numbers retrieved by the SELECT */
FdwScanPrivateRetrievedAttrs
};
/*
* Execution state of a foreign scan using postgres_fdw.
*/
typedef struct PgFdwScanState
{
Relation rel; /* relcache entry for the foreign table. NULL
* for a foreign join scan. */
TupleDesc tupdesc; /* tuple descriptor of scan */
/* extracted fdw_private data */
char *query; /* text of SELECT command */
List *retrieved_attrs;/* list of retrieved attribute numbers */
/* for remote query execution */
Portal portal; /* SPI portal */
int numParams; /* number of parameters passed to query */
int tile_pos;
uint64 table_pos;
HeapTuple spi_tuple;
Datum* src_values;
Datum* dst_values;
bool* src_nulls;
bool* dst_nulls;
vops_type* vops_types;
Oid* attr_types;
MemoryContext spi_context;
uint64 filter_mask;
} PgFdwScanState;
/*
* SQL functions
*/
PG_FUNCTION_INFO_V1(vops_fdw_handler);
PG_FUNCTION_INFO_V1(vops_fdw_validator);
/*
* FDW callback routines
*/
static void postgresGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void postgresGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *postgresGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan);
static void postgresBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *postgresIterateForeignScan(ForeignScanState *node);
static void postgresReScanForeignScan(ForeignScanState *node);
static void postgresEndForeignScan(ForeignScanState *node);
static void postgresExplainForeignScan(ForeignScanState *node,
ExplainState *es);
#if PG_VERSION_NUM>=110000
static void postgresGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
void* extra
);
#else
static void postgresGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel
);
#endif
static bool postgresIsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel,
RangeTblEntry *rte);
static bool postgresAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
/*
* Helper functions
*/
static void estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *baserel,
List *join_conds,
List *pathkeys,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost);
static bool foreign_grouping_ok(PlannerInfo *root, RelOptInfo *grouped_rel);
static void add_foreign_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *grouped_rel);
static int postgresAcquireSampleRowsFunc(Relation relation, int elevel,
HeapTuple *rows, int targrows,
double *totalrows,
double *totaldeadrows);
/*
* Foreign-data wrapper handler function: return a struct with pointers
* to my callback routines.
*/
Datum
vops_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *routine = makeNode(FdwRoutine);
/* Functions for scanning foreign tables */
routine->GetForeignRelSize = postgresGetForeignRelSize;
routine->GetForeignPaths = postgresGetForeignPaths;
routine->GetForeignPlan = postgresGetForeignPlan;
routine->BeginForeignScan = postgresBeginForeignScan;
routine->IterateForeignScan = postgresIterateForeignScan;
routine->ReScanForeignScan = postgresReScanForeignScan;
routine->EndForeignScan = postgresEndForeignScan;
routine->IsForeignScanParallelSafe = postgresIsForeignScanParallelSafe;
/* Support functions for ANALYZE */
routine->AnalyzeForeignTable = postgresAnalyzeForeignTable;
/* Support functions for EXPLAIN */
routine->ExplainForeignScan = postgresExplainForeignScan;
/* Support functions for upper relation push-down */
routine->GetForeignUpperPaths = postgresGetForeignUpperPaths;
PG_RETURN_POINTER(routine);
}
Datum
vops_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
ListCell *cell;
if (catalog == ForeignTableRelationId)
{
bool has_table_name = false;
foreach(cell, options_list)
{
DefElem *def = (DefElem *) lfirst(cell);
if (strcmp(def->defname, "table_name") == 0) {
has_table_name = true;
} else if (strcmp(def->defname, "schema_name") != 0) {
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", def->defname),
errhint("Valid options in this context are: table_name and schema_name")));
}
}
if (!has_table_name) {
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("table_name is not specified for foreign table"),
errhint("Name of VOPS table should be specified")));
}
}
PG_RETURN_VOID();
}
static Relation open_vops_relation(ForeignTable* table)
{
ListCell *lc;
char *nspname = NULL;
char *relname = NULL;
RangeVar *rv;
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "schema_name") == 0)
nspname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
relname = defGetString(def);
}
Assert(relname != NULL);
if (nspname == NULL) {
nspname = get_namespace_name(get_rel_namespace(table->relid));
}
rv = makeRangeVar(nspname, relname, -1);
return heap_openrv_extended(rv, RowExclusiveLock, false);
}
/*
* postgresGetForeignRelSize
* Estimate # of rows and width of the result of the scan
*
* We should consider the effect of all baserestrictinfo clauses here, but
* not any join clauses.
*/
static void
postgresGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
ListCell *lc;
PgFdwRelationInfo *fpinfo;
RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
char *nspname = NULL;
char *relname = NULL;
char *refname = NULL;
Relation fdw_rel;
Relation vops_rel;
TupleDesc fdw_tupdesc;
TupleDesc vops_tupdesc;
int i, j;
/*
* We use PgFdwRelationInfo to pass various information to subsequent
* functions.
*/
fpinfo = (PgFdwRelationInfo *) palloc0(sizeof(PgFdwRelationInfo));
baserel->fdw_private = (void *) fpinfo;
/* Base foreign tables need to be pushed down always. */
fpinfo->pushdown_safe = true;
/* Look up foreign-table catalog info. */
fpinfo->table = GetForeignTable(foreigntableid);
fpinfo->server = GetForeignServer(fpinfo->table->serverid);
Assert(foreigntableid == fpinfo->table->relid);
/*
* Build mappnig with VOPS table
*/
fpinfo->tile_attrs = NULL;
fpinfo->vops_attrs = NULL;
vops_rel = open_vops_relation(fpinfo->table);
fdw_rel = heap_open(rte->relid, NoLock);
estimate_rel_size(vops_rel, baserel->attr_widths,
&baserel->pages, &baserel->tuples, &baserel->allvisfrac);
baserel->tuples *= TILE_SIZE;
vops_tupdesc = RelationGetDescr(vops_rel);
fdw_tupdesc = RelationGetDescr(fdw_rel);
for (i = 0; i < fdw_tupdesc->natts; i++)
{
for (j = 0; j < vops_tupdesc->natts; j++)
{
if (strcmp(NameStr(TupleDescAttr(vops_tupdesc, j)->attname), NameStr(TupleDescAttr(fdw_tupdesc, i)->attname)) == 0)
{
fpinfo->vops_attrs = bms_add_member(fpinfo->vops_attrs, i + 1 - FirstLowInvalidHeapAttributeNumber);
if (vops_get_type(TupleDescAttr(vops_tupdesc, j)->atttypid) != VOPS_LAST)
{
fpinfo->tile_attrs = bms_add_member(fpinfo->tile_attrs, i + 1 - FirstLowInvalidHeapAttributeNumber);
}
}
}
}
heap_close(fdw_rel, NoLock);
heap_close(vops_rel, RowExclusiveLock);
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
vopsClassifyConditions(root, baserel, baserel->baserestrictinfo,
&fpinfo->remote_conds, &fpinfo->local_conds);
/*
* Identify which attributes will need to be retrieved from the remote
* server. These include all attrs needed for joins or final output, plus
* all attrs used in the local_conds. (Note: if we end up using a
* parameterized scan, it's possible that some of the join clauses will be
* sent to the remote and thus we wouldn't really need to retrieve the
* columns used in them. Doesn't seem worth detecting that case though.)
*/
fpinfo->attrs_used = NULL;
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
&fpinfo->attrs_used);
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid,
&fpinfo->attrs_used);
}
/*
* Compute the selectivity and cost of the local_conds, so we don't have
* to do it over again for each path. The best we can do for these
* conditions is to estimate selectivity on the basis of local statistics.
*/
fpinfo->local_conds_sel = clauselist_selectivity(root,
fpinfo->local_conds,
baserel->relid,
JOIN_INNER,
NULL);
cost_qual_eval(&fpinfo->local_conds_cost, fpinfo->local_conds, root);
/*
* Set cached relation costs to some negative value, so that we can detect
* when they are set to some sensible costs during one (usually the first)
* of the calls to estimate_path_cost_size().
*/
fpinfo->rel_startup_cost = -1;
fpinfo->rel_total_cost = -1;
/* Estimate baserel size as best we can with local statistics. */
set_baserel_size_estimates(root, baserel);
/* Fill in basically-bogus cost estimates for use later. */
estimate_path_cost_size(root, baserel, NIL, NIL,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost, &fpinfo->total_cost);
/*
* Set the name of relation in fpinfo, while we are constructing it here.
* It will be used to build the string describing the join relation in
* EXPLAIN output. We can't know whether VERBOSE option is specified or
* not, so always schema-qualify the foreign table name.
*/
fpinfo->relation_name = makeStringInfo();
nspname = get_namespace_name(get_rel_namespace(foreigntableid));
relname = get_rel_name(foreigntableid);
refname = rte->eref->aliasname;
appendStringInfo(fpinfo->relation_name, "%s.%s",
quote_identifier(nspname),
quote_identifier(relname));
if (*refname && strcmp(refname, relname) != 0)
appendStringInfo(fpinfo->relation_name, " %s",
quote_identifier(rte->eref->aliasname));
}
static bool postgresIsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel,
RangeTblEntry *rte)
{
return true;
}
/*
* postgresGetForeignPaths
* Create possible scan paths for a scan on the foreign table
*/
static void
postgresGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) baserel->fdw_private;
ForeignPath *path;
/*
* Create simplest ForeignScan path node and add it to baserel. This path
* corresponds to SeqScan path of regular tables (though depending on what
* baserestrict conditions we were able to send to remote, there might
* actually be an indexscan happening there). We already did all the work
* to estimate cost and size of this path.
*/
path = create_foreignscan_path(root,
baserel,
NULL, /* default pathtarget */
fpinfo->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NULL, /* no extra plan */
NIL); /* no fdw_private list */
add_path(baserel, (Path *) path);
}
/*
* postgresGetForeignPlan
* Create ForeignScan plan node which implements selected best path
*/
static ForeignScan *
postgresGetForeignPlan(PlannerInfo *root,
RelOptInfo *foreignrel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
Index scan_relid;
List *fdw_private;
List *remote_conds = NIL;
List *remote_exprs = NIL;
List *local_exprs = NIL;
List *params_list = NIL;
List *retrieved_attrs;
ListCell *lc;
List *fdw_scan_tlist = NIL;
StringInfoData sql;
/*
* For base relations, set scan_relid as the relid of the relation. For
* other kinds of relations set it to 0.
*/
if (foreignrel->reloptkind == RELOPT_BASEREL ||
foreignrel->reloptkind == RELOPT_OTHER_MEMBER_REL)
scan_relid = foreignrel->relid;
else
{
scan_relid = 0;
/*
* create_scan_plan() and create_foreignscan_plan() pass
* rel->baserestrictinfo + parameterization clauses through
* scan_clauses. For a join rel->baserestrictinfo is NIL and we are
* not considering parameterization right now, so there should be no
* scan_clauses for a joinrel and upper rel either.
*/
Assert(!scan_clauses);
}
/*
* Separate the scan_clauses into those that can be executed remotely and
* those that can't. baserestrictinfo clauses that were previously
* determined to be safe or unsafe by classifyConditions are shown in
* fpinfo->remote_conds and fpinfo->local_conds. Anything else in the
* scan_clauses list will be a join clause, which we have to check for
* remote-safety.
*
* Note: the join clauses we see here should be the exact same ones
* previously examined by postgresGetForeignPaths. Possibly it'd be worth
* passing forward the classification work done then, rather than
* repeating it here.
*
* This code must match "extract_actual_clauses(scan_clauses, false)"
* except for the additional decision about remote versus local execution.
* Note however that we don't strip the RestrictInfo nodes from the
* remote_conds list, since appendWhereClause expects a list of
* RestrictInfos.
*/
foreach(lc, scan_clauses)
{
RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc));
/* Ignore any pseudoconstants, they're dealt with elsewhere */
if (rinfo->pseudoconstant)
continue;
if (list_member_ptr(fpinfo->remote_conds, rinfo))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else if (list_member_ptr(fpinfo->local_conds, rinfo))
local_exprs = lappend(local_exprs, rinfo->clause);
else if (vops_is_foreign_expr(root, foreignrel, rinfo->clause))
{
remote_conds = lappend(remote_conds, rinfo);
remote_exprs = lappend(remote_exprs, rinfo->clause);
}
else
local_exprs = lappend(local_exprs, rinfo->clause);
}
if (foreignrel->reloptkind == RELOPT_JOINREL ||
foreignrel->reloptkind == RELOPT_UPPER_REL)
{
/* For a join relation, get the conditions from fdw_private structure */
remote_conds = fpinfo->remote_conds;
local_exprs = fpinfo->local_conds;
/* Build the list of columns to be fetched from the foreign server. */
fdw_scan_tlist = vops_build_tlist_to_deparse(foreignrel);
}
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
vopsDeparseSelectStmtForRel(&sql, root, foreignrel, fdw_scan_tlist,
remote_conds, best_path->path.pathkeys,
&retrieved_attrs, ¶ms_list);
elog(LOG, "Execute VOPS query %s", sql.data);
/*
* Build the fdw_private list that will be available to the executor.
* Items in the list must match order in enum FdwScanPrivateIndex.
*/
fdw_private = list_make2(makeString(sql.data), retrieved_attrs);
/*
* Create the ForeignScan node for the given relation.
*
* Note that the remote parameter expressions are stored in the fdw_exprs
* field of the finished plan node; we can't keep them in private state
* because then they wouldn't be subject to later planner processing.
*/
return make_foreignscan(tlist,
local_exprs,
scan_relid,
params_list,
fdw_private,
fdw_scan_tlist,
remote_exprs,
outer_plan);
}
/*
* postgresBeginForeignScan
* Initiate an executor scan of a foreign PostgreSQL table.
*/
static void
postgresBeginForeignScan(ForeignScanState *node, int eflags)
{
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
EState *estate = node->ss.ps.state;
PgFdwScanState *fsstate;
int numParams;
MemoryContext oldcontext;
/*
* Do nothing in EXPLAIN (no ANALYZE) case. node->fdw_state stays NULL.
*/
if (eflags & EXEC_FLAG_EXPLAIN_ONLY)
return;
/*
* We'll save private state in node->fdw_state.
*/
fsstate = (PgFdwScanState *) palloc0(sizeof(PgFdwScanState));
node->fdw_state = (void *) fsstate;
/* Get private info created by planner functions. */
fsstate->query = strVal(list_nth(fsplan->fdw_private, FdwScanPrivateSelectSql));
fsstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
FdwScanPrivateRetrievedAttrs);
fsstate->spi_context = AllocSetContextCreate(estate->es_query_cxt,
"vops_fdw spi context",
ALLOCSET_DEFAULT_SIZES);
oldcontext = MemoryContextSwitchTo(fsstate->spi_context);
SPI_connect();
MemoryContextSwitchTo(oldcontext);
/*
* Get info we'll need for converting data fetched from the foreign server
* into local representation and error reporting during that process.
*/
if (fsplan->scan.scanrelid > 0)
{
fsstate->rel = node->ss.ss_currentRelation;
fsstate->tupdesc = RelationGetDescr(fsstate->rel);
}
else
{
fsstate->rel = NULL;
fsstate->tupdesc = node->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
}
/*
* Prepare for processing of parameters used in remote query, if any.
*/
numParams = list_length(fsplan->fdw_exprs);
fsstate->numParams = numParams;
fsstate->dst_values = palloc(fsstate->tupdesc->natts*sizeof(Datum));
fsstate->src_values = palloc(fsstate->tupdesc->natts*sizeof(Datum));
fsstate->dst_nulls = palloc(fsstate->tupdesc->natts*sizeof(bool));
fsstate->src_nulls = palloc(fsstate->tupdesc->natts*sizeof(bool));
/* Initialize to nulls for any columns not present in result */
memset(fsstate->dst_nulls, true, fsstate->tupdesc->natts*sizeof(bool));
postgresReScanForeignScan(node);
}
/*
* postgresIterateForeignScan
* Retrieve next row from the result set, or clear tuple slot to indicate
* EOF.
*/
static TupleTableSlot *
postgresIterateForeignScan(ForeignScanState *node)
{
PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
int i, j;
HeapTuple tup;
ListCell *lc;
int n_attrs = fsstate->tupdesc->natts;
List* retrieved_attrs = fsstate->retrieved_attrs;
MemoryContext oldcontext = MemoryContextSwitchTo(fsstate->spi_context);
while (true) {
if (fsstate->spi_tuple == NULL) {
if (fsstate->portal != NULL) {
filter_mask = ~0;
SPI_cursor_fetch(fsstate->portal, true, 1);
fsstate->table_pos = 0;
}
if (fsstate->table_pos == SPI_processed) {
MemoryContextSwitchTo(oldcontext);
return ExecClearTuple(slot);
}
if (fsstate->rel == NULL) {
fsstate->tile_pos = TILE_SIZE-1;
fsstate->filter_mask = ~0;
} else {
fsstate->tile_pos = 0;
fsstate->filter_mask = filter_mask;
}
fsstate->spi_tuple = SPI_tuptable->vals[fsstate->table_pos++];
if (fsstate->vops_types == NULL) {
fsstate->vops_types = palloc(sizeof(vops_type_info)*n_attrs);
fsstate->attr_types = palloc(sizeof(Oid)*n_attrs);
for (i = 0; i < n_attrs; i++) {
fsstate->vops_types[i] = VOPS_LAST;
}
j = 0;
foreach(lc, retrieved_attrs)
{
i = lfirst_int(lc);
if (i > 0)
{
/* ordinary column */
Assert(i <= n_attrs);
Assert(j < SPI_tuptable->tupdesc->natts);
fsstate->attr_types[i-1] = TupleDescAttr(SPI_tuptable->tupdesc, j)->atttypid;
fsstate->vops_types[i-1] = vops_get_type(fsstate->attr_types[i-1]);
}
j += 1;
}
}
j = 0;
foreach(lc, retrieved_attrs)
{
i = lfirst_int(lc);
if (i > 0)
{
/* ordinary column */
fsstate->src_values[i - 1] = SPI_getbinval(fsstate->spi_tuple, SPI_tuptable->tupdesc, j+1, &fsstate->src_nulls[i - 1]);
}
j += 1;
}
}
for (j = fsstate->tile_pos; j < TILE_SIZE; j++) {
if (fsstate->filter_mask & ((uint64)1 << j))
{
for (i = 0; i < n_attrs; i++) {
if (fsstate->vops_types[i] != VOPS_LAST) {
vops_tile_hdr* tile = VOPS_GET_TILE(fsstate->src_values[i], fsstate->vops_types[i]);
if (tile != NULL && (tile->empty_mask & ((uint64)1 << j))) {
goto NextTuple;
}
if (tile == NULL || (tile->null_mask & ((uint64)1 << j))) {
fsstate->dst_nulls[i] = true;
} else {
Datum value = 0;
switch (fsstate->vops_types[i]) {
case VOPS_BOOL:
value = BoolGetDatum((((vops_bool*)tile)->payload >> j) & 1);
break;
case VOPS_CHAR:
value = CharGetDatum(((vops_char*)tile)->payload[j]);
break;
case VOPS_INT2:
value = Int16GetDatum(((vops_int2*)tile)->payload[j]);
break;
case VOPS_INT4:
case VOPS_DATE:
value = Int32GetDatum(((vops_int4*)tile)->payload[j]);
break;
case VOPS_INT8:
case VOPS_INTERVAL:
case VOPS_TIMESTAMP:
value = Int64GetDatum(((vops_int8*)tile)->payload[j]);
break;
case VOPS_FLOAT4:
value = Float4GetDatum(((vops_float4*)tile)->payload[j]);
break;
case VOPS_FLOAT8:
value = Float8GetDatum(((vops_float8*)tile)->payload[j]);
break;
case VOPS_TEXT:
{
size_t elem_size = VOPS_ELEM_SIZE((char*)tile - LONGALIGN(VARHDRSZ));
char* src = (char*)(tile + 1) + elem_size * j;
size_t len = strnlen(src, elem_size);
text* t = (text*)palloc(VARHDRSZ + len);
SET_VARSIZE(t, VARHDRSZ + len);
memcpy(VARDATA(t), src, len);
value = PointerGetDatum(t);
break;
}
default:
Assert(false);
}
fsstate->dst_values[i] = value;
fsstate->dst_nulls[i] = false;
}
} else {
if (fsstate->attr_types[i] == FLOAT8OID && TupleDescAttr(fsstate->tupdesc, i)->atttypid == FLOAT4OID)
{
fsstate->dst_values[i] = Float4GetDatum((float)DatumGetFloat8(fsstate->src_values[i]));
} else {
fsstate->dst_values[i] = fsstate->src_values[i];
}
fsstate->dst_nulls[i] = fsstate->src_nulls[i];
}
}
fsstate->tile_pos = j+1;
/*
* Return the next tuple.
*/
MemoryContextSwitchTo(oldcontext);
tup = heap_form_tuple(fsstate->tupdesc, fsstate->dst_values, fsstate->dst_nulls);
#if PG_VERSION_NUM>=120000
ExecStoreHeapTuple(tup, slot, false);
#else
ExecStoreTuple(tup, slot, InvalidBuffer, false);
#endif
return slot;
}
NextTuple:;
}
SPI_freetuple(fsstate->spi_tuple);
if (fsstate->portal) {
SPI_freetuptable(SPI_tuptable);
}
fsstate->spi_tuple = NULL;
}
}
/*
* postgresReScanForeignScan
* Restart the scan.
*/
static void
postgresReScanForeignScan(ForeignScanState *node)
{
PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
Datum* values = NULL;
char* nulls = NULL;
MemoryContext oldcontext = MemoryContextSwitchTo(fsstate->spi_context);
Oid* argtypes = NULL;
int rc;
if (fsstate->numParams > 0) {
ExprContext *econtext = node->ss.ps.ps_ExprContext;
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
List* param_exprs = (List *)ExecInitExpr((Expr *)fsplan->fdw_exprs, (PlanState *) node);
ListCell *lc;
int i = 0;
values = palloc(sizeof(Datum)*fsstate->numParams);
nulls = palloc(sizeof(bool)*fsstate->numParams);
argtypes = palloc(sizeof(Oid)*fsstate->numParams);
foreach(lc, param_exprs)
{
ExprState *expr_state = (ExprState *) lfirst(lc);
bool isnull;
/* Evaluate the parameter expression */
#if PG_VERSION_NUM<100000
ExprDoneCond isDone;
values[i] = ExecEvalExpr(expr_state, econtext, &isnull, &isDone);
#else
values[i] = ExecEvalExpr(expr_state, econtext, &isnull);
#endif
nulls[i] = (char)isnull;
argtypes[i] = exprType((Node*)expr_state->expr);
i += 1;
}
}
if (fsstate->rel == NULL) { /* aggregate is pushed down: do not use cusror to allow parallel query execution */
rc = SPI_execute_with_args(fsstate->query, fsstate->numParams, argtypes, values, nulls, true, 0);
if (rc != SPI_OK_SELECT) {
elog(ERROR, "Failed to execute VOPS query %s: %d", fsstate->query, rc);
}
fsstate->portal = NULL;
} else {
fsstate->portal = SPI_cursor_open_with_args(NULL, fsstate->query, fsstate->numParams, argtypes, values, nulls, true, CURSOR_OPT_PARALLEL_OK);
}
fsstate->table_pos = 0;
fsstate->spi_tuple = NULL;
MemoryContextSwitchTo(oldcontext);
}
/*
* postgresEndForeignScan
* Finish scanning foreign table and dispose objects used for this scan
*/
static void
postgresEndForeignScan(ForeignScanState *node)
{
PgFdwScanState *fsstate = (PgFdwScanState *) node->fdw_state;
/* if fsstate is NULL, we are in EXPLAIN; nothing to do */
if (fsstate != NULL)
{
MemoryContext oldcontext = MemoryContextSwitchTo(fsstate->spi_context);
if (fsstate->portal) {
SPI_cursor_close(fsstate->portal);
}
SPI_finish();
MemoryContextSwitchTo(oldcontext);
}
}
/*
* postgresExplainForeignScan
* Produce extra output for EXPLAIN of a ForeignScan on a foreign table
*/
static void
postgresExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
/*
* Add remote query, when VERBOSE option is specified.
*/
if (es->verbose)
{
sql = strVal(list_nth(fdw_private, FdwScanPrivateSelectSql));
ExplainPropertyText("VOPS query", sql, es);
}
}
/*
* estimate_path_cost_size
* Get cost and size estimates for a foreign scan on given foreign relation
* either a base relation or a join between foreign relations or an upper
* relation containing foreign relations.
*
* param_join_conds are the parameterization clauses with outer relations.
* pathkeys specify the expected sort order if any for given path being costed.
*
* The function returns the cost and size estimates in p_row, p_width,
* p_startup_cost and p_total_cost variables.
*/
static void
estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *foreignrel,
List *param_join_conds,
List *pathkeys,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost)
{
PgFdwRelationInfo *fpinfo = (PgFdwRelationInfo *) foreignrel->fdw_private;
double rows;
double retrieved_rows;
int width;
Cost startup_cost;
Cost total_cost;
Cost cpu_per_tuple;
Cost run_cost = 0;
/*
* We don't support join conditions in this mode (hence, no
* parameterized paths can be made).
*/
Assert(param_join_conds == NIL);
/*
* Use rows/width estimates made by set_baserel_size_estimates() for
* base foreign relations and set_joinrel_size_estimates() for join
* between foreign relations.
*/
rows = foreignrel->rows;
width = foreignrel->reltarget->width;
/* Back into an estimate of the number of retrieved rows. */
retrieved_rows = clamp_row_est(rows / fpinfo->local_conds_sel);
/*
* We will come here again and again with different set of pathkeys
* that caller wants to cost. We don't need to calculate the cost of
* bare scan each time. Instead, use the costs if we have cached them
* already.
*/
if (fpinfo->rel_startup_cost > 0 && fpinfo->rel_total_cost > 0)
{
startup_cost = fpinfo->rel_startup_cost;
run_cost = fpinfo->rel_total_cost - fpinfo->rel_startup_cost;
}
else if (foreignrel->reloptkind == RELOPT_UPPER_REL)
{
PgFdwRelationInfo *ofpinfo;
PathTarget *ptarget = root->upper_targets[UPPERREL_GROUP_AGG];
AggClauseCosts aggcosts;
double input_rows;
int numGroupCols;
double numGroups = 1;
/*
* This cost model is mixture of costing done for sorted and
* hashed aggregates in cost_agg(). We are not sure which
* strategy will be considered at remote side, thus for
* simplicity, we put all startup related costs in startup_cost
* and all finalization and run cost are added in total_cost.
*
* Also, core does not care about costing HAVING expressions and
* adding that to the costs. So similarly, here too we are not
* considering remote and local conditions for costing.
*/
ofpinfo = (PgFdwRelationInfo *) fpinfo->upperrel->fdw_private;
/* Get rows and width from input rel */
input_rows = ofpinfo->rows;
width = ofpinfo->width;
/* Collect statistics about aggregates for estimating costs. */
MemSet(&aggcosts, 0, sizeof(AggClauseCosts));
if (root->parse->hasAggs)
{
#if PG_VERSION_NUM>=140000
get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &aggcosts);
#else
get_agg_clause_costs(root, (Node *) fpinfo->grouped_tlist,
AGGSPLIT_SIMPLE, &aggcosts);
get_agg_clause_costs(root, (Node *) root->parse->havingQual,