-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathifx_utils.c
1208 lines (1040 loc) · 28.9 KB
/
ifx_utils.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_utils.c
* foreign-data wrapper for IBM INFORMIX databases
*
* Copyright (c) 2012, credativ GmbH
*
* IDENTIFICATION
* informix_fdw/ifx_utils.c
*
*-------------------------------------------------------------------------
*/
#include "ifx_fdw.h"
#include "ifx_node_utils.h"
#if PG_VERSION_NUM >= 90500
#include <access/htup_details.h>
#endif
#include <utils/syscache.h>
static void ifxFdwExecutionStateToList(Const *const_vals[],
IfxFdwExecutionState *state);
static Datum
ifxFdwPlanDataAsBytea(IfxConnectionInfo *coninfo);
#if PG_VERSION_NUM >= 90500
static char *ifxPgIntervalQualifierString(IfxTemporalRange range);
#endif
typedef struct ifxTemporalFormatIdent
{
char *_IFX;
char *_PG;
} ifxTemporalFormatIdent;
/*
* Defines various format strings to convert
* Informix temporal types.
*
* NOTE: NULL indicates that this position is currently
* unused, but to ease the access through ranges
* we still use the array indexes at this point.
* Any code iterating through this ident array must
* be aware of NULL dereferencing!
*/
static ifxTemporalFormatIdent ifxTemporalFormat[] =
{
{ "%Y", "YYYY" },
{ NULL, NULL },
{ "%m", "MM" },
{ NULL, NULL },
{ "%d", "DD" },
{ NULL, NULL},
{ "%H", "HH24" },
{ NULL, NULL },
{ "%M", "MI" },
{ NULL, NULL },
{ "%S", "SS" },
{ "%F", "MS" },
{ "%2F", "MS" },
{ "%3F", "MS" },
{ "%4F", "MS" },
{ "%5F", "MS" }
};
/*
* Maps DATETIME and INTERVAL qualifiers to
* PostgreSQL modifiers. The array index have to
* match the IFX_TU_* macros in ifx_type_compat.h.
*/
char *ifxPgTemporalQualifier[]
= {
"YEAR",
NULL,
"MONTH",
NULL,
"DAY",
NULL,
"HOUR",
NULL,
"MINUTE",
NULL,
"SECOND",
};
#define IFX_PG_INTRVL_FORMAT(ident, mode) \
(((mode) == FMT_PG) ? ifxTemporalFormat[(ident)]._PG \
: ifxTemporalFormat[(ident)]._IFX)
/*
* Deserialize data from fdw_private, passed
* from the planner via PlanForeignScan().
*
* This will initialize certain fields from
* data previously retrieved in ifxPlanForeignScan().
*/
void ifxDeserializeFdwData(IfxFdwExecutionState *state,
void *fdw_private)
{
List *params;
Assert(state != NULL);
params = (List *) fdw_private;
Assert(params != NIL);
state->stmt_info.query = ifxGetSerializedStringField(params,
SERIALIZED_QUERY);
state->stmt_info.cursor_name = ifxGetSerializedStringField(params,
SERIALIZED_CURSOR_NAME);
state->stmt_info.stmt_name = ifxGetSerializedStringField(params,
SERIALIZED_STMT_NAME);
state->stmt_info.call_stack = ifxGetSerializedInt16Field(params,
SERIALIZED_CALLSTACK);
state->stmt_info.predicate = ifxGetSerializedStringField(params,
SERIALIZED_QUALS);
state->stmt_info.cursorUsage = ifxGetSerializedInt32Field(params,
SERIALIZED_CURSOR_TYPE);
state->stmt_info.special_cols = ifxGetSerializedInt16Field(params,
SERIALIZED_SPECIAL_COLS);
state->stmt_info.refid = ifxGetSerializedInt32Field(params,
SERIALIZED_REFID);
state->use_rowid = ifxGetSerializedInt16Field(params,
SERIALIZED_USE_ROWID);
state->has_after_row_triggers = ifxGetSerializedInt16Field(params,
SERIALIZED_HAS_AFTER_TRIGGERS);
/*
* This has to be the last entry, see ifxSerializedPlanData()
* for details!
*/
state->affectedAttrNums = list_nth(params, AFFECTED_ATTR_NUMS_IDX);
}
/*
* Copies the plan data hold by the specified
* IfxConnectionInfo pointer into a bytea datum,
* suitable to be passed over by ifxSerializePlanData().
*/
static Datum
ifxFdwPlanDataAsBytea(IfxConnectionInfo *coninfo)
{
bytea *result;
result = (bytea *) palloc(sizeof(IfxPlanData) + VARHDRSZ);
SET_VARSIZE(result, sizeof(IfxPlanData));
memcpy(VARDATA(result), &(coninfo->planData), sizeof(IfxPlanData));
return PointerGetDatum(result);
}
/*
* Deserializes a IfxPlanData pointer from the
* given list of Const values. Suitable to be used to
* retrieve a IfxPlanData struct formerly serialized
* by ifxSerializePlanData().
*/
void
ifxDeserializePlanData(IfxPlanData *planData,
void *fdw_private)
{
Const *const_expr;
bytea *bvalue;
List *vals;
vals = (List *) fdw_private;
const_expr = (Const *) list_nth(vals, SERIALIZED_PLAN_DATA);
Assert((const_expr != NULL)
&& (planData != NULL)
&& (const_expr->consttype == BYTEAOID));
bvalue = DatumGetByteaP(const_expr->constvalue);
elog(DEBUG1, "deserialized planData %s\n, varsize %d",
nodeToString(const_expr),
VARSIZE(bvalue));
memcpy(planData, VARDATA(bvalue), sizeof(IfxPlanData));
}
/*
* Serialize the execution state into a list of
* Const nodes.
*
* We are going to ignore the sqlstate at this point, because
* (hopefully) we are done with all SQL stuff and checked
* for errors before calling this function.
*/
static void ifxFdwExecutionStateToList(Const *const_vals[],
IfxFdwExecutionState *state)
{
Assert(state != NULL);
const_vals[SERIALIZED_QUERY]
= makeFdwStringConst(state->stmt_info.query);
const_vals[SERIALIZED_STMT_NAME]
= makeFdwStringConst(state->stmt_info.stmt_name);
const_vals[SERIALIZED_CURSOR_NAME]
= makeFdwStringConst(state->stmt_info.cursor_name);
const_vals[SERIALIZED_CALLSTACK]
= makeFdwInt16Const(state->stmt_info.call_stack);
if (state->stmt_info.predicate != NULL)
const_vals[SERIALIZED_QUALS]
= makeFdwStringConst(state->stmt_info.predicate);
else
const_vals[SERIALIZED_QUALS]
= makeFdwStringConst("");
const_vals[SERIALIZED_CURSOR_TYPE]
= makeFdwInt32Const(state->stmt_info.cursorUsage);
const_vals[SERIALIZED_SPECIAL_COLS]
= makeFdwInt16Const(state->stmt_info.special_cols);
const_vals[SERIALIZED_REFID]
= makeFdwInt32Const(state->stmt_info.refid);
const_vals[SERIALIZED_USE_ROWID]
= makeFdwInt16Const(state->use_rowid);
const_vals[SERIALIZED_HAS_AFTER_TRIGGERS]
= makeFdwInt16Const(state->has_after_row_triggers);
}
/*
* Saves all necessary parameters from the specified structures
* into a list, suitable to pass it over from the planner
* to executor (thus it converts all values into expressions
* usable with copyObject() later on). This is required
* to save values across ifxPlanForeignScan() and
* ifxBeginForeignScan()...
*
* The current layout of the returned list is as follows:
*
* 1. Const with a bytea value, holding the binary representation
* of IfxPlanData struct
* 2. - 10. String or int fields of IfxFdwExecutionState, that are:
* query, stmt_name, cursor_name, ...
* 11. The last member is always the affectedAttrNums list from the
* state structure.
*
*/
List * ifxSerializePlanData(IfxConnectionInfo *coninfo,
IfxFdwExecutionState *state,
PlannerInfo *plan)
{
int i;
List *result;
MemoryContext old_cxt;
SERIALIZED_DATA(vals);
old_cxt = MemoryContextSwitchTo(plan->planner_cxt);
result = NIL;
/*
* Save the IfxPlanData struct, then
* serialize all fields from IfxFdwExecutionState.
*/
vals[SERIALIZED_PLAN_DATA] = makeConst(BYTEAOID, -1, InvalidOid, -1,
ifxFdwPlanDataAsBytea(coninfo),
false, false);
/*
* Save data from execution state into array.
*/
ifxFdwExecutionStateToList(vals, state);
/*
* Serialize values from Const array.
*/
for (i = 0; i < N_SERIALIZED_FIELDS; i++)
{
result = lappend(result, vals[i]);
}
/*
* ifxFdwExecutionStateToList() doesn't fold
* the affectedAttrNums list into the Const array, we
* need to address it separately here.
*
* NOTE:
*
* This should always be the last list member, since
* this makes it possible to address it via
* AFFECTED_ATTR_NUMS_IDX macro directly.
*/
result = lappend(result, state->affectedAttrNums);
MemoryContextSwitchTo(old_cxt);
return result;
}
char * ifxGetSerializedStringField(List *list, int ident)
{
Const *const_expr;
char *result;
const_expr = (Const *) list_nth(list, ident);
Assert(const_expr->consttype == TEXTOID);
result = text_to_cstring(DatumGetTextP(const_expr->constvalue));
return result;
}
int ifxGetSerializedInt32Field(List *list, int ident)
{
Const *const_expr;
int result;
const_expr = (Const *) list_nth(list, ident);
Assert(const_expr->consttype == INT4OID);
result = DatumGetInt32(const_expr->constvalue);
return result;
}
int16 ifxGetSerializedInt16Field(List *list, int ident)
{
Const *const_expr;
int16 result;
const_expr = (Const *) list_nth(list, ident);
Assert(const_expr->consttype == INT2OID);
result = DatumGetInt16(const_expr->constvalue);
return result;
}
Datum ifxSetSerializedInt32Field(List *list, int ident, int value)
{
Const *const_expr;
const_expr = (Const *) list_nth(list, ident);
Assert(const_expr->consttype == INT4OID);
const_expr->constvalue = Int32GetDatum(value);
return const_expr->constvalue;
}
Datum ifxSetSerializedInt16Field(List *list, int ident, int16 value)
{
Const *const_expr;
const_expr = (Const *) list_nth(list, ident);
Assert(const_expr->consttype = INT2OID);
const_expr->constvalue = Int16GetDatum(value);
return const_expr->constvalue;
}
/*
* Returns a format string for a given Interval
* qualifier range. This format string is suitable to be
* passed to ESQL/C format routines directly to convert
* a string formatted interval value back into its binary
* representation.
*
* In case the range qualifier of the given range value is
* out of the valid ranges an Informix interval value allows,
* NULL is returned.
*
* To summarize, the following interval ranges are supported
* currently:
*
* - TU_YEAR - TU_MONTH (gives YYYY-MM)
* - TU_DAY - TU_F1-5 (gives DD HH24:MIN:SS.FFFFF)
*
* ifxGetIntervalFromString() recognizes the precision of the
* given range as the lowest digit to be returned within the format
* string.
*/
char *ifxGetIntervalFormatString(IfxTemporalRange range, IfxFormatMode mode)
{
StringInfoData strbuf;
int i;
initStringInfo(&strbuf);
i = range.start;
while ((i <= range.end) && (i <= range.precision))
{
if (IFX_PG_INTRVL_FORMAT(i, mode) == NULL)
{
i++;
continue;
}
appendStringInfoString(&strbuf, IFX_PG_INTRVL_FORMAT(i, mode));
/* next one ... */
i++;
/*
* Append a correct filler character...if necessary ;)
*/
if ((i < range.end)
&& (i > range.start))
{
switch(i - 1)
{
case IFX_TU_MONTH:
case IFX_TU_YEAR:
appendStringInfoString(&strbuf, "-");
break;
case IFX_TU_DAY:
appendStringInfoString(&strbuf, " ");
break;
case IFX_TU_HOUR:
case IFX_TU_MINUTE:
appendStringInfoString(&strbuf, ":");
break;
case IFX_TU_SECOND:
/* must be fraction here */
appendStringInfoString(&strbuf, ".");
EXPLICIT_FALL_THROUGH;
case IFX_TU_F1:
case IFX_TU_F2:
case IFX_TU_F3:
case IFX_TU_F4:
case IFX_TU_F5:
/* abort since this is the lowest precision */
i = range.end;
break;
default:
break;
}
}
}
return strbuf.data;
}
#if PG_VERSION_NUM >= 90300
/*
* Generates a SQL statement for DELETE operation on a
* remote Informix table. Assumes the caller already
* had initialized the specified IfxFdwExecutionState
* and IfxConnectionInfo handles correctly.
*
* The generated query string will be stored into the
* specified execution state structure.
*/
void ifxGenerateDeleteSql(IfxFdwExecutionState *state,
IfxConnectionInfo *coninfo)
{
StringInfoData sql;
/* Sanity check */
Assert((state != NULL) && (coninfo != NULL)
&& (state->stmt_info.cursor_name != NULL)
&& (coninfo->tablename != NULL));
/*
* Generate the DELETE statement. Again, we use the underlying
* cursor from the remote scan to delete it's current tuple
* by using the CURRENT OF <cursor> syntax.
*/
initStringInfo(&sql);
appendStringInfo(&sql, "DELETE FROM %s",
coninfo->tablename);
/*
* We need to append the WHERE expression, but we
* need to distinguish between using a ROWID to identify
* the remote target tuple or (if disable_rowid was specified)
* the name of the updatable cursor.
*/
if (coninfo->disable_rowid)
appendStringInfo(&sql, " WHERE CURRENT OF %s",
state->stmt_info.cursor_name);
else
appendStringInfo(&sql, " WHERE rowid = ?");
state->stmt_info.query = sql.data;
}
/*
* Generates a SQL statement for UPDATE operation on a
* remote Informix table. Assumes the caller already
* had initialized the specified IfxFdwExecutionState and
* IfxConnectionInfo handles correctly.
*
* The generated query string will be stored into the
* specified execution state structure.
*/
void ifxGenerateUpdateSql(IfxFdwExecutionState *state,
IfxConnectionInfo *coninfo,
PlannerInfo *root,
Index rtindex)
{
StringInfoData sql;
bool first;
ListCell *cell;
/* Sanity checks */
Assert((state != NULL)
&& (coninfo != NULL)
&& (coninfo->tablename != NULL));
if (state->affectedAttrNums == NIL)
elog(ERROR, "empty column list for foreign table");
initStringInfo(&sql);
appendStringInfo(&sql, "UPDATE %s SET ", coninfo->tablename);
/*
* Dispatch list of attributes numbers to their
* corresponding identifiers.
*
* It is important to keep this list consistent
* to the same order we receive all affected rows from
* the local modify command. Otherwise we get into trouble.
*/
first = true;
foreach(cell, state->affectedAttrNums)
{
int attnum = lfirst_int(cell);
if (!first)
appendStringInfoString(&sql, ", ");
first = false;
appendStringInfoString(&sql,
dispatchColumnIdentifier(rtindex, attnum, root));
appendStringInfoString(&sql, " = ? ");
}
/*
* Finally the WHERE condition needs to be added.
*
* Per default we use the ROWID to identify the remote tuple for the
* UPDATE target, but we might also fallback to an updatable cursor
* if disable_rowid was passed to the table.
*/
if (coninfo->disable_rowid)
appendStringInfo(&sql, "WHERE CURRENT OF %s", state->stmt_info.cursor_name);
else
appendStringInfo(&sql, "WHERE rowid = ?");
/*
* And we're done.
*/
state->stmt_info.query = sql.data;
}
/*
* Generates a SQL statement for INSERT action on a
* remote Informix table. Assumes the caller already
* had initialized the specified IfxFdwExecutionState and
* IfxConnectionInfo handles correctly.
*
* The generated query string will be stored into the
* specified execution state structure.
*/
void ifxGenerateInsertSql(IfxFdwExecutionState *state,
IfxConnectionInfo *coninfo,
PlannerInfo *root,
Index rtindex)
{
StringInfoData sql;
ListCell *cell;
bool first;
int i;
Assert(state != NULL);
Assert((coninfo != NULL) && (coninfo->tablename));
if (state->affectedAttrNums == NIL)
elog(ERROR, "empty column list for foreign table");
initStringInfo(&sql);
appendStringInfoString(&sql, "INSERT INTO ");
/*
* Execution state already carries the table name...
*
*/
appendStringInfoString(&sql, coninfo->tablename);
appendStringInfoString(&sql, "(");
/*
* Dispatch list of attributes numbers to their
* corresponding identifiers.
*/
first = true;
foreach(cell, state->affectedAttrNums)
{
int attnum = lfirst_int(cell);
if (!first)
appendStringInfoString(&sql, ", ");
first = false;
appendStringInfoString(&sql,
dispatchColumnIdentifier(rtindex, attnum, root));
}
appendStringInfoString(&sql, ") VALUES(");
/*
* Create a list of question marks suitable to be passed
* for PREPARE...
*/
first = true;
for(i = 0; i < list_length(state->affectedAttrNums); i++)
{
if (!first)
appendStringInfoString(&sql, ", ");
first = false;
appendStringInfoString(&sql, "?");
}
appendStringInfoString(&sql, ")");
state->stmt_info.query = sql.data;
}
#endif
/*
* If the specified connection handle was initialized
* with DELIMIDENT, ifxQuoteIdent() will return a quoted
* identifier.
*
* NOTE: if DELIMIDENT is *not* set, ifxQuoteIdent() will
* return the same unmodified pointer for ident!
*/
char *ifxQuoteIdent(IfxConnectionInfo *coninfo, char *ident)
{
if (coninfo->delimident == 0)
return ident;
else
{
StringInfoData buf;
initStringInfo(&buf);
appendStringInfo(&buf, "\"%s\"", ident);
return buf.data;
}
}
#if PG_VERSION_NUM >= 90500
/*
* Given an informix INTERVAL range definition, return
* a possible matching declaration for PostgreSQL.
*
* Not all declarations from Informix do have a matching
* declaration in PostgreSQL. If an INTERVAL range in Informix
* doesn't correspond to a compatible declaration in PostgreSQL,
* we just return an empty string, which indicates that the given
* temporal range doesn't have an equivalent.
*/
static char *ifxPgIntervalQualifierString(IfxTemporalRange range)
{
int i_start = range.start;
int i_end = -1; /* indicates empty qualifier string! */
StringInfoData buf;
/*
* Check if the specified range is valid and supported.
*
* Currently supported *ranges* in PostgreSQL are
*
* YEAR TO MONTH
*
* DAY TO HOUR
* DAY TO MINUTE
* DAY TO SECOND
*
* HOUR TO MINUTE
* HOUR TO SECOND
*
* MINUTE TO SECOND
*
* So it's enough to look at YEAR, DAY, HOUR and MINUTE to
* determine any possible range declarations. If start and end define
* just a single entity, we return that instead.
*/
if (((range.start % 2) > 0)
|| ((range.end %2) > 0))
return "";
if (range.start == range.end)
return ifxPgTemporalQualifier[range.start];
initStringInfo(&buf);
switch(range.start)
{
case IFX_TU_YEAR:
i_end = (range.end == IFX_TU_MONTH) ? range.end : -1;
break;
case IFX_TU_DAY:
case IFX_TU_HOUR:
if (range.end >= IFX_TU_SECOND)
i_end = (range.end - (range.end % IFX_TU_SECOND));
else
i_end = range.end;
break;
case IFX_TU_MINUTE:
/* only remaining range is MINUTE TO SECOND */
i_end = ((range.end - (range.end % IFX_TU_SECOND)) == IFX_TU_SECOND)
? range.end : -1;
break;
default:
i_end = -1;
}
if (i_end != -1)
appendStringInfo(&buf, "%s TO %s",
ifxPgTemporalQualifier[i_start],
ifxPgTemporalQualifier[i_end]);
return buf.data;
}
char *ifxMakeColTypeDeclaration(IfxAttrDef *colDef)
{
HeapTuple ht;
Oid targetTypeId;
StringInfoData buf;
/*
* Lookup the matching PostgreSQL TYPEOID.
*/
targetTypeId = ifxTypeidToPg(ifxMaskTypeId(colDef->type),
colDef->extended_id);
if (targetTypeId == InvalidOid)
elog(ERROR, "could not convert informix type \"%d\"",
ifxMaskTypeId(colDef->type));
initStringInfo(&buf);
ht = SearchSysCache1(TYPEOID, ObjectIdGetDatum(targetTypeId));
if (HeapTupleIsValid(ht))
{
Form_pg_type typetup = (Form_pg_type) GETSTRUCT(ht);
char *typname;
short min_len; /* min_len is not used in PostgreSQL column declarations */
short max_len;
/*
* Copy the typename.
*/
typname = pstrdup(NameStr(typetup->typname));
/*
* Lookup typmods, but don't encode them.
*/
ifxDecodeColumnLength(colDef->type,
colDef->len,
&min_len,
&max_len);
elog(DEBUG5, "typename=%s, min=%d, max=%d",
typname, min_len, max_len);
if (((min_len > 0) && (max_len > 0))
|| ((colDef->type == IFX_DTIME)
|| (colDef->type == IFX_INTERVAL)))
{
/* Probably an encoded VARCHAR type with
* minimum and maximum length ? */
if (ifxCharColumnLen(colDef->type, colDef->len) > 0)
appendStringInfo(&buf, "%s(%d)", typname, max_len);
else
{
/*
* We must handle DATETIME and INTERVAL in case
* they have special qualifiers.
*/
switch (colDef->type)
{
case IFX_DTIME:
{
/*
* In case there's a FRACTION attached to the Informix
* DATETIME value, we try to match it to the PostgreSQL
* timestamp as well.
*/
if ((max_len - (max_len % IFX_TU_SECOND)) >= IFX_TU_SECOND)
{
appendStringInfo(&buf, "%s(%d)",
typname,
max_len - IFX_TU_SECOND);
}
else
{
appendStringInfo(&buf, "%s",
typname);
}
break;
}
case IFX_INTERVAL:
{
IfxTemporalRange range;
char *intv_qual;
range.start = min_len;
range.end = max_len;
range.precision = IFX_TU_SECOND;
intv_qual = ifxPgIntervalQualifierString(range);
if (range.end >= IFX_TU_SECOND)
{
/*
* This INTERVAL has a fraction value assigned.
*/
appendStringInfo(&buf, "%s %s(%d)",
typname, intv_qual,
range.end - IFX_TU_SECOND);
}
else
{
appendStringInfo(&buf, "%s %s",
typname, intv_qual);
}
break;
}
default:
appendStringInfoString(&buf, typname);
break;
}
}
}
else if ((min_len == 0) && (max_len > 0))
{
/*
* Probably a character string column type with
* an upper limit?
*/
if (ifxCharColumnLen(colDef->type, colDef->len) > 0)
appendStringInfo(&buf, "%s(%d)",
typname, max_len);
else
appendStringInfoString(&buf, typname);
}
else
{
appendStringInfoString(&buf, typname);
}
/*
* Define a NOT NULL constraint if required.
*/
if (colDef->indicator == INDICATOR_NOT_NULL)
appendStringInfoString(&buf, " NOT NULL");
/* ...and we're done */
ReleaseSysCache(ht);
}
return buf.data;
}
/*
* Map Informix type ids to PostgreSQL OID types.
*
* This merely is a suggestion what we think an Informix type
* maps at its best to a builtin PostgreSQL type.
*/
Oid ifxTypeidToPg(IfxSourceType typid, IfxExtendedType extended_id)
{
Oid mappedOid = InvalidOid;
switch (typid)
{
case IFX_TEXT:
mappedOid = TEXTOID;
break;
case IFX_CHARACTER:
mappedOid = BPCHAROID;
break;
case IFX_SMALLINT:
mappedOid = INT2OID;
break;
case IFX_SERIAL:
case IFX_INTEGER:
mappedOid = INT4OID;
break;
case IFX_FLOAT:
mappedOid = FLOAT8OID;
break;
case IFX_SMFLOAT:
mappedOid = FLOAT4OID;
break;
case IFX_MONEY:
case IFX_DECIMAL:
mappedOid = NUMERICOID;
break;
case IFX_DATE:
mappedOid = DATEOID;
break;
case IFX_DTIME:
mappedOid = TIMESTAMPOID;
break;
case IFX_BYTES:
mappedOid = BYTEAOID;
break;
case IFX_VCHAR:
mappedOid = VARCHAROID;
break;
case IFX_INTERVAL:
mappedOid = INTERVALOID;
break;
case IFX_NCHAR:
case IFX_NVCHAR:
case IFX_LVARCHAR:
mappedOid = TEXTOID;
break;
case IFX_INT8:
case IFX_SERIAL8:
case IFX_INFX_INT8:
case IFX_BIGSERIAL:
mappedOid = INT8OID;
break;
case IFX_BOOLEAN:
mappedOid = BOOLOID;
break;
case IFX_UDTVAR:
/*
* This is only a BE visible opaque type id
* indicating a variable length user defined (built-in)
* data type, like LVARCHAR. The conversion routines
* usually won't see this typeid, since ESQL/C would
* have transferred a defined FE typeid for this (like
* SQLLVARCHAR). Assume a TEXTOID column as the right target
* for this.
*
* This might not work for all cases, but for now and according
* to
*
* http://www-01.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.sqlr.doc/ids_sqr_026.htm
*
* LVARCHAR is the only pre-defined candidate so far (IFX_XTD_LVARCHAR).
* The external representation of a variable length type is a character
* string anyways, so always convert them to TEXT (others won't likely
* be suitable anyways).
*/
mappedOid = TEXTOID;
break;
case IFX_UDTFIXED:
/*
* FIXED user-defined types are special, since we have multiple types
* fitting this category according to $INFORMIXDIR/incl/esql/sqltypes.h.
* These are
*
* BOOLEAN, BLOB and CLOB.
*
* Those are distinguished by the sysxtdtypes system catalog via referencing
* them by syscolumns.extended_id.
*/
switch (extended_id)
{
case IFX_XTD_BOOLEAN:
mappedOid = BOOLOID;
break;
case IFX_XTD_BLOB:
case IFX_XTD_CLOB:
mappedOid = BYTEAOID;
break;
default:
break;
}
break;
/*
* The following types aren't handled right now.
* Return InvalidOid in this case.
*/
case IFX_NULL:
case IFX_SET:
case IFX_MULTISET:
case IFX_LIST:
case IFX_ROW:
case IFX_COLLECTION:
case IFX_ROWREF: