Line data Source code
1 : /*------------------------------------------------------------------------
2 : *
3 : * regress.c
4 : * Code for various C-language functions defined as part of the
5 : * regression tests.
6 : *
7 : * This code is released under the terms of the PostgreSQL License.
8 : *
9 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
10 : * Portions Copyright (c) 1994, Regents of the University of California
11 : *
12 : * src/test/regress/regress.c
13 : *
14 : *-------------------------------------------------------------------------
15 : */
16 :
17 : #include "postgres.h"
18 :
19 : #include <math.h>
20 : #include <signal.h>
21 :
22 : #include "access/detoast.h"
23 : #include "access/htup_details.h"
24 : #include "catalog/namespace.h"
25 : #include "catalog/pg_operator.h"
26 : #include "catalog/pg_type.h"
27 : #include "commands/sequence.h"
28 : #include "commands/trigger.h"
29 : #include "executor/executor.h"
30 : #include "executor/spi.h"
31 : #include "funcapi.h"
32 : #include "mb/pg_wchar.h"
33 : #include "miscadmin.h"
34 : #include "nodes/supportnodes.h"
35 : #include "optimizer/optimizer.h"
36 : #include "optimizer/plancat.h"
37 : #include "parser/parse_coerce.h"
38 : #include "port/atomics.h"
39 : #include "storage/spin.h"
40 : #include "utils/array.h"
41 : #include "utils/builtins.h"
42 : #include "utils/geo_decls.h"
43 : #include "utils/memutils.h"
44 : #include "utils/rel.h"
45 : #include "utils/typcache.h"
46 :
47 : #define EXPECT_TRUE(expr) \
48 : do { \
49 : if (!(expr)) \
50 : elog(ERROR, \
51 : "%s was unexpectedly false in file \"%s\" line %u", \
52 : #expr, __FILE__, __LINE__); \
53 : } while (0)
54 :
55 : #define EXPECT_EQ_U32(result_expr, expected_expr) \
56 : do { \
57 : uint32 actual_result = (result_expr); \
58 : uint32 expected_result = (expected_expr); \
59 : if (actual_result != expected_result) \
60 : elog(ERROR, \
61 : "%s yielded %u, expected %s in file \"%s\" line %u", \
62 : #result_expr, actual_result, #expected_expr, __FILE__, __LINE__); \
63 : } while (0)
64 :
65 : #define EXPECT_EQ_U64(result_expr, expected_expr) \
66 : do { \
67 : uint64 actual_result = (result_expr); \
68 : uint64 expected_result = (expected_expr); \
69 : if (actual_result != expected_result) \
70 : elog(ERROR, \
71 : "%s yielded " UINT64_FORMAT ", expected %s in file \"%s\" line %u", \
72 : #result_expr, actual_result, #expected_expr, __FILE__, __LINE__); \
73 : } while (0)
74 :
75 : #define LDELIM '('
76 : #define RDELIM ')'
77 : #define DELIM ','
78 :
79 : static void regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2);
80 :
81 116 : PG_MODULE_MAGIC;
82 :
83 :
84 : /* return the point where two paths intersect, or NULL if no intersection. */
85 14 : PG_FUNCTION_INFO_V1(interpt_pp);
86 :
87 : Datum
88 5376 : interpt_pp(PG_FUNCTION_ARGS)
89 : {
90 5376 : PATH *p1 = PG_GETARG_PATH_P(0);
91 5376 : PATH *p2 = PG_GETARG_PATH_P(1);
92 : int i,
93 : j;
94 : LSEG seg1,
95 : seg2;
96 : bool found; /* We've found the intersection */
97 :
98 5376 : found = false; /* Haven't found it yet */
99 :
100 17646 : for (i = 0; i < p1->npts - 1 && !found; i++)
101 : {
102 12270 : regress_lseg_construct(&seg1, &p1->p[i], &p1->p[i + 1]);
103 37638 : for (j = 0; j < p2->npts - 1 && !found; j++)
104 : {
105 25368 : regress_lseg_construct(&seg2, &p2->p[j], &p2->p[j + 1]);
106 25368 : if (DatumGetBool(DirectFunctionCall2(lseg_intersect,
107 : LsegPGetDatum(&seg1),
108 : LsegPGetDatum(&seg2))))
109 5364 : found = true;
110 : }
111 : }
112 :
113 5376 : if (!found)
114 12 : PG_RETURN_NULL();
115 :
116 : /*
117 : * Note: DirectFunctionCall2 will kick out an error if lseg_interpt()
118 : * returns NULL, but that should be impossible since we know the two
119 : * segments intersect.
120 : */
121 5364 : PG_RETURN_DATUM(DirectFunctionCall2(lseg_interpt,
122 : LsegPGetDatum(&seg1),
123 : LsegPGetDatum(&seg2)));
124 : }
125 :
126 :
127 : /* like lseg_construct, but assume space already allocated */
128 : static void
129 37638 : regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2)
130 : {
131 37638 : lseg->p[0].x = pt1->x;
132 37638 : lseg->p[0].y = pt1->y;
133 37638 : lseg->p[1].x = pt2->x;
134 37638 : lseg->p[1].y = pt2->y;
135 37638 : }
136 :
137 14 : PG_FUNCTION_INFO_V1(overpaid);
138 :
139 : Datum
140 36 : overpaid(PG_FUNCTION_ARGS)
141 : {
142 36 : HeapTupleHeader tuple = PG_GETARG_HEAPTUPLEHEADER(0);
143 : bool isnull;
144 : int32 salary;
145 :
146 36 : salary = DatumGetInt32(GetAttributeByName(tuple, "salary", &isnull));
147 36 : if (isnull)
148 0 : PG_RETURN_NULL();
149 36 : PG_RETURN_BOOL(salary > 699);
150 : }
151 :
152 : /* New type "widget"
153 : * This used to be "circle", but I added circle to builtins,
154 : * so needed to make sure the names do not collide. - tgl 97/04/21
155 : */
156 :
157 : typedef struct
158 : {
159 : Point center;
160 : double radius;
161 : } WIDGET;
162 :
163 20 : PG_FUNCTION_INFO_V1(widget_in);
164 14 : PG_FUNCTION_INFO_V1(widget_out);
165 :
166 : #define NARGS 3
167 :
168 : Datum
169 66 : widget_in(PG_FUNCTION_ARGS)
170 : {
171 66 : char *str = PG_GETARG_CSTRING(0);
172 : char *p,
173 : *coord[NARGS];
174 : int i;
175 : WIDGET *result;
176 :
177 378 : for (i = 0, p = str; *p && i < NARGS && *p != RDELIM; p++)
178 : {
179 312 : if (*p == DELIM || (*p == LDELIM && i == 0))
180 162 : coord[i++] = p + 1;
181 : }
182 :
183 : /*
184 : * Note: DON'T convert this error to "soft" style (errsave/ereturn). We
185 : * want this data type to stay permanently in the hard-error world so that
186 : * it can be used for testing that such cases still work reasonably.
187 : */
188 66 : if (i < NARGS)
189 24 : ereport(ERROR,
190 : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
191 : errmsg("invalid input syntax for type %s: \"%s\"",
192 : "widget", str)));
193 :
194 42 : result = (WIDGET *) palloc(sizeof(WIDGET));
195 42 : result->center.x = atof(coord[0]);
196 42 : result->center.y = atof(coord[1]);
197 42 : result->radius = atof(coord[2]);
198 :
199 42 : PG_RETURN_POINTER(result);
200 : }
201 :
202 : Datum
203 12 : widget_out(PG_FUNCTION_ARGS)
204 : {
205 12 : WIDGET *widget = (WIDGET *) PG_GETARG_POINTER(0);
206 12 : char *str = psprintf("(%g,%g,%g)",
207 : widget->center.x, widget->center.y, widget->radius);
208 :
209 12 : PG_RETURN_CSTRING(str);
210 : }
211 :
212 14 : PG_FUNCTION_INFO_V1(pt_in_widget);
213 :
214 : Datum
215 12 : pt_in_widget(PG_FUNCTION_ARGS)
216 : {
217 12 : Point *point = PG_GETARG_POINT_P(0);
218 12 : WIDGET *widget = (WIDGET *) PG_GETARG_POINTER(1);
219 : float8 distance;
220 :
221 12 : distance = DatumGetFloat8(DirectFunctionCall2(point_distance,
222 : PointPGetDatum(point),
223 : PointPGetDatum(&widget->center)));
224 :
225 12 : PG_RETURN_BOOL(distance < widget->radius);
226 : }
227 :
228 14 : PG_FUNCTION_INFO_V1(reverse_name);
229 :
230 : Datum
231 48 : reverse_name(PG_FUNCTION_ARGS)
232 : {
233 48 : char *string = PG_GETARG_CSTRING(0);
234 : int i;
235 : int len;
236 : char *new_string;
237 :
238 48 : new_string = palloc0(NAMEDATALEN);
239 336 : for (i = 0; i < NAMEDATALEN && string[i]; ++i)
240 : ;
241 48 : if (i == NAMEDATALEN || !string[i])
242 48 : --i;
243 48 : len = i;
244 336 : for (; i >= 0; --i)
245 288 : new_string[len - i] = string[i];
246 48 : PG_RETURN_CSTRING(new_string);
247 : }
248 :
249 14 : PG_FUNCTION_INFO_V1(trigger_return_old);
250 :
251 : Datum
252 90 : trigger_return_old(PG_FUNCTION_ARGS)
253 : {
254 90 : TriggerData *trigdata = (TriggerData *) fcinfo->context;
255 : HeapTuple tuple;
256 :
257 90 : if (!CALLED_AS_TRIGGER(fcinfo))
258 0 : elog(ERROR, "trigger_return_old: not fired by trigger manager");
259 :
260 90 : tuple = trigdata->tg_trigtuple;
261 :
262 90 : return PointerGetDatum(tuple);
263 : }
264 :
265 : #define TTDUMMY_INFINITY 999999
266 :
267 : static SPIPlanPtr splan = NULL;
268 : static bool ttoff = false;
269 :
270 14 : PG_FUNCTION_INFO_V1(ttdummy);
271 :
272 : Datum
273 60 : ttdummy(PG_FUNCTION_ARGS)
274 : {
275 60 : TriggerData *trigdata = (TriggerData *) fcinfo->context;
276 : Trigger *trigger; /* to get trigger name */
277 : char **args; /* arguments */
278 : int attnum[2]; /* fnumbers of start/stop columns */
279 : Datum oldon,
280 : oldoff;
281 : Datum newon,
282 : newoff;
283 : Datum *cvals; /* column values */
284 : char *cnulls; /* column nulls */
285 : char *relname; /* triggered relation name */
286 : Relation rel; /* triggered relation */
287 : HeapTuple trigtuple;
288 60 : HeapTuple newtuple = NULL;
289 : HeapTuple rettuple;
290 : TupleDesc tupdesc; /* tuple description */
291 : int natts; /* # of attributes */
292 : bool isnull; /* to know is some column NULL or not */
293 : int ret;
294 : int i;
295 :
296 60 : if (!CALLED_AS_TRIGGER(fcinfo))
297 0 : elog(ERROR, "ttdummy: not fired by trigger manager");
298 60 : if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
299 0 : elog(ERROR, "ttdummy: must be fired for row");
300 60 : if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
301 0 : elog(ERROR, "ttdummy: must be fired before event");
302 60 : if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
303 0 : elog(ERROR, "ttdummy: cannot process INSERT event");
304 60 : if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
305 48 : newtuple = trigdata->tg_newtuple;
306 :
307 60 : trigtuple = trigdata->tg_trigtuple;
308 :
309 60 : rel = trigdata->tg_relation;
310 60 : relname = SPI_getrelname(rel);
311 :
312 : /* check if TT is OFF for this relation */
313 60 : if (ttoff) /* OFF - nothing to do */
314 : {
315 30 : pfree(relname);
316 30 : return PointerGetDatum((newtuple != NULL) ? newtuple : trigtuple);
317 : }
318 :
319 30 : trigger = trigdata->tg_trigger;
320 :
321 30 : if (trigger->tgnargs != 2)
322 0 : elog(ERROR, "ttdummy (%s): invalid (!= 2) number of arguments %d",
323 : relname, trigger->tgnargs);
324 :
325 30 : args = trigger->tgargs;
326 30 : tupdesc = rel->rd_att;
327 30 : natts = tupdesc->natts;
328 :
329 90 : for (i = 0; i < 2; i++)
330 : {
331 60 : attnum[i] = SPI_fnumber(tupdesc, args[i]);
332 60 : if (attnum[i] <= 0)
333 0 : elog(ERROR, "ttdummy (%s): there is no attribute %s",
334 : relname, args[i]);
335 60 : if (SPI_gettypeid(tupdesc, attnum[i]) != INT4OID)
336 0 : elog(ERROR, "ttdummy (%s): attribute %s must be of integer type",
337 : relname, args[i]);
338 : }
339 :
340 30 : oldon = SPI_getbinval(trigtuple, tupdesc, attnum[0], &isnull);
341 30 : if (isnull)
342 0 : elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[0]);
343 :
344 30 : oldoff = SPI_getbinval(trigtuple, tupdesc, attnum[1], &isnull);
345 30 : if (isnull)
346 0 : elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[1]);
347 :
348 30 : if (newtuple != NULL) /* UPDATE */
349 : {
350 24 : newon = SPI_getbinval(newtuple, tupdesc, attnum[0], &isnull);
351 24 : if (isnull)
352 0 : elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[0]);
353 24 : newoff = SPI_getbinval(newtuple, tupdesc, attnum[1], &isnull);
354 24 : if (isnull)
355 0 : elog(ERROR, "ttdummy (%s): %s must be NOT NULL", relname, args[1]);
356 :
357 24 : if (oldon != newon || oldoff != newoff)
358 6 : ereport(ERROR,
359 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
360 : errmsg("ttdummy (%s): you cannot change %s and/or %s columns (use set_ttdummy)",
361 : relname, args[0], args[1])));
362 :
363 18 : if (newoff != TTDUMMY_INFINITY)
364 : {
365 6 : pfree(relname); /* allocated in upper executor context */
366 6 : return PointerGetDatum(NULL);
367 : }
368 : }
369 6 : else if (oldoff != TTDUMMY_INFINITY) /* DELETE */
370 : {
371 0 : pfree(relname);
372 0 : return PointerGetDatum(NULL);
373 : }
374 :
375 18 : newoff = DirectFunctionCall1(nextval, CStringGetTextDatum("ttdummy_seq"));
376 : /* nextval now returns int64; coerce down to int32 */
377 18 : newoff = Int32GetDatum((int32) DatumGetInt64(newoff));
378 :
379 : /* Connect to SPI manager */
380 18 : SPI_connect();
381 :
382 : /* Fetch tuple values and nulls */
383 18 : cvals = (Datum *) palloc(natts * sizeof(Datum));
384 18 : cnulls = (char *) palloc(natts * sizeof(char));
385 90 : for (i = 0; i < natts; i++)
386 : {
387 72 : cvals[i] = SPI_getbinval((newtuple != NULL) ? newtuple : trigtuple,
388 : tupdesc, i + 1, &isnull);
389 72 : cnulls[i] = (isnull) ? 'n' : ' ';
390 : }
391 :
392 : /* change date column(s) */
393 18 : if (newtuple) /* UPDATE */
394 : {
395 12 : cvals[attnum[0] - 1] = newoff; /* start_date eq current date */
396 12 : cnulls[attnum[0] - 1] = ' ';
397 12 : cvals[attnum[1] - 1] = TTDUMMY_INFINITY; /* stop_date eq INFINITY */
398 12 : cnulls[attnum[1] - 1] = ' ';
399 : }
400 : else
401 : /* DELETE */
402 : {
403 6 : cvals[attnum[1] - 1] = newoff; /* stop_date eq current date */
404 6 : cnulls[attnum[1] - 1] = ' ';
405 : }
406 :
407 : /* if there is no plan ... */
408 18 : if (splan == NULL)
409 : {
410 : SPIPlanPtr pplan;
411 : Oid *ctypes;
412 : char *query;
413 :
414 : /* allocate space in preparation */
415 6 : ctypes = (Oid *) palloc(natts * sizeof(Oid));
416 6 : query = (char *) palloc(100 + 16 * natts);
417 :
418 : /*
419 : * Construct query: INSERT INTO _relation_ VALUES ($1, ...)
420 : */
421 6 : sprintf(query, "INSERT INTO %s VALUES (", relname);
422 30 : for (i = 1; i <= natts; i++)
423 : {
424 24 : sprintf(query + strlen(query), "$%d%s",
425 : i, (i < natts) ? ", " : ")");
426 24 : ctypes[i - 1] = SPI_gettypeid(tupdesc, i);
427 : }
428 :
429 : /* Prepare plan for query */
430 6 : pplan = SPI_prepare(query, natts, ctypes);
431 6 : if (pplan == NULL)
432 0 : elog(ERROR, "ttdummy (%s): SPI_prepare returned %s", relname, SPI_result_code_string(SPI_result));
433 :
434 6 : if (SPI_keepplan(pplan))
435 0 : elog(ERROR, "ttdummy (%s): SPI_keepplan failed", relname);
436 :
437 6 : splan = pplan;
438 : }
439 :
440 18 : ret = SPI_execp(splan, cvals, cnulls, 0);
441 :
442 18 : if (ret < 0)
443 0 : elog(ERROR, "ttdummy (%s): SPI_execp returned %d", relname, ret);
444 :
445 : /* Tuple to return to upper Executor ... */
446 18 : if (newtuple) /* UPDATE */
447 12 : rettuple = SPI_modifytuple(rel, trigtuple, 1, &(attnum[1]), &newoff, NULL);
448 : else /* DELETE */
449 6 : rettuple = trigtuple;
450 :
451 18 : SPI_finish(); /* don't forget say Bye to SPI mgr */
452 :
453 18 : pfree(relname);
454 :
455 18 : return PointerGetDatum(rettuple);
456 : }
457 :
458 14 : PG_FUNCTION_INFO_V1(set_ttdummy);
459 :
460 : Datum
461 18 : set_ttdummy(PG_FUNCTION_ARGS)
462 : {
463 18 : int32 on = PG_GETARG_INT32(0);
464 :
465 18 : if (ttoff) /* OFF currently */
466 : {
467 6 : if (on == 0)
468 0 : PG_RETURN_INT32(0);
469 :
470 : /* turn ON */
471 6 : ttoff = false;
472 6 : PG_RETURN_INT32(0);
473 : }
474 :
475 : /* ON currently */
476 12 : if (on != 0)
477 0 : PG_RETURN_INT32(1);
478 :
479 : /* turn OFF */
480 12 : ttoff = true;
481 :
482 12 : PG_RETURN_INT32(1);
483 : }
484 :
485 :
486 : /*
487 : * Type int44 has no real-world use, but the regression tests use it
488 : * (under the alias "city_budget"). It's a four-element vector of int4's.
489 : */
490 :
491 : /*
492 : * int44in - converts "num, num, ..." to internal form
493 : *
494 : * Note: Fills any missing positions with zeroes.
495 : */
496 14 : PG_FUNCTION_INFO_V1(int44in);
497 :
498 : Datum
499 12 : int44in(PG_FUNCTION_ARGS)
500 : {
501 12 : char *input_string = PG_GETARG_CSTRING(0);
502 12 : int32 *result = (int32 *) palloc(4 * sizeof(int32));
503 : int i;
504 :
505 12 : i = sscanf(input_string,
506 : "%d, %d, %d, %d",
507 : &result[0],
508 : &result[1],
509 : &result[2],
510 : &result[3]);
511 18 : while (i < 4)
512 6 : result[i++] = 0;
513 :
514 12 : PG_RETURN_POINTER(result);
515 : }
516 :
517 : /*
518 : * int44out - converts internal form to "num, num, ..."
519 : */
520 22 : PG_FUNCTION_INFO_V1(int44out);
521 :
522 : Datum
523 28 : int44out(PG_FUNCTION_ARGS)
524 : {
525 28 : int32 *an_array = (int32 *) PG_GETARG_POINTER(0);
526 28 : char *result = (char *) palloc(16 * 4);
527 :
528 28 : snprintf(result, 16 * 4, "%d,%d,%d,%d",
529 : an_array[0],
530 28 : an_array[1],
531 28 : an_array[2],
532 28 : an_array[3]);
533 :
534 28 : PG_RETURN_CSTRING(result);
535 : }
536 :
537 14 : PG_FUNCTION_INFO_V1(test_canonicalize_path);
538 : Datum
539 132 : test_canonicalize_path(PG_FUNCTION_ARGS)
540 : {
541 132 : char *path = text_to_cstring(PG_GETARG_TEXT_PP(0));
542 :
543 132 : canonicalize_path(path);
544 132 : PG_RETURN_TEXT_P(cstring_to_text(path));
545 : }
546 :
547 14 : PG_FUNCTION_INFO_V1(make_tuple_indirect);
548 : Datum
549 126 : make_tuple_indirect(PG_FUNCTION_ARGS)
550 : {
551 126 : HeapTupleHeader rec = PG_GETARG_HEAPTUPLEHEADER(0);
552 : HeapTupleData tuple;
553 : int ncolumns;
554 : Datum *values;
555 : bool *nulls;
556 :
557 : Oid tupType;
558 : int32 tupTypmod;
559 : TupleDesc tupdesc;
560 :
561 : HeapTuple newtup;
562 :
563 : int i;
564 :
565 : MemoryContext old_context;
566 :
567 : /* Extract type info from the tuple itself */
568 126 : tupType = HeapTupleHeaderGetTypeId(rec);
569 126 : tupTypmod = HeapTupleHeaderGetTypMod(rec);
570 126 : tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
571 126 : ncolumns = tupdesc->natts;
572 :
573 : /* Build a temporary HeapTuple control structure */
574 126 : tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
575 126 : ItemPointerSetInvalid(&(tuple.t_self));
576 126 : tuple.t_tableOid = InvalidOid;
577 126 : tuple.t_data = rec;
578 :
579 126 : values = (Datum *) palloc(ncolumns * sizeof(Datum));
580 126 : nulls = (bool *) palloc(ncolumns * sizeof(bool));
581 :
582 126 : heap_deform_tuple(&tuple, tupdesc, values, nulls);
583 :
584 126 : old_context = MemoryContextSwitchTo(TopTransactionContext);
585 :
586 630 : for (i = 0; i < ncolumns; i++)
587 : {
588 : struct varlena *attr;
589 : struct varlena *new_attr;
590 : struct varatt_indirect redirect_pointer;
591 :
592 : /* only work on existing, not-null varlenas */
593 504 : if (TupleDescAttr(tupdesc, i)->attisdropped ||
594 504 : nulls[i] ||
595 438 : TupleDescAttr(tupdesc, i)->attlen != -1 ||
596 312 : TupleDescAttr(tupdesc, i)->attstorage == TYPSTORAGE_PLAIN)
597 192 : continue;
598 :
599 312 : attr = (struct varlena *) DatumGetPointer(values[i]);
600 :
601 : /* don't recursively indirect */
602 312 : if (VARATT_IS_EXTERNAL_INDIRECT(attr))
603 0 : continue;
604 :
605 : /* copy datum, so it still lives later */
606 312 : if (VARATT_IS_EXTERNAL_ONDISK(attr))
607 0 : attr = detoast_external_attr(attr);
608 : else
609 : {
610 312 : struct varlena *oldattr = attr;
611 :
612 312 : attr = palloc0(VARSIZE_ANY(oldattr));
613 312 : memcpy(attr, oldattr, VARSIZE_ANY(oldattr));
614 : }
615 :
616 : /* build indirection Datum */
617 312 : new_attr = (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
618 312 : redirect_pointer.pointer = attr;
619 312 : SET_VARTAG_EXTERNAL(new_attr, VARTAG_INDIRECT);
620 312 : memcpy(VARDATA_EXTERNAL(new_attr), &redirect_pointer,
621 : sizeof(redirect_pointer));
622 :
623 312 : values[i] = PointerGetDatum(new_attr);
624 : }
625 :
626 126 : newtup = heap_form_tuple(tupdesc, values, nulls);
627 126 : pfree(values);
628 126 : pfree(nulls);
629 126 : ReleaseTupleDesc(tupdesc);
630 :
631 126 : MemoryContextSwitchTo(old_context);
632 :
633 : /*
634 : * We intentionally don't use PG_RETURN_HEAPTUPLEHEADER here, because that
635 : * would cause the indirect toast pointers to be flattened out of the
636 : * tuple immediately, rendering subsequent testing irrelevant. So just
637 : * return the HeapTupleHeader pointer as-is. This violates the general
638 : * rule that composite Datums shouldn't contain toast pointers, but so
639 : * long as the regression test scripts don't insert the result of this
640 : * function into a container type (record, array, etc) it should be OK.
641 : */
642 126 : PG_RETURN_POINTER(newtup->t_data);
643 : }
644 :
645 4 : PG_FUNCTION_INFO_V1(get_environ);
646 :
647 : Datum
648 2 : get_environ(PG_FUNCTION_ARGS)
649 : {
650 : #if !defined(WIN32) || defined(_MSC_VER)
651 : extern char **environ;
652 : #endif
653 2 : int nvals = 0;
654 : ArrayType *result;
655 : Datum *env;
656 :
657 70 : for (char **s = environ; *s; s++)
658 68 : nvals++;
659 :
660 2 : env = palloc(nvals * sizeof(Datum));
661 :
662 70 : for (int i = 0; i < nvals; i++)
663 68 : env[i] = CStringGetTextDatum(environ[i]);
664 :
665 2 : result = construct_array_builtin(env, nvals, TEXTOID);
666 :
667 2 : PG_RETURN_POINTER(result);
668 : }
669 :
670 4 : PG_FUNCTION_INFO_V1(regress_setenv);
671 :
672 : Datum
673 2 : regress_setenv(PG_FUNCTION_ARGS)
674 : {
675 2 : char *envvar = text_to_cstring(PG_GETARG_TEXT_PP(0));
676 2 : char *envval = text_to_cstring(PG_GETARG_TEXT_PP(1));
677 :
678 2 : if (!superuser())
679 0 : elog(ERROR, "must be superuser to change environment variables");
680 :
681 2 : if (setenv(envvar, envval, 1) != 0)
682 0 : elog(ERROR, "could not set environment variable: %m");
683 :
684 2 : PG_RETURN_VOID();
685 : }
686 :
687 : /* Sleep until no process has a given PID. */
688 10 : PG_FUNCTION_INFO_V1(wait_pid);
689 :
690 : Datum
691 4 : wait_pid(PG_FUNCTION_ARGS)
692 : {
693 4 : int pid = PG_GETARG_INT32(0);
694 :
695 4 : if (!superuser())
696 0 : elog(ERROR, "must be superuser to check PID liveness");
697 :
698 8 : while (kill(pid, 0) == 0)
699 : {
700 4 : CHECK_FOR_INTERRUPTS();
701 4 : pg_usleep(50000);
702 : }
703 :
704 4 : if (errno != ESRCH)
705 0 : elog(ERROR, "could not check PID %d liveness: %m", pid);
706 :
707 4 : PG_RETURN_VOID();
708 : }
709 :
710 : static void
711 6 : test_atomic_flag(void)
712 : {
713 : pg_atomic_flag flag;
714 :
715 6 : pg_atomic_init_flag(&flag);
716 6 : EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
717 6 : EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
718 6 : EXPECT_TRUE(!pg_atomic_unlocked_test_flag(&flag));
719 6 : EXPECT_TRUE(!pg_atomic_test_set_flag(&flag));
720 6 : pg_atomic_clear_flag(&flag);
721 6 : EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
722 6 : EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
723 6 : pg_atomic_clear_flag(&flag);
724 6 : }
725 :
726 : static void
727 6 : test_atomic_uint32(void)
728 : {
729 : pg_atomic_uint32 var;
730 : uint32 expected;
731 : int i;
732 :
733 6 : pg_atomic_init_u32(&var, 0);
734 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 0);
735 6 : pg_atomic_write_u32(&var, 3);
736 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
737 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, pg_atomic_read_u32(&var) - 2),
738 : 3);
739 6 : EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, 1), 4);
740 6 : EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, 3), 0);
741 6 : EXPECT_EQ_U32(pg_atomic_add_fetch_u32(&var, 10), 10);
742 6 : EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 5), 10);
743 6 : EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 0), 5);
744 :
745 : /* test around numerical limits */
746 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), 0);
747 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), INT_MAX);
748 6 : pg_atomic_fetch_add_u32(&var, 2); /* wrap to 0 */
749 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX), 0);
750 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX + 1),
751 : PG_INT16_MAX);
752 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN),
753 : 2 * PG_INT16_MAX + 1);
754 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN - 1),
755 : PG_INT16_MAX);
756 6 : pg_atomic_fetch_add_u32(&var, 1); /* top up to UINT_MAX */
757 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), UINT_MAX);
758 6 : EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, INT_MAX), UINT_MAX);
759 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), (uint32) INT_MAX + 1);
760 6 : EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, INT_MAX), 1);
761 6 : pg_atomic_sub_fetch_u32(&var, 1);
762 6 : expected = PG_INT16_MAX;
763 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
764 6 : expected = PG_INT16_MAX + 1;
765 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
766 6 : expected = PG_INT16_MIN;
767 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
768 6 : expected = PG_INT16_MIN - 1;
769 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
770 :
771 : /* fail exchange because of old expected */
772 6 : expected = 10;
773 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
774 :
775 : /* CAS is allowed to fail due to interrupts, try a couple of times */
776 12 : for (i = 0; i < 1000; i++)
777 : {
778 12 : expected = 0;
779 12 : if (!pg_atomic_compare_exchange_u32(&var, &expected, 1))
780 6 : break;
781 : }
782 6 : if (i == 1000)
783 0 : elog(ERROR, "atomic_compare_exchange_u32() never succeeded");
784 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 1);
785 6 : pg_atomic_write_u32(&var, 0);
786 :
787 : /* try setting flagbits */
788 6 : EXPECT_TRUE(!(pg_atomic_fetch_or_u32(&var, 1) & 1));
789 6 : EXPECT_TRUE(pg_atomic_fetch_or_u32(&var, 2) & 1);
790 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
791 : /* try clearing flagbits */
792 6 : EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~2) & 3, 3);
793 6 : EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~1), 1);
794 : /* no bits set anymore */
795 6 : EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~0), 0);
796 6 : }
797 :
798 : static void
799 6 : test_atomic_uint64(void)
800 : {
801 : pg_atomic_uint64 var;
802 : uint64 expected;
803 : int i;
804 :
805 6 : pg_atomic_init_u64(&var, 0);
806 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 0);
807 6 : pg_atomic_write_u64(&var, 3);
808 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
809 6 : EXPECT_EQ_U64(pg_atomic_fetch_add_u64(&var, pg_atomic_read_u64(&var) - 2),
810 : 3);
811 6 : EXPECT_EQ_U64(pg_atomic_fetch_sub_u64(&var, 1), 4);
812 6 : EXPECT_EQ_U64(pg_atomic_sub_fetch_u64(&var, 3), 0);
813 6 : EXPECT_EQ_U64(pg_atomic_add_fetch_u64(&var, 10), 10);
814 6 : EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 5), 10);
815 6 : EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 0), 5);
816 :
817 : /* fail exchange because of old expected */
818 6 : expected = 10;
819 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u64(&var, &expected, 1));
820 :
821 : /* CAS is allowed to fail due to interrupts, try a couple of times */
822 12 : for (i = 0; i < 100; i++)
823 : {
824 12 : expected = 0;
825 12 : if (!pg_atomic_compare_exchange_u64(&var, &expected, 1))
826 6 : break;
827 : }
828 6 : if (i == 100)
829 0 : elog(ERROR, "atomic_compare_exchange_u64() never succeeded");
830 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 1);
831 :
832 6 : pg_atomic_write_u64(&var, 0);
833 :
834 : /* try setting flagbits */
835 6 : EXPECT_TRUE(!(pg_atomic_fetch_or_u64(&var, 1) & 1));
836 6 : EXPECT_TRUE(pg_atomic_fetch_or_u64(&var, 2) & 1);
837 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
838 : /* try clearing flagbits */
839 6 : EXPECT_EQ_U64((pg_atomic_fetch_and_u64(&var, ~2) & 3), 3);
840 6 : EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~1), 1);
841 : /* no bits set anymore */
842 6 : EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~0), 0);
843 6 : }
844 :
845 : /*
846 : * Perform, fairly minimal, testing of the spinlock implementation.
847 : *
848 : * It's likely worth expanding these to actually test concurrency etc, but
849 : * having some regularly run tests is better than none.
850 : */
851 : static void
852 6 : test_spinlock(void)
853 : {
854 : /*
855 : * Basic tests for spinlocks, as well as the underlying operations.
856 : *
857 : * We embed the spinlock in a struct with other members to test that the
858 : * spinlock operations don't perform too wide writes.
859 : */
860 : {
861 : struct test_lock_struct
862 : {
863 : char data_before[4];
864 : slock_t lock;
865 : char data_after[4];
866 : } struct_w_lock;
867 :
868 6 : memcpy(struct_w_lock.data_before, "abcd", 4);
869 6 : memcpy(struct_w_lock.data_after, "ef12", 4);
870 :
871 : /* test basic operations via the SpinLock* API */
872 6 : SpinLockInit(&struct_w_lock.lock);
873 6 : SpinLockAcquire(&struct_w_lock.lock);
874 6 : SpinLockRelease(&struct_w_lock.lock);
875 :
876 : /* test basic operations via underlying S_* API */
877 6 : S_INIT_LOCK(&struct_w_lock.lock);
878 6 : S_LOCK(&struct_w_lock.lock);
879 6 : S_UNLOCK(&struct_w_lock.lock);
880 :
881 : /* and that "contended" acquisition works */
882 6 : s_lock(&struct_w_lock.lock, "testfile", 17, "testfunc");
883 6 : S_UNLOCK(&struct_w_lock.lock);
884 :
885 : /*
886 : * Check, using TAS directly, that a single spin cycle doesn't block
887 : * when acquiring an already acquired lock.
888 : */
889 : #ifdef TAS
890 6 : S_LOCK(&struct_w_lock.lock);
891 :
892 6 : if (!TAS(&struct_w_lock.lock))
893 0 : elog(ERROR, "acquired already held spinlock");
894 :
895 : #ifdef TAS_SPIN
896 6 : if (!TAS_SPIN(&struct_w_lock.lock))
897 0 : elog(ERROR, "acquired already held spinlock");
898 : #endif /* defined(TAS_SPIN) */
899 :
900 6 : S_UNLOCK(&struct_w_lock.lock);
901 : #endif /* defined(TAS) */
902 :
903 : /*
904 : * Verify that after all of this the non-lock contents are still
905 : * correct.
906 : */
907 6 : if (memcmp(struct_w_lock.data_before, "abcd", 4) != 0)
908 0 : elog(ERROR, "padding before spinlock modified");
909 6 : if (memcmp(struct_w_lock.data_after, "ef12", 4) != 0)
910 0 : elog(ERROR, "padding after spinlock modified");
911 : }
912 6 : }
913 :
914 14 : PG_FUNCTION_INFO_V1(test_atomic_ops);
915 : Datum
916 6 : test_atomic_ops(PG_FUNCTION_ARGS)
917 : {
918 6 : test_atomic_flag();
919 :
920 6 : test_atomic_uint32();
921 :
922 6 : test_atomic_uint64();
923 :
924 : /*
925 : * Arguably this shouldn't be tested as part of this function, but it's
926 : * closely enough related that that seems ok for now.
927 : */
928 6 : test_spinlock();
929 :
930 6 : PG_RETURN_BOOL(true);
931 : }
932 :
933 8 : PG_FUNCTION_INFO_V1(test_fdw_handler);
934 : Datum
935 0 : test_fdw_handler(PG_FUNCTION_ARGS)
936 : {
937 0 : elog(ERROR, "test_fdw_handler is not implemented");
938 : PG_RETURN_NULL();
939 : }
940 :
941 14 : PG_FUNCTION_INFO_V1(test_support_func);
942 : Datum
943 60 : test_support_func(PG_FUNCTION_ARGS)
944 : {
945 60 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
946 60 : Node *ret = NULL;
947 :
948 60 : if (IsA(rawreq, SupportRequestSelectivity))
949 : {
950 : /*
951 : * Assume that the target is int4eq; that's safe as long as we don't
952 : * attach this to any other boolean-returning function.
953 : */
954 6 : SupportRequestSelectivity *req = (SupportRequestSelectivity *) rawreq;
955 : Selectivity s1;
956 :
957 6 : if (req->is_join)
958 0 : s1 = join_selectivity(req->root, Int4EqualOperator,
959 : req->args,
960 : req->inputcollid,
961 : req->jointype,
962 0 : req->sjinfo);
963 : else
964 6 : s1 = restriction_selectivity(req->root, Int4EqualOperator,
965 : req->args,
966 : req->inputcollid,
967 : req->varRelid);
968 :
969 6 : req->selectivity = s1;
970 6 : ret = (Node *) req;
971 : }
972 :
973 60 : if (IsA(rawreq, SupportRequestCost))
974 : {
975 : /* Provide some generic estimate */
976 18 : SupportRequestCost *req = (SupportRequestCost *) rawreq;
977 :
978 18 : req->startup = 0;
979 18 : req->per_tuple = 2 * cpu_operator_cost;
980 18 : ret = (Node *) req;
981 : }
982 :
983 60 : if (IsA(rawreq, SupportRequestRows))
984 : {
985 : /*
986 : * Assume that the target is generate_series_int4; that's safe as long
987 : * as we don't attach this to any other set-returning function.
988 : */
989 12 : SupportRequestRows *req = (SupportRequestRows *) rawreq;
990 :
991 12 : if (req->node && IsA(req->node, FuncExpr)) /* be paranoid */
992 : {
993 12 : List *args = ((FuncExpr *) req->node)->args;
994 12 : Node *arg1 = linitial(args);
995 12 : Node *arg2 = lsecond(args);
996 :
997 12 : if (IsA(arg1, Const) &&
998 12 : !((Const *) arg1)->constisnull &&
999 12 : IsA(arg2, Const) &&
1000 12 : !((Const *) arg2)->constisnull)
1001 : {
1002 12 : int32 val1 = DatumGetInt32(((Const *) arg1)->constvalue);
1003 12 : int32 val2 = DatumGetInt32(((Const *) arg2)->constvalue);
1004 :
1005 12 : req->rows = val2 - val1 + 1;
1006 12 : ret = (Node *) req;
1007 : }
1008 : }
1009 : }
1010 :
1011 60 : PG_RETURN_POINTER(ret);
1012 : }
1013 :
1014 8 : PG_FUNCTION_INFO_V1(test_opclass_options_func);
1015 : Datum
1016 0 : test_opclass_options_func(PG_FUNCTION_ARGS)
1017 : {
1018 0 : PG_RETURN_NULL();
1019 : }
1020 :
1021 : /*
1022 : * Call an encoding conversion or verification function.
1023 : *
1024 : * Arguments:
1025 : * string bytea -- string to convert
1026 : * src_enc name -- source encoding
1027 : * dest_enc name -- destination encoding
1028 : * noError bool -- if set, don't ereport() on invalid or untranslatable
1029 : * input
1030 : *
1031 : * Result is a tuple with two attributes:
1032 : * int4 -- number of input bytes successfully converted
1033 : * bytea -- converted string
1034 : */
1035 14 : PG_FUNCTION_INFO_V1(test_enc_conversion);
1036 : Datum
1037 9798 : test_enc_conversion(PG_FUNCTION_ARGS)
1038 : {
1039 9798 : bytea *string = PG_GETARG_BYTEA_PP(0);
1040 9798 : char *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
1041 9798 : int src_encoding = pg_char_to_encoding(src_encoding_name);
1042 9798 : char *dest_encoding_name = NameStr(*PG_GETARG_NAME(2));
1043 9798 : int dest_encoding = pg_char_to_encoding(dest_encoding_name);
1044 9798 : bool noError = PG_GETARG_BOOL(3);
1045 : TupleDesc tupdesc;
1046 : char *src;
1047 : char *dst;
1048 : bytea *retval;
1049 : Size srclen;
1050 : Size dstsize;
1051 : Oid proc;
1052 : int convertedbytes;
1053 : int dstlen;
1054 : Datum values[2];
1055 9798 : bool nulls[2] = {0};
1056 : HeapTuple tuple;
1057 :
1058 9798 : if (src_encoding < 0)
1059 0 : ereport(ERROR,
1060 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1061 : errmsg("invalid source encoding name \"%s\"",
1062 : src_encoding_name)));
1063 9798 : if (dest_encoding < 0)
1064 0 : ereport(ERROR,
1065 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1066 : errmsg("invalid destination encoding name \"%s\"",
1067 : dest_encoding_name)));
1068 :
1069 : /* Build a tuple descriptor for our result type */
1070 9798 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1071 0 : elog(ERROR, "return type must be a row type");
1072 9798 : tupdesc = BlessTupleDesc(tupdesc);
1073 :
1074 9798 : srclen = VARSIZE_ANY_EXHDR(string);
1075 9798 : src = VARDATA_ANY(string);
1076 :
1077 9798 : if (src_encoding == dest_encoding)
1078 : {
1079 : /* just check that the source string is valid */
1080 : int oklen;
1081 :
1082 4092 : oklen = pg_encoding_verifymbstr(src_encoding, src, srclen);
1083 :
1084 4092 : if (oklen == srclen)
1085 : {
1086 1032 : convertedbytes = oklen;
1087 1032 : retval = string;
1088 : }
1089 3060 : else if (!noError)
1090 : {
1091 1530 : report_invalid_encoding(src_encoding, src + oklen, srclen - oklen);
1092 : }
1093 : else
1094 : {
1095 : /*
1096 : * build bytea data type structure.
1097 : */
1098 : Assert(oklen < srclen);
1099 1530 : convertedbytes = oklen;
1100 1530 : retval = (bytea *) palloc(oklen + VARHDRSZ);
1101 1530 : SET_VARSIZE(retval, oklen + VARHDRSZ);
1102 1530 : memcpy(VARDATA(retval), src, oklen);
1103 : }
1104 : }
1105 : else
1106 : {
1107 5706 : proc = FindDefaultConversionProc(src_encoding, dest_encoding);
1108 5706 : if (!OidIsValid(proc))
1109 0 : ereport(ERROR,
1110 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1111 : errmsg("default conversion function for encoding \"%s\" to \"%s\" does not exist",
1112 : pg_encoding_to_char(src_encoding),
1113 : pg_encoding_to_char(dest_encoding))));
1114 :
1115 5706 : if (srclen >= (MaxAllocSize / (Size) MAX_CONVERSION_GROWTH))
1116 0 : ereport(ERROR,
1117 : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1118 : errmsg("out of memory"),
1119 : errdetail("String of %d bytes is too long for encoding conversion.",
1120 : (int) srclen)));
1121 :
1122 5706 : dstsize = (Size) srclen * MAX_CONVERSION_GROWTH + 1;
1123 5706 : dst = MemoryContextAlloc(CurrentMemoryContext, dstsize);
1124 :
1125 : /* perform conversion */
1126 5706 : convertedbytes = pg_do_encoding_conversion_buf(proc,
1127 : src_encoding,
1128 : dest_encoding,
1129 : (unsigned char *) src, srclen,
1130 : (unsigned char *) dst, dstsize,
1131 : noError);
1132 3366 : dstlen = strlen(dst);
1133 :
1134 : /*
1135 : * build bytea data type structure.
1136 : */
1137 3366 : retval = (bytea *) palloc(dstlen + VARHDRSZ);
1138 3366 : SET_VARSIZE(retval, dstlen + VARHDRSZ);
1139 3366 : memcpy(VARDATA(retval), dst, dstlen);
1140 :
1141 3366 : pfree(dst);
1142 : }
1143 :
1144 5928 : values[0] = Int32GetDatum(convertedbytes);
1145 5928 : values[1] = PointerGetDatum(retval);
1146 5928 : tuple = heap_form_tuple(tupdesc, values, nulls);
1147 :
1148 5928 : PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
1149 : }
1150 :
1151 : /* Provide SQL access to IsBinaryCoercible() */
1152 14 : PG_FUNCTION_INFO_V1(binary_coercible);
1153 : Datum
1154 37500 : binary_coercible(PG_FUNCTION_ARGS)
1155 : {
1156 37500 : Oid srctype = PG_GETARG_OID(0);
1157 37500 : Oid targettype = PG_GETARG_OID(1);
1158 :
1159 37500 : PG_RETURN_BOOL(IsBinaryCoercible(srctype, targettype));
1160 : }
|