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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
|
/*------------------------------------------------------------------------
*
* regress.c
* Code for various C-language functions defined as part of the
* regression tests.
*
* This code is released under the terms of the PostgreSQL License.
*
* Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/test/regress/regress.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <math.h>
#include <signal.h>
#include "access/detoast.h"
#include "access/htup_details.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "commands/sequence.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/supportnodes.h"
#include "optimizer/optimizer.h"
#include "optimizer/plancat.h"
#include "parser/parse_coerce.h"
#include "port/atomics.h"
#include "storage/spin.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/geo_decls.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/typcache.h"
#define EXPECT_TRUE(expr) \
do { \
if (!(expr)) \
elog(ERROR, \
"%s was unexpectedly false in file \"%s\" line %u", \
#expr, __FILE__, __LINE__); \
} while (0)
#define EXPECT_EQ_U32(result_expr, expected_expr) \
do { \
uint32 actual_result = (result_expr); \
uint32 expected_result = (expected_expr); \
if (actual_result != expected_result) \
elog(ERROR, \
"%s yielded %u, expected %s in file \"%s\" line %u", \
#result_expr, actual_result, #expected_expr, __FILE__, __LINE__); \
} while (0)
#define EXPECT_EQ_U64(result_expr, expected_expr) \
do { \
uint64 actual_result = (result_expr); \
uint64 expected_result = (expected_expr); \
if (actual_result != expected_result) \
elog(ERROR, \
"%s yielded " UINT64_FORMAT ", expected %s in file \"%s\" line %u", \
#result_expr, actual_result, #expected_expr, __FILE__, __LINE__); \
} while (0)
#define LDELIM '('
#define RDELIM ')'
#define DELIM ','
static void regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2);
PG_MODULE_MAGIC;
/* return the point where two paths intersect, or NULL if no intersection. */
PG_FUNCTION_INFO_V1(interpt_pp);
Datum
interpt_pp(PG_FUNCTION_ARGS)
{
PATH *p1 = PG_GETARG_PATH_P(0);
PATH *p2 = PG_GETARG_PATH_P(1);
int i,
j;
LSEG seg1,
seg2;
bool found; /* We've found the intersection */
found = false; /* Haven't found it yet */
for (i = 0; i < p1->npts - 1 && !found; i++)
{
regress_lseg_construct(&seg1, &p1->p[i], &p1->p[i + 1]);
for (j = 0; j < p2->npts - 1 && !found; j++)
{
regress_lseg_construct(&seg2, &p2->p[j], &p2->p[j + 1]);
if (DatumGetBool(DirectFunctionCall2(lseg_intersect,
LsegPGetDatum(&seg1),
LsegPGetDatum(&seg2))))
found = true;
}
}
if (!found)
PG_RETURN_NULL();
/*
* Note: DirectFunctionCall2 will kick out an error if lseg_interpt()
* returns NULL, but that should be impossible since we know the two
* segments intersect.
*/
PG_RETURN_DATUM(DirectFunctionCall2(lseg_interpt,
LsegPGetDatum(&seg1),
LsegPGetDatum(&seg2)));
}
/* like lseg_construct, but assume space already allocated */
static void
regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2)
{
lseg->p[0].x = pt1->x;
lseg->p[0].y = pt1->y;
lseg->p[1].x = pt2->x;
lseg->p[1].y = pt2->y;
}
PG_FUNCTION_INFO_V1(overpaid);
Datum
overpaid(PG_FUNCTION_ARGS)
{
HeapTupleHeader tuple = PG_GETARG_HEAPTUPLEHEADER(0);
bool isnull;
int32 salary;
salary = DatumGetInt32(GetAttributeByName(tuple, "salary", &isnull));
if (isnull)
PG_RETURN_NULL();
PG_RETURN_BOOL(salary > 699);
}
/* New type "widget"
* This used to be "circle", but I added circle to builtins,
* so needed to make sure the names do not collide. - tgl 97/04/21
*/
typedef struct
{
Point center;
double radius;
} WIDGET;
PG_FUNCTION_INFO_V1(widget_in);
PG_FUNCTION_INFO_V1(widget_out);
#define NARGS 3
Datum
widget_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
char *p,
*coord[NARGS];
int i;
WIDGET *result;
for (i = 0, p = str; *p && i < NARGS && *p != RDELIM; p++)
{
if (*p == DELIM || (*p == LDELIM && i == 0))
coord[i++] = p + 1;
}
/*
* Note: DON'T convert this error to "soft" style (errsave/ereturn). We
* want this data type to stay permanently in the hard-error world so that
* it can be used for testing that such cases still work reasonably.
*/
if (i < NARGS)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type %s: \"%s\"",
"widget", str)));
result = (WIDGET *) palloc(sizeof(WIDGET));
result->center.x = atof(coord[0]);
result->center.y = atof(coord[1]);
result->radius = atof(coord[2]);
PG_RETURN_POINTER(result);
}
Datum
widget_out(PG_FUNCTION_ARGS)
{
WIDGET *widget = (WIDGET *) PG_GETARG_POINTER(0);
char *str = psprintf("(%g,%g,%g)",
widget->center.x, widget->center.y, widget->radius);
PG_RETURN_CSTRING(str);
}
PG_FUNCTION_INFO_V1(pt_in_widget);
Datum
pt_in_widget(PG_FUNCTION_ARGS)
{
Point *point = PG_GETARG_POINT_P(0);
WIDGET *widget = (WIDGET *) PG_GETARG_POINTER(1);
float8 distance;
distance = DatumGetFloat8(DirectFunctionCall2(point_distance,
PointPGetDatum(point),
PointPGetDatum(&widget->center)));
PG_RETURN_BOOL(distance < widget->radius);
}
PG_FUNCTION_INFO_V1(reverse_name);
Datum
reverse_name(PG_FUNCTION_ARGS)
{
char *string = PG_GETARG_CSTRING(0);
int i;
int len;
char *new_string;
new_string = palloc0(NAMEDATALEN);
for (i = 0; i < NAMEDATALEN && string[i]; ++i)
;
if (i == NAMEDATALEN || !string[i])
--i;
len = i;
for (; i >= 0; --i)
new_string[len - i] = string[i];
PG_RETURN_CSTRING(new_string);
}
PG_FUNCTION_INFO_V1(trigger_return_old);
Datum
trigger_return_old(PG_FUNCTION_ARGS)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
HeapTuple tuple;
if (!CALLED_AS_TRIGGER(fcinfo))
elog(ERROR, "trigger_return_old: not fired by trigger manager");
tuple = trigdata->tg_trigtuple;
return PointerGetDatum(tuple);
}
#define TTDUMMY_INFINITY 999999
static SPIPlanPtr splan = NULL;
static bool ttoff = false;
PG_FUNCTION_INFO_V1(ttdummy);
Datum
ttdummy(PG_FUNCTION_ARGS)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
Trigger *trigger; /* to get trigger name */
char **args; /* arguments */
int attnum[2]; /* fnumbers of start/stop columns */
Datum oldon,
oldoff;
Datum newon,
newoff;
Datum *cvals; /* column values */
char *cnulls; /* column nulls */
char *relname; /* triggered relation name */
Relation rel; /* triggered relation */
HeapTuple trigtuple;
HeapTuple newtuple = NULL;
HeapTuple rettuple;
TupleDesc tupdesc; /* tuple description */
int natts; /* # of attributes */
bool isnull; /* to know is some column NULL or not */
int ret;
int i;
if (!CALLED_AS_TRIGGER(fcinfo))
elog(ERROR, "ttdummy: not fired by trigger manager");
if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "ttdummy: must be fired for row");
if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
elog(ERROR, "ttdummy: must be fired before event");
if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
elog(ERROR, "ttdummy: cannot process INSERT event");
if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
newtuple = trigdata->tg_newtuple;
trigtuple = trigdata->tg_trigtuple;
rel = trigdata->tg_relation;
relname = SPI_getrelname(rel);
/* check if TT is OFF for this relation */
if (ttoff) /* OFF - nothing to do */
{
pfree(relname);
return PointerGetDatum((newtuple != NULL) ? newtuple : trigtuple);
}
trigger = trigdata->tg_trigger;
if (trigger->tgnargs != 2)
elog(ERROR, "ttdummy (%s): invalid (!= 2) number of arguments %d",
relname, trigger->tgnargs);
args = trigger->tgargs;
tupdesc = rel->rd_att;
natts = tupdesc->natts;
for (i = 0; i < 2; i++)
{
attnum[i] = SPI_fnumber(tupdesc, args[i]);
if (attnum[i] <= 0)
elog(ERROR, "ttdummy (%s): there is no attribute %s",
relname, args[i]);
if (SPI_gettypeid(tupdesc, attnum[i]) != INT4OID)
elog(ERROR, "ttdummy (%s): attribute %s must be of integer type",
relname, args[i]);
}
oldon = SPI_getbinval(trigtuple, tupdesc, attnum[0], &isnull);
if (isnull)
elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[0]);
oldoff = SPI_getbinval(trigtuple, tupdesc, attnum[1], &isnull);
if (isnull)
elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[1]);
if (newtuple != NULL) /* UPDATE */
{
newon = SPI_getbinval(newtuple, tupdesc, attnum[0], &isnull);
if (isnull)
elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[0]);
newoff = SPI_getbinval(newtuple, tupdesc, attnum[1], &isnull);
if (isnull)
elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[1]);
if (oldon != newon || oldoff != newoff)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("ttdummy (%s): you cannot change %s and/or %s columns (use set_ttdummy)",
relname, args[0], args[1])));
if (newoff != TTDUMMY_INFINITY)
{
pfree(relname); /* allocated in upper executor context */
return PointerGetDatum(NULL);
}
}
else if (oldoff != TTDUMMY_INFINITY) /* DELETE */
{
pfree(relname);
return PointerGetDatum(NULL);
}
newoff = DirectFunctionCall1(nextval, CStringGetTextDatum("ttdummy_seq"));
/* nextval now returns int64; coerce down to int32 */
newoff = Int32GetDatum((int32) DatumGetInt64(newoff));
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
elog(ERROR, "ttdummy (%s): SPI_connect returned %d", relname, ret);
/* Fetch tuple values and nulls */
cvals = (Datum *) palloc(natts * sizeof(Datum));
cnulls = (char *) palloc(natts * sizeof(char));
for (i = 0; i < natts; i++)
{
cvals[i] = SPI_getbinval((newtuple != NULL) ? newtuple : trigtuple,
tupdesc, i + 1, &isnull);
cnulls[i] = (isnull) ? 'n' : ' ';
}
/* change date column(s) */
if (newtuple) /* UPDATE */
{
cvals[attnum[0] - 1] = newoff; /* start_date eq current date */
cnulls[attnum[0] - 1] = ' ';
cvals[attnum[1] - 1] = TTDUMMY_INFINITY; /* stop_date eq INFINITY */
cnulls[attnum[1] - 1] = ' ';
}
else
/* DELETE */
{
cvals[attnum[1] - 1] = newoff; /* stop_date eq current date */
cnulls[attnum[1] - 1] = ' ';
}
/* if there is no plan ... */
if (splan == NULL)
{
SPIPlanPtr pplan;
Oid *ctypes;
char *query;
/* allocate space in preparation */
ctypes = (Oid *) palloc(natts * sizeof(Oid));
query = (char *) palloc(100 + 16 * natts);
/*
* Construct query: INSERT INTO _relation_ VALUES ($1, ...)
*/
sprintf(query, "INSERT INTO %s VALUES (", relname);
for (i = 1; i <= natts; i++)
{
sprintf(query + strlen(query), "$%d%s",
i, (i < natts) ? ", " : ")");
ctypes[i - 1] = SPI_gettypeid(tupdesc, i);
}
/* Prepare plan for query */
pplan = SPI_prepare(query, natts, ctypes);
if (pplan == NULL)
elog(ERROR, "ttdummy (%s): SPI_prepare returned %s", relname, SPI_result_code_string(SPI_result));
if (SPI_keepplan(pplan))
elog(ERROR, "ttdummy (%s): SPI_keepplan failed", relname);
splan = pplan;
}
ret = SPI_execp(splan, cvals, cnulls, 0);
if (ret < 0)
elog(ERROR, "ttdummy (%s): SPI_execp returned %d", relname, ret);
/* Tuple to return to upper Executor ... */
if (newtuple) /* UPDATE */
rettuple = SPI_modifytuple(rel, trigtuple, 1, &(attnum[1]), &newoff, NULL);
else /* DELETE */
rettuple = trigtuple;
SPI_finish(); /* don't forget say Bye to SPI mgr */
pfree(relname);
return PointerGetDatum(rettuple);
}
PG_FUNCTION_INFO_V1(set_ttdummy);
Datum
set_ttdummy(PG_FUNCTION_ARGS)
{
int32 on = PG_GETARG_INT32(0);
if (ttoff) /* OFF currently */
{
if (on == 0)
PG_RETURN_INT32(0);
/* turn ON */
ttoff = false;
PG_RETURN_INT32(0);
}
/* ON currently */
if (on != 0)
PG_RETURN_INT32(1);
/* turn OFF */
ttoff = true;
PG_RETURN_INT32(1);
}
/*
* Type int44 has no real-world use, but the regression tests use it
* (under the alias "city_budget"). It's a four-element vector of int4's.
*/
/*
* int44in - converts "num, num, ..." to internal form
*
* Note: Fills any missing positions with zeroes.
*/
PG_FUNCTION_INFO_V1(int44in);
Datum
int44in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
int32 *result = (int32 *) palloc(4 * sizeof(int32));
int i;
i = sscanf(input_string,
"%d, %d, %d, %d",
&result[0],
&result[1],
&result[2],
&result[3]);
while (i < 4)
result[i++] = 0;
PG_RETURN_POINTER(result);
}
/*
* int44out - converts internal form to "num, num, ..."
*/
PG_FUNCTION_INFO_V1(int44out);
Datum
int44out(PG_FUNCTION_ARGS)
{
int32 *an_array = (int32 *) PG_GETARG_POINTER(0);
char *result = (char *) palloc(16 * 4);
snprintf(result, 16 * 4, "%d,%d,%d,%d",
an_array[0],
an_array[1],
an_array[2],
an_array[3]);
PG_RETURN_CSTRING(result);
}
PG_FUNCTION_INFO_V1(test_canonicalize_path);
Datum
test_canonicalize_path(PG_FUNCTION_ARGS)
{
char *path = text_to_cstring(PG_GETARG_TEXT_PP(0));
canonicalize_path(path);
PG_RETURN_TEXT_P(cstring_to_text(path));
}
PG_FUNCTION_INFO_V1(make_tuple_indirect);
Datum
make_tuple_indirect(PG_FUNCTION_ARGS)
{
HeapTupleHeader rec = PG_GETARG_HEAPTUPLEHEADER(0);
HeapTupleData tuple;
int ncolumns;
Datum *values;
bool *nulls;
Oid tupType;
int32 tupTypmod;
TupleDesc tupdesc;
HeapTuple newtup;
int i;
MemoryContext old_context;
/* Extract type info from the tuple itself */
tupType = HeapTupleHeaderGetTypeId(rec);
tupTypmod = HeapTupleHeaderGetTypMod(rec);
tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
ncolumns = tupdesc->natts;
/* Build a temporary HeapTuple control structure */
tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = rec;
values = (Datum *) palloc(ncolumns * sizeof(Datum));
nulls = (bool *) palloc(ncolumns * sizeof(bool));
heap_deform_tuple(&tuple, tupdesc, values, nulls);
old_context = MemoryContextSwitchTo(TopTransactionContext);
for (i = 0; i < ncolumns; i++)
{
struct varlena *attr;
struct varlena *new_attr;
struct varatt_indirect redirect_pointer;
/* only work on existing, not-null varlenas */
if (TupleDescAttr(tupdesc, i)->attisdropped ||
nulls[i] ||
TupleDescAttr(tupdesc, i)->attlen != -1)
continue;
attr = (struct varlena *) DatumGetPointer(values[i]);
/* don't recursively indirect */
if (VARATT_IS_EXTERNAL_INDIRECT(attr))
continue;
/* copy datum, so it still lives later */
if (VARATT_IS_EXTERNAL_ONDISK(attr))
attr = detoast_external_attr(attr);
else
{
struct varlena *oldattr = attr;
attr = palloc0(VARSIZE_ANY(oldattr));
memcpy(attr, oldattr, VARSIZE_ANY(oldattr));
}
/* build indirection Datum */
new_attr = (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
redirect_pointer.pointer = attr;
SET_VARTAG_EXTERNAL(new_attr, VARTAG_INDIRECT);
memcpy(VARDATA_EXTERNAL(new_attr), &redirect_pointer,
sizeof(redirect_pointer));
values[i] = PointerGetDatum(new_attr);
}
newtup = heap_form_tuple(tupdesc, values, nulls);
pfree(values);
pfree(nulls);
ReleaseTupleDesc(tupdesc);
MemoryContextSwitchTo(old_context);
/*
* We intentionally don't use PG_RETURN_HEAPTUPLEHEADER here, because that
* would cause the indirect toast pointers to be flattened out of the
* tuple immediately, rendering subsequent testing irrelevant. So just
* return the HeapTupleHeader pointer as-is. This violates the general
* rule that composite Datums shouldn't contain toast pointers, but so
* long as the regression test scripts don't insert the result of this
* function into a container type (record, array, etc) it should be OK.
*/
PG_RETURN_POINTER(newtup->t_data);
}
PG_FUNCTION_INFO_V1(regress_setenv);
Datum
regress_setenv(PG_FUNCTION_ARGS)
{
char *envvar = text_to_cstring(PG_GETARG_TEXT_PP(0));
char *envval = text_to_cstring(PG_GETARG_TEXT_PP(1));
if (!superuser())
elog(ERROR, "must be superuser to change environment variables");
if (setenv(envvar, envval, 1) != 0)
elog(ERROR, "could not set environment variable: %m");
PG_RETURN_VOID();
}
/* Sleep until no process has a given PID. */
PG_FUNCTION_INFO_V1(wait_pid);
Datum
wait_pid(PG_FUNCTION_ARGS)
{
int pid = PG_GETARG_INT32(0);
if (!superuser())
elog(ERROR, "must be superuser to check PID liveness");
while (kill(pid, 0) == 0)
{
CHECK_FOR_INTERRUPTS();
pg_usleep(50000);
}
if (errno != ESRCH)
elog(ERROR, "could not check PID %d liveness: %m", pid);
PG_RETURN_VOID();
}
static void
test_atomic_flag(void)
{
pg_atomic_flag flag;
pg_atomic_init_flag(&flag);
EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
EXPECT_TRUE(!pg_atomic_unlocked_test_flag(&flag));
EXPECT_TRUE(!pg_atomic_test_set_flag(&flag));
pg_atomic_clear_flag(&flag);
EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
pg_atomic_clear_flag(&flag);
}
static void
test_atomic_uint32(void)
{
pg_atomic_uint32 var;
uint32 expected;
int i;
pg_atomic_init_u32(&var, 0);
EXPECT_EQ_U32(pg_atomic_read_u32(&var), 0);
pg_atomic_write_u32(&var, 3);
EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, pg_atomic_read_u32(&var) - 2),
3);
EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, 1), 4);
EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, 3), 0);
EXPECT_EQ_U32(pg_atomic_add_fetch_u32(&var, 10), 10);
EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 5), 10);
EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 0), 5);
/* test around numerical limits */
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), 0);
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), INT_MAX);
pg_atomic_fetch_add_u32(&var, 2); /* wrap to 0 */
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX), 0);
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX + 1),
PG_INT16_MAX);
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN),
2 * PG_INT16_MAX + 1);
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN - 1),
PG_INT16_MAX);
pg_atomic_fetch_add_u32(&var, 1); /* top up to UINT_MAX */
EXPECT_EQ_U32(pg_atomic_read_u32(&var), UINT_MAX);
EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, INT_MAX), UINT_MAX);
EXPECT_EQ_U32(pg_atomic_read_u32(&var), (uint32) INT_MAX + 1);
EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, INT_MAX), 1);
pg_atomic_sub_fetch_u32(&var, 1);
expected = PG_INT16_MAX;
EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
expected = PG_INT16_MAX + 1;
EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
expected = PG_INT16_MIN;
EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
expected = PG_INT16_MIN - 1;
EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
/* fail exchange because of old expected */
expected = 10;
EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
/* CAS is allowed to fail due to interrupts, try a couple of times */
for (i = 0; i < 1000; i++)
{
expected = 0;
if (!pg_atomic_compare_exchange_u32(&var, &expected, 1))
break;
}
if (i == 1000)
elog(ERROR, "atomic_compare_exchange_u32() never succeeded");
EXPECT_EQ_U32(pg_atomic_read_u32(&var), 1);
pg_atomic_write_u32(&var, 0);
/* try setting flagbits */
EXPECT_TRUE(!(pg_atomic_fetch_or_u32(&var, 1) & 1));
EXPECT_TRUE(pg_atomic_fetch_or_u32(&var, 2) & 1);
EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
/* try clearing flagbits */
EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~2) & 3, 3);
EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~1), 1);
/* no bits set anymore */
EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~0), 0);
}
static void
test_atomic_uint64(void)
{
pg_atomic_uint64 var;
uint64 expected;
int i;
pg_atomic_init_u64(&var, 0);
EXPECT_EQ_U64(pg_atomic_read_u64(&var), 0);
pg_atomic_write_u64(&var, 3);
EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
EXPECT_EQ_U64(pg_atomic_fetch_add_u64(&var, pg_atomic_read_u64(&var) - 2),
3);
EXPECT_EQ_U64(pg_atomic_fetch_sub_u64(&var, 1), 4);
EXPECT_EQ_U64(pg_atomic_sub_fetch_u64(&var, 3), 0);
EXPECT_EQ_U64(pg_atomic_add_fetch_u64(&var, 10), 10);
EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 5), 10);
EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 0), 5);
/* fail exchange because of old expected */
expected = 10;
EXPECT_TRUE(!pg_atomic_compare_exchange_u64(&var, &expected, 1));
/* CAS is allowed to fail due to interrupts, try a couple of times */
for (i = 0; i < 100; i++)
{
expected = 0;
if (!pg_atomic_compare_exchange_u64(&var, &expected, 1))
break;
}
if (i == 100)
elog(ERROR, "atomic_compare_exchange_u64() never succeeded");
EXPECT_EQ_U64(pg_atomic_read_u64(&var), 1);
pg_atomic_write_u64(&var, 0);
/* try setting flagbits */
EXPECT_TRUE(!(pg_atomic_fetch_or_u64(&var, 1) & 1));
EXPECT_TRUE(pg_atomic_fetch_or_u64(&var, 2) & 1);
EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
/* try clearing flagbits */
EXPECT_EQ_U64((pg_atomic_fetch_and_u64(&var, ~2) & 3), 3);
EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~1), 1);
/* no bits set anymore */
EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~0), 0);
}
/*
* Perform, fairly minimal, testing of the spinlock implementation.
*
* It's likely worth expanding these to actually test concurrency etc, but
* having some regularly run tests is better than none.
*/
static void
test_spinlock(void)
{
/*
* Basic tests for spinlocks, as well as the underlying operations.
*
* We embed the spinlock in a struct with other members to test that the
* spinlock operations don't perform too wide writes.
*/
{
struct test_lock_struct
{
char data_before[4];
slock_t lock;
char data_after[4];
} struct_w_lock;
memcpy(struct_w_lock.data_before, "abcd", 4);
memcpy(struct_w_lock.data_after, "ef12", 4);
/* test basic operations via the SpinLock* API */
SpinLockInit(&struct_w_lock.lock);
SpinLockAcquire(&struct_w_lock.lock);
SpinLockRelease(&struct_w_lock.lock);
/* test basic operations via underlying S_* API */
S_INIT_LOCK(&struct_w_lock.lock);
S_LOCK(&struct_w_lock.lock);
S_UNLOCK(&struct_w_lock.lock);
/* and that "contended" acquisition works */
s_lock(&struct_w_lock.lock, "testfile", 17, "testfunc");
S_UNLOCK(&struct_w_lock.lock);
/*
* Check, using TAS directly, that a single spin cycle doesn't block
* when acquiring an already acquired lock.
*/
#ifdef TAS
S_LOCK(&struct_w_lock.lock);
if (!TAS(&struct_w_lock.lock))
elog(ERROR, "acquired already held spinlock");
#ifdef TAS_SPIN
if (!TAS_SPIN(&struct_w_lock.lock))
elog(ERROR, "acquired already held spinlock");
#endif /* defined(TAS_SPIN) */
S_UNLOCK(&struct_w_lock.lock);
#endif /* defined(TAS) */
/*
* Verify that after all of this the non-lock contents are still
* correct.
*/
if (memcmp(struct_w_lock.data_before, "abcd", 4) != 0)
elog(ERROR, "padding before spinlock modified");
if (memcmp(struct_w_lock.data_after, "ef12", 4) != 0)
elog(ERROR, "padding after spinlock modified");
}
/*
* Ensure that allocating more than INT32_MAX emulated spinlocks works.
* That's interesting because the spinlock emulation uses a 32bit integer
* to map spinlocks onto semaphores. There've been bugs...
*/
#ifndef HAVE_SPINLOCKS
{
/*
* Initialize enough spinlocks to advance counter close to wraparound.
* It's too expensive to perform acquire/release for each, as those
* may be syscalls when the spinlock emulation is used (and even just
* atomic TAS would be expensive).
*/
for (uint32 i = 0; i < INT32_MAX - 100000; i++)
{
slock_t lock;
SpinLockInit(&lock);
}
for (uint32 i = 0; i < 200000; i++)
{
slock_t lock;
SpinLockInit(&lock);
SpinLockAcquire(&lock);
SpinLockRelease(&lock);
SpinLockAcquire(&lock);
SpinLockRelease(&lock);
}
}
#endif
}
/*
* Verify that performing atomic ops inside a spinlock isn't a
* problem. Realistically that's only going to be a problem when both
* --disable-spinlocks and --disable-atomics are used, but it's cheap enough
* to just always test.
*
* The test works by initializing enough atomics that we'd conflict if there
* were an overlap between a spinlock and an atomic by holding a spinlock
* while manipulating more than NUM_SPINLOCK_SEMAPHORES atomics.
*
* NUM_TEST_ATOMICS doesn't really need to be more than
* NUM_SPINLOCK_SEMAPHORES, but it seems better to test a bit more
* extensively.
*/
static void
test_atomic_spin_nest(void)
{
slock_t lock;
#define NUM_TEST_ATOMICS (NUM_SPINLOCK_SEMAPHORES + NUM_ATOMICS_SEMAPHORES + 27)
pg_atomic_uint32 atomics32[NUM_TEST_ATOMICS];
pg_atomic_uint64 atomics64[NUM_TEST_ATOMICS];
SpinLockInit(&lock);
for (int i = 0; i < NUM_TEST_ATOMICS; i++)
{
pg_atomic_init_u32(&atomics32[i], 0);
pg_atomic_init_u64(&atomics64[i], 0);
}
/* just so it's not all zeroes */
for (int i = 0; i < NUM_TEST_ATOMICS; i++)
{
EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&atomics32[i], i), 0);
EXPECT_EQ_U64(pg_atomic_fetch_add_u64(&atomics64[i], i), 0);
}
/* test whether we can do atomic op with lock held */
SpinLockAcquire(&lock);
for (int i = 0; i < NUM_TEST_ATOMICS; i++)
{
EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&atomics32[i], i), i);
EXPECT_EQ_U32(pg_atomic_read_u32(&atomics32[i]), 0);
EXPECT_EQ_U64(pg_atomic_fetch_sub_u64(&atomics64[i], i), i);
EXPECT_EQ_U64(pg_atomic_read_u64(&atomics64[i]), 0);
}
SpinLockRelease(&lock);
}
#undef NUM_TEST_ATOMICS
PG_FUNCTION_INFO_V1(test_atomic_ops);
Datum
test_atomic_ops(PG_FUNCTION_ARGS)
{
test_atomic_flag();
test_atomic_uint32();
test_atomic_uint64();
/*
* Arguably this shouldn't be tested as part of this function, but it's
* closely enough related that that seems ok for now.
*/
test_spinlock();
test_atomic_spin_nest();
PG_RETURN_BOOL(true);
}
PG_FUNCTION_INFO_V1(test_fdw_handler);
Datum
test_fdw_handler(PG_FUNCTION_ARGS)
{
elog(ERROR, "test_fdw_handler is not implemented");
PG_RETURN_NULL();
}
PG_FUNCTION_INFO_V1(test_support_func);
Datum
test_support_func(PG_FUNCTION_ARGS)
{
Node *rawreq = (Node *) PG_GETARG_POINTER(0);
Node *ret = NULL;
if (IsA(rawreq, SupportRequestSelectivity))
{
/*
* Assume that the target is int4eq; that's safe as long as we don't
* attach this to any other boolean-returning function.
*/
SupportRequestSelectivity *req = (SupportRequestSelectivity *) rawreq;
Selectivity s1;
if (req->is_join)
s1 = join_selectivity(req->root, Int4EqualOperator,
req->args,
req->inputcollid,
req->jointype,
req->sjinfo);
else
s1 = restriction_selectivity(req->root, Int4EqualOperator,
req->args,
req->inputcollid,
req->varRelid);
req->selectivity = s1;
ret = (Node *) req;
}
if (IsA(rawreq, SupportRequestCost))
{
/* Provide some generic estimate */
SupportRequestCost *req = (SupportRequestCost *) rawreq;
req->startup = 0;
req->per_tuple = 2 * cpu_operator_cost;
ret = (Node *) req;
}
if (IsA(rawreq, SupportRequestRows))
{
/*
* Assume that the target is generate_series_int4; that's safe as long
* as we don't attach this to any other set-returning function.
*/
SupportRequestRows *req = (SupportRequestRows *) rawreq;
if (req->node && IsA(req->node, FuncExpr)) /* be paranoid */
{
List *args = ((FuncExpr *) req->node)->args;
Node *arg1 = linitial(args);
Node *arg2 = lsecond(args);
if (IsA(arg1, Const) &&
!((Const *) arg1)->constisnull &&
IsA(arg2, Const) &&
!((Const *) arg2)->constisnull)
{
int32 val1 = DatumGetInt32(((Const *) arg1)->constvalue);
int32 val2 = DatumGetInt32(((Const *) arg2)->constvalue);
req->rows = val2 - val1 + 1;
ret = (Node *) req;
}
}
}
PG_RETURN_POINTER(ret);
}
PG_FUNCTION_INFO_V1(test_opclass_options_func);
Datum
test_opclass_options_func(PG_FUNCTION_ARGS)
{
PG_RETURN_NULL();
}
/*
* Call an encoding conversion or verification function.
*
* Arguments:
* string bytea -- string to convert
* src_enc name -- source encoding
* dest_enc name -- destination encoding
* noError bool -- if set, don't ereport() on invalid or untranslatable
* input
*
* Result is a tuple with two attributes:
* int4 -- number of input bytes successfully converted
* bytea -- converted string
*/
PG_FUNCTION_INFO_V1(test_enc_conversion);
Datum
test_enc_conversion(PG_FUNCTION_ARGS)
{
bytea *string = PG_GETARG_BYTEA_PP(0);
char *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
int src_encoding = pg_char_to_encoding(src_encoding_name);
char *dest_encoding_name = NameStr(*PG_GETARG_NAME(2));
int dest_encoding = pg_char_to_encoding(dest_encoding_name);
bool noError = PG_GETARG_BOOL(3);
TupleDesc tupdesc;
char *src;
char *dst;
bytea *retval;
Size srclen;
Size dstsize;
Oid proc;
int convertedbytes;
int dstlen;
Datum values[2];
bool nulls[2] = {0};
HeapTuple tuple;
if (src_encoding < 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid source encoding name \"%s\"",
src_encoding_name)));
if (dest_encoding < 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid destination encoding name \"%s\"",
dest_encoding_name)));
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "return type must be a row type");
tupdesc = BlessTupleDesc(tupdesc);
srclen = VARSIZE_ANY_EXHDR(string);
src = VARDATA_ANY(string);
if (src_encoding == dest_encoding)
{
/* just check that the source string is valid */
int oklen;
oklen = pg_encoding_verifymbstr(src_encoding, src, srclen);
if (oklen == srclen)
{
convertedbytes = oklen;
retval = string;
}
else if (!noError)
{
report_invalid_encoding(src_encoding, src + oklen, srclen - oklen);
}
else
{
/*
* build bytea data type structure.
*/
Assert(oklen < srclen);
convertedbytes = oklen;
retval = (bytea *) palloc(oklen + VARHDRSZ);
SET_VARSIZE(retval, oklen + VARHDRSZ);
memcpy(VARDATA(retval), src, oklen);
}
}
else
{
proc = FindDefaultConversionProc(src_encoding, dest_encoding);
if (!OidIsValid(proc))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("default conversion function for encoding \"%s\" to \"%s\" does not exist",
pg_encoding_to_char(src_encoding),
pg_encoding_to_char(dest_encoding))));
if (srclen >= (MaxAllocSize / (Size) MAX_CONVERSION_GROWTH))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("out of memory"),
errdetail("String of %d bytes is too long for encoding conversion.",
(int) srclen)));
dstsize = (Size) srclen * MAX_CONVERSION_GROWTH + 1;
dst = MemoryContextAlloc(CurrentMemoryContext, dstsize);
/* perform conversion */
convertedbytes = pg_do_encoding_conversion_buf(proc,
src_encoding,
dest_encoding,
(unsigned char *) src, srclen,
(unsigned char *) dst, dstsize,
noError);
dstlen = strlen(dst);
/*
* build bytea data type structure.
*/
retval = (bytea *) palloc(dstlen + VARHDRSZ);
SET_VARSIZE(retval, dstlen + VARHDRSZ);
memcpy(VARDATA(retval), dst, dstlen);
pfree(dst);
}
values[0] = Int32GetDatum(convertedbytes);
values[1] = PointerGetDatum(retval);
tuple = heap_form_tuple(tupdesc, values, nulls);
PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
/* Provide SQL access to IsBinaryCoercible() */
PG_FUNCTION_INFO_V1(binary_coercible);
Datum
binary_coercible(PG_FUNCTION_ARGS)
{
Oid srctype = PG_GETARG_OID(0);
Oid targettype = PG_GETARG_OID(1);
PG_RETURN_BOOL(IsBinaryCoercible(srctype, targettype));
}
/*
* Return the length of the portion of a tuple consisting of the given array
* of data types. The input data types must be fixed-length data types.
*/
PG_FUNCTION_INFO_V1(get_columns_length);
Datum
get_columns_length(PG_FUNCTION_ARGS)
{
ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
Oid *type_oids;
int ntypes;
int column_offset = 0;
if (ARR_HASNULL(ta) && array_contains_nulls(ta))
elog(ERROR, "argument must not contain nulls");
if (ARR_NDIM(ta) > 1)
elog(ERROR, "argument must be empty or one-dimensional array");
type_oids = (Oid *) ARR_DATA_PTR(ta);
ntypes = ArrayGetNItems(ARR_NDIM(ta), ARR_DIMS(ta));
for (int i = 0; i < ntypes; i++)
{
Oid typeoid = type_oids[i];
int16 typlen;
bool typbyval;
char typalign;
get_typlenbyvalalign(typeoid, &typlen, &typbyval, &typalign);
/* the data type must be fixed-length */
if (typlen < 0)
elog(ERROR, "type %u is not fixed-length data type", typeoid);
column_offset = att_align_nominal(column_offset + typlen, typalign);
}
PG_RETURN_INT32(column_offset);
}
|