forked from bluthg/odbc_fdw
-
Notifications
You must be signed in to change notification settings - Fork 22
/
odbc_fdw.c
2308 lines (2019 loc) · 62.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]>
* Updated to 9.2+ by Gunnar "Nick" Bluth <[email protected]>
* based on tds_fdw code from Geoff Montee
*
* 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 "mb/pg_wchar.h"
#include "optimizer/cost.h"
#include "storage/fd.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/rel.h"
#include "nodes/nodes.h"
#include "nodes/makefuncs.h"
#include "nodes/pg_list.h"
#include "optimizer/pathnode.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/planmain.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>
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;
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 */
List *mapping_list; /* Column name mapping */
} odbcFdwOptions;
typedef struct odbcFdwExecutionState
{
AttInMetadata *attinmeta;
odbcFdwOptions options;
SQLHENV env;
SQLHDBC dbc;
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;
List *col_conversion_array;
char *sql_count;
int encoding;
} odbcFdwExecutionState;
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 */
{ "dsn", ForeignServerRelationId },
{ "driver", ForeignServerRelationId },
{ "encoding", ForeignServerRelationId },
/* Foreign table options */
{ "schema", ForeignTableRelationId },
{ "table", ForeignTableRelationId },
{ "prefix", ForeignTableRelationId },
{ "sql_query", ForeignTableRelationId },
{ "sql_count", ForeignTableRelationId },
/* 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 *) palloc(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 *) palloc(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);
/*
* 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);
static void odbcGetTableOptions(Oid foreigntableid, odbcFdwOptions *extracted_options);
static void odbcGetTableSize(odbcFdwOptions* options, unsigned int *size);
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);
/*
* 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);
/* FIXME */
fdwroutine->GetForeignRelSize = odbcGetForeignRelSize;
fdwroutine->GetForeignPaths = odbcGetForeignPaths;
fdwroutine->AnalyzeForeignTable = odbcAnalyzeForeignTable;
fdwroutine->GetForeignPlan = odbcGetForeignPlan;
fdwroutine->ExplainForeignScan = odbcExplainForeignScan;
fdwroutine->BeginForeignScan = odbcBeginForeignScan;
fdwroutine->IterateForeignScan = odbcIterateForeignScan;
fdwroutine->ReScanForeignScan = odbcReScanForeignScan;
fdwroutine->EndForeignScan = odbcEndForeignScan;
fdwroutine->ImportForeignSchema = odbcImportForeignSchema;
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;
}
/* Column mapping goes here */
/* TODO: is this useful? if so, how can columns names coincident
with option names be escaped? */
extracted_options->mapping_list = lappend(extracted_options->mapping_list, def);
}
}
/*
* 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 */
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);
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);
if (*env)
{
ret = SQLFreeHandle(SQL_HANDLE_ENV, *env);
check_return(ret, "env free handle", *env, SQL_HANDLE_ENV);
}
}
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))
{
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>")
));
}
/* 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;
};
}
static SQLULEN
minimum_buffer_size(SQLSMALLINT odbc_data_type)
{
switch(odbc_data_type)
{
case SQL_DECIMAL :
case SQL_NUMERIC :
return 32;
case SQL_INTEGER :
return 12;
case SQL_REAL :
case SQL_FLOAT :
return 18;
case SQL_DOUBLE :
return 26;
case SQL_SMALLINT :
case SQL_TINYINT :
return 6;
case SQL_BIGINT :
return 21;
case SQL_TYPE_DATE :
case SQL_DATE :
return 10;
case SQL_TYPE_TIME :
case SQL_TIME :
return 8;
case SQL_TYPE_TIMESTAMP :
case SQL_TIMESTAMP :
return 20;
default :
return 0;
};
}
/*
* Fetch the options for a server and options list
*/
static void
odbcGetOptions(Oid server_oid, List *add_options, odbcFdwOptions *extracted_options)
{
ForeignServer *server;
UserMapping *mapping;
List *options;
elog_debug("%s", __func__);
server = GetForeignServer(server_oid);
mapping = GetUserMapping(GetUserId(), 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)
{
ForeignTable *table;
elog_debug("%s", __func__);
table = GetForeignTable(foreigntableid);
odbcGetOptions(table->serverid, table->options, extracted_options);
}
#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))
{
#ifdef DEBUG
elog(DEBUG1, "Error result (%d): %s", ret, error_msg);
#endif
if (handle)
{
do
{
diag_ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
sizeof(text), &len );
if (SQL_SUCCEEDED(diag_ret)) {
#ifdef DEBUG
elog(DEBUG1, " %s:%ld:%ld:%s\n", state, (long int) i, (long int) native, text);
#endif
strncat(error_msg, ERROR_MSG_SEP, MAX_ERROR_MSG_LENGTH - strlen(ERROR_MSG_SEP));
strncat(error_msg, (char *)text, MAX_ERROR_MSG_LENGTH - strlen(error_msg));
}
}
while( diag_ret == SQL_SUCCESS );
}
ereport(ERROR, (errcode(err_code), errmsg("%s", error_msg)));
}
}
/*
* Get name qualifier char
*/
static void
getNameQualifierChar(SQLHDBC dbc, StringInfoData *nq_char)
{
SQLCHAR name_qualifier_char[2];
elog_debug("%s", __func__);
SQLGetInfo(dbc,
SQL_CATALOG_NAME_SEPARATOR,
(SQLPOINTER)&name_qualifier_char,
2,
NULL);
name_qualifier_char[1] = 0; // some drivers fail to copy the trailing zero
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];
elog_debug("%s", __func__);
SQLGetInfo(dbc,
SQL_IDENTIFIER_QUOTE_CHAR,
(SQLPOINTER)"e_char,
2,
NULL);
quote_char[1] = 0; // some drivers fail to copy the trailing zero
initStringInfo(q_char);
appendStringInfo(q_char, "%s", (char *) quote_char);
}
static bool appendConnAttribute(bool sep, StringInfoData *conn_str, const char* name, const char* value)
{
static const char *sep_str = ";";
if (!is_blank_string(value))
{
if (sep)
appendStringInfoString(conn_str, sep_str);
appendStringInfo(conn_str, "%s=%s", name, value);
sep = true;
}
return sep;
}
static void odbcConnStr(StringInfoData *conn_str, odbcFdwOptions* options)
{
bool sep = false;
ListCell *lc;
initStringInfo(conn_str);
foreach(lc, options->connection_list)
{
DefElem *def = (DefElem *) lfirst(lc);
sep = appendConnAttribute(sep, conn_str, get_odbc_attribute_name(def->defname), defGetString(def));
}
elog_debug("CONN STR: %s", conn_str->data);
}
/*
* get table size of a table
*/
static void
odbcGetTableSize(odbcFdwOptions* options, unsigned int *size)
{
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
StringInfoData sql_str;
SQLUBIGINT table_size;
SQLLEN indicator;
StringInfoData name_qualifier_char;
StringInfoData quote_char;
const char* schema_name;
schema_name = get_schema_name(options);
odbc_connection(options, &env, &dbc);
/* Allocate a statement handle */
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
if (is_blank_string(options->sql_count))
{
/* Get quote char */
getQuoteChar(dbc, "e_char);
/* Get name qualifier char */
getNameQualifierChar(dbc, &name_qualifier_char);
initStringInfo(&sql_str);
if (is_blank_string(options->sql_query))
{
if (is_blank_string(schema_name))
{
appendStringInfo(&sql_str, "SELECT COUNT(*) FROM %s%s%s",
quote_char.data, options->table, quote_char.data);
}
else
{
appendStringInfo(&sql_str, "SELECT COUNT(*) FROM %s%s%s%s%s%s%s",
quote_char.data, schema_name, quote_char.data,
name_qualifier_char.data,
quote_char.data, options->table, quote_char.data);
}
}
else
{
if (options->sql_query[strlen(options->sql_query)-1] == ';')
{
/* Remove trailing semicolon if present */
options->sql_query[strlen(options->sql_query)-1] = 0;
}
appendStringInfo(&sql_str, "SELECT COUNT(*) FROM (%s) AS _odbc_fwd_count_wrapped", options->sql_query);
}
}
else
{
initStringInfo(&sql_str);
appendStringInfo(&sql_str, "%s", options->sql_count);
}
elog_debug("Count query: %s", sql_str.data);
ret = SQLExecDirect(stmt, (SQLCHAR *) sql_str.data, SQL_NTS);
check_return(ret, "Executing ODBC query to get table size", stmt, SQL_HANDLE_STMT);
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;
elog_debug("Count query result: %lu", table_size);
}
}
else
{
elog(WARNING, "Error getting the table %s size", options->table);
}
/* Free handles, and disconnect */
if (stmt)
{
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
stmt = NULL;
}
odbc_disconnection(&env, &dbc);
}
static int strtoint(const char *nptr, char **endptr, int base)
{
long val = strtol(nptr, endptr, base);
return (int) val;
}
static Oid oid_from_server_name(char *serverName)
{
char *serverOidString;