PostgreSQL Source Code git master
Loading...
Searching...
No Matches
tablefunc.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "common/pg_prng.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/hsearch.h"
#include "utils/tuplestore.h"
Include dependency graph for tablefunc.c:

Go to the source code of this file.

Data Structures

struct  normal_rand_fctx
 
struct  crosstab_cat_desc
 
struct  crosstab_hashent
 

Macros

#define xpfree(var_)
 
#define xpstrdup(tgtvar_, srcvar_)
 
#define xstreq(tgtvar_, srcvar_)
 
#define INT32_STRLEN   12
 
#define MAX_CATNAME_LEN   NAMEDATALEN
 
#define INIT_CATS   64
 
#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC)
 
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
 
#define CONNECTBY_NCOLS   4
 
#define CONNECTBY_NCOLS_NOBRANCH   3
 

Typedefs

typedef struct crosstab_cat_desc crosstab_cat_desc
 
typedef struct crosstab_hashent crosstab_HashEnt
 

Functions

 PG_MODULE_MAGIC_EXT (.name="tablefunc",.version=PG_VERSION)
 
static HTABload_categories_hash (char *cats_sql, MemoryContext per_query_ctx)
 
static Tuplestorestateget_crosstab_tuplestore (char *sql, HTAB *crosstab_hash, TupleDesc tupdesc, bool randomAccess)
 
static void validateConnectbyTupleDesc (TupleDesc td, bool show_branch, bool show_serial)
 
static void compatCrosstabTupleDescs (TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
 
static void compatConnectbyTupleDescs (TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
 
static void get_normal_pair (float8 *x1, float8 *x2)
 
static Tuplestorestateconnectby (char *relname, char *key_fld, char *parent_key_fld, char *orderby_fld, char *branch_delim, char *start_with, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, bool randomAccess, AttInMetadata *attinmeta)
 
static void build_tuplestore_recursively (char *key_fld, char *parent_key_fld, char *relname, char *orderby_fld, char *branch_delim, char *start_with, char *branch, int level, int *serial, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, AttInMetadata *attinmeta, Tuplestorestate *tupstore)
 
 PG_FUNCTION_INFO_V1 (normal_rand)
 
Datum normal_rand (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (crosstab)
 
Datum crosstab (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (crosstab_hash)
 
Datum crosstab_hash (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (connectby_text)
 
Datum connectby_text (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (connectby_text_serial)
 
Datum connectby_text_serial (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ CONNECTBY_NCOLS

#define CONNECTBY_NCOLS   4

Definition at line 975 of file tablefunc.c.

◆ CONNECTBY_NCOLS_NOBRANCH

#define CONNECTBY_NCOLS_NOBRANCH   3

Definition at line 976 of file tablefunc.c.

◆ crosstab_HashTableInsert

#define crosstab_HashTableInsert (   HASHTAB,
  CATDESC 
)
Value:
do { \
crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
key, HASH_ENTER, &found); \
if (found) \
errmsg("duplicate category name"))); \
hentry->catdesc = CATDESC; \
} while(0)
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
@ HASH_ENTER
Definition hsearch.h:109
static char * errmsg
static int fb(int x)
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
#define MAX_CATNAME_LEN
Definition tablefunc.c:130

Definition at line 147 of file tablefunc.c.

148 { \
149 crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
150 \
151 MemSet(key, 0, MAX_CATNAME_LEN); \
152 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
154 key, HASH_ENTER, &found); \
155 if (found) \
158 errmsg("duplicate category name"))); \
159 hentry->catdesc = CATDESC; \
160} while(0)

◆ crosstab_HashTableLookup

#define crosstab_HashTableLookup (   HASHTAB,
  CATNAME,
  CATDESC 
)
Value:
do { \
snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
key, HASH_FIND, NULL); \
CATDESC = hentry->catdesc; \
} while(0)
@ HASH_FIND
Definition hsearch.h:108

Definition at line 133 of file tablefunc.c.

134 { \
136 \
137 MemSet(key, 0, MAX_CATNAME_LEN); \
138 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
140 key, HASH_FIND, NULL); \
141 if (hentry) \
142 CATDESC = hentry->catdesc; \
143 else \
144 CATDESC = NULL; \
145} while(0)

◆ INIT_CATS

#define INIT_CATS   64

Definition at line 131 of file tablefunc.c.

◆ INT32_STRLEN

#define INT32_STRLEN   12

Definition at line 121 of file tablefunc.c.

◆ MAX_CATNAME_LEN

#define MAX_CATNAME_LEN   NAMEDATALEN

Definition at line 130 of file tablefunc.c.

◆ xpfree

#define xpfree (   var_)
Value:
do { \
if (var_ != NULL) \
{ \
var_ = NULL; \
} \
} while (0)

Definition at line 99 of file tablefunc.c.

100 { \
101 if (var_ != NULL) \
102 { \
103 pfree(var_); \
104 var_ = NULL; \
105 } \
106 } while (0)

◆ xpstrdup

#define xpstrdup (   tgtvar_,
  srcvar_ 
)
Value:
do { \
} while (0)
char * pstrdup(const char *in)
Definition mcxt.c:1781

Definition at line 108 of file tablefunc.c.

109 { \
110 if (srcvar_) \
112 else \
113 tgtvar_ = NULL; \
114 } while (0)

◆ xstreq

#define xstreq (   tgtvar_,
  srcvar_ 
)
Value:
(((tgtvar_ == NULL) && (srcvar_ == NULL)) || \
((tgtvar_ != NULL) && (srcvar_ != NULL) && (strcmp(tgtvar_, srcvar_) == 0)))

Definition at line 116 of file tablefunc.c.

Typedef Documentation

◆ crosstab_cat_desc

◆ crosstab_HashEnt

Function Documentation

◆ build_tuplestore_recursively()

static void build_tuplestore_recursively ( char key_fld,
char parent_key_fld,
char relname,
char orderby_fld,
char branch_delim,
char start_with,
char branch,
int  level,
int serial,
int  max_depth,
bool  show_branch,
bool  show_serial,
MemoryContext  per_query_ctx,
AttInMetadata attinmeta,
Tuplestorestate tupstore 
)
static

Definition at line 1190 of file tablefunc.c.

1205{
1206 TupleDesc tupdesc = attinmeta->tupdesc;
1207 int ret;
1208 uint64 proc;
1209 int serial_column;
1210 StringInfoData sql;
1211 char **values;
1212 char *current_key;
1213 char *current_key_parent;
1216 char *current_branch;
1217 HeapTuple tuple;
1218
1219 if (max_depth > 0 && level > max_depth)
1220 return;
1221
1222 initStringInfo(&sql);
1223
1224 /* Build initial sql statement */
1225 if (!show_serial)
1226 {
1227 appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s",
1228 key_fld,
1230 relname,
1234 serial_column = 0;
1235 }
1236 else
1237 {
1238 appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s ORDER BY %s",
1239 key_fld,
1241 relname,
1245 orderby_fld);
1246 serial_column = 1;
1247 }
1248
1249 if (show_branch)
1250 values = (char **) palloc((CONNECTBY_NCOLS + serial_column) * sizeof(char *));
1251 else
1252 values = (char **) palloc((CONNECTBY_NCOLS_NOBRANCH + serial_column) * sizeof(char *));
1253
1254 /* First time through, do a little setup */
1255 if (level == 0)
1256 {
1257 /* root value is the one we initially start with */
1258 values[0] = start_with;
1259
1260 /* root value has no parent */
1261 values[1] = NULL;
1262
1263 /* root level is 0 */
1264 sprintf(current_level, "%d", level);
1265 values[2] = current_level;
1266
1267 /* root branch is just starting root value */
1268 if (show_branch)
1269 values[3] = start_with;
1270
1271 /* root starts the serial with 1 */
1272 if (show_serial)
1273 {
1274 sprintf(serial_str, "%d", (*serial)++);
1275 if (show_branch)
1276 values[4] = serial_str;
1277 else
1278 values[3] = serial_str;
1279 }
1280
1281 /* construct the tuple */
1282 tuple = BuildTupleFromCStrings(attinmeta, values);
1283
1284 /* now store it */
1285 tuplestore_puttuple(tupstore, tuple);
1286
1287 /* increment level */
1288 level++;
1289 }
1290
1291 /* Retrieve the desired rows */
1292 ret = SPI_execute(sql.data, true, 0);
1293 proc = SPI_processed;
1294
1295 /* Check for qualifying tuples */
1296 if ((ret == SPI_OK_SELECT) && (proc > 0))
1297 {
1299 SPITupleTable *tuptable = SPI_tuptable;
1300 TupleDesc spi_tupdesc = tuptable->tupdesc;
1301 uint64 i;
1305
1306 /*
1307 * Check that return tupdesc is compatible with the one we got from
1308 * the query.
1309 */
1311
1315
1316 for (i = 0; i < proc; i++)
1317 {
1318 /* initialize branch for this pass */
1321
1322 /* get the next sql result tuple */
1323 spi_tuple = tuptable->vals[i];
1324
1325 /* get the current key (might be NULL) */
1327
1328 /* get the parent key (might be NULL) */
1330
1331 /* get the current level */
1332 sprintf(current_level, "%d", level);
1333
1334 /* check to see if this key is also an ancestor */
1335 if (current_key)
1336 {
1339 if (strstr(chk_branchstr.data, chk_current_key.data))
1340 ereport(ERROR,
1342 errmsg("infinite recursion detected")));
1343 }
1344
1345 /* OK, extend the branch */
1346 if (current_key)
1349
1350 /* build a tuple */
1351 values[0] = current_key;
1353 values[2] = current_level;
1354 if (show_branch)
1356 if (show_serial)
1357 {
1358 sprintf(serial_str, "%d", (*serial)++);
1359 if (show_branch)
1360 values[4] = serial_str;
1361 else
1362 values[3] = serial_str;
1363 }
1364
1365 tuple = BuildTupleFromCStrings(attinmeta, values);
1366
1367 /* store the tuple for later use */
1368 tuplestore_puttuple(tupstore, tuple);
1369
1370 heap_freetuple(tuple);
1371
1372 /* recurse using current_key as the new start_with */
1373 if (current_key)
1376 relname,
1381 level + 1,
1382 serial,
1383 max_depth,
1387 attinmeta,
1388 tupstore);
1389
1392
1393 /* reset branch for next pass */
1397 }
1398
1399 xpfree(branchstr.data);
1400 xpfree(chk_branchstr.data);
1401 xpfree(chk_current_key.data);
1402 }
1403}
static Datum values[MAXATTR]
Definition bootstrap.c:190
uint64_t uint64
Definition c.h:625
#define ereport(elevel,...)
Definition elog.h:152
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
int i
Definition isn.c:77
void * palloc(Size size)
Definition mcxt.c:1387
NameData relname
Definition pg_class.h:40
#define sprintf
Definition port.h:262
char * quote_literal_cstr(const char *rawstr)
Definition quote.c:101
uint64 SPI_processed
Definition spi.c:45
SPITupleTable * SPI_tuptable
Definition spi.c:46
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition spi.c:1221
int SPI_execute(const char *src, bool read_only, long tcount)
Definition spi.c:597
#define SPI_OK_SELECT
Definition spi.h:86
void resetStringInfo(StringInfo str)
Definition stringinfo.c:126
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
TupleDesc tupdesc
Definition funcapi.h:38
TupleDesc tupdesc
Definition spi.h:25
HeapTuple * vals
Definition spi.h:26
#define CONNECTBY_NCOLS_NOBRANCH
Definition tablefunc.c:976
#define INT32_STRLEN
Definition tablefunc.c:121
static void build_tuplestore_recursively(char *key_fld, char *parent_key_fld, char *relname, char *orderby_fld, char *branch_delim, char *start_with, char *branch, int level, int *serial, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, AttInMetadata *attinmeta, Tuplestorestate *tupstore)
Definition tablefunc.c:1190
#define CONNECTBY_NCOLS
Definition tablefunc.c:975
static void compatConnectbyTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
Definition tablefunc.c:1469
#define xpfree(var_)
Definition tablefunc.c:99
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition tuplestore.c:765

References appendStringInfo(), appendStringInfoString(), build_tuplestore_recursively(), BuildTupleFromCStrings(), compatConnectbyTupleDescs(), CONNECTBY_NCOLS, CONNECTBY_NCOLS_NOBRANCH, StringInfoData::data, ereport, errcode(), errmsg, ERROR, fb(), heap_freetuple(), i, initStringInfo(), INT32_STRLEN, palloc(), quote_literal_cstr(), relname, resetStringInfo(), SPI_execute(), SPI_getvalue(), SPI_OK_SELECT, SPI_processed, SPI_tuptable, sprintf, SPITupleTable::tupdesc, AttInMetadata::tupdesc, tuplestore_puttuple(), SPITupleTable::vals, values, and xpfree.

Referenced by build_tuplestore_recursively(), and connectby().

◆ compatConnectbyTupleDescs()

static void compatConnectbyTupleDescs ( TupleDesc  ret_tupdesc,
TupleDesc  sql_tupdesc 
)
static

Definition at line 1469 of file tablefunc.c.

1470{
1475
1476 /*
1477 * Query result must have at least 2 columns.
1478 */
1479 if (sql_tupdesc->natts < 2)
1480 ereport(ERROR,
1482 errmsg("invalid connectby source data query"),
1483 errdetail("The query must return at least two columns.")));
1484
1485 /*
1486 * These columns must match the result type indicated by the calling
1487 * query.
1488 */
1489 ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1490 sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1491 ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1492 sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1493 if (ret_atttypid != sql_atttypid ||
1495 ereport(ERROR,
1497 errmsg("invalid connectby return type"),
1498 errdetail("Source key type %s does not match return key type %s.",
1501
1502 ret_atttypid = TupleDescAttr(ret_tupdesc, 1)->atttypid;
1503 sql_atttypid = TupleDescAttr(sql_tupdesc, 1)->atttypid;
1504 ret_atttypmod = TupleDescAttr(ret_tupdesc, 1)->atttypmod;
1505 sql_atttypmod = TupleDescAttr(sql_tupdesc, 1)->atttypmod;
1506 if (ret_atttypid != sql_atttypid ||
1508 ereport(ERROR,
1510 errmsg("invalid connectby return type"),
1511 errdetail("Source parent key type %s does not match return parent key type %s.",
1514
1515 /* OK, the two tupdescs are compatible for our purposes */
1516}
int32_t int32
Definition c.h:620
int errdetail(const char *fmt,...) pg_attribute_printf(1
char * format_type_with_typemod(Oid type_oid, int32 typemod)
unsigned int Oid
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References ereport, errcode(), errdetail(), errmsg, ERROR, fb(), format_type_with_typemod(), and TupleDescAttr().

Referenced by build_tuplestore_recursively().

◆ compatCrosstabTupleDescs()

static void compatCrosstabTupleDescs ( TupleDesc  ret_tupdesc,
TupleDesc  sql_tupdesc 
)
static

Definition at line 1522 of file tablefunc.c.

1523{
1524 int i;
1529
1530 if (ret_tupdesc->natts < 2)
1531 ereport(ERROR,
1533 errmsg("invalid crosstab return type"),
1534 errdetail("Return row must have at least two columns.")));
1535 Assert(sql_tupdesc->natts == 3); /* already checked by caller */
1536
1537 /* check the row_name types match */
1538 ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1539 sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1540 ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1541 sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1542 if (ret_atttypid != sql_atttypid ||
1544 ereport(ERROR,
1546 errmsg("invalid crosstab return type"),
1547 errdetail("Source row_name datatype %s does not match return row_name datatype %s.",
1550
1551 /*
1552 * attribute [1] of sql tuple is the category; no need to check it
1553 * attribute [2] of sql tuple should match attributes [1] to [natts - 1]
1554 * of the return tuple
1555 */
1556 sql_atttypid = TupleDescAttr(sql_tupdesc, 2)->atttypid;
1557 sql_atttypmod = TupleDescAttr(sql_tupdesc, 2)->atttypmod;
1558 for (i = 1; i < ret_tupdesc->natts; i++)
1559 {
1560 ret_atttypid = TupleDescAttr(ret_tupdesc, i)->atttypid;
1561 ret_atttypmod = TupleDescAttr(ret_tupdesc, i)->atttypmod;
1562
1563 if (ret_atttypid != sql_atttypid ||
1565 ereport(ERROR,
1567 errmsg("invalid crosstab return type"),
1568 errdetail("Source value datatype %s does not match return value datatype %s in column %d.",
1571 i + 1)));
1572 }
1573
1574 /* OK, the two tupdescs are compatible for our purposes */
1575}
#define Assert(condition)
Definition c.h:943

References Assert, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), format_type_with_typemod(), i, TupleDescData::natts, and TupleDescAttr().

Referenced by crosstab().

◆ connectby()

static Tuplestorestate * connectby ( char relname,
char key_fld,
char parent_key_fld,
char orderby_fld,
char branch_delim,
char start_with,
int  max_depth,
bool  show_branch,
bool  show_serial,
MemoryContext  per_query_ctx,
bool  randomAccess,
AttInMetadata attinmeta 
)
static

Definition at line 1139 of file tablefunc.c.

1151{
1152 Tuplestorestate *tupstore = NULL;
1153 MemoryContext oldcontext;
1154 int serial = 1;
1155
1156 /* Connect to SPI manager */
1157 SPI_connect();
1158
1159 /* switch to longer term context to create the tuple store */
1161
1162 /* initialize our tuplestore */
1163 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1164
1165 MemoryContextSwitchTo(oldcontext);
1166
1167 /* now go get the whole tree */
1170 relname,
1173 start_with,
1174 start_with, /* current_branch */
1175 0, /* initial level is 0 */
1176 &serial, /* initial serial is 1 */
1177 max_depth,
1181 attinmeta,
1182 tupstore);
1183
1184 SPI_finish();
1185
1186 return tupstore;
1187}
int work_mem
Definition globals.c:133
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
int SPI_connect(void)
Definition spi.c:95
int SPI_finish(void)
Definition spi.c:183
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition tuplestore.c:331

References build_tuplestore_recursively(), fb(), MemoryContextSwitchTo(), relname, SPI_connect(), SPI_finish(), tuplestore_begin_heap(), and work_mem.

Referenced by connectby_text(), and connectby_text_serial().

◆ connectby_text()

Datum connectby_text ( PG_FUNCTION_ARGS  )

Definition at line 979 of file tablefunc.c.

980{
985 int max_depth = PG_GETARG_INT32(4);
986 char *branch_delim = NULL;
987 bool show_branch = false;
988 bool show_serial = false;
989 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
990 TupleDesc tupdesc;
991 AttInMetadata *attinmeta;
993 MemoryContext oldcontext;
994
995 /* check to see if caller supports us returning a tuplestore */
996 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
999 errmsg("set-valued function called in context that cannot accept a set")));
1000 if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1001 rsinfo->expectedDesc == NULL)
1002 ereport(ERROR,
1004 errmsg("materialize mode required, but it is not allowed in this context")));
1005
1006 if (fcinfo->nargs == 6)
1007 {
1009 show_branch = true;
1010 }
1011 else
1012 /* default is no show, tilde for the delimiter */
1013 branch_delim = pstrdup("~");
1014
1015 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1017
1018 /* get the requested return tuple description */
1019 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1020
1021 /* does it meet our needs */
1023
1024 /* OK, use it then */
1025 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1026
1027 /* OK, go to work */
1028 rsinfo->returnMode = SFRM_Materialize;
1029 rsinfo->setResult = connectby(relname,
1030 key_fld,
1032 NULL,
1034 start_with,
1035 max_depth,
1039 rsinfo->allowedModes & SFRM_Materialize_Random,
1040 attinmeta);
1041 rsinfo->setDesc = tupdesc;
1042
1043 MemoryContextSwitchTo(oldcontext);
1044
1045 /*
1046 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1047 * tuples are in our tuplestore and passed back through rsinfo->setResult.
1048 * rsinfo->setDesc is set to the tuple description that we actually used
1049 * to build our tuples with, so the caller can verify we did what it was
1050 * expecting.
1051 */
1052 return (Datum) 0;
1053}
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
@ SFRM_Materialize_Random
Definition execnodes.h:356
@ SFRM_Materialize
Definition execnodes.h:355
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
#define IsA(nodeptr, _type_)
Definition nodes.h:164
uint64_t Datum
Definition postgres.h:70
static void validateConnectbyTupleDesc(TupleDesc td, bool show_branch, bool show_serial)
Definition tablefunc.c:1409
static Tuplestorestate * connectby(char *relname, char *key_fld, char *parent_key_fld, char *orderby_fld, char *branch_delim, char *start_with, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, bool randomAccess, AttInMetadata *attinmeta)
Definition tablefunc.c:1139
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition tupdesc.c:242
char * text_to_cstring(const text *t)
Definition varlena.c:217

References connectby(), CreateTupleDescCopy(), ereport, errcode(), errmsg, ERROR, fb(), IsA, MemoryContextSwitchTo(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pstrdup(), relname, SFRM_Materialize, SFRM_Materialize_Random, text_to_cstring(), TupleDescGetAttInMetadata(), and validateConnectbyTupleDesc().

◆ connectby_text_serial()

Datum connectby_text_serial ( PG_FUNCTION_ARGS  )

Definition at line 1057 of file tablefunc.c.

1058{
1064 int max_depth = PG_GETARG_INT32(5);
1065 char *branch_delim = NULL;
1066 bool show_branch = false;
1067 bool show_serial = true;
1068 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1069 TupleDesc tupdesc;
1070 AttInMetadata *attinmeta;
1072 MemoryContext oldcontext;
1073
1074 /* check to see if caller supports us returning a tuplestore */
1075 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1076 ereport(ERROR,
1078 errmsg("set-valued function called in context that cannot accept a set")));
1079 if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1080 rsinfo->expectedDesc == NULL)
1081 ereport(ERROR,
1083 errmsg("materialize mode required, but it is not allowed in this context")));
1084
1085 if (fcinfo->nargs == 7)
1086 {
1088 show_branch = true;
1089 }
1090 else
1091 /* default is no show, tilde for the delimiter */
1092 branch_delim = pstrdup("~");
1093
1094 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1096
1097 /* get the requested return tuple description */
1098 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1099
1100 /* does it meet our needs */
1102
1103 /* OK, use it then */
1104 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1105
1106 /* OK, go to work */
1107 rsinfo->returnMode = SFRM_Materialize;
1108 rsinfo->setResult = connectby(relname,
1109 key_fld,
1113 start_with,
1114 max_depth,
1118 rsinfo->allowedModes & SFRM_Materialize_Random,
1119 attinmeta);
1120 rsinfo->setDesc = tupdesc;
1121
1122 MemoryContextSwitchTo(oldcontext);
1123
1124 /*
1125 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1126 * tuples are in our tuplestore and passed back through rsinfo->setResult.
1127 * rsinfo->setDesc is set to the tuple description that we actually used
1128 * to build our tuples with, so the caller can verify we did what it was
1129 * expecting.
1130 */
1131 return (Datum) 0;
1132}

References connectby(), CreateTupleDescCopy(), ereport, errcode(), errmsg, ERROR, fb(), IsA, MemoryContextSwitchTo(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pstrdup(), relname, SFRM_Materialize, SFRM_Materialize_Random, text_to_cstring(), TupleDescGetAttInMetadata(), and validateConnectbyTupleDesc().

◆ crosstab()

Datum crosstab ( PG_FUNCTION_ARGS  )

Definition at line 360 of file tablefunc.c.

361{
362 char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
363 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
364 Tuplestorestate *tupstore;
365 TupleDesc tupdesc;
366 uint64 call_cntr;
367 uint64 max_calls;
368 AttInMetadata *attinmeta;
371 bool firstpass;
372 char *lastrowid;
373 int i;
374 int num_categories;
376 MemoryContext oldcontext;
377 int ret;
378 uint64 proc;
379
380 /* check to see if caller supports us returning a tuplestore */
381 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
384 errmsg("set-valued function called in context that cannot accept a set")));
385 if (!(rsinfo->allowedModes & SFRM_Materialize))
388 errmsg("materialize mode required, but it is not allowed in this context")));
389
390 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
391
392 /* Connect to SPI manager */
393 SPI_connect();
394
395 /* Retrieve the desired rows */
396 ret = SPI_execute(sql, true, 0);
397 proc = SPI_processed;
398
399 /* If no qualifying tuples, fall out early */
400 if (ret != SPI_OK_SELECT || proc == 0)
401 {
402 SPI_finish();
403 rsinfo->isDone = ExprEndResult;
405 }
406
409
410 /*----------
411 * The provided SQL query must always return three columns.
412 *
413 * 1. rowname
414 * the label or identifier for each row in the final result
415 * 2. category
416 * the label or identifier for each column in the final result
417 * 3. values
418 * the value for each column in the final result
419 *----------
420 */
421 if (spi_tupdesc->natts != 3)
424 errmsg("invalid crosstab source data query"),
425 errdetail("The query must return 3 columns: row_name, category, and value.")));
426
427 /* get a tuple descriptor for our result type */
428 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
429 {
431 /* success */
432 break;
433 case TYPEFUNC_RECORD:
434 /* failed to determine actual type of RECORD */
437 errmsg("function returning record called in context "
438 "that cannot accept type record")));
439 break;
440 default:
441 /* result type isn't composite */
444 errmsg("return type must be a row type")));
445 break;
446 }
447
448 /*
449 * Check that return tupdesc is compatible with the data we got from SPI,
450 * at least based on number and type of attributes
451 */
453
454 /*
455 * switch to long-lived memory context
456 */
458
459 /* make sure we have a persistent copy of the result tupdesc */
460 tupdesc = CreateTupleDescCopy(tupdesc);
461
462 /* initialize our tuplestore in long-lived context */
463 tupstore =
465 false, work_mem);
466
467 MemoryContextSwitchTo(oldcontext);
468
469 /*
470 * Generate attribute metadata needed later to produce tuples from raw C
471 * strings
472 */
473 attinmeta = TupleDescGetAttInMetadata(tupdesc);
474
475 /* total number of tuples to be examined */
476 max_calls = proc;
477
478 /* the return tuple always must have 1 rowid + num_categories columns */
479 num_categories = tupdesc->natts - 1;
480
481 firstpass = true;
482 lastrowid = NULL;
483
484 for (call_cntr = 0; call_cntr < max_calls; call_cntr++)
485 {
486 bool skip_tuple = false;
487 char **values;
488
489 /* allocate and zero space */
490 values = (char **) palloc0((1 + num_categories) * sizeof(char *));
491
492 /*
493 * now loop through the sql results and assign each value in sequence
494 * to the next category
495 */
496 for (i = 0; i < num_categories; i++)
497 {
499 char *rowid;
500
501 /* see if we've gone too far already */
502 if (call_cntr >= max_calls)
503 break;
504
505 /* get the next sql result tuple */
506 spi_tuple = spi_tuptable->vals[call_cntr];
507
508 /* get the rowid from the current sql result tuple */
510
511 /*
512 * If this is the first pass through the values for this rowid,
513 * set the first column to rowid
514 */
515 if (i == 0)
516 {
517 xpstrdup(values[0], rowid);
518
519 /*
520 * Check to see if the rowid is the same as that of the last
521 * tuple sent -- if so, skip this tuple entirely
522 */
524 {
525 xpfree(rowid);
526 skip_tuple = true;
527 break;
528 }
529 }
530
531 /*
532 * If rowid hasn't changed on us, continue building the output
533 * tuple.
534 */
535 if (xstreq(rowid, values[0]))
536 {
537 /*
538 * Get the next category item value, which is always attribute
539 * number three.
540 *
541 * Be careful to assign the value to the array index based on
542 * which category we are presently processing.
543 */
545
546 /*
547 * increment the counter since we consume a row for each
548 * category, but not for last pass because the outer loop will
549 * do that for us
550 */
551 if (i < (num_categories - 1))
552 call_cntr++;
553 xpfree(rowid);
554 }
555 else
556 {
557 /*
558 * We'll fill in NULLs for the missing values, but we need to
559 * decrement the counter since this sql result row doesn't
560 * belong to the current output tuple.
561 */
562 call_cntr--;
563 xpfree(rowid);
564 break;
565 }
566 }
567
568 if (!skip_tuple)
569 {
570 HeapTuple tuple;
571
572 /* build the tuple and store it */
573 tuple = BuildTupleFromCStrings(attinmeta, values);
574 tuplestore_puttuple(tupstore, tuple);
575 heap_freetuple(tuple);
576 }
577
578 /* Remember current rowid */
581 firstpass = false;
582
583 /* Clean up */
584 for (i = 0; i < num_categories + 1; i++)
585 if (values[i] != NULL)
586 pfree(values[i]);
587 pfree(values);
588 }
589
590 /* let the caller know we're sending back a tuplestore */
591 rsinfo->returnMode = SFRM_Materialize;
592 rsinfo->setResult = tupstore;
593 rsinfo->setDesc = tupdesc;
594
595 /* release SPI related resources (and return to caller's context) */
596 SPI_finish();
597
598 return (Datum) 0;
599}
@ ExprEndResult
Definition execnodes.h:343
#define PG_RETURN_NULL()
Definition fmgr.h:346
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition funcapi.c:276
@ TYPEFUNC_COMPOSITE
Definition funcapi.h:149
@ TYPEFUNC_RECORD
Definition funcapi.h:151
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
#define xpstrdup(tgtvar_, srcvar_)
Definition tablefunc.c:108
static void compatCrosstabTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
Definition tablefunc.c:1522
#define xstreq(tgtvar_, srcvar_)
Definition tablefunc.c:116

References BuildTupleFromCStrings(), compatCrosstabTupleDescs(), CreateTupleDescCopy(), ereport, errcode(), errdetail(), errmsg, ERROR, ExprEndResult, fb(), get_call_result_type(), heap_freetuple(), i, IsA, MemoryContextSwitchTo(), TupleDescData::natts, palloc0(), pfree(), PG_GETARG_TEXT_PP, PG_RETURN_NULL, SFRM_Materialize, SFRM_Materialize_Random, SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_SELECT, SPI_processed, SPI_tuptable, text_to_cstring(), SPITupleTable::tupdesc, TupleDescGetAttInMetadata(), tuplestore_begin_heap(), tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, values, work_mem, xpfree, xpstrdup, and xstreq.

◆ crosstab_hash()

Datum crosstab_hash ( PG_FUNCTION_ARGS  )

Definition at line 638 of file tablefunc.c.

639{
640 char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
642 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
643 TupleDesc tupdesc;
645 MemoryContext oldcontext;
647
648 /* check to see if caller supports us returning a tuplestore */
649 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
652 errmsg("set-valued function called in context that cannot accept a set")));
653 if (!(rsinfo->allowedModes & SFRM_Materialize) ||
654 rsinfo->expectedDesc == NULL)
657 errmsg("materialize mode required, but it is not allowed in this context")));
658
659 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
661
662 /* get the requested return tuple description */
663 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
664
665 /*
666 * Check to make sure we have a reasonable tuple descriptor
667 *
668 * Note we will attempt to coerce the values into whatever the return
669 * attribute type is and depend on the "in" function to complain if
670 * needed.
671 */
672 if (tupdesc->natts < 2)
675 errmsg("invalid crosstab return type"),
676 errdetail("Return row must have at least two columns.")));
677
678 /* load up the categories hash table */
680
681 /* let the caller know we're sending back a tuplestore */
682 rsinfo->returnMode = SFRM_Materialize;
683
684 /* now go build it */
685 rsinfo->setResult = get_crosstab_tuplestore(sql,
687 tupdesc,
688 rsinfo->allowedModes & SFRM_Materialize_Random);
689
690 /*
691 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
692 * tuples are in our tuplestore and passed back through rsinfo->setResult.
693 * rsinfo->setDesc is set to the tuple description that we actually used
694 * to build our tuples with, so the caller can verify we did what it was
695 * expecting.
696 */
697 rsinfo->setDesc = tupdesc;
698 MemoryContextSwitchTo(oldcontext);
699
700 return (Datum) 0;
701}
static Tuplestorestate * get_crosstab_tuplestore(char *sql, HTAB *crosstab_hash, TupleDesc tupdesc, bool randomAccess)
Definition tablefunc.c:793
Datum crosstab_hash(PG_FUNCTION_ARGS)
Definition tablefunc.c:638
static HTAB * load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
Definition tablefunc.c:707

References CreateTupleDescCopy(), crosstab_hash(), ereport, errcode(), errdetail(), errmsg, ERROR, fb(), get_crosstab_tuplestore(), IsA, load_categories_hash(), MemoryContextSwitchTo(), TupleDescData::natts, PG_GETARG_TEXT_PP, SFRM_Materialize, SFRM_Materialize_Random, and text_to_cstring().

Referenced by crosstab_hash(), get_crosstab_tuplestore(), and load_categories_hash().

◆ get_crosstab_tuplestore()

static Tuplestorestate * get_crosstab_tuplestore ( char sql,
HTAB crosstab_hash,
TupleDesc  tupdesc,
bool  randomAccess 
)
static

Definition at line 793 of file tablefunc.c.

797{
798 Tuplestorestate *tupstore;
800 AttInMetadata *attinmeta = TupleDescGetAttInMetadata(tupdesc);
801 char **values;
802 HeapTuple tuple;
803 int ret;
804 uint64 proc;
805
806 /* initialize our tuplestore (while still in query context!) */
807 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
808
809 /* Connect to SPI manager */
810 SPI_connect();
811
812 /* Now retrieve the crosstab source rows */
813 ret = SPI_execute(sql, true, 0);
814 proc = SPI_processed;
815
816 /* Check for qualifying tuples */
817 if ((ret == SPI_OK_SELECT) && (proc > 0))
818 {
821 int ncols = spi_tupdesc->natts;
822 char *rowid;
823 char *lastrowid = NULL;
824 bool firstpass = true;
825 uint64 i;
826 int j;
827 int result_ncols;
828
829 if (num_categories == 0)
830 {
831 /* no qualifying category tuples */
834 errmsg("crosstab categories query must return at least one row")));
835 }
836
837 /*
838 * The provided SQL query must always return at least three columns:
839 *
840 * 1. rowname the label for each row - column 1 in the final result
841 * 2. category the label for each value-column in the final result 3.
842 * value the values used to populate the value-columns
843 *
844 * If there are more than three columns, the last two are taken as
845 * "category" and "values". The first column is taken as "rowname".
846 * Additional columns (2 thru N-2) are assumed the same for the same
847 * "rowname", and are copied into the result tuple from the first time
848 * we encounter a particular rowname.
849 */
850 if (ncols < 3)
853 errmsg("invalid crosstab source data query"),
854 errdetail("The query must return at least 3 columns: row_name, category, and value.")));
855
856 result_ncols = (ncols - 2) + num_categories;
857
858 /* Recheck to make sure output tuple descriptor looks reasonable */
859 if (tupdesc->natts != result_ncols)
862 errmsg("invalid crosstab return type"),
863 errdetail("Return row must have %d columns, not %d.",
864 result_ncols, tupdesc->natts)));
865
866 /* allocate space and make sure it's clear */
867 values = (char **) palloc0(result_ncols * sizeof(char *));
868
869 for (i = 0; i < proc; i++)
870 {
872 crosstab_cat_desc *catdesc;
873 char *catname;
874
875 /* get the next sql result tuple */
876 spi_tuple = spi_tuptable->vals[i];
877
878 /* get the rowid from the current sql result tuple */
880
881 /*
882 * if we're on a new output row, grab the column values up to
883 * column N-2 now
884 */
886 {
887 /*
888 * a new row means we need to flush the old one first, unless
889 * we're on the very first row
890 */
891 if (!firstpass)
892 {
893 /* rowid changed, flush the previous output row */
894 tuple = BuildTupleFromCStrings(attinmeta, values);
895
896 tuplestore_puttuple(tupstore, tuple);
897
898 for (j = 0; j < result_ncols; j++)
899 xpfree(values[j]);
900 }
901
902 values[0] = rowid;
903 for (j = 1; j < ncols - 2; j++)
905
906 /* we're no longer on the first pass */
907 firstpass = false;
908 }
909
910 /* look up the category and fill in the appropriate column */
911 catname = SPI_getvalue(spi_tuple, spi_tupdesc, ncols - 1);
912
913 if (catname != NULL)
914 {
915 crosstab_HashTableLookup(crosstab_hash, catname, catdesc);
916
917 if (catdesc)
918 values[catdesc->attidx + ncols - 2] =
920 }
921
924 }
925
926 /* flush the last output row */
927 tuple = BuildTupleFromCStrings(attinmeta, values);
928
929 tuplestore_puttuple(tupstore, tuple);
930 }
931
932 if (SPI_finish() != SPI_OK_FINISH)
933 /* internal error */
934 elog(ERROR, "get_crosstab_tuplestore: SPI_finish() failed");
935
936 return tupstore;
937}
int64 hash_get_num_entries(HTAB *hashp)
Definition dynahash.c:1273
#define elog(elevel,...)
Definition elog.h:228
int j
Definition isn.c:78
#define SPI_OK_FINISH
Definition spi.h:83
#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC)
Definition tablefunc.c:133

References crosstab_cat_desc::attidx, BuildTupleFromCStrings(), crosstab_hash(), crosstab_HashTableLookup, elog, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), hash_get_num_entries(), i, j, TupleDescData::natts, palloc0(), SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_processed, SPI_tuptable, TupleDescGetAttInMetadata(), tuplestore_begin_heap(), tuplestore_puttuple(), values, work_mem, xpfree, xpstrdup, and xstreq.

Referenced by crosstab_hash().

◆ get_normal_pair()

static void get_normal_pair ( float8 x1,
float8 x2 
)
static

Definition at line 289 of file tablefunc.c.

290{
291 float8 u1,
292 u2,
293 v1,
294 v2,
295 s;
296
297 do
298 {
301
302 v1 = (2.0 * u1) - 1.0;
303 v2 = (2.0 * u2) - 1.0;
304
305 s = v1 * v1 + v2 * v2;
306 } while (s >= 1.0);
307
308 if (s == 0)
309 {
310 *x1 = 0;
311 *x2 = 0;
312 }
313 else
314 {
315 s = sqrt((-2.0 * log(s)) / s);
316 *x1 = v1 * s;
317 *x2 = v2 * s;
318 }
319}
double float8
Definition c.h:714
double pg_prng_double(pg_prng_state *state)
Definition pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition pg_prng.c:34

References fb(), pg_global_prng_state, and pg_prng_double().

Referenced by normal_rand().

◆ load_categories_hash()

static HTAB * load_categories_hash ( char cats_sql,
MemoryContext  per_query_ctx 
)
static

Definition at line 707 of file tablefunc.c.

708{
710 HASHCTL ctl;
711 int ret;
712 uint64 proc;
714
715 /* initialize the category hash table */
716 ctl.keysize = MAX_CATNAME_LEN;
717 ctl.entrysize = sizeof(crosstab_HashEnt);
718 ctl.hcxt = per_query_ctx;
719
720 /*
721 * use INIT_CATS, defined above as a guess of how many hash table entries
722 * to create, initially
723 */
724 crosstab_hash = hash_create("crosstab hash",
725 INIT_CATS,
726 &ctl,
728
729 /* Connect to SPI manager */
730 SPI_connect();
731
732 /* Retrieve the category name rows */
733 ret = SPI_execute(cats_sql, true, 0);
734 proc = SPI_processed;
735
736 /* Check for qualifying tuples */
737 if ((ret == SPI_OK_SELECT) && (proc > 0))
738 {
741 uint64 i;
742
743 /*
744 * The provided categories SQL query must always return one column:
745 * category - the label or identifier for each column
746 */
747 if (spi_tupdesc->natts != 1)
750 errmsg("invalid crosstab categories query"),
751 errdetail("The query must return one column.")));
752
753 for (i = 0; i < proc; i++)
754 {
755 crosstab_cat_desc *catdesc;
756 char *catname;
758
759 /* get the next sql result tuple */
760 spi_tuple = spi_tuptable->vals[i];
761
762 /* get the category from the current sql result tuple */
763 catname = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
764 if (catname == NULL)
767 errmsg("crosstab category value must not be null")));
768
770
772 catdesc->catname = catname;
773 catdesc->attidx = i;
774
775 /* Add the proc description block to the hashtable */
777
779 }
780 }
781
782 if (SPI_finish() != SPI_OK_FINISH)
783 /* internal error */
784 elog(ERROR, "load_categories_hash: SPI_finish() failed");
785
786 return crosstab_hash;
787}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
#define palloc_object(type)
Definition fe_memutils.h:74
#define HASH_STRINGS
Definition hsearch.h:91
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
tree ctl
Definition radixtree.h:1838
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
Definition tablefunc.c:147
#define INIT_CATS
Definition tablefunc.c:131
struct crosstab_hashent crosstab_HashEnt

References crosstab_cat_desc::attidx, crosstab_cat_desc::catname, crosstab_hash(), crosstab_HashTableInsert, ctl, elog, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_STRINGS, i, INIT_CATS, MAX_CATNAME_LEN, MemoryContextSwitchTo(), palloc_object, SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_processed, and SPI_tuptable.

Referenced by crosstab_hash().

◆ normal_rand()

Datum normal_rand ( PG_FUNCTION_ARGS  )

Definition at line 178 of file tablefunc.c.

179{
181 uint64 call_cntr;
182 uint64 max_calls;
184 float8 mean;
185 float8 stddev;
186 float8 carry_val;
187 bool use_carry;
188 MemoryContext oldcontext;
189
190 /* stuff done only on the first call of the function */
191 if (SRF_IS_FIRSTCALL())
192 {
193 int32 num_tuples;
194
195 /* create a function context for cross-call persistence */
197
198 /*
199 * switch to memory context appropriate for multiple function calls
200 */
201 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
202
203 /* total number of tuples to be returned */
204 num_tuples = PG_GETARG_INT32(0);
205 if (num_tuples < 0)
208 errmsg("number of rows cannot be negative")));
209 funcctx->max_calls = num_tuples;
210
211 /* allocate memory for user context */
213
214 /*
215 * Use fctx to keep track of upper and lower bounds from call to call.
216 * It will also be used to carry over the spare value we get from the
217 * Box-Muller algorithm so that we only actually calculate a new value
218 * every other call.
219 */
220 fctx->mean = PG_GETARG_FLOAT8(1);
221 fctx->stddev = PG_GETARG_FLOAT8(2);
222 fctx->carry_val = 0;
223 fctx->use_carry = false;
224
225 funcctx->user_fctx = fctx;
226
227 MemoryContextSwitchTo(oldcontext);
228 }
229
230 /* stuff done on every call of the function */
232
233 call_cntr = funcctx->call_cntr;
234 max_calls = funcctx->max_calls;
235 fctx = funcctx->user_fctx;
236 mean = fctx->mean;
237 stddev = fctx->stddev;
238 carry_val = fctx->carry_val;
239 use_carry = fctx->use_carry;
240
241 if (call_cntr < max_calls) /* do when there is more left to send */
242 {
244
245 if (use_carry)
246 {
247 /*
248 * reset use_carry and use second value obtained on last pass
249 */
250 fctx->use_carry = false;
251 result = carry_val;
252 }
253 else
254 {
257
258 /* Get the next two normal values */
260
261 /* use the first */
262 result = mean + (stddev * normval_1);
263
264 /* and save the second */
265 fctx->carry_val = mean + (stddev * normval_2);
266 fctx->use_carry = true;
267 }
268
269 /* send the result */
271 }
272 else
273 /* do when there is no more left */
275}
uint32 result
#define PG_GETARG_FLOAT8(n)
Definition fmgr.h:283
#define SRF_IS_FIRSTCALL()
Definition funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition funcapi.h:306
#define SRF_RETURN_DONE(_funcctx)
Definition funcapi.h:328
static Datum Float8GetDatum(float8 X)
Definition postgres.h:515
static void get_normal_pair(float8 *x1, float8 *x2)
Definition tablefunc.c:289

References ereport, errcode(), errmsg, ERROR, fb(), Float8GetDatum(), get_normal_pair(), MemoryContextSwitchTo(), palloc_object, PG_GETARG_FLOAT8, PG_GETARG_INT32, result, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, and SRF_RETURN_NEXT.

◆ PG_FUNCTION_INFO_V1() [1/5]

PG_FUNCTION_INFO_V1 ( connectby_text  )

◆ PG_FUNCTION_INFO_V1() [2/5]

PG_FUNCTION_INFO_V1 ( connectby_text_serial  )

◆ PG_FUNCTION_INFO_V1() [3/5]

PG_FUNCTION_INFO_V1 ( crosstab  )

◆ PG_FUNCTION_INFO_V1() [4/5]

PG_FUNCTION_INFO_V1 ( crosstab_hash  )

◆ PG_FUNCTION_INFO_V1() [5/5]

PG_FUNCTION_INFO_V1 ( normal_rand  )

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "tablefunc",
version = PG_VERSION 
)

◆ validateConnectbyTupleDesc()

static void validateConnectbyTupleDesc ( TupleDesc  td,
bool  show_branch,
bool  show_serial 
)
static

Definition at line 1409 of file tablefunc.c.

1410{
1411 int expected_cols;
1412
1413 /* are there the correct number of columns */
1414 if (show_branch)
1416 else
1418 if (show_serial)
1419 expected_cols++;
1420
1421 if (td->natts != expected_cols)
1422 ereport(ERROR,
1424 errmsg("invalid connectby return type"),
1425 errdetail("Return row must have %d columns, not %d.",
1426 expected_cols, td->natts)));
1427
1428 /* the first two columns will be checked against the input tuples later */
1429
1430 /* check that the type of the third column is INT4 */
1431 if (TupleDescAttr(td, 2)->atttypid != INT4OID)
1432 ereport(ERROR,
1434 errmsg("invalid connectby return type"),
1435 errdetail("Third return column (depth) must be type %s.",
1437
1438 /* check that the type of the branch column is TEXT if applicable */
1439 if (show_branch && TupleDescAttr(td, 3)->atttypid != TEXTOID)
1440 ereport(ERROR,
1442 errmsg("invalid connectby return type"),
1443 errdetail("Fourth return column (branch) must be type %s.",
1445
1446 /* check that the type of the serial column is INT4 if applicable */
1447 if (show_branch && show_serial &&
1448 TupleDescAttr(td, 4)->atttypid != INT4OID)
1449 ereport(ERROR,
1451 errmsg("invalid connectby return type"),
1452 errdetail("Fifth return column (serial) must be type %s.",
1454 if (!show_branch && show_serial &&
1455 TupleDescAttr(td, 3)->atttypid != INT4OID)
1456 ereport(ERROR,
1458 errmsg("invalid connectby return type"),
1459 errdetail("Fourth return column (serial) must be type %s.",
1461
1462 /* OK, the tupdesc is valid for our purposes */
1463}
char * format_type_be(Oid type_oid)

References CONNECTBY_NCOLS, CONNECTBY_NCOLS_NOBRANCH, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), format_type_be(), TupleDescData::natts, and TupleDescAttr().

Referenced by connectby_text(), and connectby_text_serial().