-
Notifications
You must be signed in to change notification settings - Fork 44
/
odbc_fdw.c
1251 lines (1067 loc) · 33.9 KB
/
odbc_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 ODBC
*
* Copyright (c) 2011, PostgreSQL Global Development Group
*
* This software is released under the PostgreSQL Licence.
*
* Author: Zheng Yang <[email protected]>
*
* IDENTIFICATION
* odbc_fdw/odbc_fdw.c
*
*----------------------------------------------------------
*/
/* Debug mode flag */
/*
#define DEBUG
*/
#include "postgres.h"
#include <string.h>
#include "funcapi.h"
#include "access/reloptions.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 "utils/memutils.h"
#include "utils/builtins.h"
#include "utils/relcache.h"
#include "storage/lock.h"
#include "miscadmin.h"
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>
PG_MODULE_MAGIC;
#define PROCID_TEXTEQ 67
#define PROCID_TEXTCONST 25
typedef struct odbcFdwExecutionState
{
AttInMetadata *attinmeta;
char *svr_dsn;
char *svr_database;
char *svr_schema;
char *svr_table;
char *svr_username;
char *svr_password;
SQLHSTMT stmt;
int num_of_result_cols;
int num_of_table_cols;
StringInfoData *table_columns;
bool first_iteration;
List *col_position_mask;
List *col_size_array;
char *sql_count;
} odbcFdwExecutionState;
struct odbcFdwOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
};
/*
* Array of valid options
*
*/
static struct odbcFdwOption valid_options[] =
{
/* Foreign server options */
{ "dsn", ForeignServerRelationId },
/* Foreign table options */
{ "database", ForeignTableRelationId },
{ "schema", ForeignTableRelationId },
{ "table", ForeignTableRelationId },
{ "sql_query", ForeignTableRelationId },
{ "sql_count", ForeignTableRelationId },
/* User mapping options */
{ "username", UserMappingRelationId },
{ "password", UserMappingRelationId },
/* Sentinel */
{ NULL, InvalidOid}
};
/*
* SQL functions
*/
extern Datum odbc_fdw_handler(PG_FUNCTION_ARGS);
extern Datum odbc_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(odbc_fdw_handler);
PG_FUNCTION_INFO_V1(odbc_fdw_validator);
/*
* FDW callback routines
*/
static FdwPlan *odbcPlanForeignScan(Oid foreigntableid, PlannerInfo *root, RelOptInfo *baserel);
static void odbcExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void odbcBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *odbcIterateForeignScan(ForeignScanState *node);
static void odbcReScanForeignScan(ForeignScanState *node);
static void odbcEndForeignScan(ForeignScanState *node);
/*
* helper functions
*/
static bool odbcIsValidOption(const char *option, Oid context);
Datum
odbc_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
fdwroutine->PlanForeignScan = odbcPlanForeignScan;
fdwroutine->ExplainForeignScan = odbcExplainForeignScan;
fdwroutine->BeginForeignScan = odbcBeginForeignScan;
fdwroutine->IterateForeignScan = odbcIterateForeignScan;
fdwroutine->ReScanForeignScan = odbcReScanForeignScan;
fdwroutine->EndForeignScan = odbcEndForeignScan;
PG_RETURN_POINTER(fdwroutine);
}
/*
* Validate function
*/
Datum
odbc_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
char *dsn = NULL;
char *svr_database = NULL;
char *svr_schema = NULL;
char *svr_table = NULL;
char *sql_query = NULL;
char *sql_count = NULL;
char *username = NULL;
char *password = NULL;
ListCell *cell;
#ifdef DEBUG
elog(NOTICE, "odbc_fdw_validator");
#endif
/*
* Check that the necessary options: address, port, database
*/
foreach(cell, options_list)
{
DefElem *def = (DefElem *) lfirst(cell);
/* Complain invalid options */
if (!odbcIsValidOption(def->defname, catalog))
{
struct odbcFdwOption *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>")
));
}
/* Complain about redundent options */
if (strcmp(def->defname, "dsn") == 0)
{
if (dsn)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: dsn (%s)", defGetString(def))
));
dsn = 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 = defGetString(def);
}
else if (strcmp(def->defname, "schema") == 0)
{
if (svr_schema)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: schema (%s)", defGetString(def))
));
svr_schema = defGetString(def);
}
else if (strcmp(def->defname, "table") == 0)
{
if (svr_table)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: table (%s)", defGetString(def))
));
svr_table = defGetString(def);
}
else if (strcmp(def->defname, "sql_query") == 0)
{
if (sql_query)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: sql_query (%s)", defGetString(def))
));
sql_query = defGetString(def);
}
else if (strcmp(def->defname, "sql_count") == 0)
{
if (sql_count)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: sql_count (%s)", defGetString(def))
));
sql_count = defGetString(def);
}
else if (strcmp(def->defname, "username") == 0)
{
if (username)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: username (%s)", defGetString(def))
));
username = defGetString(def);
}
else if (strcmp(def->defname, "password") == 0)
{
if (password)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: password (%s)", defGetString(def))
));
password = defGetString(def);
}
}
/* Complain about missing essential options: dsn */
if (!dsn && catalog == ForeignServerRelationId)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("missing eaaential information: dsn (Database Source Name)")
));
PG_RETURN_VOID();
}
/*
* Fetch the options for a odbc_fdw foreign table.
*/
static void
odbcGetOptions(Oid foreigntableid, char **svr_dsn, char **svr_database, char **svr_schema, char ** svr_table, char ** sql_query,
char **sql_count, char **username, char **password, List **mapping_list)
{
ForeignTable *table;
ForeignServer *server;
UserMapping *mapping;
List *options;
ListCell *lc;
#ifdef DEBUG
elog(NOTICE, "odbcGetOptions");
#endif
/*
* Extract options from FDW objects.
*/
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);
*mapping_list = NIL;
/* Loop through the options, and get the foreign table options */
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "dsn") == 0)
{
*svr_dsn = defGetString(def);
continue;
}
if (strcmp(def->defname, "database") == 0)
{
*svr_database = defGetString(def);
continue;
}
if (strcmp(def->defname, "schema") == 0)
{
*svr_schema = defGetString(def);
continue;
}
if (strcmp(def->defname, "table") == 0)
{
*svr_table = defGetString(def);
continue;
}
if (strcmp(def->defname, "sql_query") == 0)
{
*sql_query = defGetString(def);
continue;
}
if (strcmp(def->defname, "sql_count") == 0)
{
*sql_count = defGetString(def);
continue;
}
if (strcmp(def->defname, "username") == 0)
{
*username = defGetString(def);
continue;
}
if (strcmp(def->defname, "password") == 0)
{
*password = defGetString(def);
continue;
}
/* Column mapping goes here */
*mapping_list = lappend(*mapping_list, def);
}
#ifdef DEBUG
elog(NOTICE, "list length: %i", (*mapping_list)->length);
#endif
/* Default values, if required */
if (!*svr_dsn)
*svr_dsn = NULL;
if (!*svr_database)
*svr_database = NULL;
if (!*svr_schema)
*svr_schema = NULL;
if (!*svr_table)
*svr_table = NULL;
if (!*sql_query)
{
*sql_query = NULL;
}
if (!*sql_count)
{
*sql_count = NULL;
}
if (!*username)
*username = NULL;
if (!*password)
*password = NULL;
}
#ifdef DEBUG
void static extract_error(char *fn,
SQLHANDLE handle,
SQLSMALLINT type)
{
SQLINTEGER i = 0;
SQLINTEGER native;
SQLCHAR state[ 7 ];
SQLCHAR text[256];
SQLSMALLINT len;
SQLRETURN ret;
elog(NOTICE,
"\n"
"The driver reported the following diagnostics whilst running "
"%s\n\n",
fn);
do
{
ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
sizeof(text), &len );
if (SQL_SUCCEEDED(ret))
elog(NOTICE, "%s:%ld:%ld:%s\n", state, (long int) i, (long int) native, text);
}
while( ret == SQL_SUCCESS );
}
#endif
/*
* Get name qualifier char
*/
static void
getNameQualifierChar(SQLHDBC dbc, StringInfoData *nq_char)
{
SQLCHAR name_qualifier_char[2];
#ifdef DUBUG
elog(NOTICE, "getNameQualifierChar");
#endif
SQLGetInfo(dbc,
SQL_QUALIFIER_NAME_SEPARATOR,
(SQLPOINTER)&name_qualifier_char,
2,
NULL);
initStringInfo(nq_char);
appendStringInfo(nq_char, "%s", (char *) name_qualifier_char);
}
/*
* Get quote cahr
*/
static void
getQuoteChar(SQLHDBC dbc, StringInfoData *q_char)
{
SQLCHAR quote_char[2];
#ifdef DEBUG
elog(NOTICE, "getQuoteChar");
#endif
SQLGetInfo(dbc,
SQL_IDENTIFIER_QUOTE_CHAR,
(SQLPOINTER)"e_char,
2,
NULL);
initStringInfo(q_char);
appendStringInfo(q_char, "%s", (char *) quote_char);
}
/*
* get table size of a table
*/
static void
odbcGetTableSize(char *svr_dsn, char *svr_database, char *svr_schema, char *svr_table,
char *username, char *password, char *sql_count, unsigned int *size)
{
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
StringInfoData conn_str;
StringInfoData sql_str;
SQLCHAR OutConnStr[1024];
SQLSMALLINT OutConnStrLen;
SQLUBIGINT table_size;
SQLLEN indicator;
StringInfoData name_qualifier_char;
StringInfoData quote_char;
/* Construct connection string */
initStringInfo(&conn_str);
appendStringInfo(&conn_str, "DSN=%s;DATABASE=%s;UID=%s;PWD=%s;", svr_dsn, svr_database, username, password);
#ifdef DEBUG
elog(NOTICE, "Connection string: %s", conn_str.data);
#endif
/* Allocate an environment handle */
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
/* We want ODBC 3 support */
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
/* Allocate a connection handle */
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
/* Connect to the DSN */
ret = SQLDriverConnect(dbc, NULL, (SQLCHAR *) conn_str.data, SQL_NTS,
OutConnStr, 1024, &OutConnStrLen, SQL_DRIVER_COMPLETE);
#ifdef DEBUG
if (SQL_SUCCEEDED(ret))
elog(NOTICE, "Successfully connected to driver");
else
{
extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
}
#endif
/* Allocate a statement handle */
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
if (sql_count == NULL)
{
/* Get quote char */
getQuoteChar(dbc, "e_char);
/* Get name qualifier char */
getNameQualifierChar(dbc, &name_qualifier_char);
initStringInfo(&sql_str);
appendStringInfo(&sql_str, "SELECT COUNT(*) FROM %s%s%s%s%s%s%s",
quote_char.data, svr_schema, quote_char.data,
name_qualifier_char.data,
quote_char.data, svr_table, quote_char.data);
}
else
{
initStringInfo(&sql_str);
appendStringInfo(&sql_str, "%s", sql_count);
}
#ifdef DEBUG
elog(NOTICE, "%s", sql_str.data);
#endif
ret = SQLExecDirect(stmt, (SQLCHAR *) sql_str.data, SQL_NTS);
if (SQL_SUCCEEDED(ret))
{
SQLFetch(stmt);
/* retrieve column data as a big int */
ret = SQLGetData(stmt, 1, SQL_C_UBIGINT, &table_size, 0, &indicator);
if (SQL_SUCCEEDED(ret))
{
*size = (unsigned int) table_size;
}
}
else
{
elog(NOTICE, "Opps!");
}
/* Free handles, and disconnect */
if (stmt)
{
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
stmt = NULL;
}
if (dbc)
{
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
dbc = NULL;
}
if (env)
{
SQLFreeHandle(SQL_HANDLE_ENV, env);
env = NULL;
}
if (dbc)
SQLDisconnect(dbc);
#ifdef DEBUG
elog(NOTICE, "Count: %u", *size);
#endif
}
/*
* get quals in the select if there is one
*/
static void
odbcGetQual(Node *node, TupleDesc tupdesc, List *col_mapping_list, char **key, char **value, bool *pushdown)
{
ListCell *col_mapping;
*key = NULL;
*value = NULL;
*pushdown = false;
#ifdef DEBUG
elog(NOTICE, "odbcGetQual");
#endif
if (!node)
return;
if (IsA(node, OpExpr))
{
OpExpr *op = (OpExpr *) node;
Node *left, *right;
Index varattno;
if (list_length(op->args) != 2)
return;
left = list_nth(op->args, 0);
if (!IsA(left, Var))
return;
varattno = ((Var *) left)->varattno;
right = list_nth(op->args, 1);
if (IsA(right, Const))
{
StringInfoData buf;
initStringInfo(&buf);
/* And get the column and value... */
*key = NameStr(tupdesc->attrs[varattno - 1]->attname);
#ifdef DEBUG
elog(NOTICE, "constant type: %u", ((Const *) right)->consttype);
#endif
if (((Const *) right)->consttype == PROCID_TEXTCONST)
*value = TextDatumGetCString(((Const *) right)->constvalue);
else
{
return;
}
/* convert qual keys to mapped couchdb attribute name */
foreach(col_mapping, col_mapping_list)
{
DefElem *def = (DefElem *) lfirst(col_mapping);
if (strcmp(def->defname, *key) == 0)
{
*key = defGetString(def);
break;
}
}
/*
* We can push down this qual if:
* - The operatory is TEXTEQ
* - The qual is on the _id column (in addition, _rev column can be also valid)
*/
if (op->opfuncid == PROCID_TEXTEQ)
*pushdown = true;
#ifdef DEBUG
elog(NOTICE, "Got qual %s = %s", *key, *value);
#endif
return;
}
}
return;
}
/*
* 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
odbcIsValidOption(const char *option, Oid context)
{
struct odbcFdwOption *opt;
#ifdef DEBUG
elog(NOTICE, "odbcIsValidOption");
#endif
/* Check if the options presents in the valid option list */
for (opt = valid_options; opt->optname; opt++)
{
if (context == opt->optcontext && strcmp(opt->optname, option) == 0)
return true;
}
/* Foreign table may have anything as a mapping option */
if (context == ForeignTableRelationId)
return true;
else
return false;
}
/*
* odbcPlanForeignScan
* Create a FdwPlan for a scan on the foreign table
*/
static FdwPlan *
odbcPlanForeignScan(Oid foreigntableid, PlannerInfo *root, RelOptInfo *baserel)
{
FdwPlan *fdwplan;
unsigned int table_size = 0;
char *svr_dsn = NULL;
char *svr_database = NULL;
char *svr_schema = NULL;
char *svr_table = NULL;
char *sql_query = NULL;
char *sql_count = NULL;
char *username = NULL;
char *password = NULL;
List *col_mapping_list;
#ifdef DEBUG
elog(NOTICE, "odbcPlanForeignScan");
#endif
/* Fetch the foreign table options */
odbcGetOptions(foreigntableid, &svr_dsn, &svr_database, &svr_schema, &svr_table, &sql_query,
&sql_count, &username, &password, &col_mapping_list);
fdwplan = makeNode(FdwPlan);
fdwplan->startup_cost = 10;
fdwplan->total_cost = 100 + fdwplan->startup_cost;
fdwplan->fdw_private = NIL; /* not used */
#ifdef DEBUG
elog(NOTICE, "new total cost: %f", fdwplan->total_cost);
#endif
odbcGetTableSize(svr_dsn, svr_database, svr_schema, svr_table, username, password, sql_count, &table_size);
fdwplan->total_cost = fdwplan->total_cost + table_size;
#ifdef DEBUG
elog(NOTICE, "new total cost: %f", fdwplan->total_cost);
#endif
return fdwplan;
}
/*
* odbcBeginForeignScan
*
*/
static void
odbcBeginForeignScan(ForeignScanState *node, int eflags)
{
SQLHENV env;
SQLHDBC dbc;
odbcFdwExecutionState *festate;
SQLSMALLINT result_columns;
SQLHSTMT stmt;
SQLRETURN ret;
SQLCHAR OutConnStr[1024];
SQLSMALLINT OutConnStrLen;
#ifdef DEBUG
char dsn[256];
char desc[256];
SQLSMALLINT dsn_ret;
SQLSMALLINT desc_ret;
SQLUSMALLINT direction;
#endif
char *svr_dsn = NULL;
char *svr_database = NULL;
char *svr_schema = NULL;
char *svr_table = NULL;
char *sql_query = NULL;
char *sql_count = NULL;
char *username = NULL;
char *password = NULL;
StringInfoData conn_str;
Relation rel;
int num_of_columns;
StringInfoData *columns;
int i;
ListCell *col_mapping;
List *col_mapping_list;
StringInfoData sql;
StringInfoData col_str;
SQLCHAR quote_char[2];
SQLCHAR name_qualifier_char[2];
char *qual_key = NULL;
char *qual_value = NULL;
bool pushdown = FALSE;
#ifdef DEBUG
elog(NOTICE, "odbcBeginForeignScan");
#endif
/* Fetch the foreign table options */
odbcGetOptions(RelationGetRelid(node->ss.ss_currentRelation), &svr_dsn, &svr_database, &svr_schema, &svr_table, &sql_query,
&sql_count, &username, &password, &col_mapping_list);
#ifdef DEBUG
elog(NOTICE, "dsn: %s", svr_dsn);
elog(NOTICE, "db: %s", svr_database);
elog(NOTICE, "schema: %s", svr_schema);
elog(NOTICE, "table: %s", svr_table);
elog(NOTICE, "sql_query: %s", sql_query);
elog(NOTICE, "sql_count: %s", sql_count);
elog(NOTICE, "username: %s", username);
elog(NOTICE, "password: %s", password);
#endif
initStringInfo(&conn_str);
appendStringInfo(&conn_str, "DSN=%s;DATABASE=%s;UID=%s;PWD=%s;", svr_dsn, svr_database, username, password);
#ifdef DEBUG
elog(NOTICE, "connection string: %s", conn_str.data);
#endif
/* Allocate an environment handle */
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
/* We want ODBC 3 support */
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
#ifdef DEBUG
/* Print DSNs available: for debugging purposes */
direction = SQL_FETCH_FIRST;
while(SQL_SUCCEEDED(ret = SQLDataSources(env, direction,
(SQLCHAR *) dsn, sizeof(dsn), &dsn_ret,
(SQLCHAR *) desc, sizeof(desc), &desc_ret)))
{
direction = SQL_FETCH_NEXT;
elog(NOTICE, "%s - %s", dsn, desc);
if (ret == SQL_SUCCESS_WITH_INFO) elog(NOTICE, "data truncation");
}
#endif
/* Allocate a connection handle */
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
/* Connect to the DSN */
ret = SQLDriverConnect(dbc, NULL, (SQLCHAR *) conn_str.data, SQL_NTS,
OutConnStr, 1024, &OutConnStrLen, SQL_DRIVER_COMPLETE);
#ifdef DEBUG
if (SQL_SUCCEEDED(ret))
elog(NOTICE, "Successfully connected to driver");
else
{
extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
}
#endif
/* Getting the Quote char */
SQLGetInfo(dbc,
SQL_IDENTIFIER_QUOTE_CHAR,
(SQLPOINTER)"e_char,
2,
NULL);
/* Getting the Qualifier name separator */
SQLGetInfo(dbc,
SQL_QUALIFIER_NAME_SEPARATOR,
(SQLPOINTER)&name_qualifier_char,
2,
NULL);
#ifdef DEBUG
elog(NOTICE, "QUOTE CHAR: %s", quote_char);
elog(NOTICE, "SQL_QUALIFIER_NAME_SEPARATOR: %s", name_qualifier_char);
#endif
/* Fetch the table column info */
rel = heap_open(RelationGetRelid(node->ss.ss_currentRelation), AccessShareLock);
num_of_columns = rel->rd_att->natts;
columns = (StringInfoData *) palloc(sizeof(StringInfoData) * num_of_columns);
initStringInfo(&col_str);
for (i = 0; i < num_of_columns; i++)
{
StringInfoData col;
StringInfoData mapping;
bool mapped;
/* retrieve the column name */
initStringInfo(&col);
appendStringInfo(&col, "%s", NameStr(rel->rd_att->attrs[i]->attname));
mapped = FALSE;
/* check if the column name is mapping to a different name in remote table */
foreach(col_mapping, col_mapping_list)
{
DefElem *def = (DefElem *) lfirst(col_mapping);
if (strcmp(def->defname, col.data) == 0)
{
initStringInfo(&mapping);
appendStringInfo(&mapping, "%s", defGetString(def));
mapped = TRUE;
break;
}
}
/* decide which name is going to be used */
if (mapped)
columns[i] = mapping;
else
columns[i] = col;
appendStringInfo(&col_str, i == 0 ? "%s%s%s" : ",%s%s%s", (char *) quote_char, columns[i].data, (char *) quote_char);
}
heap_close(rel, NoLock);
#ifdef DEBUG
/* print out the actual column names in remote table for debug only*/
for (i = 0; i < num_of_columns; i++)
{
elog(NOTICE, "Column Mapping %i: %s", i, columns[i].data);
}
elog(NOTICE, "Column String: %s", col_str.data);
elog(NOTICE, "Experiment: ");
/*
// SUBSTRING supported
if (fFuncs & SQL_FN_STR_CHAR_LENGTH)
elog(NOTICE, "HAS COUNT!"); // do something
// SUBSTRING not supported
else
elog(NOTICE, "DUN HAVE!"); // do something else
*/
#endif
/* See if we've got a qual we can push down */
if (node->ss.ps.plan->qual)
{
ListCell *lc;
foreach (lc, node->ss.ps.qual)
{
/* Only the first qual can be pushed down to remote DBMS */
ExprState *state = lfirst(lc);
odbcGetQual((Node *) state->expr, node->ss.ss_currentRelation->rd_att, col_mapping_list, &qual_key, &qual_value, &pushdown);
if (pushdown)
break;
}
}
/* Construct the SQL statement used for remote querying */
initStringInfo(&sql);
if (pushdown)
{
appendStringInfo(&sql, "SELECT %s FROM `%s`.`%s` WHERE `%s` = '%s'",
col_str.data, svr_database, svr_table, qual_key, qual_value);
}
else
{
/* Use custom query if it's available */
if (sql_query)
{
appendStringInfo(&sql, "%s", sql_query);
}
else
{
appendStringInfo(&sql, "SELECT %s FROM %s%s%s%s%s%s%s", col_str.data,
(char *) quote_char, svr_schema, (char *) quote_char,
(char *) name_qualifier_char, (char *) quote_char, svr_table, (char *) quote_char);
}
}
#ifdef DEBUG
elog(NOTICE, "SQL: %s", sql.data);
#endif
/* Allocate a statement handle */
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
/* Retrieve a list of rows */
SQLExecDirect(stmt, (SQLCHAR *) sql.data, SQL_NTS);
SQLNumResultCols(stmt, &result_columns);
#ifdef DEBUG
elog(NOTICE, "num of columns (begin): %i", (int) result_columns);
#endif
festate = (odbcFdwExecutionState *) palloc(sizeof(odbcFdwExecutionState));
festate->attinmeta = TupleDescGetAttInMetadata(node->ss.ss_currentRelation->rd_att);
festate->svr_dsn = svr_dsn;
festate->svr_database = svr_database;
festate->svr_schema = svr_schema;
festate->svr_table = svr_table;
festate->svr_username = username;
festate->svr_password = password;
festate->stmt = stmt;
festate->table_columns = columns;