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