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