forked from CartoDB/odbc_fdw
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathodbc_fdw.c
4425 lines (3896 loc) · 125 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) 2021, TOSHIBA CORPORATION
* Copyright (c) 2011, PostgreSQL Global Development Group
*
* This software is released under the PostgreSQL Licence.
*
* Author: Zheng Yang <[email protected]>
* Updated to 9.2+ by Gunnar "Nick" Bluth <[email protected]>
* based on tds_fdw code from Geoff Montee
* Version 0.6 or higher
* by Takuya Koda <[email protected]>
*
* IDENTIFICATION
* odbc_fdw/odbc_fdw.c
*
*----------------------------------------------------------
*/
/* Debug mode flag */
/* #define DEBUG */
#include "postgres.h"
#include <string.h>
#include "odbc_fdw.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"
#if ((PG_VERSION_NUM >= 130010 && PG_VERSION_NUM < 140000) || \
(PG_VERSION_NUM >= 140007 && PG_VERSION_NUM < 150000) || \
PG_VERSION_NUM >= 150002)
#include "optimizer/inherit.h"
#endif
#include "utils/memutils.h"
#include "utils/builtins.h"
#include "utils/relcache.h"
#include "utils/syscache.h"
#include "storage/lock.h"
#include "miscadmin.h"
#include "mb/pg_wchar.h"
#include "optimizer/cost.h"
#include "storage/fd.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/rel.h"
#if PG_VERSION_NUM >= 160000
#include "utils/varlena.h"
#endif
#include "nodes/nodes.h"
#include "nodes/makefuncs.h"
#include "nodes/pg_list.h"
#include "optimizer/appendinfo.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/planmain.h"
#include "optimizer/tlist.h"
#include "access/tupdesc.h"
#if PG_VERSION_NUM < 120000
#include "access/heapam.h"
#define table_open heap_open
#define table_close heap_close
#else
#include "access/table.h"
#endif
#if defined(_WIN32)
#define strcasecmp _stricmp
#endif
/* TupleDescAttr was backported into 9.5.9 and 9.6.5 but we support any 9.5.X */
#ifndef TupleDescAttr
#define TupleDescAttr(tupdesc, i) ((tupdesc)->attrs[(i)])
#endif
#include "executor/spi.h"
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>
// for INSERT/UPDATE/DELETE
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
#include "utils/float.h"
#include "utils/guc.h"
#include "utils/date.h"
#include "utils/datetime.h"
#if (PG_VERSION_NUM < 140000)
/* source-code-compatibility hacks for pull_varnos() API change */
#define make_restrictinfo(a,b,c,d,e,f,g,h,i) make_restrictinfo_new(a,b,c,d,e,f,g,h,i)
#endif
PG_MODULE_MAGIC;
/* Macro to make conditional DEBUG more terse */
#ifdef DEBUG
#define elog_debug(...) elog(DEBUG1, __VA_ARGS__)
#else
#define elog_debug(...) ((void) 0)
#endif
#define PROCID_TEXTEQ 67
#define PROCID_TEXTCONST 25
/* Provisional limit to name lengths in characters */
#define MAXIMUM_CATALOG_NAME_LEN 255
#define MAXIMUM_SCHEMA_NAME_LEN 255
#define MAXIMUM_TABLE_NAME_LEN 255
#define MAXIMUM_COLUMN_NAME_LEN 255
/* Maximum GetData buffer size */
#define MAXIMUM_BUFFER_SIZE 8192
/*
* Numbers of the columns returned by SQLTables:
* 1: TABLE_CAT (ODBC 3.0) TABLE_QUALIFIER (ODBC 2.0) -- database name
* 2: TABLE_SCHEM (ODBC 3.0) TABLE_OWNER (ODBC 2.0) -- schema name
* 3: TABLE_NAME
* 4: TABLE_TYPE
* 5: REMARKS
*/
#define SQLTABLES_SCHEMA_COLUMN 2
#define SQLTABLES_NAME_COLUMN 3
#define ODBC_SQLSTATE_FRACTIONAL_TRUNCATION "01S07"
#define ODBC_SQLSTATE_STRING_TRUNCATION "01004"
#define ODBC_SQLSTATE_BQ_TRUNCATION "01000"
#define ODBC_SQLSTATE_LENGTH 5
typedef enum { NO_TRUNCATION, FRACTIONAL_TRUNCATION, STRING_TRUNCATION } GetDataTruncation;
#define IS_KEY_COLUMN(A) ((strcmp(A->defname, "key") == 0) && \
(strcmp(strVal(A->arg), "true") == 0))
/*
* Similarly, this enum describes what's kept in the fdw_private list for
* a ModifyTable node referencing a odbc_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) Oid list of target type for INSERT/UPDATE
* 4) Boolean flag showing if the remote query has a RETURNING clause
* 5) Integer list of attribute numbers retrieved by RETURNING, if any
*/
enum OdbcFdwModifyPrivateIndex
{
/* SQL statement to execute remotely (as a String node) */
OdbcFdwModifyPrivateUpdateSql,
/* Integer list of target attribute numbers for INSERT/UPDATE */
OdbcFdwModifyPrivateTargetAttnums,
};
/*
* 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
};
typedef struct odbcFdwOptions
{
char *schema; /* Foreign schema name */
char *table; /* Foreign table */
char *prefix; /* Prefix for imported foreign table names */
char *sql_query; /* SQL query (overrides table) */
char *sql_count; /* SQL query for counting results */
char *encoding; /* Character encoding name */
List *connection_list; /* ODBC connection attributes */
} odbcFdwOptions;
typedef struct odbcFdwScanState
{
AttInMetadata *attinmeta;
odbcFdwOptions options;
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
char *query;
bool query_executed;
List *retrieved_attrs; /* list of target attribute numbers */
StringInfoData *table_columns;
bool first_iteration;
List *col_size_array;
List *col_conversion_array;
char *sql_count;
int encoding;
} odbcFdwScanState;
typedef struct odbcFdwModifyState
{
odbcFdwOptions options;
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
char *query;
List *target_attrs;
/* info about parameters for prepared statement */
int p_nums; /* number of parameters to transmit */
FmgrInfo *p_flinfo; /* output conversion functions for them */
/* working memory context */
MemoryContext temp_cxt; /* context for per-tuple temporary data */
AttrNumber *junk_idx;
} odbcFdwModifyState;
struct odbcFdwOption
{
const char *optname;
Oid optcontext; /* Oid of catalog in which option may appear */
};
/*
* Array of valid options
* In addition to this, any option with a name prefixed
* by odbc_ is accepted as an ODBC connection attribute
* and can be defined in foreign servier, user mapping or
* table statements.
* Note that dsn and driver can be defined by
* prefixed or non-prefixed options.
*/
static struct odbcFdwOption valid_options[] =
{
/* Foreign server options */
{ "odbc_driver", ForeignServerRelationId },
{ "odbc_server", ForeignServerRelationId },
{ "odbc_port", ForeignServerRelationId },
{ "odbc_database", ForeignServerRelationId },
/* Foreign table options */
{ "schema", ForeignTableRelationId },
{ "table", ForeignTableRelationId },
{ "prefix", ForeignTableRelationId },
{ "sql_query", ForeignTableRelationId },
{ "sql_count", ForeignTableRelationId },
{ "column", AttributeRelationId },
{ "key", AttributeRelationId },
/* updatable is available on both server and table */
{"updatable", ForeignServerRelationId},
{"updatable", ForeignTableRelationId},
/* user mapping*/
{"odbc_uid", UserMappingRelationId},
{"odbc_pwd", UserMappingRelationId},
/* Sentinel */
{ NULL, InvalidOid}
};
typedef enum { TEXT_CONVERSION, BIN_CONVERSION, BOOL_CONVERSION } ColumnConversion;
static GetDataTruncation
result_truncation(SQLRETURN ret, SQLHSTMT stmt)
{
SQLCHAR sqlstate[ODBC_SQLSTATE_LENGTH + 1];
GetDataTruncation truncation = NO_TRUNCATION;
if (ret == SQL_SUCCESS_WITH_INFO)
{
SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, sqlstate, NULL, NULL, 0, NULL);
if (strncmp((char*)sqlstate, ODBC_SQLSTATE_STRING_TRUNCATION, ODBC_SQLSTATE_LENGTH) == 0 || strncmp((char*)sqlstate, ODBC_SQLSTATE_BQ_TRUNCATION, ODBC_SQLSTATE_LENGTH) == 0)
{
truncation = STRING_TRUNCATION;
}
else if (strncmp((char*)sqlstate, ODBC_SQLSTATE_FRACTIONAL_TRUNCATION, ODBC_SQLSTATE_LENGTH) == 0)
{
truncation = FRACTIONAL_TRUNCATION;
}
}
return truncation;
}
static void
resize_buffer(char ** buffer, int *size, int used_size, int required_size)
{
if (required_size > *size)
{
int new_size = required_size; // TODO: use min increment size, maybe in relation to current size
char * new_buffer = (char *) palloc0(new_size);
// TODO: out of memory error if !new_buffer
if (used_size > 0)
{
memmove(new_buffer, *buffer, used_size);
pfree(*buffer);
}
*buffer = new_buffer;
*size = new_size;
}
}
static const char * HEX_DIGITS = "0123456789ABCDEF";
static char * binary_to_hex(char * buffer, int buffer_size)
{
int i;
int hex_size = buffer_size*2;
char * hex = (char *) palloc0(hex_size + 1);
hex[hex_size] = 0;
for (i=0; i<buffer_size; i++)
{
unsigned char byte = buffer[i];
hex[i*2] = HEX_DIGITS[(byte >> 4)];
hex[i*2+1] = HEX_DIGITS[(byte & 0xF)];
}
return hex;
}
/*
* SQL functions
*/
PGDLLEXPORT Datum odbc_fdw_handler(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum odbc_fdw_validator(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum odbc_tables_list(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum odbc_table_size(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum odbc_query_size(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(odbc_fdw_handler);
PG_FUNCTION_INFO_V1(odbc_fdw_validator);
PG_FUNCTION_INFO_V1(odbc_tables_list);
PG_FUNCTION_INFO_V1(odbc_table_size);
PG_FUNCTION_INFO_V1(odbc_query_size);
/*
* FDW callback routines
*/
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);
static void odbcGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static void odbcEstimateCosts(PlannerInfo *root, RelOptInfo *baserel, Cost *startup_cost, Cost *total_cost, Oid foreigntableid);
static void odbcGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
static bool odbcAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func, BlockNumber *totalpages);
static ForeignScan* odbcGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid, ForeignPath *best_path, List *tlist, List *scan_clauses, Plan *outer_plan);
List* odbcImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid);
static List *odbcPlanForeignModify(PlannerInfo *root, ModifyTable *plan, Index resultRelation, int subplan_index);
static void odbcBeginForeignModify(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo, List *fdw_private, int subplan_index, int eflags);
static void odbcEndForeignModify(EState *estate, ResultRelInfo *resultRelInfo);
static TupleTableSlot *odbcExecForeignInsert(EState *estate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, TupleTableSlot *planSlot);
#if (PG_VERSION_NUM < 140000)
static void odbcAddForeignUpdateTargets(Query *parsetree, RangeTblEntry *target_rte, Relation target_relation);
#else
static void odbcAddForeignUpdateTargets(PlannerInfo *root, Index rtindex, RangeTblEntry *target_rte, Relation target_relation);
#endif
static TupleTableSlot *odbcExecForeignUpdate(EState *estate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, TupleTableSlot *planSlot);
static TupleTableSlot *odbcExecForeignDelete(EState *estate, ResultRelInfo *resultRelInfo, TupleTableSlot *slot, TupleTableSlot *planSlot);
static int odbcIsForeignRelUpdatable(Relation rel);
static void odbcExplainForeignModify(ModifyTableState *mtstate, ResultRelInfo *rinfo, List *fdw_private, int subplan_index, ExplainState *es);
static void odbcBeginForeignInsert(ModifyTableState *mtstate, ResultRelInfo *resultRelInfo);
static void odbcEndForeignInsert(EState *estate, ResultRelInfo *resultRelInfo);
static void odbcGetForeignUpperPaths(PlannerInfo *root,
UpperRelationKind stage,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
void *extra);
/*
* helper functions
*/
static bool odbcIsValidOption(const char *option, Oid context);
static void check_return(SQLRETURN ret, char *msg, SQLHANDLE handle, SQLSMALLINT type);
static const char* empty_string_if_null(char *string);
static void extract_odbcFdwOptions(List *options_list, odbcFdwOptions *extracted_options);
static void init_odbcFdwOptions(odbcFdwOptions* options);
static void copy_odbcFdwOptions(odbcFdwOptions* to, odbcFdwOptions* from);
static void odbc_connection(odbcFdwOptions* options, SQLHENV *env, SQLHDBC *dbc);
static void odbc_disconnection(SQLHENV *env, SQLHDBC *dbc);
static void sql_data_type(SQLSMALLINT odbc_data_type, SQLULEN column_size, SQLSMALLINT decimal_digits, SQLSMALLINT nullable, StringInfo sql_type);
static void odbcGetOptions(Oid server_oid, List *add_options, odbcFdwOptions *extracted_options, Oid userid);
static void odbcGetTableOptions(Oid foreigntableid, odbcFdwOptions *extracted_options, Oid userid);
static void odbcGetTableInfo(odbcFdwOptions* options, unsigned int *size, char **quote_char_out, char **name_qualifier_char_out);
static void check_return(SQLRETURN ret, char *msg, SQLHANDLE handle, SQLSMALLINT type);
static void odbcConnStr(StringInfoData *conn_str, odbcFdwOptions* options);
static char* get_schema_name(odbcFdwOptions *options);
static inline bool is_blank_string(const char *s);
static Oid oid_from_server_name(char *serverName);
static odbcFdwModifyState *create_foreign_modify(EState *estate, ResultRelInfo *resultRelInfo, CmdType operation, Plan *subplan, char *query, List *target_attrs);
static void finish_foreign_modify(odbcFdwModifyState *fmstate);
static TupleTableSlot *execute_foreign_modify(EState *estate, ResultRelInfo *resultRelInfo, CmdType operation, TupleTableSlot *slot, TupleTableSlot *planSlot);
static void bind_stmt_params(odbcFdwModifyState *fmstate, TupleTableSlot *slot);
static void bind_stmt_param(odbcFdwModifyState *fmstate, Oid type, int attnum, Datum value);
static void bindJunkColumnValue(odbcFdwModifyState *fmstate, TupleTableSlot *slot, TupleTableSlot *planSlot, Oid foreignTableId, int bindnum);
static void release_odbc_resources(odbcFdwModifyState *fmstate);
static SQLRETURN validate_retrieved_string(SQLHSTMT stmt, SQLUSMALLINT ColumnNumber, const char *string_value, bool *is_mapped, bool *is_empty_retrieved_string);
static void odbc_get_column_info(SQLHSTMT *stmt, ForeignScanState *node, odbcFdwScanState *festate);
static char* odbc_get_attr_value(odbcFdwScanState *festate, int attid, Oid pgtype, SQLLEN *result_size, ColumnConversion conversion);
static Datum odbc_convert_to_pg(Oid pgtyp, int pgtypmod, char* value, int size, ColumnConversion conversion);
static void odbc_make_tuple_from_result_row(SQLHSTMT * stmt,
TupleDesc tupleDescriptor,
List *retrieved_attrs,
Datum *row,
bool *is_null,
odbcFdwScanState * festate);
static void odbc_add_foreign_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
RelOptInfo *grouped_rel, GroupPathExtraData *extra);
#define REL_ALIAS_PREFIX "r"
/* Handy macro to add relation name qualification */
#define ADD_REL_QUALIFIER(buf, varno) \
appendStringInfo((buf), "%s%d.", REL_ALIAS_PREFIX, (varno))
static void deparseInsertSql(StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *targetAttrs, bool doNothing, List *withCheckOptionList, char *name_qualifier_char, char *quote_char);
static void deparseUpdateSql(StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *attname, List *targetAttrs, List *withCheckOptionList, char *name_qualifier_char, char *quote_char);
static void deparseDeleteSql(StringInfo buf, RangeTblEntry *rte, Index rtindex, Relation rel, List *name, char *name_qualifier_char, char *quote_char);
/*
* Check if string pointer is NULL or points to empty string
*/
static inline bool is_blank_string(const char *s)
{
return s == NULL || s[0] == '\0';
}
Datum
odbc_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
/* Functions for scanning foreign tables */
fdwroutine->GetForeignRelSize = odbcGetForeignRelSize;
fdwroutine->GetForeignPaths = odbcGetForeignPaths;
fdwroutine->GetForeignPlan = odbcGetForeignPlan;
fdwroutine->BeginForeignScan = odbcBeginForeignScan;
fdwroutine->IterateForeignScan = odbcIterateForeignScan;
fdwroutine->ReScanForeignScan = odbcReScanForeignScan;
fdwroutine->EndForeignScan = odbcEndForeignScan;
/* Functions for updating foreign tables */
fdwroutine->AddForeignUpdateTargets = odbcAddForeignUpdateTargets;
fdwroutine->PlanForeignModify = odbcPlanForeignModify;
fdwroutine->BeginForeignModify = odbcBeginForeignModify;
fdwroutine->ExecForeignInsert = odbcExecForeignInsert;
fdwroutine->ExecForeignUpdate = odbcExecForeignUpdate;
fdwroutine->ExecForeignDelete = odbcExecForeignDelete;
fdwroutine->EndForeignModify = odbcEndForeignModify;
fdwroutine->BeginForeignInsert = odbcBeginForeignInsert;
fdwroutine->EndForeignInsert = odbcEndForeignInsert;
fdwroutine->IsForeignRelUpdatable = odbcIsForeignRelUpdatable;
fdwroutine->PlanDirectModify = NULL;
fdwroutine->BeginDirectModify = NULL;
fdwroutine->IterateDirectModify = NULL;
fdwroutine->EndDirectModify = NULL;
/* Function for EvalPlanQual rechecks */
fdwroutine->RecheckForeignScan = NULL;
/* Support functions for EXPLAIN */
fdwroutine->ExplainForeignScan = odbcExplainForeignScan;
fdwroutine->ExplainForeignModify = odbcExplainForeignModify;
fdwroutine->ExplainDirectModify = NULL;
/* Support functions for ANALYZE */
fdwroutine->AnalyzeForeignTable = odbcAnalyzeForeignTable;
/* Support functions for IMPORT FOREIGN SCHEMA */
fdwroutine->ImportForeignSchema = odbcImportForeignSchema;
/* Support functions for join push-down */
fdwroutine->GetForeignJoinPaths = NULL;
/* Support functions for upper relation push-down */
fdwroutine->GetForeignUpperPaths = odbcGetForeignUpperPaths;
PG_RETURN_POINTER(fdwroutine);
}
static void
init_odbcFdwOptions(odbcFdwOptions* options)
{
memset(options, 0, sizeof(odbcFdwOptions));
}
static void
copy_odbcFdwOptions(odbcFdwOptions* to, odbcFdwOptions* from)
{
if (to && from)
{
*to = *from;
}
}
/*
* Avoid NULL string: return original string, or empty string if NULL
*/
static const char*
empty_string_if_null(char *string)
{
static const char* empty_string = "";
return string == NULL ? empty_string : string;
}
static const char odbc_attribute_prefix[] = "odbc_";
static const size_t odbc_attribute_prefix_len = sizeof(odbc_attribute_prefix) - 1; /* strlen(odbc_attribute_prefix); */
static bool
is_odbc_attribute(const char* defname)
{
return (strlen(defname) > odbc_attribute_prefix_len && strncmp(defname, odbc_attribute_prefix, odbc_attribute_prefix_len) == 0);
}
/* These ODBC attributes names are always uppercase */
static const char *normalized_attributes[] = { "DRIVER", "DSN", "UID", "PWD" };
static const char *normalized_attribute(const char* attribute_name)
{
size_t i;
for (i=0; i < sizeof(normalized_attributes)/sizeof(normalized_attributes[0]); i++)
{
if (strcasecmp(attribute_name, normalized_attributes[i])==0)
{
attribute_name = normalized_attributes[i];
break;
}
}
return attribute_name;
}
static const char*
get_odbc_attribute_name(const char* defname)
{
int offset = is_odbc_attribute(defname) ? odbc_attribute_prefix_len : 0;
return normalized_attribute(defname + offset);
}
static void
extract_odbcFdwOptions(List *options_list, odbcFdwOptions *extracted_options)
{
ListCell *lc;
elog_debug("%s", __func__);
init_odbcFdwOptions(extracted_options);
/* Loop through the options, and get the foreign table options */
foreach(lc, options_list)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "dsn") == 0)
{
extracted_options->connection_list = lappend(extracted_options->connection_list, def);
continue;
}
if (strcmp(def->defname, "driver") == 0)
{
extracted_options->connection_list = lappend(extracted_options->connection_list, def);
continue;
}
if (strcmp(def->defname, "schema") == 0)
{
extracted_options->schema = defGetString(def);
continue;
}
if (strcmp(def->defname, "table") == 0)
{
extracted_options->table = defGetString(def);
continue;
}
if (strcmp(def->defname, "prefix") == 0)
{
extracted_options->prefix = defGetString(def);
continue;
}
if (strcmp(def->defname, "sql_query") == 0)
{
extracted_options->sql_query = defGetString(def);
continue;
}
if (strcmp(def->defname, "sql_count") == 0)
{
extracted_options->sql_count = defGetString(def);
continue;
}
if (strcmp(def->defname, "encoding") == 0)
{
extracted_options->encoding = defGetString(def);
continue;
}
if (is_odbc_attribute(def->defname))
{
extracted_options->connection_list = lappend(extracted_options->connection_list, def);
continue;
}
}
}
/*
* Get the schema name from the options
*/
static char* get_schema_name(odbcFdwOptions *options)
{
return options->schema;
}
/*
* Establish ODBC connection
*/
static void
odbc_connection(odbcFdwOptions* options, SQLHENV *env, SQLHDBC *dbc)
{
StringInfoData conn_str;
SQLCHAR OutConnStr[1024];
SQLSMALLINT OutConnStrLen;
SQLRETURN ret;
odbcConnStr(&conn_str, options);
/* Allocate an environment handle */
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, env);
check_return(ret, "Allocate hENV", NULL, SQL_INVALID_HANDLE);
/* We want ODBC 3 support */
ret = SQLSetEnvAttr(*env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
if (!SQL_SUCCEEDED(ret))
{
SQLFreeHandle(SQL_HANDLE_ENV, env);
env = NULL;
}
check_return(ret, "set ODBC version", NULL, SQL_INVALID_HANDLE);
/* Allocate a connection handle */
ret = SQLAllocHandle(SQL_HANDLE_DBC, *env, dbc);
if (!SQL_SUCCEEDED(ret))
{
SQLFreeHandle(SQL_HANDLE_ENV, env);
env = NULL;
}
check_return(ret, "Allocate hDBC", NULL, SQL_INVALID_HANDLE);
/* Connect to the DSN */
ret = SQLDriverConnect(*dbc, NULL, (SQLCHAR *) conn_str.data, SQL_NTS,
OutConnStr, 1024, &OutConnStrLen, SQL_DRIVER_COMPLETE);
if (!SQL_SUCCEEDED(ret))
{
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
dbc = NULL;
SQLFreeHandle(SQL_HANDLE_ENV, env);
env = NULL;
}
check_return(ret, "Connecting to driver", dbc, SQL_HANDLE_DBC);
elog_debug("Connection opened");
}
/*
* Close the ODBC connection
*/
static void
odbc_disconnection(SQLHENV *env, SQLHDBC *dbc)
{
SQLRETURN ret;
if (*dbc)
{
ret = SQLDisconnect(*dbc);
check_return(ret, "dbc disconnect", *dbc, SQL_HANDLE_DBC);
ret = SQLFreeHandle(SQL_HANDLE_DBC, *dbc);
check_return(ret, "dbc free handle", *dbc, SQL_HANDLE_DBC);
dbc = NULL;
if (*env)
{
ret = SQLFreeHandle(SQL_HANDLE_ENV, *env);
check_return(ret, "env free handle", *env, SQL_HANDLE_ENV);
env = NULL;
}
}
elog_debug("Connection closed");
}
/*
* Validate function
*/
Datum
odbc_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
char *svr_schema = NULL;
char *svr_table = NULL;
char *svr_prefix = NULL;
char *sql_query = NULL;
char *sql_count = NULL;
ListCell *cell;
elog_debug("%s", __func__);
/*
* 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))
{
/*
* Unknown option specified, complain about it. Provide a hint
* with a valid option that looks similar, if there is one.
*/
struct odbcFdwOption *opt;
#if (PG_VERSION_NUM >= 160000)
const char *closest_match;
ClosestMatchState match_state;
bool has_valid_options = false;
initClosestMatch(&match_state, def->defname, 4);
for (opt = valid_options; opt->optname; opt++)
{
if (catalog == opt->optcontext)
{
has_valid_options = true;
updateClosestMatch(&match_state, opt->optname);
}
}
closest_match = getClosestMatch(&match_state);
ereport(ERROR,
(errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", def->defname),
has_valid_options ? closest_match ?
errhint("Perhaps you meant the option \"%s\".",
closest_match) : 0 :
errhint("There are no valid options in this context.")));
}
#else
StringInfoData buf;
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>")
));
}
#endif
/* TODO: detect redundant connection attributes and missing required attributs (dsn or driver)
* Complain about redundent options
*/
if (strcmp(def->defname, "schema") == 0)
{
if (!is_blank_string(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 (!is_blank_string(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, "prefix") == 0)
{
if (!is_blank_string(svr_prefix))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: prefix (%s)", defGetString(def))
));
svr_prefix = 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 (!is_blank_string(sql_count))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("conflicting or redundant options: sql_count (%s)", defGetString(def))
));
sql_count = defGetString(def);
}
}
PG_RETURN_VOID();
}
/*
* Map ODBC data types to PostgreSQL
*/
static void
sql_data_type(
SQLSMALLINT odbc_data_type,
SQLULEN column_size,
SQLSMALLINT decimal_digits,
SQLSMALLINT nullable,
StringInfo sql_type
)
{
initStringInfo(sql_type);
switch(odbc_data_type)
{
case SQL_CHAR:
case SQL_WCHAR :
appendStringInfo(sql_type, "char(%u)", (unsigned)column_size);
break;
case SQL_VARCHAR :
case SQL_WVARCHAR :
if (column_size <= 255 && column_size > 0)
{
appendStringInfo(sql_type, "varchar(%u)", (unsigned)column_size);
}
else
{
appendStringInfo(sql_type, "text");
}
break;
case SQL_LONGVARCHAR :
case SQL_WLONGVARCHAR :
appendStringInfo(sql_type, "text");
break;
case SQL_DECIMAL :
appendStringInfo(sql_type, "decimal(%u,%d)", (unsigned)column_size, decimal_digits);
break;
case SQL_NUMERIC :
appendStringInfo(sql_type, "numeric(%u,%d)", (unsigned)column_size, decimal_digits);
break;
case SQL_INTEGER :
appendStringInfo(sql_type, "integer");
break;
case SQL_REAL :
appendStringInfo(sql_type, "real");
break;
case SQL_FLOAT :
appendStringInfo(sql_type, "real");
break;
case SQL_DOUBLE :
appendStringInfo(sql_type, "float8");
break;
case SQL_BIT :
/* Use boolean instead of bit(1) because:
* * binary types are not yet fully supported
* * boolean is more commonly used in PG
* * With options BoolsAsChar=0 this allows
* preserving boolean columns from pSQL ODBC.
*/
appendStringInfo(sql_type, "boolean");
break;
case SQL_SMALLINT :
case SQL_TINYINT :
appendStringInfo(sql_type, "smallint");
break;
case SQL_BIGINT :
appendStringInfo(sql_type, "bigint");
break;
/*
* TODO: Implement these cases properly. See #23
*
case SQL_BINARY :
appendStringInfo(sql_type, "bit(%u)", (unsigned)column_size);
break;
case SQL_VARBINARY :
appendStringInfo(sql_type, "varbit(%u)", (unsigned)column_size);
break;
*/
case SQL_LONGVARBINARY :
appendStringInfo(sql_type, "bytea");
break;
case SQL_TYPE_DATE :
case SQL_DATE :
appendStringInfo(sql_type, "date");
break;
case SQL_TYPE_TIME :
case SQL_TIME :
appendStringInfo(sql_type, "time");
break;
case SQL_TYPE_TIMESTAMP :
case SQL_TIMESTAMP :
appendStringInfo(sql_type, "timestamp");
break;
case SQL_GUID :
appendStringInfo(sql_type, "uuid");
break;
};
}
/*
* Fetch the options for a server and options list
*/
static void
odbcGetOptions(Oid server_oid, List *add_options, odbcFdwOptions *extracted_options, Oid userid)
{
ForeignServer *server;
UserMapping *mapping;
List *options;
elog_debug("%s", __func__);
server = GetForeignServer(server_oid);
if (userid == InvalidOid)
mapping = GetUserMapping(GetUserId(), server_oid);
else
mapping = GetUserMapping(userid, server_oid);
options = NIL;
options = list_concat(options, add_options);
options = list_concat(options, server->options);
options = list_concat(options, mapping->options);
extract_odbcFdwOptions(options, extracted_options);
}
/*
* Fetch the options for a odbc_fdw foreign table.
*/
static void
odbcGetTableOptions(Oid foreigntableid, odbcFdwOptions *extracted_options, Oid userid)
{
ForeignTable *table;
elog_debug("%s", __func__);
table = GetForeignTable(foreigntableid);
odbcGetOptions(table->serverid, table->options, extracted_options, userid);
if (is_blank_string(extracted_options->table))
extracted_options->table = get_rel_name(foreigntableid);
}
#define MAX_ERROR_MSG_LENGTH 512
#define ERROR_MSG_SEP "\n"
static void
check_return(SQLRETURN ret, char *msg, SQLHANDLE handle, SQLSMALLINT type)
{
SQLINTEGER i = 0;
SQLINTEGER native;
SQLCHAR state[ 7 ];
SQLCHAR text[256];
SQLSMALLINT len;
SQLRETURN diag_ret;
static char error_msg[MAX_ERROR_MSG_LENGTH+1];
int err_code = ERRCODE_SYSTEM_ERROR;
strncpy(error_msg, msg, MAX_ERROR_MSG_LENGTH);
if (!SQL_SUCCEEDED(ret))
{
elog_debug("Error result (%d): %s", ret, error_msg);
if (handle)
{
do
{
diag_ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
sizeof(text), &len );
if (SQL_SUCCEEDED(diag_ret))