-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathtds_fdw.c
4168 lines (3524 loc) · 108 KB
/
tds_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 TDS (Sybase and Microsoft SQL Server)
*
* Author: Geoff Montee
* Name: tds_fdw
* File: tds_fdw/src/tds_fdw.c
*
* Description:
* This is a PostgreSQL foreign data wrapper for use to connect to databases that use TDS,
* such as Sybase databases and Microsoft SQL server.
*
* This foreign data wrapper requires requires a library that uses the DB-Library interface,
* such as FreeTDS (http://www.freetds.org/). This has been tested with FreeTDS, but not
* the proprietary implementations of DB-Library.
*----------------------------------------------------------------------------
*/
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
/* Override PGDLLEXPORT for visibility */
#include "visibility.h"
/* postgres headers */
#include "postgres.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 "miscadmin.h"
#include "mb/pg_wchar.h"
#include "libpq/pqsignal.h"
#include "optimizer/cost.h"
#include "optimizer/paths.h"
#include "optimizer/prep.h"
#if (PG_VERSION_NUM < 120000)
#include "optimizer/var.h"
#else
#include "optimizer/optimizer.h"
#endif
#include "storage/fd.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/rel.h"
#include "utils/memutils.h"
#include "utils/guc.h"
#include "utils/timestamp.h"
#if (PG_VERSION_NUM >= 90300)
#include "access/htup_details.h"
#else
#include "access/htup.h"
#endif
#include "optimizer/pathnode.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/planmain.h"
/* DB-Library headers (e.g. FreeTDS */
#include <sybfront.h>
#include <sybdb.h>
/* #define DEBUG */
PG_MODULE_MAGIC;
#include "tds_fdw.h"
#include "options.h"
#include "deparse.h"
/* run on module load */
extern PGDLLEXPORT void _PG_init(void);
static const bool DEFAULT_SHOW_FINISHED_MEMORY_STATS = false;
static bool show_finished_memory_stats = false;
static const bool DEFAULT_SHOW_BEFORE_ROW_MEMORY_STATS = false;
static bool show_before_row_memory_stats = false;
static const bool DEFAULT_SHOW_AFTER_ROW_MEMORY_STATS = false;
static bool show_after_row_memory_stats = false;
static const double DEFAULT_FDW_SORT_MULTIPLIER=1.2;
/* error handling */
static char* last_error_message = NULL;
static int tds_err_capture(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr);
static char *tds_err_msg(int severity, int dberr, int oserr, char *dberrstr, char *oserrstr);
/* signal handling */
static volatile bool interrupt_flag = false;
static void tds_signal_handler(int signum);
static void tds_clear_signals(void);
static int tds_chkintr_func(void* vdbproc);
static int tds_hndlintr_func(void* vdbproc);
/* Executes server query */
static bool
tdsExecuteQuery(char *query, DBPROCESS *dbproc);
/*
* Checks database vendor being either Microsoft or Sybase.
* Returns 1 in case the connected instance is SQL Server.
*/
static bool tdsIsSqlServer(DBPROCESS *dbproc);
/*
* Internal helper to set ANSI compatible server-side settings for SQL Server
* in case foreign server was configured with sqlserver_ansi_mode 'true'.
*/
static void tdsSetSqlServerAnsiMode(DBPROCESS **dbproc);
/*
* Indexes of FDW-private information stored in fdw_private lists.
*
* We store various information in ForeignScan.fdw_private to pass it from
* planner to executor. Currently we store:
*
* 1) SELECT statement text to be sent to the remote server
* 2) Integer list of attribute numbers retrieved by the SELECT
*
* 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
};
PG_FUNCTION_INFO_V1(tds_fdw_handler);
PG_FUNCTION_INFO_V1(tds_fdw_validator);
PGDLLEXPORT Datum tds_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> starting tds_fdw_handler")
));
#endif
#if (PG_VERSION_NUM >= 90200)
fdwroutine->GetForeignRelSize = tdsGetForeignRelSize;
fdwroutine->GetForeignPaths = tdsGetForeignPaths;
fdwroutine->AnalyzeForeignTable = tdsAnalyzeForeignTable;
fdwroutine->GetForeignPlan = tdsGetForeignPlan;
#else
fdwroutine->PlanForeignScan = tdsPlanForeignScan;
#endif
fdwroutine->ExplainForeignScan = tdsExplainForeignScan;
fdwroutine->BeginForeignScan = tdsBeginForeignScan;
fdwroutine->IterateForeignScan = tdsIterateForeignScan;
fdwroutine->ReScanForeignScan = tdsReScanForeignScan;
fdwroutine->EndForeignScan = tdsEndForeignScan;
#ifdef IMPORT_API
fdwroutine->ImportForeignSchema = tdsImportForeignSchema;
#endif /* IMPORT_API */
pqsignal(SIGINT, tds_signal_handler);
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> finishing tds_fdw_handler")
));
#endif
PG_RETURN_POINTER(fdwroutine);
}
PGDLLEXPORT Datum tds_fdw_validator(PG_FUNCTION_ARGS)
{
List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
Oid catalog = PG_GETARG_OID(1);
TdsFdwOptionSet option_set;
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> starting tds_fdw_validator")
));
#endif
tdsValidateOptions(options_list, catalog, &option_set);
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> finishing tds_fdw_validator")
));
#endif
PG_RETURN_VOID();
}
void _PG_init(void)
{
DefineCustomBoolVariable("tds_fdw.show_finished_memory_stats",
"Show finished memory stats",
"Set to true to show memory stats after a query finishes",
&show_finished_memory_stats,
DEFAULT_SHOW_FINISHED_MEMORY_STATS,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("tds_fdw.show_before_row_memory_stats",
"Show before row memory stats",
"Set to true to show memory stats before fetching each row",
&show_before_row_memory_stats,
DEFAULT_SHOW_BEFORE_ROW_MEMORY_STATS,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("tds_fdw.show_after_row_memory_stats",
"Show after row memory stats",
"Set to true to show memory stats after fetching each row",
&show_after_row_memory_stats,
DEFAULT_SHOW_AFTER_ROW_MEMORY_STATS,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
}
/*
* Find an equivalence class member expression, all of whose Vars, come from
* the indicated relation.
*/
Expr * find_em_expr_for_rel(EquivalenceClass *ec, RelOptInfo *rel)
{
ListCell *lc_em;
foreach(lc_em, ec->ec_members)
{
EquivalenceMember *em = lfirst(lc_em);
if (bms_equal(em->em_relids, rel->relids))
{
/*
* If there is more than one equivalence member whose Vars are
* taken entirely from this relation, we'll be content to choose
* any one of those.
*/
return em->em_expr;
}
}
/* We didn't find any suitable equivalence class expression */
return NULL;
}
/* This is used for JOIN pushdowns, so it is only needed on 9.5+ */
#if (PG_VERSION_NUM >= 90500)
/*
* Detect whether we want to process an EquivalenceClass member.
*
* This is a callback for use by generate_implied_equalities_for_column.
*/
static bool
ec_member_matches_foreign(PlannerInfo *root, RelOptInfo *rel,
EquivalenceClass *ec, EquivalenceMember *em,
void *arg)
{
ec_member_foreign_arg *state = (ec_member_foreign_arg *) arg;
Expr *expr = em->em_expr;
/*
* If we've identified what we're processing in the current scan, we only
* want to match that expression.
*/
if (state->current != NULL)
return equal(expr, state->current);
/*
* Otherwise, ignore anything we've already processed.
*/
if (list_member(state->already_used, expr))
return false;
/* This is the new target to process. */
state->current = expr;
return true;
}
#endif
/* build query that gets sent to remote server */
void tdsBuildForeignQuery(PlannerInfo *root, RelOptInfo *baserel, TdsFdwOptionSet* option_set,
Bitmapset* attrs_used, List** retrieved_attrs, List* remote_conds, List* remote_join_conds,
List* pathkeys)
{
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> starting tdsBuildForeignQuery")
));
#endif
ereport(DEBUG3,
(errmsg("tds_fdw: Getting query")
));
if (option_set->query)
{
ereport(DEBUG3,
(errmsg("tds_fdw: Query is explicitly set")
));
if (option_set->match_column_names)
{
/* do this, so that retrieved_attrs is filled in */
StringInfoData sql;
initStringInfo(&sql);
deparseSelectSql(&sql, root, baserel, attrs_used,
retrieved_attrs, option_set);
}
}
else
{
StringInfoData sql;
initStringInfo(&sql);
deparseSelectSql(&sql, root, baserel, attrs_used,
retrieved_attrs, option_set);
if (remote_conds)
appendWhereClause(&sql, root, baserel, remote_conds,
true, NULL);
if (remote_join_conds)
appendWhereClause(&sql, root, baserel, remote_join_conds,
(remote_conds == NIL), NULL);
if (pathkeys)
appendOrderByClause(&sql, root, baserel, pathkeys);
/*
* Add FOR UPDATE/SHARE if appropriate. We apply locking during the
* initial row fetch, rather than later on as is done for local tables.
* The extra roundtrips involved in trying to duplicate the local
* semantics exactly don't seem worthwhile (see also comments for
* RowMarkType).
*
* Note: because we actually run the query as a cursor, this assumes that
* DECLARE CURSOR ... FOR UPDATE is supported, which it isn't before 8.3.
*/
if (baserel->relid == root->parse->resultRelation &&
(root->parse->commandType == CMD_UPDATE ||
root->parse->commandType == CMD_DELETE))
{
/* Relation is UPDATE/DELETE target, so use FOR UPDATE */
appendStringInfoString(&sql, " FOR UPDATE");
}
#if (PG_VERSION_NUM >= 90500)
else
{
PlanRowMark *rc = get_plan_rowmark(root->rowMarks, baserel->relid);
if (rc)
{
/*
* Relation is specified as a FOR UPDATE/SHARE target, so handle
* that. (But we could also see LCS_NONE, meaning this isn't a
* target relation after all.)
*
* For now, just ignore any [NO] KEY specification, since (a) it's
* not clear what that means for a remote table that we don't have
* complete information about, and (b) it wouldn't work anyway on
* older remote servers. Likewise, we don't worry about NOWAIT.
*/
switch (rc->strength)
{
case LCS_NONE:
/* No locking needed */
break;
case LCS_FORKEYSHARE:
case LCS_FORSHARE:
appendStringInfoString(&sql, " FOR SHARE");
break;
case LCS_FORNOKEYUPDATE:
case LCS_FORUPDATE:
appendStringInfoString(&sql, " FOR UPDATE");
break;
}
}
}
#endif
/* now copy it to option_set->query */
if ((option_set->query = palloc((sql.len + 1) * sizeof(char))) == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_OUT_OF_MEMORY),
errmsg("Failed to allocate memory for query")
));
}
strcpy(option_set->query, sql.data);
}
ereport(DEBUG3,
(errmsg("tds_fdw: Value of query is %s", option_set->query)
));
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> finishing tdsBuildForeignQuery")
));
#endif
}
/* helper function, check database vendor is Microsoft or not */
bool tdsIsSqlServer(DBPROCESS *dbproc)
{
char *check_vendor_query = "SELECT CHARINDEX('Microsoft', @@version) AS is_sql_server";
bool result = true;
if (!tdsExecuteQuery(check_vendor_query, dbproc))
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmsg("Failed to check server version")
));
else
{
RETCODE erc;
int ret_code,
is_sql_server_pos;
erc = dbbind(dbproc, 1, INTBIND, sizeof(int), (BYTE *) &is_sql_server_pos);
if (erc == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to bind results for column \"is_sql_server\" to a variable.")
));
}
/* Process result */
ret_code = dbnextrow(dbproc);
if (ret_code == NO_MORE_ROWS)
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmsg("Failed to check server version")
));
switch (ret_code)
{
case REG_ROW:
ereport(DEBUG3,
(errmsg("tds_fdw: is_sql_server %d", is_sql_server_pos)
));
if (is_sql_server_pos == 0)
result = false;
break;
case BUF_FULL:
ereport(ERROR,
(errcode(ERRCODE_FDW_OUT_OF_MEMORY),
errmsg("Buffer filled up while getting plan for query")
));
case FAIL:
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to get row while getting plan for query")
));
default:
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to get plan for query. Unknown return code.")
));
}
}
return result;
}
/* helper function to set ANSI options */
void tdsSetSqlServerAnsiMode(DBPROCESS **dbproc)
{
char *set_ansi_options_query = "SET CONCAT_NULL_YIELDS_NULL, "
"ANSI_NULLS, "
"ANSI_WARNINGS, "
"QUOTED_IDENTIFIER, "
"ANSI_PADDING, "
"ANSI_NULL_DFLT_ON ON";
RETCODE erc;
elog(DEBUG3, "tds_fdw: checking for SQL Server");
if (!tdsIsSqlServer(*dbproc))
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("tds_fdw: option sqlserver_ansi_mode only supported for SQL Server"),
errdetail("The foreign server is configured with sqlserver_ansi_mode=true"),
errhint("use ALTER SERVER ... OPTIONS(DROP sqlserver_ansi_mode)")));
}
elog(DEBUG3, "tds_fdw: enabling ansi settings");
if ((erc = dbcmd(*dbproc, set_ansi_options_query)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to set %s", set_ansi_options_query)
));
}
ereport(DEBUG3,
(errmsg("tds_fdw: Executing the query \"%s\"", set_ansi_options_query)));
if ((erc = dbsqlexec(*dbproc)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to execute query %s", set_ansi_options_query)
));
}
}
/* set up connection */
int tdsSetupConnection(TdsFdwOptionSet* option_set, LOGINREC *login, DBPROCESS **dbproc)
{
char *servers;
RETCODE erc;
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> starting tdsSetupConnection")
));
#endif
ereport(DEBUG3,
(errmsg("tds_fdw: Setting login user to %s", option_set->username)
));
DBSETLUSER(login, option_set->username);
ereport(DEBUG3,
(errmsg("tds_fdw: Setting login password to %s", option_set->password)
));
DBSETLPWD(login, option_set->password);
if (option_set->character_set)
{
ereport(DEBUG3,
(errmsg("tds_fdw: Setting login character set to %s", option_set->character_set)
));
DBSETLCHARSET(login, option_set->character_set);
}
if (option_set->language)
{
DBSETLNATLANG(login, option_set->language);
ereport(DEBUG3,
(errmsg("tds_fdw: Setting login language to %s", option_set->language)
));
}
if (option_set->tds_version)
{
BYTE tds_version = DBVERSION_UNKNOWN;
if (strcmp(option_set->tds_version, "4.2") == 0)
{
tds_version = DBVER42;
}
else if (strcmp(option_set->tds_version, "5.0") == 0)
{
tds_version = DBVERSION_100;
}
else if (strcmp(option_set->tds_version, "7.0") == 0)
{
tds_version = DBVER60;
}
#ifdef DBVERSION_71
else if (strcmp(option_set->tds_version, "7.1") == 0)
{
tds_version = DBVERSION_71;
}
#endif
#ifdef DBVERSION_72
else if (strcmp(option_set->tds_version, "7.2") == 0)
{
tds_version = DBVERSION_72;
}
#endif
#ifdef DBVERSION_73
else if (strcmp(option_set->tds_version, "7.3") == 0)
{
tds_version = DBVERSION_73;
}
#endif
#ifdef DBVERSION_74
else if (strcmp(option_set->tds_version, "7.4") == 0)
{
tds_version = DBVERSION_74;
}
#endif
if (tds_version == DBVERSION_UNKNOWN)
{
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("Unknown tds version: %s.", option_set->tds_version)
));
}
dbsetlversion(login, tds_version);
ereport(DEBUG3,
(errmsg("tds_fdw: Setting login tds version to %s", option_set->tds_version)
));
}
if (option_set->database && !option_set->dbuse)
{
DBSETLDBNAME(login, option_set->database);
ereport(DEBUG3,
(errmsg("tds_fdw: Setting login database to %s", option_set->database)
));
}
/* set an error handler that does not abort */
dberrhandle(tds_err_capture);
/* try all server names until we find a good one */
servers = option_set->servername;
last_error_message = NULL;
while (servers != NULL)
{
/* find the length of the next server name */
char *next_server = strchr(servers, ',');
int server_len = next_server == NULL ? strlen(servers) : next_server - servers;
/* construct a connect string */
char *conn_string = palloc(server_len + 10);
strncpy(conn_string, servers, server_len);
if (option_set->port)
sprintf(conn_string + server_len, ":%i", option_set->port);
else
conn_string[server_len] = '\0';
ereport(DEBUG3,
(errmsg("tds_fdw: Connection string is %s", conn_string)
));
ereport(DEBUG3,
(errmsg("tds_fdw: Connecting to server")
));
/* try to connect */
if ((*dbproc = dbopen(login, conn_string)) == NULL)
{
/* failure, will continue with the next server */
ereport(DEBUG3,
(errmsg("Failed to connect using connection string %s with user %s", conn_string, option_set->username)
));
pfree(conn_string);
}
else
{
/* success, break the loop */
ereport(DEBUG3,
(errmsg("tds_fdw: Connected successfully")
));
pfree(conn_string);
break;
}
/* skip the comma if appropriate */
servers = next_server ? next_server + 1 : NULL;
}
/* report an error if all connections fail */
if (*dbproc == NULL)
{
if (last_error_message)
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("%s", last_error_message)
));
else
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("Failed to connect to server %s with user %s", option_set->servername, option_set->username)
));
}
/* set the normal error handler again */
dberrhandle(tds_err_handler);
/* set a signal handler that cancels now that dbopen() is complete */
dbsetinterrupt(*dbproc, tds_chkintr_func, tds_hndlintr_func);
if (option_set->database && option_set->dbuse)
{
ereport(DEBUG3,
(errmsg("tds_fdw: Selecting database %s", option_set->database)
));
if ((erc = dbuse(*dbproc, option_set->database)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("Failed to select database %s", option_set->database)
));
}
ereport(DEBUG3,
(errmsg("tds_fdw: Selected database")
));
}
/* Enable ANSI mode if requested */
if (option_set->sqlserver_ansi_mode) {
tdsSetSqlServerAnsiMode(dbproc);
}
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> finishing tdsSetupConnection")
));
#endif
return 0;
}
double tdsGetRowCountShowPlanAll(TdsFdwOptionSet* option_set, LOGINREC *login, DBPROCESS *dbproc)
{
double rows = 0;
RETCODE erc;
int ret_code;
char* show_plan_query = "SET SHOWPLAN_ALL ON";
char* show_plan_query_off = "SET SHOWPLAN_ALL OFF";
#ifdef DEBUG
ereport(NOTICE,
(errmsg("----> starting tdsGetRowCountShowPlanAll")
));
#endif
ereport(DEBUG3,
(errmsg("tds_fdw: Setting database command to %s", show_plan_query)
));
if ((erc = dbcmd(dbproc, show_plan_query)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to set current query to %s", show_plan_query)
));
}
ereport(DEBUG3,
(errmsg("tds_fdw: Executing the query")
));
if ((erc = dbsqlexec(dbproc)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to execute query %s", show_plan_query)
));
}
ereport(DEBUG3,
(errmsg("tds_fdw: Query executed correctly")
));
ereport(DEBUG3,
(errmsg("tds_fdw: Getting results")
));
erc = dbresults(dbproc);
if (erc == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to get results from query %s", show_plan_query)
));
}
ereport(DEBUG3,
(errmsg("tds_fdw: Setting database command to %s", option_set->query)
));
if ((erc = dbcmd(dbproc, option_set->query)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to set current query to %s", option_set->query)
));
}
ereport(DEBUG3,
(errmsg("tds_fdw: Executing the query")
));
if ((erc = dbsqlexec(dbproc)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to execute query %s", option_set->query)
));
}
ereport(DEBUG3,
(errmsg("tds_fdw: Query executed correctly")
));
ereport(DEBUG3,
(errmsg("tds_fdw: Getting results")
));
erc = dbresults(dbproc);
if (erc == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to get results from query %s", option_set->query)
));
}
else if (erc == NO_MORE_RESULTS)
{
ereport(DEBUG3,
(errmsg("tds_fdw: There appears to be no results from query %s", option_set->query)
));
goto cleanup_after_show_plan;
}
else if (erc == SUCCEED)
{
int ncol;
int ncols;
int parent = 0;
double estimate_rows = 0;
ncols = dbnumcols(dbproc);
ereport(DEBUG3,
(errmsg("tds_fdw: %i columns", ncols)
));
for (ncol = 0; ncol < ncols; ncol++)
{
char *col_name;
col_name = dbcolname(dbproc, ncol + 1);
if (strcmp(col_name, "Parent") == 0)
{
ereport(DEBUG3,
(errmsg("tds_fdw: Binding column %s (%i)", col_name, ncol + 1)
));
erc = dbbind(dbproc, ncol + 1, INTBIND, sizeof(int), (BYTE *)&parent);
if (erc == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to bind results for column %s to a variable.", col_name)
));
}
}
if (strcmp(col_name, "EstimateRows") == 0)
{
ereport(DEBUG3,
(errmsg("tds_fdw: Binding column %s (%i)", col_name, ncol + 1)
));
erc = dbbind(dbproc, ncol + 1, FLT8BIND, sizeof(double), (BYTE *)&estimate_rows);
if (erc == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to bind results for column %s to a variable.", col_name)
));
}
}
}
ereport(DEBUG3,
(errmsg("tds_fdw: Successfully got results")
));
while ((ret_code = dbnextrow(dbproc)) != NO_MORE_ROWS)
{
switch (ret_code)
{
case REG_ROW:
ereport(DEBUG3,
(errmsg("tds_fdw: Parent is %i. EstimateRows is %g.", parent, estimate_rows)
));
if (parent == 0)
{
rows += estimate_rows;
}
break;
case BUF_FULL:
ereport(ERROR,
(errcode(ERRCODE_FDW_OUT_OF_MEMORY),
errmsg("Buffer filled up while getting plan for query")
));
case FAIL:
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to get row while getting plan for query")
));
default:
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to get plan for query. Unknown return code.")
));
}
}
ereport(DEBUG3,
(errmsg("tds_fdw: We estimated %g rows.", rows)
));
}
else
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Unknown return code getting results from query %s", option_set->query)
));
}
cleanup_after_show_plan:
ereport(DEBUG3,
(errmsg("tds_fdw: Setting database command to %s", show_plan_query_off)
));
if ((erc = dbcmd(dbproc, show_plan_query_off)) == FAIL)
{
ereport(ERROR,
(errcode(ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION),
errmsg("Failed to set current query to %s", show_plan_query_off)
));
}
ereport(DEBUG3,