forked from engobi/redis_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_fdw.c
2949 lines (2536 loc) · 73.3 KB
/
redis_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
/*-------------------------------------------------------------------------
*
* foreign-data wrapper for Redis
*
* Copyright (c) 2011,2013 PostgreSQL Global Development Group
*
* This software is released under the PostgreSQL Licence
*
* Authors: Dave Page <dpage@pgadmin.org>
* Andrew Dunstan <andrew@dunslane.net>
*
* IDENTIFICATION
* redis_fdw/redis_fdw.c
*
*-------------------------------------------------------------------------
*/
/* Debug mode */
/* #define DEBUG */
#include "postgres.h"
/* check that we are compiling for the right postgres version */
#if PG_VERSION_NUM < 180000
#error wrong Postgresql version this branch is only for 18.
#endif
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <hiredis/hiredis.h>
#include "funcapi.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/table.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 "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "mb/pg_wchar.h"
#include "nodes/pathnodes.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/appendinfo.h"
#include "optimizer/inherit.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "parser/parsetree.h"
#include "storage/fd.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
PG_MODULE_MAGIC;
#define PROCID_TEXTEQ 67
/*
* Describes the valid options for objects that use this wrapper.
*/
struct RedisFdwOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
};
/*
* Valid options for redis_fdw.
*
*/
static struct RedisFdwOption valid_options[] =
{
/* Connection options */
{"address", ForeignServerRelationId},
{"port", ForeignServerRelationId},
{"password", UserMappingRelationId},
{"database", ForeignTableRelationId},
/* table options */
{"singleton_key", ForeignTableRelationId},
{"tablekeyprefix", ForeignTableRelationId},
{"tablekeyset", ForeignTableRelationId},
{"tabletype", ForeignTableRelationId},
/* Sentinel */
{NULL, InvalidOid}
};
typedef enum
{
PG_REDIS_SCALAR_TABLE = 0,
PG_REDIS_HASH_TABLE,
PG_REDIS_LIST_TABLE,
PG_REDIS_SET_TABLE,
PG_REDIS_ZSET_TABLE
} redis_table_type;
typedef struct redisTableOptions
{
char *address;
int port;
char *password;
int database;
char *keyprefix;
char *keyset;
char *singleton_key;
redis_table_type table_type;
} redisTableOptions;
typedef struct
{
char *svr_address;
int svr_port;
char *svr_password;
int svr_database;
} RedisFdwPlanState;
/*
* FDW-specific information for ForeignScanState.fdw_state.
*/
typedef struct RedisFdwExecutionState
{
AttInMetadata *attinmeta;
redisContext *context;
redisReply *reply;
long long row;
char *address;
int port;
char *password;
int database;
char *keyprefix;
char *keyset;
char *qual_value;
char *singleton_key;
redis_table_type table_type;
char *cursor_search_string;
char *cursor_id;
MemoryContext mctxt;
} RedisFdwExecutionState;
typedef struct RedisFdwModifyState
{
redisContext *context;
char *address;
int port;
char *password;
int database;
char *keyprefix;
char *keyset;
char *qual_value;
char *singleton_key;
Relation rel;
redis_table_type table_type;
List *target_attrs;
int *targetDims;
int p_nums;
int keyAttno;
Oid array_elem_type;
FmgrInfo *p_flinfo;
} RedisFdwModifyState;
/* initial cursor */
#define ZERO "0"
/* redis default is 10 - let's fetch 1000 at a time */
#define COUNT " COUNT 1000"
/*
* SQL functions
*/
extern Datum redis_fdw_handler(PG_FUNCTION_ARGS);
extern Datum redis_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(redis_fdw_handler);
PG_FUNCTION_INFO_V1(redis_fdw_validator);
/*
* FDW callback routines
*/
static void redisGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void redisGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *redisGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan);
static void redisExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void redisBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *redisIterateForeignScan(ForeignScanState *node);
static inline TupleTableSlot *redisIterateForeignScanMulti(ForeignScanState *node);
static inline TupleTableSlot *redisIterateForeignScanSingleton(ForeignScanState *node);
static void redisReScanForeignScan(ForeignScanState *node);
static void redisEndForeignScan(ForeignScanState *node);
static List *redisPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void redisBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot *redisExecForeignInsert(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void redisEndForeignModify(EState *estate,
ResultRelInfo *rinfo);
static void redisAddForeignUpdateTargets(PlannerInfo *root,
Index rtindex,
RangeTblEntry *target_rte,
Relation target_relation);
static TupleTableSlot *redisExecForeignDelete(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *redisExecForeignUpdate(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
/*
* Helper functions
*/
static bool redisIsValidOption(const char *option, Oid context);
static void redisGetOptions(Oid foreigntableid, redisTableOptions *options);
static void redisGetQual(Node *node, TupleDesc tupdesc, char **key,
char **value, bool *pushdown);
static char *process_redis_array(redisReply *reply, redis_table_type type);
static void check_reply(redisReply *reply, redisContext *context,
int error_code, char *message, char *arg);
/*
* Name we will use for the junk attribute that holds the redis key
* for update and delete operations.
*/
#define REDISMODKEYNAME "__redis_mod_key_name"
/*
* Foreign-data wrapper handler function: return a struct with pointers
* to my callback routines.
*/
Datum
redis_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
#ifdef DEBUG
elog(NOTICE, "redis_fdw_handler");
#endif
fdwroutine->GetForeignRelSize = redisGetForeignRelSize;
fdwroutine->GetForeignPaths = redisGetForeignPaths;
fdwroutine->GetForeignPlan = redisGetForeignPlan;
/* can't ANALYSE redis */
fdwroutine->AnalyzeForeignTable = NULL;
fdwroutine->ExplainForeignScan = redisExplainForeignScan;
fdwroutine->BeginForeignScan = redisBeginForeignScan;
fdwroutine->IterateForeignScan = redisIterateForeignScan;
fdwroutine->ReScanForeignScan = redisReScanForeignScan;
fdwroutine->EndForeignScan = redisEndForeignScan;
fdwroutine->PlanForeignModify = redisPlanForeignModify; /* I U D */
fdwroutine->BeginForeignModify = redisBeginForeignModify; /* I U D */
fdwroutine->ExecForeignInsert = redisExecForeignInsert; /* I */
fdwroutine->EndForeignModify = redisEndForeignModify; /* I U D */
fdwroutine->ExecForeignUpdate = redisExecForeignUpdate; /* U */
fdwroutine->ExecForeignDelete = redisExecForeignDelete; /* D */
fdwroutine->AddForeignUpdateTargets = redisAddForeignUpdateTargets; /* U D */
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
redis_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
char *svr_address = NULL;
int svr_port = 0;
char *svr_password = NULL;
int svr_database = 0;
redis_table_type tabletype = PG_REDIS_SCALAR_TABLE;
char *tablekeyprefix = NULL;
char *tablekeyset = NULL;
char *singletonkey = NULL;
ListCell *cell;
#ifdef DEBUG
elog(NOTICE, "redis_fdw_validator");
#endif
/*
* Check that only options supported by redis_fdw, and allowed for the
* current object type, are given.
*/
foreach(cell, options_list)
{
DefElem *def = (DefElem *) lfirst(cell);
if (!redisIsValidOption(def->defname, catalog))
{
struct RedisFdwOption *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),
errhint("Valid options in this context are: %s",
buf.len ? buf.data : "<none>")
));
}
if (strcmp(def->defname, "address") == 0)
{
if (svr_address)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: "
"address (%s)", defGetString(def))
));
svr_address = defGetString(def);
}
else if (strcmp(def->defname, "port") == 0)
{
if (svr_port)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: port (%s)",
defGetString(def))
));
svr_port = atoi(defGetString(def));
}
if (strcmp(def->defname, "password") == 0)
{
if (svr_password)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: password")
));
svr_password = defGetString(def);
}
else if (strcmp(def->defname, "database") == 0)
{
if (svr_database)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: database "
"(%s)", defGetString(def))
));
svr_database = atoi(defGetString(def));
}
else if (strcmp(def->defname, "singleton_key ") == 0)
{
if (tablekeyset)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: tablekeyset(%s) and "
"singleton_key (%s)", tablekeyset,
defGetString(def))
));
if (tablekeyprefix)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: tablekeyprefix(%s) and "
"singleton_key (%s)", tablekeyprefix,
defGetString(def))
));
if (singletonkey)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: "
"singleton_key (%s)", defGetString(def))
));
singletonkey = defGetString(def);
}
else if (strcmp(def->defname, "tablekeyprefix") == 0)
{
if (tablekeyset)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: tablekeyset(%s) and "
"tablekeyprefix (%s)", tablekeyset,
defGetString(def))
));
if (singletonkey)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: singleton_key(%s) and "
"tablekeyprefix (%s)", singletonkey,
defGetString(def))
));
if (tablekeyprefix)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: "
"tablekeyprefix (%s)", defGetString(def))
));
tablekeyprefix = defGetString(def);
}
else if (strcmp(def->defname, "tablekeyset") == 0)
{
if (tablekeyprefix)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: tablekeyprefix (%s) and "
"tablekeyset (%s)", tablekeyprefix,
defGetString(def))
));
if (singletonkey)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting options: singleton_key(%s) and "
"tablekeyset (%s)", singletonkey,
defGetString(def))
));
if (tablekeyset)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: "
"tablekeyset (%s)", defGetString(def))
));
tablekeyset = defGetString(def);
}
else if (strcmp(def->defname, "tabletype") == 0)
{
char *typeval = defGetString(def);
if (tabletype)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: tabletype "
"(%s)", typeval)));
if (strcmp(typeval, "hash") == 0)
tabletype = PG_REDIS_HASH_TABLE;
else if (strcmp(typeval, "list") == 0)
tabletype = PG_REDIS_LIST_TABLE;
else if (strcmp(typeval, "set") == 0)
tabletype = PG_REDIS_SET_TABLE;
else if (strcmp(typeval, "zset") == 0)
tabletype = PG_REDIS_ZSET_TABLE;
else
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("invalid tabletype (%s) - must be hash, "
"list, set or zset", typeval)));
}
}
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
redisIsValidOption(const char *option, Oid context)
{
struct RedisFdwOption *opt;
#ifdef DEBUG
elog(NOTICE, "redisIsValidOption");
#endif
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 redis_fdw foreign table.
*/
static void
redisGetOptions(Oid foreigntableid, redisTableOptions *table_options)
{
ForeignTable *table;
ForeignServer *server;
UserMapping *mapping;
List *options;
ListCell *lc;
#ifdef DEBUG
elog(NOTICE, "redisGetOptions");
#endif
/*
* Extract options from FDW objects. We only need to worry about server
* options for Redis
*
*/
table = GetForeignTable(foreigntableid);
server = GetForeignServer(table->serverid);
mapping = GetUserMapping(GetUserId(), table->serverid);
options = NIL;
options = list_concat(options, table->options);
options = list_concat(options, server->options);
options = list_concat(options, mapping->options);
/* Loop through the options, and get the server/port */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "address") == 0)
table_options->address = defGetString(def);
if (strcmp(def->defname, "port") == 0)
table_options->port = atoi(defGetString(def));
if (strcmp(def->defname, "password") == 0)
table_options->password = defGetString(def);
if (strcmp(def->defname, "database") == 0)
table_options->database = atoi(defGetString(def));
if (strcmp(def->defname, "tablekeyprefix") == 0)
table_options->keyprefix = defGetString(def);
if (strcmp(def->defname, "tablekeyset") == 0)
table_options->keyset = defGetString(def);
if (strcmp(def->defname, "singleton_key") == 0)
table_options->singleton_key = defGetString(def);
if (strcmp(def->defname, "tabletype") == 0)
{
char *typeval = defGetString(def);
if (strcmp(typeval, "hash") == 0)
table_options->table_type = PG_REDIS_HASH_TABLE;
else if (strcmp(typeval, "list") == 0)
table_options->table_type = PG_REDIS_LIST_TABLE;
else if (strcmp(typeval, "set") == 0)
table_options->table_type = PG_REDIS_SET_TABLE;
else if (strcmp(typeval, "zset") == 0)
table_options->table_type = PG_REDIS_ZSET_TABLE;
/* XXX detect error here */
}
}
/* Default values, if required */
if (!table_options->address)
table_options->address = "127.0.0.1";
if (!table_options->port)
table_options->port = 6379;
if (!table_options->database)
table_options->database = 0;
}
static void
redisGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
RedisFdwPlanState *fdw_private;
redisTableOptions table_options;
redisContext *context;
redisReply *reply;
struct timeval timeout = {1, 500000};
#ifdef DEBUG
elog(NOTICE, "redisGetForeignRelSize");
#endif
/*
* Fetch options. Get everything so we don't need to re-fetch it later in
* planning.
*/
fdw_private = (RedisFdwPlanState *) palloc(sizeof(RedisFdwPlanState));
baserel->fdw_private = (void *) fdw_private;
table_options.address = NULL;
table_options.port = 0;
table_options.password = NULL;
table_options.database = 0;
table_options.keyprefix = NULL;
table_options.keyset = NULL;
table_options.singleton_key = NULL;
table_options.table_type = PG_REDIS_SCALAR_TABLE;
redisGetOptions(foreigntableid, &table_options);
fdw_private->svr_address = table_options.address;
fdw_private->svr_password = table_options.password;
fdw_private->svr_port = table_options.port;
fdw_private->svr_database = table_options.database;
/* Connect to the database */
context = redisConnectWithTimeout(table_options.address, table_options.port,
timeout);
if (context->err)
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to connect to Redis: %d", context->err)
));
/* Authenticate */
if (table_options.password)
{
reply = redisCommand(context, "AUTH %s", table_options.password);
if (!reply)
{
redisFree(context);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to authenticate to redis: %d",
context->err)));
}
freeReplyObject(reply);
}
/* Select the appropriate database */
reply = redisCommand(context, "SELECT %d", table_options.database);
if (!reply)
{
redisFree(context);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to select database %d: %d",
table_options.database, context->err)
));
}
/* Execute a query to get the table size */
#if 0
/*
* KEYS is potentiallyexpensive, so this test is disabled and we use a
* fairly dubious heuristic instead.
*/
if (table_options.keyprefix)
{
/* it's a pity there isn't an NKEYS command in Redis */
int len = strlen(table_options.keyprefix) + 2;
char *buff = palloc(len * sizeof(char));
snprintf(buff, len, "%s*", table_options.keyprefix);
reply = redisCommand(context, "KEYS %s", buff);
}
else
#endif
if (table_options.singleton_key)
{
switch (table_options.table_type)
{
case PG_REDIS_SCALAR_TABLE:
baserel->rows = 1;
return;
case PG_REDIS_HASH_TABLE:
reply = redisCommand(context, "HLEN %s", table_options.singleton_key);
break;
case PG_REDIS_LIST_TABLE:
reply = redisCommand(context, "LLEN %s", table_options.singleton_key);
break;
case PG_REDIS_SET_TABLE:
reply = redisCommand(context, "SCARD %s", table_options.singleton_key);
break;
case PG_REDIS_ZSET_TABLE:
reply = redisCommand(context, "ZCARD %s", table_options.singleton_key);
break;
default:
;
}
}
else if (table_options.keyset)
{
reply = redisCommand(context, "SCARD %s", table_options.keyset);
}
else
{
reply = redisCommand(context, "DBSIZE");
}
if (!reply)
{
redisFree(context);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("failed to get the database size: %d", context->err)
));
}
#if 0
if (reply->type == REDIS_REPLY_ARRAY)
baserel->rows = reply->elements;
else
#endif
if (table_options.keyprefix)
baserel->rows = reply->integer / 20;
else
baserel->rows = reply->integer;
freeReplyObject(reply);
redisFree(context);
}
/*
* redisGetForeignPaths
* Create possible access paths for a scan on the foreign table
*
* Currently we don't support any push-down feature, so there is only one
* possible access path, which simply returns all records in redis.
*/
static void
redisGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
RedisFdwPlanState *fdw_private = baserel->fdw_private;
Cost startup_cost,
total_cost;
#ifdef DEBUG
elog(NOTICE, "redisGetForeignPaths");
#endif
if (strcmp(fdw_private->svr_address, "127.0.0.1") == 0 ||
strcmp(fdw_private->svr_address, "localhost") == 0)
startup_cost = 10;
else
startup_cost = 25;
total_cost = startup_cost + baserel->rows;
/* Create a ForeignPath node and add it as only possible path */
add_path(baserel, (Path *)
create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
baserel->rows,
startup_cost,
total_cost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NULL, /* no extra plan */
NIL, /* no fdw_restrictinfo list */
NIL)); /* no fdw_private data */
}
static ForeignScan *
redisGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
Index scan_relid = baserel->relid;
#ifdef DEBUG
elog(NOTICE, "redisGetForeignPlan");
#endif
/*
* We have no native ability to evaluate restriction clauses, so we just
* put all the scan_clauses into the plan node's qual list for the
* executor to check. So all we have to do here is strip RestrictInfo
* nodes from the clauses and ignore pseudoconstants (which will be
* handled elsewhere).
*/
scan_clauses = extract_actual_clauses(scan_clauses, false);
/* Create the ForeignScan node */
return make_foreignscan(tlist,
scan_clauses,
scan_relid,
NIL, /* no expressions to evaluate */
NIL, /* no private state either */
NIL, /* no custom tlist */
NIL, /* no remote quals */
outer_plan);
}
/*
* fileExplainForeignScan
* Produce extra output for EXPLAIN
*/
static void
redisExplainForeignScan(ForeignScanState *node, ExplainState *es)
{
redisReply *reply;
RedisFdwExecutionState *festate = (RedisFdwExecutionState *) node->fdw_state;
#ifdef DEBUG
elog(NOTICE, "redisExplainForeignScan");
#endif
if (!es->costs)
return;
/*
* Execute a query to get the table size
*
* See above for more details.
*/
if (festate->keyset)
{
reply = redisCommand(festate->context, "SCARD %s", festate->keyset);
}
else
{
reply = redisCommand(festate->context, "DBSIZE");
}
if (!reply)
{
redisFree(festate->context);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to get the table size: %d", festate->context->err)
));
}
if (reply->type == REDIS_REPLY_ERROR)
{
char *err = pstrdup(reply->str);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to get the table size: %s", err)
));
}
ExplainPropertyInteger("Foreign Redis Table Size", "b",
festate->keyprefix ? reply->integer / 20 :
reply->integer,
es);
freeReplyObject(reply);
}
/*
* redisBeginForeignScan
* Initiate access to the database
*/
static void
redisBeginForeignScan(ForeignScanState *node, int eflags)
{
redisTableOptions table_options;
redisContext *context;
redisReply *reply;
char *qual_key = NULL;
char *qual_value = NULL;
bool pushdown = false;
RedisFdwExecutionState *festate;
struct timeval timeout = {1, 500000};
#ifdef DEBUG
elog(NOTICE, "BeginForeignScan");
#endif
table_options.address = NULL;
table_options.port = 0;
table_options.password = NULL;
table_options.database = 0;
table_options.keyprefix = NULL;
table_options.keyset = NULL;
table_options.singleton_key = NULL;
table_options.table_type = PG_REDIS_SCALAR_TABLE;
/* Fetch options */
redisGetOptions(RelationGetRelid(node->ss.ss_currentRelation),
&table_options);
/* Connect to the server */
context = redisConnectWithTimeout(table_options.address,
table_options.port, timeout);
if (context->err)
{
redisFree(context);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to connect to Redis: %s", context->errstr)
));
}
/* Authenticate */
if (table_options.password)
{
reply = redisCommand(context, "AUTH %s", table_options.password);
if (!reply)
{
redisFree(context);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to authenticate to redis: %s", context->errstr)
));
}
freeReplyObject(reply);
}
/* Select the appropriate database */
reply = redisCommand(context, "SELECT %d", table_options.database);
if (!reply)
{
redisFree(context);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to select database %d: %s",
table_options.database, context->errstr)
));
}
if (reply->type == REDIS_REPLY_ERROR)
{
char *err = pstrdup(reply->str);
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("failed to select database %d: %s",
table_options.database, err)
));
}
freeReplyObject(reply);
/* See if we've got a qual we can push down */
if (node->ss.ps.plan->qual)
{
ListCell *lc;
foreach(lc, node->ss.ps.plan->qual)
{
/* Only the first qual can be pushed down to Redis */
Expr *state = lfirst(lc);