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