LCOV - code coverage report
Current view: top level - src/test/regress - regress.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 90.6 % 587 532
Test Date: 2026-05-04 01:16:22 Functions: 97.4 % 76 74
Legend: Lines:     hit not hit

            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-2026, 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 "common/pg_lzcompress.h"
      31              : #include "executor/executor.h"
      32              : #include "executor/functions.h"
      33              : #include "executor/spi.h"
      34              : #include "funcapi.h"
      35              : #include "mb/pg_wchar.h"
      36              : #include "miscadmin.h"
      37              : #include "nodes/supportnodes.h"
      38              : #include "optimizer/optimizer.h"
      39              : #include "optimizer/plancat.h"
      40              : #include "parser/parse_coerce.h"
      41              : #include "port/atomics.h"
      42              : #include "portability/instr_time.h"
      43              : #include "postmaster/postmaster.h"    /* for MAX_BACKENDS */
      44              : #include "storage/spin.h"
      45              : #include "tcop/tcopprot.h"
      46              : #include "utils/array.h"
      47              : #include "utils/builtins.h"
      48              : #include "utils/geo_decls.h"
      49              : #include "utils/memutils.h"
      50              : #include "utils/rel.h"
      51              : #include "utils/typcache.h"
      52              : 
      53              : /* define our text domain for translations */
      54              : #undef TEXTDOMAIN
      55              : #define TEXTDOMAIN PG_TEXTDOMAIN("postgresql-regress")
      56              : 
      57              : #define EXPECT_TRUE(expr)   \
      58              :     do { \
      59              :         if (!(expr)) \
      60              :             elog(ERROR, \
      61              :                  "%s was unexpectedly false in file \"%s\" line %u", \
      62              :                  #expr, __FILE__, __LINE__); \
      63              :     } while (0)
      64              : 
      65              : #define EXPECT_EQ_U32(result_expr, expected_expr)   \
      66              :     do { \
      67              :         uint32      actual_result = (result_expr); \
      68              :         uint32      expected_result = (expected_expr); \
      69              :         if (actual_result != expected_result) \
      70              :             elog(ERROR, \
      71              :                  "%s yielded %u, expected %s in file \"%s\" line %u", \
      72              :                  #result_expr, actual_result, #expected_expr, __FILE__, __LINE__); \
      73              :     } while (0)
      74              : 
      75              : #define EXPECT_EQ_U64(result_expr, expected_expr)   \
      76              :     do { \
      77              :         uint64      actual_result = (result_expr); \
      78              :         uint64      expected_result = (expected_expr); \
      79              :         if (actual_result != expected_result) \
      80              :             elog(ERROR, \
      81              :                  "%s yielded " UINT64_FORMAT ", expected %s in file \"%s\" line %u", \
      82              :                  #result_expr, actual_result, #expected_expr, __FILE__, __LINE__); \
      83              :     } while (0)
      84              : 
      85              : #define LDELIM          '('
      86              : #define RDELIM          ')'
      87              : #define DELIM           ','
      88              : 
      89              : static void regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2);
      90              : 
      91           95 : PG_MODULE_MAGIC_EXT(
      92              :                     .name = "regress",
      93              :                     .version = PG_VERSION
      94              : );
      95              : 
      96              : 
      97              : /* return the point where two paths intersect, or NULL if no intersection. */
      98            9 : PG_FUNCTION_INFO_V1(interpt_pp);
      99              : 
     100              : Datum
     101         3584 : interpt_pp(PG_FUNCTION_ARGS)
     102              : {
     103         3584 :     PATH       *p1 = PG_GETARG_PATH_P(0);
     104         3584 :     PATH       *p2 = PG_GETARG_PATH_P(1);
     105              :     int         i,
     106              :                 j;
     107              :     LSEG        seg1,
     108              :                 seg2;
     109              :     bool        found;          /* We've found the intersection */
     110              : 
     111         3584 :     found = false;              /* Haven't found it yet */
     112              : 
     113        11764 :     for (i = 0; i < p1->npts - 1 && !found; i++)
     114              :     {
     115         8180 :         regress_lseg_construct(&seg1, &p1->p[i], &p1->p[i + 1]);
     116        25092 :         for (j = 0; j < p2->npts - 1 && !found; j++)
     117              :         {
     118        16912 :             regress_lseg_construct(&seg2, &p2->p[j], &p2->p[j + 1]);
     119        16912 :             if (DatumGetBool(DirectFunctionCall2(lseg_intersect,
     120              :                                                  LsegPGetDatum(&seg1),
     121              :                                                  LsegPGetDatum(&seg2))))
     122         3576 :                 found = true;
     123              :         }
     124              :     }
     125              : 
     126         3584 :     if (!found)
     127            8 :         PG_RETURN_NULL();
     128              : 
     129              :     /*
     130              :      * Note: DirectFunctionCall2 will kick out an error if lseg_interpt()
     131              :      * returns NULL, but that should be impossible since we know the two
     132              :      * segments intersect.
     133              :      */
     134         3576 :     PG_RETURN_DATUM(DirectFunctionCall2(lseg_interpt,
     135              :                                         LsegPGetDatum(&seg1),
     136              :                                         LsegPGetDatum(&seg2)));
     137              : }
     138              : 
     139              : 
     140              : /* like lseg_construct, but assume space already allocated */
     141              : static void
     142        25092 : regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2)
     143              : {
     144        25092 :     lseg->p[0].x = pt1->x;
     145        25092 :     lseg->p[0].y = pt1->y;
     146        25092 :     lseg->p[1].x = pt2->x;
     147        25092 :     lseg->p[1].y = pt2->y;
     148        25092 : }
     149              : 
     150            9 : PG_FUNCTION_INFO_V1(overpaid);
     151              : 
     152              : Datum
     153           24 : overpaid(PG_FUNCTION_ARGS)
     154              : {
     155           24 :     HeapTupleHeader tuple = PG_GETARG_HEAPTUPLEHEADER(0);
     156              :     bool        isnull;
     157              :     int32       salary;
     158              : 
     159           24 :     salary = DatumGetInt32(GetAttributeByName(tuple, "salary", &isnull));
     160           24 :     if (isnull)
     161            0 :         PG_RETURN_NULL();
     162           24 :     PG_RETURN_BOOL(salary > 699);
     163              : }
     164              : 
     165              : /* New type "widget"
     166              :  * This used to be "circle", but I added circle to builtins,
     167              :  *  so needed to make sure the names do not collide. - tgl 97/04/21
     168              :  */
     169              : 
     170              : typedef struct
     171              : {
     172              :     Point       center;
     173              :     double      radius;
     174              : } WIDGET;
     175              : 
     176           13 : PG_FUNCTION_INFO_V1(widget_in);
     177            9 : PG_FUNCTION_INFO_V1(widget_out);
     178              : 
     179              : #define NARGS   3
     180              : 
     181              : Datum
     182           44 : widget_in(PG_FUNCTION_ARGS)
     183              : {
     184           44 :     char       *str = PG_GETARG_CSTRING(0);
     185              :     char       *p,
     186              :                *coord[NARGS];
     187              :     int         i;
     188              :     WIDGET     *result;
     189              : 
     190          252 :     for (i = 0, p = str; *p && i < NARGS && *p != RDELIM; p++)
     191              :     {
     192          208 :         if (*p == DELIM || (*p == LDELIM && i == 0))
     193          108 :             coord[i++] = p + 1;
     194              :     }
     195              : 
     196              :     /*
     197              :      * Note: DON'T convert this error to "soft" style (errsave/ereturn).  We
     198              :      * want this data type to stay permanently in the hard-error world so that
     199              :      * it can be used for testing that such cases still work reasonably.
     200              :      */
     201           44 :     if (i < NARGS)
     202           16 :         ereport(ERROR,
     203              :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     204              :                  errmsg("invalid input syntax for type %s: \"%s\"",
     205              :                         "widget", str)));
     206              : 
     207           28 :     result = palloc_object(WIDGET);
     208           28 :     result->center.x = atof(coord[0]);
     209           28 :     result->center.y = atof(coord[1]);
     210           28 :     result->radius = atof(coord[2]);
     211              : 
     212           28 :     PG_RETURN_POINTER(result);
     213              : }
     214              : 
     215              : Datum
     216            8 : widget_out(PG_FUNCTION_ARGS)
     217              : {
     218            8 :     WIDGET     *widget = (WIDGET *) PG_GETARG_POINTER(0);
     219            8 :     char       *str = psprintf("(%g,%g,%g)",
     220              :                                widget->center.x, widget->center.y, widget->radius);
     221              : 
     222            8 :     PG_RETURN_CSTRING(str);
     223              : }
     224              : 
     225            9 : PG_FUNCTION_INFO_V1(pt_in_widget);
     226              : 
     227              : Datum
     228            8 : pt_in_widget(PG_FUNCTION_ARGS)
     229              : {
     230            8 :     Point      *point = PG_GETARG_POINT_P(0);
     231            8 :     WIDGET     *widget = (WIDGET *) PG_GETARG_POINTER(1);
     232              :     float8      distance;
     233              : 
     234            8 :     distance = DatumGetFloat8(DirectFunctionCall2(point_distance,
     235              :                                                   PointPGetDatum(point),
     236              :                                                   PointPGetDatum(&widget->center)));
     237              : 
     238            8 :     PG_RETURN_BOOL(distance < widget->radius);
     239              : }
     240              : 
     241            9 : PG_FUNCTION_INFO_V1(reverse_name);
     242              : 
     243              : Datum
     244           32 : reverse_name(PG_FUNCTION_ARGS)
     245              : {
     246           32 :     char       *string = PG_GETARG_CSTRING(0);
     247              :     int         i;
     248              :     int         len;
     249              :     char       *new_string;
     250              : 
     251           32 :     new_string = palloc0(NAMEDATALEN);
     252          224 :     for (i = 0; i < NAMEDATALEN && string[i]; ++i)
     253              :         ;
     254           32 :     if (i == NAMEDATALEN || !string[i])
     255           32 :         --i;
     256           32 :     len = i;
     257          224 :     for (; i >= 0; --i)
     258          192 :         new_string[len - i] = string[i];
     259           32 :     PG_RETURN_CSTRING(new_string);
     260              : }
     261              : 
     262            9 : PG_FUNCTION_INFO_V1(trigger_return_old);
     263              : 
     264              : Datum
     265           60 : trigger_return_old(PG_FUNCTION_ARGS)
     266              : {
     267           60 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
     268              :     HeapTuple   tuple;
     269              : 
     270           60 :     if (!CALLED_AS_TRIGGER(fcinfo))
     271            0 :         elog(ERROR, "trigger_return_old: not fired by trigger manager");
     272              : 
     273           60 :     tuple = trigdata->tg_trigtuple;
     274              : 
     275           60 :     return PointerGetDatum(tuple);
     276              : }
     277              : 
     278              : 
     279              : /*
     280              :  * Type int44 has no real-world use, but the regression tests use it
     281              :  * (under the alias "city_budget").  It's a four-element vector of int4's.
     282              :  */
     283              : 
     284              : /*
     285              :  *      int44in         - converts "num, num, ..." to internal form
     286              :  *
     287              :  *      Note: Fills any missing positions with zeroes.
     288              :  */
     289            9 : PG_FUNCTION_INFO_V1(int44in);
     290              : 
     291              : Datum
     292            8 : int44in(PG_FUNCTION_ARGS)
     293              : {
     294            8 :     char       *input_string = PG_GETARG_CSTRING(0);
     295            8 :     int32      *result = (int32 *) palloc(4 * sizeof(int32));
     296              :     int         i;
     297              : 
     298            8 :     i = sscanf(input_string,
     299              :                "%d, %d, %d, %d",
     300              :                &result[0],
     301              :                &result[1],
     302              :                &result[2],
     303              :                &result[3]);
     304           12 :     while (i < 4)
     305            4 :         result[i++] = 0;
     306              : 
     307            8 :     PG_RETURN_POINTER(result);
     308              : }
     309              : 
     310              : /*
     311              :  *      int44out        - converts internal form to "num, num, ..."
     312              :  */
     313           13 : PG_FUNCTION_INFO_V1(int44out);
     314              : 
     315              : Datum
     316           16 : int44out(PG_FUNCTION_ARGS)
     317              : {
     318           16 :     int32      *an_array = (int32 *) PG_GETARG_POINTER(0);
     319           16 :     char       *result = (char *) palloc(16 * 4);
     320              : 
     321           16 :     snprintf(result, 16 * 4, "%d,%d,%d,%d",
     322              :              an_array[0],
     323           16 :              an_array[1],
     324           16 :              an_array[2],
     325           16 :              an_array[3]);
     326              : 
     327           16 :     PG_RETURN_CSTRING(result);
     328              : }
     329              : 
     330            9 : PG_FUNCTION_INFO_V1(test_canonicalize_path);
     331              : Datum
     332          110 : test_canonicalize_path(PG_FUNCTION_ARGS)
     333              : {
     334          110 :     char       *path = text_to_cstring(PG_GETARG_TEXT_PP(0));
     335              : 
     336          110 :     canonicalize_path(path);
     337          110 :     PG_RETURN_TEXT_P(cstring_to_text(path));
     338              : }
     339              : 
     340            9 : PG_FUNCTION_INFO_V1(make_tuple_indirect);
     341              : Datum
     342           84 : make_tuple_indirect(PG_FUNCTION_ARGS)
     343              : {
     344           84 :     HeapTupleHeader rec = PG_GETARG_HEAPTUPLEHEADER(0);
     345              :     HeapTupleData tuple;
     346              :     int         ncolumns;
     347              :     Datum      *values;
     348              :     bool       *nulls;
     349              : 
     350              :     Oid         tupType;
     351              :     int32       tupTypmod;
     352              :     TupleDesc   tupdesc;
     353              : 
     354              :     HeapTuple   newtup;
     355              : 
     356              :     int         i;
     357              : 
     358              :     MemoryContext old_context;
     359              : 
     360              :     /* Extract type info from the tuple itself */
     361           84 :     tupType = HeapTupleHeaderGetTypeId(rec);
     362           84 :     tupTypmod = HeapTupleHeaderGetTypMod(rec);
     363           84 :     tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
     364           84 :     ncolumns = tupdesc->natts;
     365              : 
     366              :     /* Build a temporary HeapTuple control structure */
     367           84 :     tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
     368           84 :     ItemPointerSetInvalid(&(tuple.t_self));
     369           84 :     tuple.t_tableOid = InvalidOid;
     370           84 :     tuple.t_data = rec;
     371              : 
     372           84 :     values = (Datum *) palloc(ncolumns * sizeof(Datum));
     373           84 :     nulls = (bool *) palloc(ncolumns * sizeof(bool));
     374              : 
     375           84 :     heap_deform_tuple(&tuple, tupdesc, values, nulls);
     376              : 
     377           84 :     old_context = MemoryContextSwitchTo(TopTransactionContext);
     378              : 
     379          420 :     for (i = 0; i < ncolumns; i++)
     380              :     {
     381              :         varlena    *attr;
     382              :         varlena    *new_attr;
     383              :         varatt_indirect redirect_pointer;
     384              : 
     385              :         /* only work on existing, not-null varlenas */
     386          336 :         if (TupleDescAttr(tupdesc, i)->attisdropped ||
     387          336 :             nulls[i] ||
     388          292 :             TupleDescAttr(tupdesc, i)->attlen != -1 ||
     389          208 :             TupleDescAttr(tupdesc, i)->attstorage == TYPSTORAGE_PLAIN)
     390          128 :             continue;
     391              : 
     392          208 :         attr = (varlena *) DatumGetPointer(values[i]);
     393              : 
     394              :         /* don't recursively indirect */
     395          208 :         if (VARATT_IS_EXTERNAL_INDIRECT(attr))
     396            0 :             continue;
     397              : 
     398              :         /* copy datum, so it still lives later */
     399          208 :         if (VARATT_IS_EXTERNAL_ONDISK(attr))
     400            0 :             attr = detoast_external_attr(attr);
     401              :         else
     402              :         {
     403          208 :             varlena    *oldattr = attr;
     404              : 
     405          208 :             attr = palloc0(VARSIZE_ANY(oldattr));
     406          208 :             memcpy(attr, oldattr, VARSIZE_ANY(oldattr));
     407              :         }
     408              : 
     409              :         /* build indirection Datum */
     410          208 :         new_attr = (varlena *) palloc0(INDIRECT_POINTER_SIZE);
     411          208 :         redirect_pointer.pointer = attr;
     412          208 :         SET_VARTAG_EXTERNAL(new_attr, VARTAG_INDIRECT);
     413          208 :         memcpy(VARDATA_EXTERNAL(new_attr), &redirect_pointer,
     414              :                sizeof(redirect_pointer));
     415              : 
     416          208 :         values[i] = PointerGetDatum(new_attr);
     417              :     }
     418              : 
     419           84 :     newtup = heap_form_tuple(tupdesc, values, nulls);
     420           84 :     pfree(values);
     421           84 :     pfree(nulls);
     422           84 :     ReleaseTupleDesc(tupdesc);
     423              : 
     424           84 :     MemoryContextSwitchTo(old_context);
     425              : 
     426              :     /*
     427              :      * We intentionally don't use PG_RETURN_HEAPTUPLEHEADER here, because that
     428              :      * would cause the indirect toast pointers to be flattened out of the
     429              :      * tuple immediately, rendering subsequent testing irrelevant.  So just
     430              :      * return the HeapTupleHeader pointer as-is.  This violates the general
     431              :      * rule that composite Datums shouldn't contain toast pointers, but so
     432              :      * long as the regression test scripts don't insert the result of this
     433              :      * function into a container type (record, array, etc) it should be OK.
     434              :      */
     435           84 :     PG_RETURN_POINTER(newtup->t_data);
     436              : }
     437              : 
     438            2 : PG_FUNCTION_INFO_V1(get_environ);
     439              : 
     440              : Datum
     441            1 : get_environ(PG_FUNCTION_ARGS)
     442              : {
     443              : #if !defined(WIN32)
     444              :     extern char **environ;
     445              : #endif
     446            1 :     int         nvals = 0;
     447              :     ArrayType  *result;
     448              :     Datum      *env;
     449              : 
     450           35 :     for (char **s = environ; *s; s++)
     451           34 :         nvals++;
     452              : 
     453            1 :     env = palloc(nvals * sizeof(Datum));
     454              : 
     455           35 :     for (int i = 0; i < nvals; i++)
     456           34 :         env[i] = CStringGetTextDatum(environ[i]);
     457              : 
     458            1 :     result = construct_array_builtin(env, nvals, TEXTOID);
     459              : 
     460            1 :     PG_RETURN_POINTER(result);
     461              : }
     462              : 
     463            2 : PG_FUNCTION_INFO_V1(regress_setenv);
     464              : 
     465              : Datum
     466            1 : regress_setenv(PG_FUNCTION_ARGS)
     467              : {
     468            1 :     char       *envvar = text_to_cstring(PG_GETARG_TEXT_PP(0));
     469            1 :     char       *envval = text_to_cstring(PG_GETARG_TEXT_PP(1));
     470              : 
     471            1 :     if (!superuser())
     472            0 :         elog(ERROR, "must be superuser to change environment variables");
     473              : 
     474            1 :     if (setenv(envvar, envval, 1) != 0)
     475            0 :         elog(ERROR, "could not set environment variable: %m");
     476              : 
     477            1 :     PG_RETURN_VOID();
     478              : }
     479              : 
     480              : /* Sleep until no process has a given PID. */
     481            5 : PG_FUNCTION_INFO_V1(wait_pid);
     482              : 
     483              : Datum
     484            2 : wait_pid(PG_FUNCTION_ARGS)
     485              : {
     486            2 :     int         pid = PG_GETARG_INT32(0);
     487              : 
     488            2 :     if (!superuser())
     489            0 :         elog(ERROR, "must be superuser to check PID liveness");
     490              : 
     491            7 :     while (kill(pid, 0) == 0)
     492              :     {
     493            5 :         CHECK_FOR_INTERRUPTS();
     494            5 :         pg_usleep(50000);
     495              :     }
     496              : 
     497            2 :     if (errno != ESRCH)
     498            0 :         elog(ERROR, "could not check PID %d liveness: %m", pid);
     499              : 
     500            2 :     PG_RETURN_VOID();
     501              : }
     502              : 
     503              : static void
     504            4 : test_atomic_flag(void)
     505              : {
     506              :     pg_atomic_flag flag;
     507              : 
     508            4 :     pg_atomic_init_flag(&flag);
     509            4 :     EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
     510            4 :     EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
     511            4 :     EXPECT_TRUE(!pg_atomic_unlocked_test_flag(&flag));
     512            4 :     EXPECT_TRUE(!pg_atomic_test_set_flag(&flag));
     513            4 :     pg_atomic_clear_flag(&flag);
     514            4 :     EXPECT_TRUE(pg_atomic_unlocked_test_flag(&flag));
     515            4 :     EXPECT_TRUE(pg_atomic_test_set_flag(&flag));
     516            4 :     pg_atomic_clear_flag(&flag);
     517            4 : }
     518              : 
     519              : static void
     520            4 : test_atomic_uint32(void)
     521              : {
     522              :     pg_atomic_uint32 var;
     523              :     uint32      expected;
     524              :     int         i;
     525              : 
     526            4 :     pg_atomic_init_u32(&var, 0);
     527            4 :     EXPECT_EQ_U32(pg_atomic_read_u32(&var), 0);
     528            4 :     pg_atomic_write_u32(&var, 3);
     529            4 :     EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
     530            4 :     EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, pg_atomic_read_u32(&var) - 2),
     531              :                   3);
     532            4 :     EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, 1), 4);
     533            4 :     EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, 3), 0);
     534            4 :     EXPECT_EQ_U32(pg_atomic_add_fetch_u32(&var, 10), 10);
     535            4 :     EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 5), 10);
     536            4 :     EXPECT_EQ_U32(pg_atomic_exchange_u32(&var, 0), 5);
     537              : 
     538              :     /* test around numerical limits */
     539            4 :     EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), 0);
     540            4 :     EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, INT_MAX), INT_MAX);
     541            4 :     pg_atomic_fetch_add_u32(&var, 2);   /* wrap to 0 */
     542            4 :     EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX), 0);
     543            4 :     EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MAX + 1),
     544              :                   PG_INT16_MAX);
     545            4 :     EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN),
     546              :                   2 * PG_INT16_MAX + 1);
     547            4 :     EXPECT_EQ_U32(pg_atomic_fetch_add_u32(&var, PG_INT16_MIN - 1),
     548              :                   PG_INT16_MAX);
     549            4 :     pg_atomic_fetch_add_u32(&var, 1);   /* top up to UINT_MAX */
     550            4 :     EXPECT_EQ_U32(pg_atomic_read_u32(&var), UINT_MAX);
     551            4 :     EXPECT_EQ_U32(pg_atomic_fetch_sub_u32(&var, INT_MAX), UINT_MAX);
     552            4 :     EXPECT_EQ_U32(pg_atomic_read_u32(&var), (uint32) INT_MAX + 1);
     553            4 :     EXPECT_EQ_U32(pg_atomic_sub_fetch_u32(&var, INT_MAX), 1);
     554            4 :     pg_atomic_sub_fetch_u32(&var, 1);
     555            4 :     expected = PG_INT16_MAX;
     556            4 :     EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
     557            4 :     expected = PG_INT16_MAX + 1;
     558            4 :     EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
     559            4 :     expected = PG_INT16_MIN;
     560            4 :     EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
     561            4 :     expected = PG_INT16_MIN - 1;
     562            4 :     EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
     563              : 
     564              :     /* fail exchange because of old expected */
     565            4 :     expected = 10;
     566            4 :     EXPECT_TRUE(!pg_atomic_compare_exchange_u32(&var, &expected, 1));
     567              : 
     568              :     /* CAS is allowed to fail due to interrupts, try a couple of times */
     569            8 :     for (i = 0; i < 1000; i++)
     570              :     {
     571            8 :         expected = 0;
     572            8 :         if (!pg_atomic_compare_exchange_u32(&var, &expected, 1))
     573            4 :             break;
     574              :     }
     575            4 :     if (i == 1000)
     576            0 :         elog(ERROR, "atomic_compare_exchange_u32() never succeeded");
     577            4 :     EXPECT_EQ_U32(pg_atomic_read_u32(&var), 1);
     578            4 :     pg_atomic_write_u32(&var, 0);
     579              : 
     580              :     /* try setting flagbits */
     581            4 :     EXPECT_TRUE(!(pg_atomic_fetch_or_u32(&var, 1) & 1));
     582            4 :     EXPECT_TRUE(pg_atomic_fetch_or_u32(&var, 2) & 1);
     583            4 :     EXPECT_EQ_U32(pg_atomic_read_u32(&var), 3);
     584              :     /* try clearing flagbits */
     585            4 :     EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~2) & 3, 3);
     586            4 :     EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~1), 1);
     587              :     /* no bits set anymore */
     588            4 :     EXPECT_EQ_U32(pg_atomic_fetch_and_u32(&var, ~0), 0);
     589            4 : }
     590              : 
     591              : static void
     592            4 : test_atomic_uint64(void)
     593              : {
     594              :     pg_atomic_uint64 var;
     595              :     uint64      expected;
     596              :     int         i;
     597              : 
     598            4 :     pg_atomic_init_u64(&var, 0);
     599            4 :     EXPECT_EQ_U64(pg_atomic_read_u64(&var), 0);
     600            4 :     pg_atomic_write_u64(&var, 3);
     601            4 :     EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
     602            4 :     EXPECT_EQ_U64(pg_atomic_fetch_add_u64(&var, pg_atomic_read_u64(&var) - 2),
     603              :                   3);
     604            4 :     EXPECT_EQ_U64(pg_atomic_fetch_sub_u64(&var, 1), 4);
     605            4 :     EXPECT_EQ_U64(pg_atomic_sub_fetch_u64(&var, 3), 0);
     606            4 :     EXPECT_EQ_U64(pg_atomic_add_fetch_u64(&var, 10), 10);
     607            4 :     EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 5), 10);
     608            4 :     EXPECT_EQ_U64(pg_atomic_exchange_u64(&var, 0), 5);
     609              : 
     610              :     /* fail exchange because of old expected */
     611            4 :     expected = 10;
     612            4 :     EXPECT_TRUE(!pg_atomic_compare_exchange_u64(&var, &expected, 1));
     613              : 
     614              :     /* CAS is allowed to fail due to interrupts, try a couple of times */
     615            8 :     for (i = 0; i < 100; i++)
     616              :     {
     617            8 :         expected = 0;
     618            8 :         if (!pg_atomic_compare_exchange_u64(&var, &expected, 1))
     619            4 :             break;
     620              :     }
     621            4 :     if (i == 100)
     622            0 :         elog(ERROR, "atomic_compare_exchange_u64() never succeeded");
     623            4 :     EXPECT_EQ_U64(pg_atomic_read_u64(&var), 1);
     624              : 
     625            4 :     pg_atomic_write_u64(&var, 0);
     626              : 
     627              :     /* try setting flagbits */
     628            4 :     EXPECT_TRUE(!(pg_atomic_fetch_or_u64(&var, 1) & 1));
     629            4 :     EXPECT_TRUE(pg_atomic_fetch_or_u64(&var, 2) & 1);
     630            4 :     EXPECT_EQ_U64(pg_atomic_read_u64(&var), 3);
     631              :     /* try clearing flagbits */
     632            4 :     EXPECT_EQ_U64((pg_atomic_fetch_and_u64(&var, ~2) & 3), 3);
     633            4 :     EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~1), 1);
     634              :     /* no bits set anymore */
     635            4 :     EXPECT_EQ_U64(pg_atomic_fetch_and_u64(&var, ~0), 0);
     636            4 : }
     637              : 
     638              : /*
     639              :  * Perform, fairly minimal, testing of the spinlock implementation.
     640              :  *
     641              :  * It's likely worth expanding these to actually test concurrency etc, but
     642              :  * having some regularly run tests is better than none.
     643              :  */
     644              : static void
     645            4 : test_spinlock(void)
     646              : {
     647              :     /*
     648              :      * Basic tests for spinlocks, as well as the underlying operations.
     649              :      *
     650              :      * We embed the spinlock in a struct with other members to test that the
     651              :      * spinlock operations don't perform too wide writes.
     652              :      */
     653              :     {
     654              :         struct test_lock_struct
     655              :         {
     656              :             char        data_before[4];
     657              :             slock_t     lock;
     658              :             char        data_after[4];
     659              :         }           struct_w_lock;
     660              : 
     661            4 :         memcpy(struct_w_lock.data_before, "abcd", 4);
     662            4 :         memcpy(struct_w_lock.data_after, "ef12", 4);
     663              : 
     664              :         /* test basic operations via the SpinLock* API */
     665            4 :         SpinLockInit(&struct_w_lock.lock);
     666            4 :         SpinLockAcquire(&struct_w_lock.lock);
     667            4 :         SpinLockRelease(&struct_w_lock.lock);
     668              : 
     669              :         /* test basic operations via underlying S_* API */
     670            4 :         S_INIT_LOCK(&struct_w_lock.lock);
     671            4 :         S_LOCK(&struct_w_lock.lock);
     672            4 :         S_UNLOCK(&struct_w_lock.lock);
     673              : 
     674              :         /* and that "contended" acquisition works */
     675            4 :         s_lock(&struct_w_lock.lock, "testfile", 17, "testfunc");
     676            4 :         S_UNLOCK(&struct_w_lock.lock);
     677              : 
     678              :         /*
     679              :          * Check, using TAS directly, that a single spin cycle doesn't block
     680              :          * when acquiring an already acquired lock.
     681              :          */
     682              : #ifdef TAS
     683            4 :         S_LOCK(&struct_w_lock.lock);
     684              : 
     685            4 :         if (!TAS(&struct_w_lock.lock))
     686            0 :             elog(ERROR, "acquired already held spinlock");
     687              : 
     688              : #ifdef TAS_SPIN
     689            4 :         if (!TAS_SPIN(&struct_w_lock.lock))
     690            0 :             elog(ERROR, "acquired already held spinlock");
     691              : #endif                          /* defined(TAS_SPIN) */
     692              : 
     693            4 :         S_UNLOCK(&struct_w_lock.lock);
     694              : #endif                          /* defined(TAS) */
     695              : 
     696              :         /*
     697              :          * Verify that after all of this the non-lock contents are still
     698              :          * correct.
     699              :          */
     700            4 :         if (memcmp(struct_w_lock.data_before, "abcd", 4) != 0)
     701            0 :             elog(ERROR, "padding before spinlock modified");
     702            4 :         if (memcmp(struct_w_lock.data_after, "ef12", 4) != 0)
     703            0 :             elog(ERROR, "padding after spinlock modified");
     704              :     }
     705            4 : }
     706              : 
     707            9 : PG_FUNCTION_INFO_V1(test_atomic_ops);
     708              : Datum
     709            4 : test_atomic_ops(PG_FUNCTION_ARGS)
     710              : {
     711            4 :     test_atomic_flag();
     712              : 
     713            4 :     test_atomic_uint32();
     714              : 
     715            4 :     test_atomic_uint64();
     716              : 
     717              :     /*
     718              :      * Arguably this shouldn't be tested as part of this function, but it's
     719              :      * closely enough related that that seems ok for now.
     720              :      */
     721            4 :     test_spinlock();
     722              : 
     723            4 :     PG_RETURN_BOOL(true);
     724              : }
     725              : 
     726            5 : PG_FUNCTION_INFO_V1(test_fdw_handler);
     727              : Datum
     728            0 : test_fdw_handler(PG_FUNCTION_ARGS)
     729              : {
     730            0 :     elog(ERROR, "test_fdw_handler is not implemented");
     731              :     PG_RETURN_NULL();
     732              : }
     733              : 
     734           13 : PG_FUNCTION_INFO_V1(test_fdw_connection);
     735              : Datum
     736            8 : test_fdw_connection(PG_FUNCTION_ARGS)
     737              : {
     738            8 :     PG_RETURN_TEXT_P(cstring_to_text("dbname=regress_doesnotexist user=doesnotexist password=secret"));
     739              : }
     740              : 
     741            9 : PG_FUNCTION_INFO_V1(is_catalog_text_unique_index_oid);
     742              : Datum
     743          880 : is_catalog_text_unique_index_oid(PG_FUNCTION_ARGS)
     744              : {
     745          880 :     return BoolGetDatum(IsCatalogTextUniqueIndexOid(PG_GETARG_OID(0)));
     746              : }
     747              : 
     748            9 : PG_FUNCTION_INFO_V1(test_support_func);
     749              : Datum
     750           60 : test_support_func(PG_FUNCTION_ARGS)
     751              : {
     752           60 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
     753           60 :     Node       *ret = NULL;
     754              : 
     755           60 :     if (IsA(rawreq, SupportRequestSelectivity))
     756              :     {
     757              :         /*
     758              :          * Assume that the target is int4eq; that's safe as long as we don't
     759              :          * attach this to any other boolean-returning function.
     760              :          */
     761            5 :         SupportRequestSelectivity *req = (SupportRequestSelectivity *) rawreq;
     762              :         Selectivity s1;
     763              : 
     764            5 :         if (req->is_join)
     765            0 :             s1 = join_selectivity(req->root, Int4EqualOperator,
     766              :                                   req->args,
     767              :                                   req->inputcollid,
     768              :                                   req->jointype,
     769              :                                   req->sjinfo);
     770              :         else
     771            5 :             s1 = restriction_selectivity(req->root, Int4EqualOperator,
     772              :                                          req->args,
     773              :                                          req->inputcollid,
     774              :                                          req->varRelid);
     775              : 
     776            5 :         req->selectivity = s1;
     777            5 :         ret = (Node *) req;
     778              :     }
     779              : 
     780           60 :     if (IsA(rawreq, SupportRequestCost))
     781              :     {
     782              :         /* Provide some generic estimate */
     783           15 :         SupportRequestCost *req = (SupportRequestCost *) rawreq;
     784              : 
     785           15 :         req->startup = 0;
     786           15 :         req->per_tuple = 2 * cpu_operator_cost;
     787           15 :         ret = (Node *) req;
     788              :     }
     789              : 
     790           60 :     if (IsA(rawreq, SupportRequestRows))
     791              :     {
     792              :         /*
     793              :          * Assume that the target is generate_series_int4; that's safe as long
     794              :          * as we don't attach this to any other set-returning function.
     795              :          */
     796           10 :         SupportRequestRows *req = (SupportRequestRows *) rawreq;
     797              : 
     798           10 :         if (req->node && IsA(req->node, FuncExpr))    /* be paranoid */
     799              :         {
     800           10 :             List       *args = ((FuncExpr *) req->node)->args;
     801           10 :             Node       *arg1 = linitial(args);
     802           10 :             Node       *arg2 = lsecond(args);
     803              : 
     804           10 :             if (IsA(arg1, Const) &&
     805           10 :                 !((Const *) arg1)->constisnull &&
     806           10 :                 IsA(arg2, Const) &&
     807           10 :                 !((Const *) arg2)->constisnull)
     808              :             {
     809           10 :                 int32       val1 = DatumGetInt32(((Const *) arg1)->constvalue);
     810           10 :                 int32       val2 = DatumGetInt32(((Const *) arg2)->constvalue);
     811              : 
     812           10 :                 req->rows = val2 - val1 + 1;
     813           10 :                 ret = (Node *) req;
     814              :             }
     815              :         }
     816              :     }
     817              : 
     818           60 :     PG_RETURN_POINTER(ret);
     819              : }
     820              : 
     821            9 : PG_FUNCTION_INFO_V1(test_inline_in_from_support_func);
     822              : Datum
     823           40 : test_inline_in_from_support_func(PG_FUNCTION_ARGS)
     824              : {
     825           40 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
     826              : 
     827           40 :     if (IsA(rawreq, SupportRequestInlineInFrom))
     828              :     {
     829              :         /*
     830              :          * Assume that the target is foo_from_bar; that's safe as long as we
     831              :          * don't attach this to any other function.
     832              :          */
     833           20 :         SupportRequestInlineInFrom *req = (SupportRequestInlineInFrom *) rawreq;
     834              :         StringInfoData sql;
     835           20 :         RangeTblFunction *rtfunc = req->rtfunc;
     836           20 :         FuncExpr   *expr = (FuncExpr *) rtfunc->funcexpr;
     837              :         Node       *node;
     838              :         Const      *c;
     839              :         char       *colname;
     840              :         char       *tablename;
     841              :         SQLFunctionParseInfoPtr pinfo;
     842              :         List       *raw_parsetree_list;
     843              :         List       *querytree_list;
     844              :         Query      *querytree;
     845              : 
     846           20 :         if (list_length(expr->args) != 3)
     847              :         {
     848            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func called with %d args but expected 3", list_length(expr->args))));
     849            0 :             PG_RETURN_POINTER(NULL);
     850              :         }
     851              : 
     852              :         /* Get colname */
     853           20 :         node = linitial(expr->args);
     854           20 :         if (!IsA(node, Const))
     855              :         {
     856            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func called with non-Const parameters")));
     857            0 :             PG_RETURN_POINTER(NULL);
     858              :         }
     859              : 
     860           20 :         c = (Const *) node;
     861           20 :         if (c->consttype != TEXTOID || c->constisnull)
     862              :         {
     863            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func called with non-TEXT parameters")));
     864            0 :             PG_RETURN_POINTER(NULL);
     865              :         }
     866           20 :         colname = TextDatumGetCString(c->constvalue);
     867              : 
     868              :         /* Get tablename */
     869           20 :         node = lsecond(expr->args);
     870           20 :         if (!IsA(node, Const))
     871              :         {
     872            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func called with non-Const parameters")));
     873            0 :             PG_RETURN_POINTER(NULL);
     874              :         }
     875              : 
     876           20 :         c = (Const *) node;
     877           20 :         if (c->consttype != TEXTOID || c->constisnull)
     878              :         {
     879            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func called with non-TEXT parameters")));
     880            0 :             PG_RETURN_POINTER(NULL);
     881              :         }
     882           20 :         tablename = TextDatumGetCString(c->constvalue);
     883              : 
     884              :         /* Begin constructing replacement SELECT query. */
     885           20 :         initStringInfo(&sql);
     886           20 :         appendStringInfo(&sql, "SELECT %s::text FROM %s",
     887              :                          quote_identifier(colname),
     888              :                          quote_identifier(tablename));
     889              : 
     890              :         /* Add filter expression if present. */
     891           20 :         node = lthird(expr->args);
     892           20 :         if (!(IsA(node, Const) && ((Const *) node)->constisnull))
     893              :         {
     894              :             /*
     895              :              * We only filter if $3 is not constant-NULL.  This is not a very
     896              :              * exact implementation of the PL/pgSQL original, but it's close
     897              :              * enough for demonstration purposes.
     898              :              */
     899           10 :             appendStringInfo(&sql, " WHERE %s::text = $3",
     900              :                              quote_identifier(colname));
     901              :         }
     902              : 
     903              :         /* Build a SQLFunctionParseInfo with the parameters of my function. */
     904           20 :         pinfo = prepare_sql_fn_parse_info(req->proc,
     905              :                                           (Node *) expr,
     906              :                                           expr->inputcollid);
     907              : 
     908              :         /* Parse the generated SQL. */
     909           20 :         raw_parsetree_list = pg_parse_query(sql.data);
     910           20 :         if (list_length(raw_parsetree_list) != 1)
     911              :         {
     912            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func parsed to more than one node")));
     913            0 :             PG_RETURN_POINTER(NULL);
     914              :         }
     915              : 
     916              :         /* Analyze the parse tree as if it were a SQL-language body. */
     917           20 :         querytree_list = pg_analyze_and_rewrite_withcb(linitial(raw_parsetree_list),
     918           20 :                                                        sql.data,
     919              :                                                        (ParserSetupHook) sql_fn_parser_setup,
     920              :                                                        pinfo, NULL);
     921           20 :         if (list_length(querytree_list) != 1)
     922              :         {
     923            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func rewrote to more than one node")));
     924            0 :             PG_RETURN_POINTER(NULL);
     925              :         }
     926              : 
     927           20 :         querytree = linitial(querytree_list);
     928           20 :         if (!IsA(querytree, Query))
     929              :         {
     930            0 :             ereport(WARNING, (errmsg("test_inline_in_from_support_func didn't parse to a Query")));
     931            0 :             PG_RETURN_POINTER(NULL);
     932              :         }
     933              : 
     934           20 :         PG_RETURN_POINTER(querytree);
     935              :     }
     936              : 
     937           20 :     PG_RETURN_POINTER(NULL);
     938              : }
     939              : 
     940            5 : PG_FUNCTION_INFO_V1(test_opclass_options_func);
     941              : Datum
     942            0 : test_opclass_options_func(PG_FUNCTION_ARGS)
     943              : {
     944            0 :     PG_RETURN_NULL();
     945              : }
     946              : 
     947              : /* one-time tests for encoding infrastructure */
     948            9 : PG_FUNCTION_INFO_V1(test_enc_setup);
     949              : Datum
     950            4 : test_enc_setup(PG_FUNCTION_ARGS)
     951              : {
     952              :     /* Test pg_encoding_set_invalid() */
     953          172 :     for (int i = 0; i < _PG_LAST_ENCODING_; i++)
     954              :     {
     955              :         char        buf[2],
     956              :                     bigbuf[16];
     957              :         int         len,
     958              :                     mblen,
     959              :                     valid;
     960              : 
     961          168 :         if (!PG_VALID_ENCODING(i))
     962          116 :             continue;
     963          164 :         if (pg_encoding_max_length(i) == 1)
     964          112 :             continue;
     965           52 :         pg_encoding_set_invalid(i, buf);
     966           52 :         len = strnlen(buf, 2);
     967           52 :         if (len != 2)
     968            0 :             elog(WARNING,
     969              :                  "official invalid string for encoding \"%s\" has length %d",
     970              :                  pg_enc2name_tbl[i].name, len);
     971           52 :         mblen = pg_encoding_mblen(i, buf);
     972           52 :         if (mblen != 2)
     973            0 :             elog(WARNING,
     974              :                  "official invalid string for encoding \"%s\" has mblen %d",
     975              :                  pg_enc2name_tbl[i].name, mblen);
     976           52 :         valid = pg_encoding_verifymbstr(i, buf, len);
     977           52 :         if (valid != 0)
     978            0 :             elog(WARNING,
     979              :                  "official invalid string for encoding \"%s\" has valid prefix of length %d",
     980              :                  pg_enc2name_tbl[i].name, valid);
     981           52 :         valid = pg_encoding_verifymbstr(i, buf, 1);
     982           52 :         if (valid != 0)
     983            0 :             elog(WARNING,
     984              :                  "first byte of official invalid string for encoding \"%s\" has valid prefix of length %d",
     985              :                  pg_enc2name_tbl[i].name, valid);
     986           52 :         memset(bigbuf, ' ', sizeof(bigbuf));
     987           52 :         bigbuf[0] = buf[0];
     988           52 :         bigbuf[1] = buf[1];
     989           52 :         valid = pg_encoding_verifymbstr(i, bigbuf, sizeof(bigbuf));
     990           52 :         if (valid != 0)
     991            0 :             elog(WARNING,
     992              :                  "trailing data changed official invalid string for encoding \"%s\" to have valid prefix of length %d",
     993              :                  pg_enc2name_tbl[i].name, valid);
     994              :     }
     995              : 
     996            4 :     PG_RETURN_VOID();
     997              : }
     998              : 
     999              : /*
    1000              :  * Call an encoding conversion or verification function.
    1001              :  *
    1002              :  * Arguments:
    1003              :  *  string    bytea -- string to convert
    1004              :  *  src_enc   name  -- source encoding
    1005              :  *  dest_enc  name  -- destination encoding
    1006              :  *  noError   bool  -- if set, don't ereport() on invalid or untranslatable
    1007              :  *                     input
    1008              :  *
    1009              :  * Result is a tuple with two attributes:
    1010              :  *  int4    -- number of input bytes successfully converted
    1011              :  *  bytea   -- converted string
    1012              :  */
    1013            9 : PG_FUNCTION_INFO_V1(test_enc_conversion);
    1014              : Datum
    1015         5152 : test_enc_conversion(PG_FUNCTION_ARGS)
    1016              : {
    1017         5152 :     bytea      *string = PG_GETARG_BYTEA_PP(0);
    1018         5152 :     char       *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
    1019         5152 :     int         src_encoding = pg_char_to_encoding(src_encoding_name);
    1020         5152 :     char       *dest_encoding_name = NameStr(*PG_GETARG_NAME(2));
    1021         5152 :     int         dest_encoding = pg_char_to_encoding(dest_encoding_name);
    1022         5152 :     bool        noError = PG_GETARG_BOOL(3);
    1023              :     TupleDesc   tupdesc;
    1024              :     char       *src;
    1025              :     char       *dst;
    1026              :     bytea      *retval;
    1027              :     Size        srclen;
    1028              :     Size        dstsize;
    1029              :     Oid         proc;
    1030              :     int         convertedbytes;
    1031              :     int         dstlen;
    1032              :     Datum       values[2];
    1033         5152 :     bool        nulls[2] = {0};
    1034              :     HeapTuple   tuple;
    1035              : 
    1036         5152 :     if (src_encoding < 0)
    1037            0 :         ereport(ERROR,
    1038              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1039              :                  errmsg("invalid source encoding name \"%s\"",
    1040              :                         src_encoding_name)));
    1041         5152 :     if (dest_encoding < 0)
    1042            0 :         ereport(ERROR,
    1043              :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1044              :                  errmsg("invalid destination encoding name \"%s\"",
    1045              :                         dest_encoding_name)));
    1046              : 
    1047              :     /* Build a tuple descriptor for our result type */
    1048         5152 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
    1049            0 :         elog(ERROR, "return type must be a row type");
    1050         5152 :     tupdesc = BlessTupleDesc(tupdesc);
    1051              : 
    1052         5152 :     srclen = VARSIZE_ANY_EXHDR(string);
    1053         5152 :     src = VARDATA_ANY(string);
    1054              : 
    1055         5152 :     if (src_encoding == dest_encoding)
    1056              :     {
    1057              :         /* just check that the source string is valid */
    1058              :         int         oklen;
    1059              : 
    1060         2572 :         oklen = pg_encoding_verifymbstr(src_encoding, src, srclen);
    1061              : 
    1062         2572 :         if (oklen == srclen)
    1063              :         {
    1064          652 :             convertedbytes = oklen;
    1065          652 :             retval = string;
    1066              :         }
    1067         1920 :         else if (!noError)
    1068              :         {
    1069          960 :             report_invalid_encoding(src_encoding, src + oklen, srclen - oklen);
    1070              :         }
    1071              :         else
    1072              :         {
    1073              :             /*
    1074              :              * build bytea data type structure.
    1075              :              */
    1076              :             Assert(oklen < srclen);
    1077          960 :             convertedbytes = oklen;
    1078          960 :             retval = (bytea *) palloc(oklen + VARHDRSZ);
    1079          960 :             SET_VARSIZE(retval, oklen + VARHDRSZ);
    1080          960 :             memcpy(VARDATA(retval), src, oklen);
    1081              :         }
    1082              :     }
    1083              :     else
    1084              :     {
    1085         2580 :         proc = FindDefaultConversionProc(src_encoding, dest_encoding);
    1086         2580 :         if (!OidIsValid(proc))
    1087            0 :             ereport(ERROR,
    1088              :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1089              :                      errmsg("default conversion function for encoding \"%s\" to \"%s\" does not exist",
    1090              :                             pg_encoding_to_char(src_encoding),
    1091              :                             pg_encoding_to_char(dest_encoding))));
    1092              : 
    1093         2580 :         if (srclen >= (MaxAllocSize / (Size) MAX_CONVERSION_GROWTH))
    1094            0 :             ereport(ERROR,
    1095              :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1096              :                      errmsg("out of memory"),
    1097              :                      errdetail("String of %d bytes is too long for encoding conversion.",
    1098              :                                (int) srclen)));
    1099              : 
    1100         2580 :         dstsize = (Size) srclen * MAX_CONVERSION_GROWTH + 1;
    1101         2580 :         dst = MemoryContextAlloc(CurrentMemoryContext, dstsize);
    1102              : 
    1103              :         /* perform conversion */
    1104         2580 :         convertedbytes = pg_do_encoding_conversion_buf(proc,
    1105              :                                                        src_encoding,
    1106              :                                                        dest_encoding,
    1107              :                                                        (unsigned char *) src, srclen,
    1108              :                                                        (unsigned char *) dst, dstsize,
    1109              :                                                        noError);
    1110         1548 :         dstlen = strlen(dst);
    1111              : 
    1112              :         /*
    1113              :          * build bytea data type structure.
    1114              :          */
    1115         1548 :         retval = (bytea *) palloc(dstlen + VARHDRSZ);
    1116         1548 :         SET_VARSIZE(retval, dstlen + VARHDRSZ);
    1117         1548 :         memcpy(VARDATA(retval), dst, dstlen);
    1118              : 
    1119         1548 :         pfree(dst);
    1120              :     }
    1121              : 
    1122         3160 :     values[0] = Int32GetDatum(convertedbytes);
    1123         3160 :     values[1] = PointerGetDatum(retval);
    1124         3160 :     tuple = heap_form_tuple(tupdesc, values, nulls);
    1125              : 
    1126         3160 :     PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
    1127              : }
    1128              : 
    1129              : /* Convert bytea to text without validation for corruption tests from SQL. */
    1130            8 : PG_FUNCTION_INFO_V1(test_bytea_to_text);
    1131              : Datum
    1132          220 : test_bytea_to_text(PG_FUNCTION_ARGS)
    1133              : {
    1134          220 :     PG_RETURN_TEXT_P(PG_GETARG_BYTEA_PP(0));
    1135              : }
    1136              : 
    1137              : /* And the reverse. */
    1138            8 : PG_FUNCTION_INFO_V1(test_text_to_bytea);
    1139              : Datum
    1140          200 : test_text_to_bytea(PG_FUNCTION_ARGS)
    1141              : {
    1142          200 :     PG_RETURN_BYTEA_P(PG_GETARG_TEXT_PP(0));
    1143              : }
    1144              : 
    1145              : /* Corruption tests in C. */
    1146            8 : PG_FUNCTION_INFO_V1(test_mblen_func);
    1147              : Datum
    1148           24 : test_mblen_func(PG_FUNCTION_ARGS)
    1149              : {
    1150           24 :     const char *func = text_to_cstring(PG_GETARG_BYTEA_PP(0));
    1151           24 :     const char *encoding = text_to_cstring(PG_GETARG_BYTEA_PP(1));
    1152           24 :     text       *string = PG_GETARG_BYTEA_PP(2);
    1153           24 :     int         offset = PG_GETARG_INT32(3);
    1154           24 :     const char *data = VARDATA_ANY(string);
    1155           24 :     size_t      size = VARSIZE_ANY_EXHDR(string);
    1156           24 :     int         result = 0;
    1157              : 
    1158           24 :     if (strcmp(func, "pg_mblen_unbounded") == 0)
    1159            8 :         result = pg_mblen_unbounded(data + offset);
    1160           16 :     else if (strcmp(func, "pg_mblen_cstr") == 0)
    1161            4 :         result = pg_mblen_cstr(data + offset);
    1162           12 :     else if (strcmp(func, "pg_mblen_with_len") == 0)
    1163            4 :         result = pg_mblen_with_len(data + offset, size - offset);
    1164            8 :     else if (strcmp(func, "pg_mblen_range") == 0)
    1165            4 :         result = pg_mblen_range(data + offset, data + size);
    1166            4 :     else if (strcmp(func, "pg_encoding_mblen") == 0)
    1167            4 :         result = pg_encoding_mblen(pg_char_to_encoding(encoding), data + offset);
    1168              :     else
    1169            0 :         elog(ERROR, "unknown function");
    1170              : 
    1171           12 :     PG_RETURN_INT32(result);
    1172              : }
    1173              : 
    1174            8 : PG_FUNCTION_INFO_V1(test_text_to_wchars);
    1175              : Datum
    1176          200 : test_text_to_wchars(PG_FUNCTION_ARGS)
    1177              : {
    1178          200 :     const char *encoding_name = text_to_cstring(PG_GETARG_BYTEA_PP(0));
    1179          200 :     text       *string = PG_GETARG_TEXT_PP(1);
    1180          200 :     const char *data = VARDATA_ANY(string);
    1181          200 :     size_t      size = VARSIZE_ANY_EXHDR(string);
    1182          200 :     pg_wchar   *wchars = palloc(sizeof(pg_wchar) * (size + 1));
    1183              :     Datum      *datums;
    1184              :     int         wlen;
    1185              :     int         encoding;
    1186              : 
    1187          200 :     encoding = pg_char_to_encoding(encoding_name);
    1188          200 :     if (encoding < 0)
    1189            0 :         elog(ERROR, "unknown encoding name: %s", encoding_name);
    1190              : 
    1191          200 :     if (size > 0)
    1192              :     {
    1193          200 :         datums = palloc(sizeof(Datum) * size);
    1194          200 :         wlen = pg_encoding_mb2wchar_with_len(encoding,
    1195              :                                              data,
    1196              :                                              wchars,
    1197              :                                              size);
    1198              :         Assert(wlen >= 0);
    1199              :         Assert(wlen <= size);
    1200              :         Assert(wchars[wlen] == 0);
    1201              : 
    1202          416 :         for (int i = 0; i < wlen; ++i)
    1203          216 :             datums[i] = UInt32GetDatum(wchars[i]);
    1204              :     }
    1205              :     else
    1206              :     {
    1207            0 :         datums = NULL;
    1208            0 :         wlen = 0;
    1209              :     }
    1210              : 
    1211          200 :     PG_RETURN_ARRAYTYPE_P(construct_array_builtin(datums, wlen, INT4OID));
    1212              : }
    1213              : 
    1214            8 : PG_FUNCTION_INFO_V1(test_wchars_to_text);
    1215              : Datum
    1216          200 : test_wchars_to_text(PG_FUNCTION_ARGS)
    1217              : {
    1218          200 :     const char *encoding_name = text_to_cstring(PG_GETARG_BYTEA_PP(0));
    1219          200 :     ArrayType  *array = PG_GETARG_ARRAYTYPE_P(1);
    1220              :     Datum      *datums;
    1221              :     bool       *nulls;
    1222              :     char       *mb;
    1223              :     text       *result;
    1224              :     int         wlen;
    1225              :     int         bytes;
    1226              :     int         encoding;
    1227              : 
    1228          200 :     encoding = pg_char_to_encoding(encoding_name);
    1229          200 :     if (encoding < 0)
    1230            0 :         elog(ERROR, "unknown encoding name: %s", encoding_name);
    1231              : 
    1232          200 :     deconstruct_array_builtin(array, INT4OID, &datums, &nulls, &wlen);
    1233              : 
    1234          200 :     if (wlen > 0)
    1235              :     {
    1236          116 :         pg_wchar   *wchars = palloc(sizeof(pg_wchar) * wlen);
    1237              : 
    1238          332 :         for (int i = 0; i < wlen; ++i)
    1239              :         {
    1240          216 :             if (nulls[i])
    1241            0 :                 elog(ERROR, "unexpected NULL in array");
    1242          216 :             wchars[i] = DatumGetInt32(datums[i]);
    1243              :         }
    1244              : 
    1245          116 :         mb = palloc(pg_encoding_max_length(encoding) * wlen + 1);
    1246          116 :         bytes = pg_encoding_wchar2mb_with_len(encoding, wchars, mb, wlen);
    1247              :     }
    1248              :     else
    1249              :     {
    1250           84 :         mb = "";
    1251           84 :         bytes = 0;
    1252              :     }
    1253              : 
    1254          200 :     result = palloc(bytes + VARHDRSZ);
    1255          200 :     SET_VARSIZE(result, bytes + VARHDRSZ);
    1256          200 :     memcpy(VARDATA(result), mb, bytes);
    1257              : 
    1258          200 :     PG_RETURN_TEXT_P(result);
    1259              : }
    1260              : 
    1261            8 : PG_FUNCTION_INFO_V1(test_valid_server_encoding);
    1262              : Datum
    1263          200 : test_valid_server_encoding(PG_FUNCTION_ARGS)
    1264              : {
    1265          200 :     PG_RETURN_BOOL(pg_valid_server_encoding(text_to_cstring(PG_GETARG_TEXT_PP(0))) >= 0);
    1266              : }
    1267              : 
    1268              : /* Provide SQL access to IsBinaryCoercible() */
    1269            9 : PG_FUNCTION_INFO_V1(binary_coercible);
    1270              : Datum
    1271        25378 : binary_coercible(PG_FUNCTION_ARGS)
    1272              : {
    1273        25378 :     Oid         srctype = PG_GETARG_OID(0);
    1274        25378 :     Oid         targettype = PG_GETARG_OID(1);
    1275              : 
    1276        25378 :     PG_RETURN_BOOL(IsBinaryCoercible(srctype, targettype));
    1277              : }
    1278              : 
    1279              : /*
    1280              :  * Sanity checks for functions in relpath.h
    1281              :  */
    1282            9 : PG_FUNCTION_INFO_V1(test_relpath);
    1283              : Datum
    1284            4 : test_relpath(PG_FUNCTION_ARGS)
    1285              : {
    1286              :     RelPathStr  rpath;
    1287              : 
    1288              :     /*
    1289              :      * Verify that PROCNUMBER_CHARS and MAX_BACKENDS stay in sync.
    1290              :      * Unfortunately I don't know how to express that in a way suitable for a
    1291              :      * static assert.
    1292              :      */
    1293              :     if ((int) ceil(log10(MAX_BACKENDS)) != PROCNUMBER_CHARS)
    1294              :         elog(WARNING, "mismatch between MAX_BACKENDS and PROCNUMBER_CHARS");
    1295              : 
    1296              :     /* verify that the max-length relpath is generated ok */
    1297            4 :     rpath = GetRelationPath(OID_MAX, OID_MAX, OID_MAX, MAX_BACKENDS - 1,
    1298              :                             INIT_FORKNUM);
    1299              : 
    1300            4 :     if (strlen(rpath.str) != REL_PATH_STR_MAXLEN)
    1301            0 :         elog(WARNING, "maximum length relpath is if length %zu instead of %zu",
    1302              :              strlen(rpath.str), REL_PATH_STR_MAXLEN);
    1303              : 
    1304            4 :     PG_RETURN_VOID();
    1305              : }
    1306              : 
    1307              : /*
    1308              :  * Simple test to verify NLS support, particularly that the PRI* macros work.
    1309              :  *
    1310              :  * A secondary objective is to verify that <inttypes.h>'s values for the
    1311              :  * PRI* macros match what our snprintf.c code will do.  Therefore, we run
    1312              :  * the ereport() calls even when we know that translation will not happen.
    1313              :  */
    1314            9 : PG_FUNCTION_INFO_V1(test_translation);
    1315              : Datum
    1316            4 : test_translation(PG_FUNCTION_ARGS)
    1317              : {
    1318              : #ifdef ENABLE_NLS
    1319              :     static bool inited = false;
    1320              : 
    1321              :     /*
    1322              :      * Ideally we'd do this bit in a _PG_init() hook.  However, it seems best
    1323              :      * that the Solaris hack only get applied in the nls.sql test, so it
    1324              :      * doesn't risk affecting other tests that load this module.
    1325              :      */
    1326            4 :     if (!inited)
    1327              :     {
    1328              :         /*
    1329              :          * Solaris' built-in gettext is not bright about associating locales
    1330              :          * with message catalogs that are named after just the language.
    1331              :          * Apparently the customary workaround is for users to set the
    1332              :          * LANGUAGE environment variable to provide a mapping.  Do so here to
    1333              :          * ensure that the nls.sql regression test will work.
    1334              :          */
    1335              : #if defined(__sun__)
    1336              :         setenv("LANGUAGE", "es_ES.UTF-8:es", 1);
    1337              : #endif
    1338            4 :         pg_bindtextdomain(TEXTDOMAIN);
    1339            4 :         inited = true;
    1340              :     }
    1341              : 
    1342              :     /*
    1343              :      * If nls.sql failed to select a non-C locale, no translation will happen.
    1344              :      * Report that so that we can distinguish this outcome from brokenness.
    1345              :      * (We do this here, not in nls.sql, so as to need only 3 expected files.)
    1346              :      */
    1347            4 :     if (strcmp(GetConfigOption("lc_messages", false, false), "C") == 0)
    1348            4 :         elog(NOTICE, "lc_messages is 'C'");
    1349              : #else
    1350              :     elog(NOTICE, "NLS is not enabled");
    1351              : #endif
    1352              : 
    1353            4 :     ereport(NOTICE,
    1354              :             errmsg("translated PRId64 = %" PRId64, (int64) 424242424242));
    1355            4 :     ereport(NOTICE,
    1356              :             errmsg("translated PRId32 = %" PRId32, (int32) -1234));
    1357            4 :     ereport(NOTICE,
    1358              :             errmsg("translated PRIdMAX = %" PRIdMAX, (intmax_t) -123456789012));
    1359            4 :     ereport(NOTICE,
    1360              :             errmsg("translated PRIdPTR = %" PRIdPTR, (intptr_t) -9999));
    1361              : 
    1362            4 :     ereport(NOTICE,
    1363              :             errmsg("translated PRIu64 = %" PRIu64, (uint64) 424242424242));
    1364            4 :     ereport(NOTICE,
    1365              :             errmsg("translated PRIu32 = %" PRIu32, (uint32) -1234));
    1366            4 :     ereport(NOTICE,
    1367              :             errmsg("translated PRIuMAX = %" PRIuMAX, (uintmax_t) 123456789012));
    1368            4 :     ereport(NOTICE,
    1369              :             errmsg("translated PRIuPTR = %" PRIuPTR, (uintptr_t) 9999));
    1370              : 
    1371            4 :     ereport(NOTICE,
    1372              :             errmsg("translated PRIx64 = %" PRIx64, (uint64) 424242424242));
    1373            4 :     ereport(NOTICE,
    1374              :             errmsg("translated PRIx32 = %" PRIx32, (uint32) -1234));
    1375            4 :     ereport(NOTICE,
    1376              :             errmsg("translated PRIxMAX = %" PRIxMAX, (uintmax_t) 123456789012));
    1377            4 :     ereport(NOTICE,
    1378              :             errmsg("translated PRIxPTR = %" PRIxPTR, (uintptr_t) 9999));
    1379              : 
    1380            4 :     ereport(NOTICE,
    1381              :             errmsg("translated PRIX64 = %" PRIX64, (uint64) 424242424242));
    1382            4 :     ereport(NOTICE,
    1383              :             errmsg("translated PRIX32 = %" PRIX32, (uint32) -1234));
    1384            4 :     ereport(NOTICE,
    1385              :             errmsg("translated PRIXMAX = %" PRIXMAX, (uintmax_t) 123456789012));
    1386            4 :     ereport(NOTICE,
    1387              :             errmsg("translated PRIXPTR = %" PRIXPTR, (uintptr_t) 9999));
    1388              : 
    1389            4 :     PG_RETURN_VOID();
    1390              : }
    1391              : 
    1392              : /* Verify that pg_ticks_to_ns behaves correct, including overflow */
    1393            9 : PG_FUNCTION_INFO_V1(test_instr_time);
    1394              : Datum
    1395            4 : test_instr_time(PG_FUNCTION_ARGS)
    1396              : {
    1397              :     instr_time  t;
    1398            4 :     int64       test_ns[] = {0, 1000, INT64CONST(1000000000000000)};
    1399              :     int64       max_err;
    1400              : 
    1401              :     /*
    1402              :      * The ns-to-ticks-to-ns roundtrip may lose precision due to integer
    1403              :      * truncation in the fixed-point conversion. The maximum error depends on
    1404              :      * ticks_per_ns_scaled relative to the shift factor.
    1405              :      */
    1406            4 :     max_err = (ticks_per_ns_scaled >> TICKS_TO_NS_SHIFT) + 1;
    1407              : 
    1408           16 :     for (int i = 0; i < lengthof(test_ns); i++)
    1409              :     {
    1410              :         int64       result;
    1411              : 
    1412           12 :         INSTR_TIME_SET_ZERO(t);
    1413           12 :         INSTR_TIME_ADD_NANOSEC(t, test_ns[i]);
    1414           12 :         result = INSTR_TIME_GET_NANOSEC(t);
    1415              : 
    1416           12 :         if (result < test_ns[i] - max_err || result > test_ns[i])
    1417            0 :             elog(ERROR,
    1418              :                  "INSTR_TIME_GET_NANOSEC(t) yielded " INT64_FORMAT
    1419              :                  ", expected " INT64_FORMAT " (max_err " INT64_FORMAT
    1420              :                  ") in file \"%s\" line %u",
    1421              :                  result, test_ns[i], max_err, __FILE__, __LINE__);
    1422              :     }
    1423              : 
    1424            4 :     PG_RETURN_BOOL(true);
    1425              : }
    1426              : 
    1427              : /*
    1428              :  * test_pglz_compress
    1429              :  *
    1430              :  * Compress the input using pglz_compress().  Only the "always" strategy is
    1431              :  * currently supported.
    1432              :  *
    1433              :  * Returns the compressed data, or NULL if compression fails.
    1434              :  */
    1435            8 : PG_FUNCTION_INFO_V1(test_pglz_compress);
    1436              : Datum
    1437           16 : test_pglz_compress(PG_FUNCTION_ARGS)
    1438              : {
    1439           16 :     bytea      *input = PG_GETARG_BYTEA_PP(0);
    1440           16 :     char       *source = VARDATA_ANY(input);
    1441           16 :     int32       slen = VARSIZE_ANY_EXHDR(input);
    1442           16 :     int32       maxout = PGLZ_MAX_OUTPUT(slen);
    1443              :     bytea      *result;
    1444              :     int32       clen;
    1445              : 
    1446           16 :     result = (bytea *) palloc(maxout + VARHDRSZ);
    1447           16 :     clen = pglz_compress(source, slen, VARDATA(result),
    1448              :                          PGLZ_strategy_always);
    1449           16 :     if (clen < 0)
    1450            0 :         PG_RETURN_NULL();
    1451              : 
    1452           16 :     SET_VARSIZE(result, clen + VARHDRSZ);
    1453           16 :     PG_RETURN_BYTEA_P(result);
    1454              : }
    1455              : 
    1456              : /*
    1457              :  * test_pglz_decompress
    1458              :  *
    1459              :  * Decompress the input using pglz_decompress().
    1460              :  *
    1461              :  * The second argument is the expected uncompressed data size.  The third
    1462              :  * argument is here for the check_complete flag.
    1463              :  *
    1464              :  * Returns the decompressed data, or raises an error if decompression fails.
    1465              :  */
    1466            8 : PG_FUNCTION_INFO_V1(test_pglz_decompress);
    1467              : Datum
    1468           40 : test_pglz_decompress(PG_FUNCTION_ARGS)
    1469              : {
    1470           40 :     bytea      *input = PG_GETARG_BYTEA_PP(0);
    1471           40 :     int32       rawsize = PG_GETARG_INT32(1);
    1472           40 :     bool        check_complete = PG_GETARG_BOOL(2);
    1473           40 :     char       *source = VARDATA_ANY(input);
    1474           40 :     int32       slen = VARSIZE_ANY_EXHDR(input);
    1475              :     bytea      *result;
    1476              :     int32       dlen;
    1477              : 
    1478           40 :     if (rawsize < 0)
    1479            0 :         elog(ERROR, "rawsize must not be negative");
    1480              : 
    1481           40 :     result = (bytea *) palloc(rawsize + VARHDRSZ);
    1482              : 
    1483           40 :     dlen = pglz_decompress(source, slen, VARDATA(result),
    1484              :                            rawsize, check_complete);
    1485           40 :     if (dlen < 0)
    1486           28 :         elog(ERROR, "pglz_decompress failed");
    1487              : 
    1488           12 :     SET_VARSIZE(result, dlen + VARHDRSZ);
    1489           12 :     PG_RETURN_BYTEA_P(result);
    1490              : }
        

Generated by: LCOV version 2.0-1