-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcstar_fdw.c
2398 lines (2100 loc) · 67.5 KB
/
cstar_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
#include "postgres.h"
#include <cassandra.h>
#include <inttypes.h>
#include <time.h>
#include "cstar_fdw.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "executor/spi.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "mb/pg_wchar.h"
#include "optimizer/cost.h"
#include "optimizer/restrictinfo.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "commands/vacuum.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/lsyscache.h"
#include "utils/timestamp.h"
#if PG_VERSION_NUM >= 90300
# define CSTAR_FDW_WRITE_API
#endif /* PG_VERSION_NUM >= 90300 */
#if PG_VERSION_NUM >= 90500
#define CSTAR_FDW_IMPORT_API
#else
#undef CSTAR_FDW_IMPORT_API
#endif /* PG_VERSION_NUM >= 90500 */
PG_MODULE_MAGIC;
/* Default CPU cost to start up a foreign query. */
#define DEFAULT_FDW_STARTUP_COST 100.0
/* Default CPU cost to process 1 row (above and beyond cpu_tuple_cost). */
#define DEFAULT_FDW_TUPLE_COST 0.01
/* The PRIMARY KEY OPTION name */
/* TODO: Add support for multiple comma-separated PK columns */
#define OPT_PK "primary_key"
#define SMALLINT_NULL_SET_ISSUE_URL "https://groups.google.com/a/lists.datastax.com/forum/#!topic/cpp-driver-user/b1XRQdnVH6A"
struct CassFdwOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
};
static struct CassFdwOption valid_options[] =
{
/* Connection options */
{ "host", ForeignServerRelationId },
{ "port", ForeignServerRelationId },
{ "protocol", ForeignServerRelationId },
{ "username", UserMappingRelationId },
{ "password", UserMappingRelationId },
{ "query", ForeignTableRelationId },
{ "schema_name", ForeignTableRelationId },
{ "table_name", ForeignTableRelationId },
/* Pre-req for UPDATE and DELETE support */
{ OPT_PK, ForeignTableRelationId },
/* Sentinel */
{ NULL, InvalidOid }
};
#ifdef CSTAR_FDW_WRITE_API
/*
* This enum describes what's kept in the fdw_private list for a ModifyTable
* node referencing a cassandra_fdw foreign table. We store:
*
* 1) INSERT/UPDATE/DELETE statement text to be sent to the remote server
* 2) Integer list of target attribute numbers for INSERT/UPDATE
* (NIL for a DELETE)
* 3) Boolean flag showing if the remote query has a RETURNING clause
* 4) Integer list of attribute numbers retrieved by RETURNING, if any
*/
enum FdwModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
FdwModifyPrivateUpdateSql,
/* Integer list of target attribute numbers for INSERT/UPDATE */
FdwModifyPrivateTargetAttnums,
/* has-returning flag (as an integer Value node) */
FdwModifyPrivateHasReturning,
/* Integer list of attribute numbers retrieved by RETURNING */
FdwModifyPrivateRetrievedAttrs
};
/*
* Execution state of a foreign INSERT/UPDATE/DELETE operation.
*/
typedef struct CassFdwModifyState
{
Relation rel; /* relcache entry for the foreign table */
AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
/* for remote query execution */
CassSession *cass_conn; /* connection for the modify */
bool sql_sent;
CassStatement *statement;
/* extracted fdw_private data */
char *query; /* text of INSERT/UPDATE/DELETE command */
List *target_attrs; /* list of target attribute numbers */
bool has_returning; /* is there a RETURNING clause? */
List *retrieved_attrs; /* attr numbers retrieved by RETURNING */
/* info about parameters for prepared statement */
AttrNumber keyAttno; /* attnum of input resjunk key column */
int p_nums; /* number of parameters to transmit */
Oid *p_type_oids; /* Type OIDs for them */
/* working memory context */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
} CassFdwModifyState;
#endif /* CSTAR_FDW_WRITE_API */
/*
* FDW-specific information for RelOptInfo.fdw_private.
*/
typedef struct CassFdwPlanState
{
/* baserestrictinfo clauses, broken down into safe and unsafe subsets. */
List *remote_conds;
List *local_conds;
/* Bitmap of attr numbers we need to fetch from the remote server. */
Bitmapset *attrs_used;
/* Estimated size and cost for a scan with baserestrictinfo quals. */
double rows;
int width;
Cost startup_cost;
Cost total_cost;
} CassFdwPlanState;
/*
* FDW-specific information for ForeignScanState.fdw_state.
*/
typedef struct CassFdwScanState
{
Relation rel; /* relcache entry for the foreign table */
AttInMetadata *attinmeta; /* attribute datatype conversion metadata */
/* extracted fdw_private data */
char *query; /* text of SELECT command */
List *retrieved_attrs; /* list of retrieved attribute numbers */
int NumberOfColumns;
/* for remote query execution */
CassSession *cass_conn; /* connection for the scan */
bool sql_sended;
CassStatement *statement;
/* for storing result tuples */
HeapTuple *tuples; /* array of currently-retrieved tuples */
int num_tuples; /* # of tuples in array */
int next_tuple; /* index of next one to return */
/* batch-level state, for optimizing rewinds and avoiding useless fetch */
int fetch_ct_2; /* Min(# of fetches done, 2) */
bool eof_reached; /* true if last fetch reached EOF */
/* working memory contexts */
MemoryContext batch_cxt; /* context holding current batch of tuples */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
} CassFdwScanState;
enum CassFdwScanPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
CassFdwScanPrivateSelectSql,
/* Integer list of attribute numbers retrieved by the SELECT */
CassFdwScanPrivateRetrievedAttrs
};
/*
* SQL functions
*/
extern Datum cstar_fdw_handler(PG_FUNCTION_ARGS);
extern Datum cstar_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(cstar_fdw_handler);
PG_FUNCTION_INFO_V1(cstar_fdw_validator);
/*
* FDW callback routines
*/
static void cassGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static void cassGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static ForeignScan *cassGetForeignPlan(
PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses
#if PG_VERSION_NUM >= 90500
, Plan *outer_plan
#endif /* PG_VERSION_NUM >= 90500 */
);
static void cassExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void cassBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *cassIterateForeignScan(ForeignScanState *node);
static void cassReScanForeignScan(ForeignScanState *node);
static void cassEndForeignScan(ForeignScanState *node);
#ifdef CSTAR_FDW_IMPORT_API
static List *cassImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid);
#endif /* CSTAR_FDW_IMPORT_API */
#ifdef CSTAR_FDW_WRITE_API
static void
cassAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
static List *
cassPlanForeignModify(PlannerInfo *root, ModifyTable *plan,
Index resultRelation, int subplan_index);
static void cassBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo, List *fdw_private,
int subplan_index, int eflags);
static TupleTableSlot *cassExecForeignInsert(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *cassExecForeignUpdate(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *cassExecForeignDelete(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void cassEndForeignModify(EState *estate, ResultRelInfo *rinfo);
static void cassExplainForeignModify(ModifyTableState *mtstate,
ResultRelInfo *resultRelInfo, List *fdw_private,
int subplan_index,
struct ExplainState *es);
static int cassIsForeignRelUpdatable(Relation rel);
#endif /* CSTAR_FDW_WRITE_API */
/*
* Helper functions
*/
static void estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *baserel,
List *join_conds,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost);
static bool cassIsValidOption(const char *option, Oid context);
static void
cassGetOptions(Oid foreigntableid,
char **host, int *port,
char **username, char **password,
char **query, char **tablename, char **primarykey);
static void
cassGetPKOption(Oid foreigntableid,
const char **primarykey);
static void create_cursor(ForeignScanState *node);
static void close_cursor(CassFdwScanState *fsstate);
static void fetch_more_data(ForeignScanState *node);
static void pgcass_transferValue(StringInfo buf, const CassValue* value);
#ifdef CSTAR_FDW_IMPORT_API
static void pgcass_transformDataType(StringInfo buf, CassValueType type);
#endif /* CSTAR_FDW_IMPORT_API */
static HeapTuple make_tuple_from_result_row(const CassRow* row,
int ncolumn,
Relation rel,
AttInMetadata *attinmeta,
List *retrieved_attrs,
MemoryContext temp_context);
static void cassClassifyConditions(PlannerInfo *root,
RelOptInfo *baserel,
List *input_conds,
List **remote_conds,
List **local_conds);
#ifdef CSTAR_FDW_WRITE_API
static void
cassStatementBindNull(const CassStatement * stmt,
int pindex, Oid ptypeid, const char *opname,
EState *estate, ResultRelInfo *resultRelInfo);
static void releaseCassResources(EState *estate, ResultRelInfo *resultRelInfo);
static void
bind_cass_statement_param(Oid type, Datum value,
CassStatement * statement, int pindex);
static TupleTableSlot *
cassExecPKPredWrite(EState *estate,
ResultRelInfo *resultRelInfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot,
const char *cqlOpName);
#endif /* CSTAR_FDW_WRITE_API */
/*
* Foreign-data wrapper handler function: return a struct with pointers
* to my callback routines.
*/
Datum
cstar_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
fdwroutine->GetForeignRelSize = cassGetForeignRelSize;
fdwroutine->GetForeignPaths = cassGetForeignPaths;
fdwroutine->GetForeignPlan = cassGetForeignPlan;
fdwroutine->ExplainForeignScan = cassExplainForeignScan;
fdwroutine->BeginForeignScan = cassBeginForeignScan;
fdwroutine->IterateForeignScan = cassIterateForeignScan;
fdwroutine->ReScanForeignScan = cassReScanForeignScan;
fdwroutine->EndForeignScan = cassEndForeignScan;
fdwroutine->AnalyzeForeignTable = NULL;
#ifdef CSTAR_FDW_IMPORT_API
fdwroutine->ImportForeignSchema = cassImportForeignSchema;
#endif /* CSTAR_FDW_IMPORT_API */
#ifdef CSTAR_FDW_WRITE_API
fdwroutine->AddForeignUpdateTargets = cassAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = cassPlanForeignModify;
fdwroutine->BeginForeignModify = cassBeginForeignModify;
fdwroutine->ExecForeignInsert = cassExecForeignInsert;
fdwroutine->ExecForeignUpdate = cassExecForeignUpdate;
fdwroutine->ExecForeignDelete = cassExecForeignDelete;
fdwroutine->EndForeignModify = cassEndForeignModify;
fdwroutine->ExplainForeignModify = cassExplainForeignModify;
fdwroutine->IsForeignRelUpdatable = cassIsForeignRelUpdatable;
#endif /* CSTAR_FDW_WRITE_API */
PG_RETURN_POINTER(fdwroutine);
}
/*
* Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
* USER MAPPING or FOREIGN TABLE that uses file_fdw.
*
* Raise an ERROR if the option or its value is considered invalid.
*/
Datum
cstar_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
char *svr_host = NULL;
int svr_port = 0;
char *svr_username = NULL;
char *svr_password = NULL;
char *svr_query = NULL;
char *svr_schema = NULL;
char *svr_table = NULL;
char *primary_key = NULL;
ListCell *cell;
/*
* Check that only options supported by cassandra_fdw,
* and allowed for the current object type, are given.
*/
foreach(cell, options_list)
{
DefElem *def = (DefElem *) lfirst(cell);
if (!cassIsValidOption(def->defname, catalog))
{
const struct CassFdwOption *opt;
StringInfoData buf;
/*
* Unknown option specified, complain about it. Provide a hint
* with list of valid options for the object.
*/
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.")));
}
if (strcmp(def->defname, "host") == 0)
{
if (svr_host)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
svr_host = defGetString(def);
}
if (strcmp(def->defname, "port") == 0)
{
if (svr_port)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
svr_port = atoi(defGetString(def));
}
else if (strcmp(def->defname, "username") == 0)
{
if (svr_username)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
svr_username = defGetString(def);
}
else if (strcmp(def->defname, "password") == 0)
{
if (svr_password)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
svr_password = defGetString(def);
}
else if (strcmp(def->defname, "query") == 0)
{
if (svr_table)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: query cannot be used with table")));
if (svr_query)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
svr_query = defGetString(def);
}
else if (strcmp(def->defname, "schema_name") == 0)
{
if (svr_schema)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
svr_schema = defGetString(def);
}
else if (strcmp(def->defname, "table_name") == 0)
{
if (svr_query)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: table_name cannot be used with query")));
if (svr_table)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
svr_table = defGetString(def);
}
if (strcmp(def->defname, OPT_PK) == 0)
{
if (primary_key)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options")));
primary_key = defGetString(def);
}
}
if (catalog == ForeignServerRelationId && svr_host == NULL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("host must be specified")));
if (catalog == ForeignTableRelationId &&
svr_query == NULL && svr_table == NULL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("either table_name or query must be specified")));
PG_RETURN_VOID();
}
/*
* Check if the provided option is one of the valid options.
* context is the Oid of the catalog holding the object the option is for.
*/
static bool
cassIsValidOption(const char *option, Oid context)
{
const struct CassFdwOption *opt;
for (opt = valid_options; opt->optname; opt++)
{
if (context == opt->optcontext && strcmp(opt->optname, option) == 0)
return true;
}
return false;
}
/*
* Fetch the options for a fdw foreign table.
*/
static void
cassGetOptions(Oid foreigntableid, char **host, int *port,
char **username, char **password, char **query,
char **tablename, char **primarykey)
{
ForeignTable *table;
ForeignServer *server;
UserMapping *user;
List *options;
ListCell *lc;
/*
* Extract options from FDW objects.
*/
table = GetForeignTable(foreigntableid);
server = GetForeignServer(table->serverid);
user = GetUserMapping(GetUserId(), server->serverid);
options = NIL;
options = list_concat(options, table->options);
options = list_concat(options, server->options);
options = list_concat(options, user->options);
/* Loop through the options, and get the server/port */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "username") == 0)
{
*username = defGetString(def);
}
else if (strcmp(def->defname, "password") == 0)
{
*password = defGetString(def);
}
else if (strcmp(def->defname, "query") == 0)
{
*query = defGetString(def);
}
else if (strcmp(def->defname, "table_name") == 0)
{
*tablename = defGetString(def);
}
else if (strcmp(def->defname, "host") == 0)
{
*host = defGetString(def);
}
else if (strcmp(def->defname, "port") == 0)
{
*port = atoi(defGetString(def));
}
else if (strcmp(def->defname, OPT_PK) == 0)
{
*primarykey = defGetString(def);
}
}
}
/*
* Fetch the primary_key option for a FOREIGN TABLE without returning the
* remaining options; the PK is the only one needed for certain callbacks such
* as cassAddForeignUpdateTargets().
*/
static void
cassGetPKOption(Oid foreigntableid,
const char **primarykey)
{
ForeignTable *table;
List *options;
ListCell *lc;
table = GetForeignTable(foreigntableid);
options = NIL;
options = list_concat(options, table->options);
/* Loop through the options to get the primary_key option. */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, OPT_PK) == 0)
{
*primarykey = defGetString(def);
}
}
}
//#if (PG_VERSION_NUM >= 90200)
/*
* cassGetForeignRelSize
* Obtain relation size estimates for a foreign table
*/
static void
cassGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
CassFdwPlanState *fpinfo;
ListCell *lc;
elog(DEBUG1, CSTAR_FDW_NAME
": get foreign rel size for relation ID %d", foreigntableid);
fpinfo = (CassFdwPlanState *) palloc0(sizeof(CassFdwPlanState));
baserel->fdw_private = (void *) fpinfo;
/*
* Identify which baserestrictinfo clauses can be sent to the remote
* server and which can't.
*/
cassClassifyConditions(root, baserel, baserel->baserestrictinfo,
&fpinfo->remote_conds, &fpinfo->local_conds);
fpinfo->attrs_used = NULL;
#if (PG_VERSION_NUM < 90600)
pull_varattnos((Node *) baserel->reltargetlist, baserel->relid,
&fpinfo->attrs_used);
#else
pull_varattnos((Node *) baserel->reltarget->exprs, baserel->relid,
&fpinfo->attrs_used);
#endif /* PG_VERSION_NUM < 90600 */
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
pull_varattnos((Node *) rinfo->clause, baserel->relid,
&fpinfo->attrs_used);
}
//TODO
/* Fetch options */
/* Estimate relation size */
{
/*
* If the foreign table has never been ANALYZEd, it will have relpages
* and reltuples equal to zero, which most likely has nothing to do
* with reality. We can't do a whole lot about that if we're not
* allowed to consult the remote server, but we can use a hack similar
* to plancat.c's treatment of empty relations: use a minimum size
* estimate of 10 pages, and divide by the column-datatype-based width
* estimate to get the corresponding number of tuples.
*/
if (baserel->pages == 0 && baserel->tuples == 0)
{
baserel->pages = 10;
#if (PG_VERSION_NUM < 90600)
baserel->tuples =
(10 * BLCKSZ) / (baserel->width + sizeof(HeapTupleHeaderData));
#else
baserel->tuples =
(10 * BLCKSZ) / (baserel->reltarget->width + sizeof(HeapTupleHeaderData));
#endif /* PG_VERSION_NUM < 90600 */
}
/* 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,
&fpinfo->rows, &fpinfo->width,
&fpinfo->startup_cost, &fpinfo->total_cost);
}
}
static void
estimate_path_cost_size(PlannerInfo *root,
RelOptInfo *baserel,
List *join_conds,
double *p_rows, int *p_width,
Cost *p_startup_cost, Cost *p_total_cost)
{
*p_rows = baserel->rows;
#if (PG_VERSION_NUM < 90600)
*p_width = baserel->width;
#else
*p_width = baserel->reltarget->width;
#endif /* PG_VERSION_NUM < 90600 */
*p_startup_cost = DEFAULT_FDW_STARTUP_COST;
*p_total_cost = DEFAULT_FDW_TUPLE_COST * 100;
}
/*
* cassGetForeignPaths
* (9.2+) Get the foreign paths
*/
static void
cassGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
CassFdwPlanState *fpinfo = (CassFdwPlanState *) baserel->fdw_private;
ForeignPath *path;
elog(DEBUG1, CSTAR_FDW_NAME
": get foreign paths for relation ID %d", foreigntableid);
/*
* 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.
*/
#if PG_VERSION_NUM < 90500
path = create_foreignscan_path(root, baserel,
fpinfo->rows + baserel->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NIL); /* no fdw_private list */
#elif PG_VERSION_NUM < 90600
path = create_foreignscan_path(root, baserel,
fpinfo->rows + baserel->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NULL, /* no outer path either */
NIL); /* no fdw_private list */
#else
path = create_foreignscan_path(root, baserel,
NULL,
fpinfo->rows + baserel->rows,
fpinfo->startup_cost,
fpinfo->total_cost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NULL, /* no outer path either */
NIL); /* no fdw_private list */
#endif
add_path(baserel, (Path *) path);
//TODO
}
/*
* cassGetForeignPlan
* Create ForeignScan plan node which implements selected best path
*/
static ForeignScan *
cassGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses
#if PG_VERSION_NUM >= 90500
, Plan *outer_plan
#endif /* PG_VERSION_NUM >= 90500 */
)
{
CassFdwPlanState *fpinfo = (CassFdwPlanState *) baserel->fdw_private;
Index scan_relid = baserel->relid;
List *fdw_private;
List *local_exprs = NIL;
StringInfoData sql;
List *retrieved_attrs;
elog(DEBUG1, CSTAR_FDW_NAME
": get foreign plan for relation ID %d", foreigntableid);
local_exprs = extract_actual_clauses(scan_clauses, false);
/*
* Build the query string to be sent for execution, and identify
* expressions to be sent as parameters.
*/
initStringInfo(&sql);
cassDeparseSelectSql(&sql, root, baserel, fpinfo->attrs_used,
&retrieved_attrs);
/*
* Build the fdw_private list that will be available to the executor.
* Items in the list must match enum CassFdwScanPrivateIndex, above.
*/
fdw_private = list_make2(makeString(sql.data),
retrieved_attrs);
/*
* Create the ForeignScan node from target list, local filtering
* expressions, remote parameter expressions, and FDW private information.
*
* 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.
*/
#if PG_VERSION_NUM < 90500
return make_foreignscan(tlist,
local_exprs,
scan_relid,
NIL,
fdw_private);
#else
return make_foreignscan(tlist,
local_exprs,
scan_relid,
NIL,
fdw_private,
NIL,
NIL,
NULL);
#endif
}
//#endif /* #if (PG_VERSION_NUM >= 90200) */
/*
* cassExplainForeignScan
* Produce extra output for EXPLAIN
*/
static void
cassExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
List *fdw_private;
char *sql;
char *svr_host = NULL;
int svr_port = 0;
char *svr_username = NULL;
char *svr_password = NULL;
char *svr_query = NULL;
char *svr_table = NULL;
char *primary_key = NULL;
elog(DEBUG1, CSTAR_FDW_NAME ": explain foreign scan for relation ID %d",
RelationGetRelid(node->ss.ss_currentRelation));
if (es->verbose)
{
/* Fetch options */
cassGetOptions(RelationGetRelid(node->ss.ss_currentRelation),
&svr_host, &svr_port,
&svr_username, &svr_password,
&svr_query, &svr_table, &primary_key);
fdw_private = ((ForeignScan *) node->ss.ps.plan)->fdw_private;
sql = strVal(list_nth(fdw_private, CassFdwScanPrivateSelectSql));
ExplainPropertyText("Remote SQL", sql, es);
}
}
/*
* cassBeginForeignScan
* Initiate access to the database
*/
static void
cassBeginForeignScan(ForeignScanState *node, int eflags)
{
ForeignScan *fsplan = (ForeignScan *) node->ss.ps.plan;
EState *estate = node->ss.ps.state;
CassFdwScanState *fsstate;
RangeTblEntry *rte;
Oid userid;
ForeignTable *table;
ForeignServer *server;
UserMapping *user;
elog(DEBUG1, CSTAR_FDW_NAME ": begin foreign scan for relation ID %d",
RelationGetRelid(node->ss.ss_currentRelation));
/*
* 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 = (CassFdwScanState *) palloc0(sizeof(CassFdwScanState));
node->fdw_state = (void *) fsstate;
/*
* Identify which user to do the remote access as. This should match what
* ExecCheckRTEPerms() does.
*/
rte = rt_fetch(fsplan->scan.scanrelid, estate->es_range_table);
userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
/* Get info about foreign table. */
fsstate->rel = node->ss.ss_currentRelation;
table = GetForeignTable(RelationGetRelid(fsstate->rel));
server = GetForeignServer(table->serverid);
user = GetUserMapping(userid, server->serverid);
/*
* Get connection to the foreign server. Connection manager will
* establish new connection if necessary.
*/
fsstate->cass_conn = pgcass_GetConnection(server, user, false);
fsstate->sql_sended = false;
/* Get private info created by planner functions. */
fsstate->query = strVal(list_nth(fsplan->fdw_private,
CassFdwScanPrivateSelectSql));
fsstate->retrieved_attrs = (List *) list_nth(fsplan->fdw_private,
CassFdwScanPrivateRetrievedAttrs);
/* Create contexts for batches of tuples and per-tuple temp workspace. */
fsstate->batch_cxt = AllocSetContextCreate(estate->es_query_cxt,
"cassandra_fdw tuple data",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
fsstate->temp_cxt = AllocSetContextCreate(estate->es_query_cxt,
"cassandra_fdw temporary data",
ALLOCSET_SMALL_MINSIZE,
ALLOCSET_SMALL_INITSIZE,
ALLOCSET_SMALL_MAXSIZE);
/* Get info we'll need for input data conversion. */
fsstate->attinmeta = TupleDescGetAttInMetadata(RelationGetDescr(fsstate->rel));
}
/*
* cassIterateForeignScan
* Read next record from the data file and store it into the
* ScanTupleSlot as a virtual tuple
*/
static TupleTableSlot*
cassIterateForeignScan(ForeignScanState *node)
{
CassFdwScanState *fsstate = (CassFdwScanState *) node->fdw_state;
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
/*
* If this is the first call after Begin or ReScan, we need to create the
* cursor on the remote side.
*/
if (!fsstate->sql_sended)
create_cursor(node);
/*
* Get some more tuples, if we've run out.
*/
if (fsstate->next_tuple >= fsstate->num_tuples)
{
/* No point in another fetch if we already detected EOF, though. */
if (!fsstate->eof_reached)
fetch_more_data(node);
/* If we didn't get any tuples, must be end of data. */
if (fsstate->next_tuple >= fsstate->num_tuples)
return ExecClearTuple(slot);
}
/*
* Return the next tuple.
*/
ExecStoreTuple(fsstate->tuples[fsstate->next_tuple++],
slot,
InvalidBuffer,
false);
return slot;
}
/*
* cassReScanForeignScan
* Rescan table, possibly with new parameters
*/