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