-
Notifications
You must be signed in to change notification settings - Fork 5
/
ifx_fdw.c
6083 lines (5246 loc) · 159 KB
/
ifx_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
/*-------------------------------------------------------------------------
*
* ifx_fdw.c
* foreign-data wrapper for IBM INFORMIX databases
*
* Copyright (c) 2012, credativ GmbH
*
* IDENTIFICATION
* informix_fdw/ifx_fdw.c
*
*-------------------------------------------------------------------------
*/
#include "ifx_fdw.h"
#include "ifx_node_utils.h"
#include "ifx_conncache.h"
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "parser/parsetree.h"
#endif
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#include "access/relation.h"
#endif
/* For PG14 we need add_row_identity_var() */
#if PG_VERSION_NUM >= 140000
#include "optimizer/appendinfo.h"
#endif
/*
* For REL_16_STABLE, as of commit a61b1f74823 we need optimizer/inherit.h
* for get_rel_all_updated_cols().
*/
#if PG_VERSION_NUM >= 160000
#include "optimizer/inherit.h"
#endif
#include "access/xact.h"
#include "utils/lsyscache.h"
PG_MODULE_MAGIC;
/*
* Object options using this wrapper module
*/
struct IfxFdwOption
{
const char *optname;
Oid optcontext;
};
/*
* Global per-backend transaction counter.
*/
extern unsigned int ifxXactInProgress;
/*
* Valid options for informix_fdw.
*/
static struct IfxFdwOption ifx_valid_options[] =
{
{ "informixserver", ForeignServerRelationId },
{ "informixdir", ForeignServerRelationId },
{ "delimident", ForeignServerRelationId },
{ "username", UserMappingRelationId },
{ "password", UserMappingRelationId },
{ "database", ForeignTableRelationId },
{ "database", ForeignServerRelationId },
{ "database", UserMappingRelationId },
{ "query", ForeignTableRelationId },
{ "table", ForeignTableRelationId },
{ "gl_datetime", ForeignTableRelationId },
{ "gl_date", ForeignTableRelationId },
{ "client_locale", ForeignTableRelationId },
{ "db_locale", ForeignTableRelationId },
{ "db_monetary", ForeignTableRelationId },
{ "db_locale", ForeignServerRelationId },
{ "db_monetary", ForeignServerRelationId },
{ "gl_datetime", ForeignServerRelationId },
{ "gl_date", ForeignServerRelationId },
{ "client_locale", ForeignServerRelationId },
{ "disable_predicate_pushdown", ForeignTableRelationId },
{ "disable_rowid", ForeignTableRelationId },
{ "enable_blobs", ForeignTableRelationId },
{ NULL, ForeignTableRelationId }
};
/*
* Data structure for intercall data
* used by ifxGetConnections().
*/
struct ifx_sp_call_data
{
HASH_SEQ_STATUS *hash_status;
TupleDesc tupdesc;
};
/*
* informix_fdw handler and validator function
*/
extern Datum ifx_fdw_handler(PG_FUNCTION_ARGS);
extern Datum ifx_fdw_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(ifx_fdw_handler);
PG_FUNCTION_INFO_V1(ifx_fdw_validator);
PG_FUNCTION_INFO_V1(ifxGetConnections);
PG_FUNCTION_INFO_V1(ifxCloseConnection);
#if PG_VERSION_NUM >= 120000
extern PGDLLIMPORT double cpu_tuple_cost;
#endif
/*******************************************************************************
* FDW internal macros
*/
#if PG_VERSION_NUM < 90200
#define PG_SCANSTATE_PRIVATE_P(a) \
(List *) (FdwPlan *)(((ForeignScan *)(a)->ss.ps.plan)->fdwplan)->fdw_private
#else
#define PG_SCANSTATE_PRIVATE_P(a) \
(List *) ((ForeignScan *)(a)->ss.ps.plan)->fdw_private
#endif
/*
* The following definitions vary between PostgreSQL releases.
* Thus we encapsulate them within macros, so we don't need to
# #ifdef the function itself...
*/
#if PG_VERSION_NUM < 90300
#define IFX_PGFDWAPI_SUBXACT_COMMIT SUBXACT_EVENT_COMMIT_SUB
#else
#define IFX_PGFDWAPI_SUBXACT_COMMIT SUBXACT_EVENT_PRE_COMMIT_SUB
#endif
#if PG_VERSION_NUM < 90400
#define IFX_SYSTABLE_SCAN_SNAPSHOT SnapshotNow
#else
#define IFX_SYSTABLE_SCAN_SNAPSHOT NULL
#endif
#if PG_VERSION_NUM >= 90500 && PG_VERSION_NUM < 160000
#define RTE_UPDATED_COLS(planInfo, resultRel, set) \
RangeTblEntry *rte = planner_rt_fetch((resultRel), (planInfo)); \
(set) = bms_copy(rte->updatedCols);
#define BMS_LOOKUP_COL(set, attnum) bms_first_member((set))
#elif PG_VERSION_NUM >= 160000
#define RTE_UPDATED_COLS(planInfo, resultRel, set) \
RelOptInfo *relInfo = find_base_rel((planInfo), (resultRel)); \
(set) = get_rel_all_updated_cols((planInfo), (relInfo));
#define BMS_LOOKUP_COL(set, attnum) bms_next_member((set), (attnum))
#else
#define RTE_UPDATED_COLS(planInfo, resultRel, set) \
RangeTblEntry *rte = planner_rt_fetch((resultRel), (planInfo)); \
(set) = bms_copy(rte->modifiedCols);
#define BMS_LOOKUP_COL(set, attnum) bms_first_member((set))
#endif
/*
* get_relid_attribute_name() is dead as of REL_11_STABLE
* (see commit 8237f27b504ff1d1e2da7ae4c81a7f72ea0e0e3e in the
* pg repository). Use get_attname() instead. Wrap this into a
* compatibility macro, to safe further ifdef's...
*/
#if PG_VERSION_NUM >= 110000
#define pg_attname_by_relid(relid, attnum, missing_ok) \
get_attname((relid), (attnum), (missing_ok))
#else
#define pg_attname_by_relid(relid, attnum, missing_ok) \
get_relid_attribute_name((relid), (attnum))
#endif
/*
* PostgreSQL 10 introduced TupleDescrAttr() to access
* attributes stored in a tuple descriptor. Use that instead
* of directly accessing the tupdesc attribute array, if available.
*
* CAUTION: This macro was introduced in backpatches
* in various major releases (e.g. with commit
* 5b286cae3cc1c43d6eedf6cf1181d41f653c6a93),
* so we make sure it's not defined yet.
*/
#if PG_VERSION_NUM < 100000
#ifndef TupleDescAttr
#define TupleDescAttr(desc, index) ((desc)->attrs[(index)])
#endif
#endif
#define TUPDESC_GET_ATTR(desc, index) \
TupleDescAttr((desc), (index))
/*******************************************************************************
* FDW helper functions.
*/
static void ifxSetupFdwScan(IfxConnectionInfo **coninfo,
IfxFdwExecutionState **state,
List **plan_values,
Oid foreignTableOid,
IfxForeignScanMode mode);
static IfxCachedConnection * ifxSetupConnection(IfxConnectionInfo **coninfo,
Oid foreignTableOid,
IfxForeignScanMode mode,
bool error_ok);
static IfxFdwExecutionState *makeIfxFdwExecutionState(int refid);
static StringInfoData *
ifxFdwOptionsToStringBuf(Oid context);
static bool
ifxIsValidOption(const char *option, Oid context);
static void
ifxGetOptions(Oid foreigntableOid, IfxConnectionInfo *coninfo);
static void ifxAssignOptions(IfxConnectionInfo *coninfo,
List *options,
bool mandatory[IFX_REQUIRED_CONN_KEYWORDS]);
static StringInfoData *
ifxGetDatabaseString(IfxConnectionInfo *coninfo);
static StringInfoData *
ifxGenerateConnName(IfxConnectionInfo *coninfo);
static char *
ifxGenStatementName(int stmt_id);
static char *
ifxGenDescrName(int descr_id);
static void
ifxGetOptionDups(IfxConnectionInfo *coninfo, DefElem *def);
static void ifxConnInfoSetDefaults(IfxConnectionInfo *coninfo);
static IfxConnectionInfo *ifxMakeConnectionInfo(Oid foreignTableOid);
static void ifxStatementInfoInit(IfxStatementInfo *info,
int refid);
static char *ifxGenCursorName(int curid);
static void ifxPgColumnData(Oid foreignTableOid, IfxFdwExecutionState *festate);
static IfxSqlStateClass
ifxCatchExceptions(IfxStatementInfo *state, unsigned short stackentry);
static inline void ifxPopCallstack(IfxStatementInfo *info,
unsigned short stackentry);
static inline void ifxPushCallstack(IfxStatementInfo *info,
unsigned short stackentry);
static void ifxColumnValueByAttNum(IfxFdwExecutionState *state, int attnum,
bool *isnull);
static void ifxPrepareCursorForScan(IfxStatementInfo *info,
IfxConnectionInfo *coninfo);
static char *ifxFilterQuals(PlannerInfo *planInfo,
RelOptInfo *baserel,
List **excl_restrictInfo,
Oid foreignTableOid);
static void ifxPrepareParamsForScan(IfxFdwExecutionState *state,
IfxConnectionInfo *coninfo);
static IfxSqlStateClass
ifxFetchTuple(IfxFdwExecutionState *state);
static void
ifxGetValuesFromTuple(IfxFdwExecutionState *state,
TupleTableSlot *tupleSlot);
static HeapTuple ifxFdwMakeTuple(IfxFdwExecutionState *state,
Relation rel,
ItemPointer encoded_rowid,
TupleTableSlot *slot);
static ItemPointer ifxGetRowIdForTuple(IfxFdwExecutionState *state);
__attribute__((unused)) static bool ifxCheckForAfterRowTriggers(Oid foreignTableOid,
IfxFdwExecutionState *state,
CmdType cmd);
#if PG_VERSION_NUM >= 90300
static void ifxRowIdValueToSqlda(IfxFdwExecutionState *state,
int paramId,
TupleTableSlot *planSlot);
static void ifxPrepareModifyQuery(IfxStatementInfo *info,
IfxConnectionInfo *coninfo,
CmdType operation);
static void ifxPrepareParamsForModify(IfxFdwExecutionState *state,
PlannerInfo *planInfo,
Index resultRelation,
ModifyTable *plan,
Oid foreignTableOid);
static void ifxColumnValuesToSqlda(IfxFdwExecutionState *state,
TupleTableSlot *slot,
int attnum);
static IfxFdwExecutionState *ifxCopyExecutionState(IfxFdwExecutionState *state);
static int
ifxIsForeignRelUpdatable(Relation rel);
static void
ifxExplainForeignModify(ModifyTableState *mstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
ExplainState *es);
#endif
#ifdef __USE_EDB_API__
#warning building with experimental EDB API support
static void ifx_fdw_xact_callback(XactEvent event, void *arg, bool spl_context);
static void ifx_fdw_subxact_callback(SubXactEvent event,
SubTransactionId subId,
SubTransactionId parentId,
void *arg,
bool spl_context);
#else
static void ifx_fdw_xact_callback(XactEvent event, void *arg);
static void ifx_fdw_subxact_callback(SubXactEvent event,
SubTransactionId subId,
SubTransactionId parentId,
void *arg);
#endif
static void ifx_fdw_xact_callback_internal(IfxCachedConnection *cached,
XactEvent event);
static int ifxXactFinalize(IfxCachedConnection *cached,
IfxXactAction action,
bool connection_error_ok);
#if PG_VERSION_NUM >= 90500
static void ifxGetForeignTableDetails(IfxConnectionInfo *coninfo,
IfxImportTableDef *tableDef,
int refid);
static List * ifxGetImportCandidates(ImportForeignSchemaStmt *stmt,
IfxConnectionInfo *coninfo,
Oid serverOid,
int refid);
static void ifxPrepareImport(ImportForeignSchemaStmt *stmt,
IfxConnectionInfo **coninfo,
Oid serveroid);
static void ifxGetImportOptions(ImportForeignSchemaStmt *stmt,
IfxConnectionInfo *coninfo,
Oid serveroid);
#endif
/*
* Shared Library initialization.
*/
void _PG_init(void);
/*******************************************************************************
* FDW callback routines.
*/
/*
* IMPORT FOREIGN SCHEMA starting with PostgreSQL 9.5
*/
#if PG_VERSION_NUM >= 90500
static List * ifxImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid);
#endif
/*
* Modifyable FDW API (Starting with PostgreSQL 9.3).
*/
#if PG_VERSION_NUM >= 90300
/*
* PG14 has changed the signature of AddForeignUpdateTargets() to a
* different argument list, so we need to do some additional
* version magic here, too.
*/
#if PG_VERSION_NUM < 140000
static void
ifxAddForeignUpdateTargets(Query *parsetree,
RangeTblEntry *target_rte,
Relation target_relation);
#else
static void
ifxAddForeignUpdateTargets(PlannerInfo *root,
Index rtindex,
RangeTblEntry *target_rte,
Relation target_relation);
#endif
static List *
ifxPlanForeignModify(PlannerInfo *root,
ModifyTable *plan,
Index resultRelation,
int subplan_index);
static void
ifxBeginForeignModify(ModifyTableState *mstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
int eflags);
static TupleTableSlot *
ifxExecForeignInsert(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *
ifxExecForeignDelete(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static TupleTableSlot *
ifxExecForeignUpdate(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
#endif
#if PG_VERSION_NUM >= 90200
static void ifxGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreignTableId);
static void ifxGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreignTableId);
static ForeignScan *ifxGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreignTableId,
ForeignPath *best_path,
List *tlist,
List *scan_clauses
#if PG_VERSION_NUM >= 90500
, Plan *outer_plan
#endif
);
static int
ifxAcquireSampleRows(Relation relation, int elevel, HeapTuple *rows,
int targrows, double *totalrows, double *totaldeadrows);
static bool
ifxAnalyzeForeignTable(Relation relation, AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
#else
static FdwPlan *ifxPlanForeignScan(Oid foreignTableOid,
PlannerInfo *planInfo,
RelOptInfo *baserel);
#endif
static void
ifxExplainForeignScan(ForeignScanState *node, ExplainState *es);
static void
ifxBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *ifxIterateForeignScan(ForeignScanState *node);
static void ifxReScanForeignScan(ForeignScanState *state);
static void ifxEndForeignScan(ForeignScanState *node);
static void ifxPrepareScan(IfxConnectionInfo *coninfo,
IfxFdwExecutionState *state);
/*******************************************************************************
* SQL status and helper functions.
*/
Datum
ifxGetConnections(PG_FUNCTION_ARGS);
Datum
ifxCloseConnection(PG_FUNCTION_ARGS);
/*******************************************************************************
* Implementation starts here
*/
#if PG_VERSION_NUM >= 90500
/*
* Prepare IMPORT FOREIGN SCHEMA command...
*/
static void ifxPrepareImport(ImportForeignSchemaStmt *stmt,
IfxConnectionInfo **coninfo,
Oid serveroid)
{
StringInfoData *buf;
/*
* Prepare the database connection. We can't use
* ifxMakeConnectionInfo(), since it makes all option
* parsing itself and requires a foreign table OID.
*/
*coninfo = (IfxConnectionInfo *) palloc(sizeof(IfxConnectionInfo));
memset((*coninfo)->conname, '\0', IFX_CONNAME_LEN + 1);
ifxConnInfoSetDefaults(*coninfo);
/*
* Read all options
*/
ifxGetImportOptions(stmt,
*coninfo,
serveroid);
/*
* Generate connection identifier.
*/
buf = ifxGenerateConnName(*coninfo);
strncpy((*coninfo)->conname, buf->data, IFX_CONNAME_LEN);
/*
* Generate connection DSN.
*/
buf = ifxGetDatabaseString(*coninfo);
(*coninfo)->dsn = pstrdup(buf->data);
}
/*
* Retrieve options for IMPORT FOREIGN SCHEMA
*/
static void ifxGetImportOptions(ImportForeignSchemaStmt *stmt,
IfxConnectionInfo *coninfo,
Oid serveroid)
{
ForeignServer *foreignServer;
UserMapping *userMap;
List *options;
int i;
bool mandatory[IFX_REQUIRED_CONN_KEYWORDS] = { false, false, false, false };
Assert(serveroid != InvalidOid);
foreignServer = GetForeignServer(serveroid);
userMap = GetUserMapping(GetUserId(), serveroid);
options = NIL;
options = list_concat(options, foreignServer->options);
options = list_concat(options, userMap->options);
options = list_concat(options, stmt->options);
ifxAssignOptions(coninfo, options, mandatory);
/*
* Check for all other mandatory options
*/
for (i = 0; i < IFX_REQUIRED_CONN_KEYWORDS; i++)
{
if (!mandatory[i])
ereport(ERROR, (errcode(ERRCODE_FDW_ERROR),
errmsg("missing required FDW options (informixserver, informixdir, client_locale, database)")));
}
}
/*
* Create an adhoc IfxStatementInfo structure with
* the given query. Describes, plans and executes the
* query with a cursor and returns a pointer to it.
*/
static IfxStatementInfo *ifxExecStmt(IfxConnectionInfo *coninfo,
int refid,
char *query)
{
IfxStatementInfo *stmtinfo = NULL;
/*
* No-op if query is not defined.
*/
if (query == NULL)
return stmtinfo;
/*
* Initialize a new statement info structure.
*/
stmtinfo = (IfxStatementInfo *) palloc(sizeof(IfxStatementInfo));
ifxStatementInfoInit(stmtinfo, refid);
/*
* Set query string and object idenfifiers required
* for preparing, describing and executing the query with
* a SCROLL cursor.
*/
stmtinfo->query = query;
ifxPrepareCursorForScan(stmtinfo, coninfo);
/*
* Populate the DESCRIPTOR area.
*/
ifxDescribeAllocatorByName(stmtinfo);
ifxCatchExceptions(stmtinfo, IFX_STACK_ALLOCATE | IFX_STACK_DESCRIBE);
/* Number of columns in the result set */
stmtinfo->ifxAttrCount = ifxDescriptorColumnCount(stmtinfo);
ifxCatchExceptions(stmtinfo, 0);
stmtinfo->ifxAttrDefs = palloc0(stmtinfo->ifxAttrCount
* sizeof(IfxAttrDef));
/* Populate result set column info array */
if ((stmtinfo->row_size = ifxGetColumnAttributes(stmtinfo)) == 0)
{
/* oops, no memory to allocate? Something surely went wrong,
* so abort */
ifxRewindCallstack(stmtinfo);
ereport(ERROR, (errcode(ERRCODE_FDW_ERROR),
errmsg("could not initialize informix column properties")));
}
/*
* Allocate memory for SQLVAR result array.
*/
stmtinfo->data = (char *) palloc0(stmtinfo->row_size);
stmtinfo->indicator = (short *) palloc0(sizeof(short)
* stmtinfo->ifxAttrCount);
/* Allocate memory within SQLDA structure */
ifxSetupDataBufferAligned(stmtinfo);
/* Finally open the cursor and we're done */
ifxOpenCursorForPrepared(stmtinfo);
ifxCatchExceptions(stmtinfo, IFX_STACK_OPEN);
return stmtinfo;
}
/*
* Get details for the given foreign table from the
* foreign server. Currently we retrieve column names,
* column types and NOT NULL constraints.
*/
static void ifxGetForeignTableDetails(IfxConnectionInfo *coninfo,
IfxImportTableDef *tableDef,
int refid)
{
IfxStatementInfo *stmtinfo;
stmtinfo = ifxExecStmt(coninfo, refid, ifxGetTableDetailsSQL(tableDef->tabid));
if (stmtinfo != NULL)
{
IfxSqlStateClass errclass;
/*
* Iterate through column list
*/
ifxFetchRowFromCursor(stmtinfo);
/* obtain error class to enter result set loop */
errclass = ifxCatchExceptions(stmtinfo, 0);
while (errclass == IFX_SUCCESS)
{
IfxAttrDef *colDef;
/*
* Get column information...
*/
colDef = (IfxAttrDef *) palloc0(sizeof(IfxAttrDef));
colDef->type = (IfxSourceType) ifxGetInt2(stmtinfo, 3);
colDef->len = (int) ifxGetInt2(stmtinfo, 4);
colDef->extended_id = (IfxExtendedType) ifxGetInt4(stmtinfo, 5);
/*
* We need to flag the import handler to remember
* any special column here. This is required to set certain
* options to the CREATE FOREIGN TABLE statement later, so
* that the table gets the correct settings (e.g. enable_blobs).
*/
switch (colDef->type)
{
case IFX_TEXT:
case IFX_BYTES:
tableDef->special_cols |= IFX_HAS_BLOBS;
break;
case IFX_LVARCHAR:
case IFX_BOOLEAN:
/*
* Not really used anywhere yet, but also remember
* any OPAQUE datatypes.
*/
tableDef->special_cols |= IFX_HAS_OPAQUE;
break;
default:
break;
}
/*
* Set the indicator value, this will
* define wether we need to create a NOT NULL constraint.
*/
if (ifxIsColumnNullable(colDef->type))
colDef->indicator = INDICATOR_NULL;
else
colDef->indicator = INDICATOR_NOT_NULL;
/*
* We need this identifier value to be persistent, so
* copy it. The cursor will move forward and reuse
* the column slot.
*/
colDef->name = pstrdup((char *) ifxGetText(stmtinfo, 2));
elog(DEBUG3, "column list for tabid \"%d\", name = \"%s\", type = \"%d\", null = \"%d\"",
tableDef->tabid, colDef->name,
ifxSQLType(colDef->type),
ifxIsColumnNullable(colDef->type));
/* ...and add 'em to the column list */
tableDef->columnDef = lappend(tableDef->columnDef, colDef);
/* next one and/or set loop abort condition */
ifxFetchRowFromCursor(stmtinfo);
errclass = ifxCatchExceptions(stmtinfo, 0);
}
/* ...and we're done. */
ifxRewindCallstack(stmtinfo);
}
}
/*
* Prepare a list of tables matching the import criteria.
*
* The returned List is either NIL if no import candidates
* are found or contains a list of pointers to
* IfxImportTableDef structures describing the table candidate.
*/
static List * ifxGetImportCandidates(ImportForeignSchemaStmt *stmt,
IfxConnectionInfo *coninfo,
Oid serverOid,
int refid)
{
List *result = NIL;
char *get_table_info;
IfxStatementInfo *stmtinfo;
Assert(coninfo != NULL);
get_table_info = ifxGetTableImportListSQL(coninfo, stmt);
stmtinfo = ifxExecStmt(coninfo, refid, get_table_info);
if (stmtinfo != NULL)
{
IfxSqlStateClass errclass;
/* Iterate through table list */
ifxFetchRowFromCursor(stmtinfo);
errclass = ifxCatchExceptions(stmtinfo, 0);
while (errclass == IFX_SUCCESS)
{
/*
* Extract tabid, table owner and table name from result set.
*/
IfxImportTableDef *tableDef;
/*
* Initialize an IfxImportTableDef structure.
*/
tableDef = (IfxImportTableDef *) palloc0(sizeof(IfxImportTableDef));
tableDef->tabid = ifxGetInt4(stmtinfo, 0);
tableDef->columnDef = NIL;
/*
* Initialize the table definition to explicitely *not*
* having any special columns. IfxGetForeignTableDetails() will
* set this property right away.
*/
tableDef->special_cols = IFX_NO_SPECIAL_COLS;
/*
* Since we need those identifier persistent, we must
* copy them, otherwise the cursor machinery will reuse
* them under us when moving the cursor forward.
*/
tableDef->tablename = pstrdup(ifxGetText(stmtinfo, 2));
tableDef->owner = pstrdup(ifxGetText(stmtinfo, 1));
elog(DEBUG3, "import candidates: tabid %d, table owner %s, table name %s",
tableDef->tabid,
ifxQuoteIdent(coninfo, tableDef->owner),
ifxQuoteIdent(coninfo, tableDef->tablename));
/*
* Retrieve table column list...
*/
ifxGetForeignTableDetails(coninfo,
tableDef,
++refid);
/*
* Push the new candidate relation to the list.
*/
result = lappend(result, tableDef);
/* next one */
ifxFetchRowFromCursor(stmtinfo);
errclass = ifxCatchExceptions(stmtinfo, 0);
}
/* ...we're done */
ifxRewindCallstack(stmtinfo);
}
return result;
}
/*
* Callback for IMPORT FOREIGN SCHEMA statement
*/
static List * ifxImportForeignSchema(ImportForeignSchemaStmt *stmt,
Oid serverOid)
{
List *result = NIL;
IfxConnectionInfo *coninfo = NULL;
IfxCachedConnection *cached;
/*
* Prepare connection for IMPORT FOREIGN SCHEMA.
*/
ifxPrepareImport(stmt, &coninfo, serverOid);
if ((cached = ifxSetupConnection(&coninfo,
InvalidOid,
IFX_IMPORT_SCHEMA,
true)) != NULL)
{
List *table_candidates = NIL;
ListCell *cell;
/*
* List of IfxImportTableDef definitions.
*/
table_candidates = ifxGetImportCandidates(stmt,
coninfo,
serverOid,
cached->con.usage);
foreach(cell, table_candidates)
{
IfxImportTableDef *def = (IfxImportTableDef *) lfirst(cell);
elog(DEBUG1, "extracted candidate: tabid = %d, tabname = %s",
def->tabid, def->tablename);
}
/*
* Generate the SQL script from candidates list.
*/
result = ifxCreateImportScript(coninfo, stmt, table_candidates, serverOid);
}
else
{
/*
* ifxSetupConnection() returned a NULL cache handle
* which shouldn't happen. Guard against this case and exit
* immediately.
*/
ereport(ERROR, (errcode(ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION),
errmsg("could not establish remote connection for server OID \"%u\"",
serverOid)));
}
return result;
}
#endif
#if PG_VERSION_NUM >= 90300
/*
* Set the given ROWID into the Informix
* SQLDA structure.
*/
static void ifxRowIdValueToSqlda(IfxFdwExecutionState *state,
int paramId,
TupleTableSlot *planSlot)
{
int rowid;
ItemPointer iptr;
bool isnull;
/*
* Fetch the current rowid from the resjunk column...
*/
iptr = (ItemPointer) DatumGetPointer(ExecGetJunkAttribute(planSlot,
state->rowid_attno,
&isnull));
/* Should be valid */
Assert(PointerIsValid(iptr));
if (isnull)
elog(ERROR, "informix_fdw: could not extract rowid");
/*
* Convert the ItemPointer back into a 4 Byte ROWID value
* for Informix. We can't rely on ItemPointerGetBlockNumber()
* since it will fail the Assertion for a given OffsetNumber
* otherwise.
*/
rowid = (int) ((iptr->ip_blkid.bi_hi << 16) | ((uint16) iptr->ip_blkid.bi_lo));
/*
* Mark the value valid, otherwise the conversion routine
* will give up immediately...
*/
IFX_SET_INDICATOR_P(state, paramId, INDICATOR_NOT_NULL);
/*
* ...let the conversion do its job.
*/
ifxSetInteger(&(state->stmt_info), paramId, rowid);
}
/*
* Extra information for EXPLAIN on a modify action.
*/
static void
ifxExplainForeignModify(ModifyTableState *mstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
ExplainState *es)
{
/*
* Get the current SQL and display it in the VERBOSE output
* of this EXPLAIN command.
*/
if (es->verbose)
{
IfxFdwExecutionState state;
/* Deserialize from list */
ifxDeserializeFdwData(&state, fdw_private);
/* Give some possibly useful info about the remote query used */
if (es->costs)
{
ExplainPropertyText("Informix query", state.stmt_info.query, es);
}
}
}
/*
* Determines wether a remote Informix table is updatable.
*
* The Informix FDW assumes that every relation is updatable, except
* a remote table was specified with the 'query' option.
*
* A foreign table might also reference a view on the remote
* Informix server, but we leave it up to the remote server
* to give an appropiate error message, if that remote view
* is not updatable.
*
* Additionally, we check wether the disable_rowid option was
* added to the foreign table, effectively disabling the property
* to uniquely identify a row required to do safe DML. Disallow
* UPDATE and DELETE in this case.
*/
static int
ifxIsForeignRelUpdatable(Relation rel)
{
ForeignTable *table;
bool updatable;
ListCell *lc;
elog(DEBUG3, "informix_fdw: foreign rel updatable");
table = GetForeignTable(RelationGetRelid(rel));
updatable = true;
foreach(lc, table->options)
{