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-2024, 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 : extern char **environ;
651 2 : int nvals = 0;
652 : ArrayType *result;
653 : Datum *env;
654 :
655 70 : for (char **s = environ; *s; s++)
656 68 : nvals++;
657 :
658 2 : env = palloc(nvals * sizeof(Datum));
659 :
660 70 : for (int i = 0; i < nvals; i++)
661 68 : env[i] = CStringGetTextDatum(environ[i]);
662 :
663 2 : result = construct_array_builtin(env, nvals, TEXTOID);
664 :
665 2 : PG_RETURN_POINTER(result);
666 : }
667 :
668 4 : PG_FUNCTION_INFO_V1(regress_setenv);
669 :
670 : Datum
671 2 : regress_setenv(PG_FUNCTION_ARGS)
672 : {
673 2 : char *envvar = text_to_cstring(PG_GETARG_TEXT_PP(0));
674 2 : char *envval = text_to_cstring(PG_GETARG_TEXT_PP(1));
675 :
676 2 : if (!superuser())
677 0 : elog(ERROR, "must be superuser to change environment variables");
678 :
679 2 : if (setenv(envvar, envval, 1) != 0)
680 0 : elog(ERROR, "could not set environment variable: %m");
681 :
682 2 : PG_RETURN_VOID();
683 : }
684 :
685 : /* Sleep until no process has a given PID. */
686 10 : PG_FUNCTION_INFO_V1(wait_pid);
687 :
688 : Datum
689 4 : wait_pid(PG_FUNCTION_ARGS)
690 : {
691 4 : int pid = PG_GETARG_INT32(0);
692 :
693 4 : if (!superuser())
694 0 : elog(ERROR, "must be superuser to check PID liveness");
695 :
696 10 : while (kill(pid, 0) == 0)
697 : {
698 6 : CHECK_FOR_INTERRUPTS();
699 6 : pg_usleep(50000);
700 : }
701 :
702 4 : if (errno != ESRCH)
703 0 : elog(ERROR, "could not check PID %d liveness: %m", pid);
704 :
705 4 : PG_RETURN_VOID();
706 : }
707 :
708 : static void
709 6 : test_atomic_flag(void)
710 : {
711 : pg_atomic_flag flag;
712 :
713 6 : pg_atomic_init_flag(&flag);
714 6 : EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
715 6 : EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
716 6 : EXPECT_TRUE(!pg_atomic_unlocked_test_flag(&flag));
717 6 : EXPECT_TRUE(!pg_atomic_test_set_flag(&flag));
718 6 : pg_atomic_clear_flag(&flag);
719 6 : EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
720 6 : EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
721 6 : pg_atomic_clear_flag(&flag);
722 6 : }
723 :
724 : static void
725 6 : test_atomic_uint32(void)
726 : {
727 : pg_atomic_uint32 var;
728 : uint32 expected;
729 : int i;
730 :
731 6 : pg_atomic_init_u32(&var, 0);
732 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 0);
733 6 : pg_atomic_write_u32(&var, 3);
734 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
735 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, pg_atomic_read_u32(&var) - 2),
736 : 3);
737 6 : EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, 1), 4);
738 6 : EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, 3), 0);
739 6 : EXPECT_EQ_U32(pg_atomic_add_fetch_u32(&var, 10), 10);
740 6 : EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 5), 10);
741 6 : EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 0), 5);
742 :
743 : /* test around numerical limits */
744 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), 0);
745 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), INT_MAX);
746 6 : pg_atomic_fetch_add_u32(&var, 2); /* wrap to 0 */
747 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX), 0);
748 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX + 1),
749 : PG_INT16_MAX);
750 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN),
751 : 2 * PG_INT16_MAX + 1);
752 6 : EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN - 1),
753 : PG_INT16_MAX);
754 6 : pg_atomic_fetch_add_u32(&var, 1); /* top up to UINT_MAX */
755 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), UINT_MAX);
756 6 : EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, INT_MAX), UINT_MAX);
757 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), (uint32) INT_MAX + 1);
758 6 : EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, INT_MAX), 1);
759 6 : pg_atomic_sub_fetch_u32(&var, 1);
760 6 : expected = PG_INT16_MAX;
761 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
762 6 : expected = PG_INT16_MAX + 1;
763 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
764 6 : expected = PG_INT16_MIN;
765 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
766 6 : expected = PG_INT16_MIN - 1;
767 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
768 :
769 : /* fail exchange because of old expected */
770 6 : expected = 10;
771 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
772 :
773 : /* CAS is allowed to fail due to interrupts, try a couple of times */
774 12 : for (i = 0; i < 1000; i++)
775 : {
776 12 : expected = 0;
777 12 : if (!pg_atomic_compare_exchange_u32(&var, &expected, 1))
778 6 : break;
779 : }
780 6 : if (i == 1000)
781 0 : elog(ERROR, "atomic_compare_exchange_u32() never succeeded");
782 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 1);
783 6 : pg_atomic_write_u32(&var, 0);
784 :
785 : /* try setting flagbits */
786 6 : EXPECT_TRUE(!(pg_atomic_fetch_or_u32(&var, 1) & 1));
787 6 : EXPECT_TRUE(pg_atomic_fetch_or_u32(&var, 2) & 1);
788 6 : EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
789 : /* try clearing flagbits */
790 6 : EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~2) & 3, 3);
791 6 : EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~1), 1);
792 : /* no bits set anymore */
793 6 : EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~0), 0);
794 6 : }
795 :
796 : static void
797 6 : test_atomic_uint64(void)
798 : {
799 : pg_atomic_uint64 var;
800 : uint64 expected;
801 : int i;
802 :
803 6 : pg_atomic_init_u64(&var, 0);
804 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 0);
805 6 : pg_atomic_write_u64(&var, 3);
806 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
807 6 : EXPECT_EQ_U64(pg_atomic_fetch_add_u64(&var, pg_atomic_read_u64(&var) - 2),
808 : 3);
809 6 : EXPECT_EQ_U64(pg_atomic_fetch_sub_u64(&var, 1), 4);
810 6 : EXPECT_EQ_U64(pg_atomic_sub_fetch_u64(&var, 3), 0);
811 6 : EXPECT_EQ_U64(pg_atomic_add_fetch_u64(&var, 10), 10);
812 6 : EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 5), 10);
813 6 : EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 0), 5);
814 :
815 : /* fail exchange because of old expected */
816 6 : expected = 10;
817 6 : EXPECT_TRUE(!pg_atomic_compare_exchange_u64(&var, &expected, 1));
818 :
819 : /* CAS is allowed to fail due to interrupts, try a couple of times */
820 12 : for (i = 0; i < 100; i++)
821 : {
822 12 : expected = 0;
823 12 : if (!pg_atomic_compare_exchange_u64(&var, &expected, 1))
824 6 : break;
825 : }
826 6 : if (i == 100)
827 0 : elog(ERROR, "atomic_compare_exchange_u64() never succeeded");
828 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 1);
829 :
830 6 : pg_atomic_write_u64(&var, 0);
831 :
832 : /* try setting flagbits */
833 6 : EXPECT_TRUE(!(pg_atomic_fetch_or_u64(&var, 1) & 1));
834 6 : EXPECT_TRUE(pg_atomic_fetch_or_u64(&var, 2) & 1);
835 6 : EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
836 : /* try clearing flagbits */
837 6 : EXPECT_EQ_U64((pg_atomic_fetch_and_u64(&var, ~2) & 3), 3);
838 6 : EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~1), 1);
839 : /* no bits set anymore */
840 6 : EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~0), 0);
841 6 : }
842 :
843 : /*
844 : * Perform, fairly minimal, testing of the spinlock implementation.
845 : *
846 : * It's likely worth expanding these to actually test concurrency etc, but
847 : * having some regularly run tests is better than none.
848 : */
849 : static void
850 6 : test_spinlock(void)
851 : {
852 : /*
853 : * Basic tests for spinlocks, as well as the underlying operations.
854 : *
855 : * We embed the spinlock in a struct with other members to test that the
856 : * spinlock operations don't perform too wide writes.
857 : */
858 : {
859 : struct test_lock_struct
860 : {
861 : char data_before[4];
862 : slock_t lock;
863 : char data_after[4];
864 : } struct_w_lock;
865 :
866 6 : memcpy(struct_w_lock.data_before, "abcd", 4);
867 6 : memcpy(struct_w_lock.data_after, "ef12", 4);
868 :
869 : /* test basic operations via the SpinLock* API */
870 6 : SpinLockInit(&struct_w_lock.lock);
871 6 : SpinLockAcquire(&struct_w_lock.lock);
872 6 : SpinLockRelease(&struct_w_lock.lock);
873 :
874 : /* test basic operations via underlying S_* API */
875 6 : S_INIT_LOCK(&struct_w_lock.lock);
876 6 : S_LOCK(&struct_w_lock.lock);
877 6 : S_UNLOCK(&struct_w_lock.lock);
878 :
879 : /* and that "contended" acquisition works */
880 6 : s_lock(&struct_w_lock.lock, "testfile", 17, "testfunc");
881 6 : S_UNLOCK(&struct_w_lock.lock);
882 :
883 : /*
884 : * Check, using TAS directly, that a single spin cycle doesn't block
885 : * when acquiring an already acquired lock.
886 : */
887 : #ifdef TAS
888 6 : S_LOCK(&struct_w_lock.lock);
889 :
890 6 : if (!TAS(&struct_w_lock.lock))
891 0 : elog(ERROR, "acquired already held spinlock");
892 :
893 : #ifdef TAS_SPIN
894 6 : if (!TAS_SPIN(&struct_w_lock.lock))
895 0 : elog(ERROR, "acquired already held spinlock");
896 : #endif /* defined(TAS_SPIN) */
897 :
898 6 : S_UNLOCK(&struct_w_lock.lock);
899 : #endif /* defined(TAS) */
900 :
901 : /*
902 : * Verify that after all of this the non-lock contents are still
903 : * correct.
904 : */
905 6 : if (memcmp(struct_w_lock.data_before, "abcd", 4) != 0)
906 0 : elog(ERROR, "padding before spinlock modified");
907 6 : if (memcmp(struct_w_lock.data_after, "ef12", 4) != 0)
908 0 : elog(ERROR, "padding after spinlock modified");
909 : }
910 6 : }
911 :
912 14 : PG_FUNCTION_INFO_V1(test_atomic_ops);
913 : Datum
914 6 : test_atomic_ops(PG_FUNCTION_ARGS)
915 : {
916 6 : test_atomic_flag();
917 :
918 6 : test_atomic_uint32();
919 :
920 6 : test_atomic_uint64();
921 :
922 : /*
923 : * Arguably this shouldn't be tested as part of this function, but it's
924 : * closely enough related that that seems ok for now.
925 : */
926 6 : test_spinlock();
927 :
928 6 : PG_RETURN_BOOL(true);
929 : }
930 :
931 8 : PG_FUNCTION_INFO_V1(test_fdw_handler);
932 : Datum
933 0 : test_fdw_handler(PG_FUNCTION_ARGS)
934 : {
935 0 : elog(ERROR, "test_fdw_handler is not implemented");
936 : PG_RETURN_NULL();
937 : }
938 :
939 14 : PG_FUNCTION_INFO_V1(test_support_func);
940 : Datum
941 60 : test_support_func(PG_FUNCTION_ARGS)
942 : {
943 60 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
944 60 : Node *ret = NULL;
945 :
946 60 : if (IsA(rawreq, SupportRequestSelectivity))
947 : {
948 : /*
949 : * Assume that the target is int4eq; that's safe as long as we don't
950 : * attach this to any other boolean-returning function.
951 : */
952 6 : SupportRequestSelectivity *req = (SupportRequestSelectivity *) rawreq;
953 : Selectivity s1;
954 :
955 6 : if (req->is_join)
956 0 : s1 = join_selectivity(req->root, Int4EqualOperator,
957 : req->args,
958 : req->inputcollid,
959 : req->jointype,
960 0 : req->sjinfo);
961 : else
962 6 : s1 = restriction_selectivity(req->root, Int4EqualOperator,
963 : req->args,
964 : req->inputcollid,
965 : req->varRelid);
966 :
967 6 : req->selectivity = s1;
968 6 : ret = (Node *) req;
969 : }
970 :
971 60 : if (IsA(rawreq, SupportRequestCost))
972 : {
973 : /* Provide some generic estimate */
974 18 : SupportRequestCost *req = (SupportRequestCost *) rawreq;
975 :
976 18 : req->startup = 0;
977 18 : req->per_tuple = 2 * cpu_operator_cost;
978 18 : ret = (Node *) req;
979 : }
980 :
981 60 : if (IsA(rawreq, SupportRequestRows))
982 : {
983 : /*
984 : * Assume that the target is generate_series_int4; that's safe as long
985 : * as we don't attach this to any other set-returning function.
986 : */
987 12 : SupportRequestRows *req = (SupportRequestRows *) rawreq;
988 :
989 12 : if (req->node && IsA(req->node, FuncExpr)) /* be paranoid */
990 : {
991 12 : List *args = ((FuncExpr *) req->node)->args;
992 12 : Node *arg1 = linitial(args);
993 12 : Node *arg2 = lsecond(args);
994 :
995 12 : if (IsA(arg1, Const) &&
996 12 : !((Const *) arg1)->constisnull &&
997 12 : IsA(arg2, Const) &&
998 12 : !((Const *) arg2)->constisnull)
999 : {
1000 12 : int32 val1 = DatumGetInt32(((Const *) arg1)->constvalue);
1001 12 : int32 val2 = DatumGetInt32(((Const *) arg2)->constvalue);
1002 :
1003 12 : req->rows = val2 - val1 + 1;
1004 12 : ret = (Node *) req;
1005 : }
1006 : }
1007 : }
1008 :
1009 60 : PG_RETURN_POINTER(ret);
1010 : }
1011 :
1012 8 : PG_FUNCTION_INFO_V1(test_opclass_options_func);
1013 : Datum
1014 0 : test_opclass_options_func(PG_FUNCTION_ARGS)
1015 : {
1016 0 : PG_RETURN_NULL();
1017 : }
1018 :
1019 : /*
1020 : * Call an encoding conversion or verification function.
1021 : *
1022 : * Arguments:
1023 : * string bytea -- string to convert
1024 : * src_enc name -- source encoding
1025 : * dest_enc name -- destination encoding
1026 : * noError bool -- if set, don't ereport() on invalid or untranslatable
1027 : * input
1028 : *
1029 : * Result is a tuple with two attributes:
1030 : * int4 -- number of input bytes successfully converted
1031 : * bytea -- converted string
1032 : */
1033 14 : PG_FUNCTION_INFO_V1(test_enc_conversion);
1034 : Datum
1035 9798 : test_enc_conversion(PG_FUNCTION_ARGS)
1036 : {
1037 9798 : bytea *string = PG_GETARG_BYTEA_PP(0);
1038 9798 : char *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
1039 9798 : int src_encoding = pg_char_to_encoding(src_encoding_name);
1040 9798 : char *dest_encoding_name = NameStr(*PG_GETARG_NAME(2));
1041 9798 : int dest_encoding = pg_char_to_encoding(dest_encoding_name);
1042 9798 : bool noError = PG_GETARG_BOOL(3);
1043 : TupleDesc tupdesc;
1044 : char *src;
1045 : char *dst;
1046 : bytea *retval;
1047 : Size srclen;
1048 : Size dstsize;
1049 : Oid proc;
1050 : int convertedbytes;
1051 : int dstlen;
1052 : Datum values[2];
1053 9798 : bool nulls[2] = {0};
1054 : HeapTuple tuple;
1055 :
1056 9798 : if (src_encoding < 0)
1057 0 : ereport(ERROR,
1058 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1059 : errmsg("invalid source encoding name \"%s\"",
1060 : src_encoding_name)));
1061 9798 : if (dest_encoding < 0)
1062 0 : ereport(ERROR,
1063 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1064 : errmsg("invalid destination encoding name \"%s\"",
1065 : dest_encoding_name)));
1066 :
1067 : /* Build a tuple descriptor for our result type */
1068 9798 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1069 0 : elog(ERROR, "return type must be a row type");
1070 9798 : tupdesc = BlessTupleDesc(tupdesc);
1071 :
1072 9798 : srclen = VARSIZE_ANY_EXHDR(string);
1073 9798 : src = VARDATA_ANY(string);
1074 :
1075 9798 : if (src_encoding == dest_encoding)
1076 : {
1077 : /* just check that the source string is valid */
1078 : int oklen;
1079 :
1080 4092 : oklen = pg_encoding_verifymbstr(src_encoding, src, srclen);
1081 :
1082 4092 : if (oklen == srclen)
1083 : {
1084 1032 : convertedbytes = oklen;
1085 1032 : retval = string;
1086 : }
1087 3060 : else if (!noError)
1088 : {
1089 1530 : report_invalid_encoding(src_encoding, src + oklen, srclen - oklen);
1090 : }
1091 : else
1092 : {
1093 : /*
1094 : * build bytea data type structure.
1095 : */
1096 : Assert(oklen < srclen);
1097 1530 : convertedbytes = oklen;
1098 1530 : retval = (bytea *) palloc(oklen + VARHDRSZ);
1099 1530 : SET_VARSIZE(retval, oklen + VARHDRSZ);
1100 1530 : memcpy(VARDATA(retval), src, oklen);
1101 : }
1102 : }
1103 : else
1104 : {
1105 5706 : proc = FindDefaultConversionProc(src_encoding, dest_encoding);
1106 5706 : if (!OidIsValid(proc))
1107 0 : ereport(ERROR,
1108 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1109 : errmsg("default conversion function for encoding \"%s\" to \"%s\" does not exist",
1110 : pg_encoding_to_char(src_encoding),
1111 : pg_encoding_to_char(dest_encoding))));
1112 :
1113 5706 : if (srclen >= (MaxAllocSize / (Size) MAX_CONVERSION_GROWTH))
1114 0 : ereport(ERROR,
1115 : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1116 : errmsg("out of memory"),
1117 : errdetail("String of %d bytes is too long for encoding conversion.",
1118 : (int) srclen)));
1119 :
1120 5706 : dstsize = (Size) srclen * MAX_CONVERSION_GROWTH + 1;
1121 5706 : dst = MemoryContextAlloc(CurrentMemoryContext, dstsize);
1122 :
1123 : /* perform conversion */
1124 5706 : convertedbytes = pg_do_encoding_conversion_buf(proc,
1125 : src_encoding,
1126 : dest_encoding,
1127 : (unsigned char *) src, srclen,
1128 : (unsigned char *) dst, dstsize,
1129 : noError);
1130 3366 : dstlen = strlen(dst);
1131 :
1132 : /*
1133 : * build bytea data type structure.
1134 : */
1135 3366 : retval = (bytea *) palloc(dstlen + VARHDRSZ);
1136 3366 : SET_VARSIZE(retval, dstlen + VARHDRSZ);
1137 3366 : memcpy(VARDATA(retval), dst, dstlen);
1138 :
1139 3366 : pfree(dst);
1140 : }
1141 :
1142 5928 : values[0] = Int32GetDatum(convertedbytes);
1143 5928 : values[1] = PointerGetDatum(retval);
1144 5928 : tuple = heap_form_tuple(tupdesc, values, nulls);
1145 :
1146 5928 : PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
1147 : }
1148 :
1149 : /* Provide SQL access to IsBinaryCoercible() */
1150 14 : PG_FUNCTION_INFO_V1(binary_coercible);
1151 : Datum
1152 37500 : binary_coercible(PG_FUNCTION_ARGS)
1153 : {
1154 37500 : Oid srctype = PG_GETARG_OID(0);
1155 37500 : Oid targettype = PG_GETARG_OID(1);
1156 :
1157 37500 : PG_RETURN_BOOL(IsBinaryCoercible(srctype, targettype));
1158 : }
|