4 * Sample to demonstrate C functions which return setof scalar
6 * Joe Conway <mail@joeconway.com>
8 * Nabil Sayegh <postgresql@e-trolley.de>
10 * Copyright (c) 2002-2003, PostgreSQL Global Development Group
12 * Permission to use, copy, modify, and distribute this software and its
13 * documentation for any purpose, without fee, and without a written agreement
14 * is hereby granted, provided that the above copyright notice and this
15 * paragraph and the following two paragraphs appear in all copies.
17 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
18 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
19 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
20 * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
21 * POSSIBILITY OF SUCH DAMAGE.
23 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
24 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
25 * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
26 * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
27 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
36 #include "executor/spi.h"
37 #include "lib/stringinfo.h"
38 #include "miscadmin.h"
39 #include "utils/builtins.h"
40 #include "utils/guc.h"
41 #include "utils/lsyscache.h"
43 #include "tablefunc.h"
45 static int load_categories_hash(char *cats_sql, MemoryContext per_query_ctx);
46 static Tuplestorestate *get_crosstab_tuplestore(char *sql,
49 MemoryContext per_query_ctx);
50 static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial);
51 static bool compatCrosstabTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2);
52 static bool compatConnectbyTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2);
53 static void get_normal_pair(float8 *x1, float8 *x2);
54 static TupleDesc make_crosstab_tupledesc(TupleDesc spi_tupdesc,
56 static Tuplestorestate *connectby(char *relname,
65 MemoryContext per_query_ctx,
66 AttInMetadata *attinmeta);
67 static Tuplestorestate *build_tuplestore_recursively(char *key_fld,
79 MemoryContext per_query_ctx,
80 AttInMetadata *attinmeta,
81 Tuplestorestate *tupstore);
85 float8 mean; /* mean of the distribution */
86 float8 stddev; /* stddev of the distribution */
87 float8 carry_val; /* hold second generated value */
88 bool use_carry; /* use second generated value */
93 SPITupleTable *spi_tuptable; /* sql results from user query */
94 char *lastrowid; /* rowid of the last tuple sent */
97 #define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
98 #define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
99 #define xpfree(var_) \
108 /* sign, 10 digits, '\0' */
109 #define INT32_STRLEN 12
111 /* hash table support */
112 static HTAB *crosstab_HashTable;
114 /* The information we cache about loaded procedures */
115 typedef struct crosstab_cat_desc
118 int attidx; /* zero based */
121 #define MAX_CATNAME_LEN NAMEDATALEN
124 #define crosstab_HashTableLookup(CATNAME, CATDESC) \
126 crosstab_HashEnt *hentry; char key[MAX_CATNAME_LEN]; \
128 MemSet(key, 0, MAX_CATNAME_LEN); \
129 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
130 hentry = (crosstab_HashEnt*) hash_search(crosstab_HashTable, \
131 key, HASH_FIND, NULL); \
133 CATDESC = hentry->catdesc; \
138 #define crosstab_HashTableInsert(CATDESC) \
140 crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
142 MemSet(key, 0, MAX_CATNAME_LEN); \
143 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
144 hentry = (crosstab_HashEnt*) hash_search(crosstab_HashTable, \
145 key, HASH_ENTER, &found); \
146 if (hentry == NULL) \
148 (errcode(ERRCODE_OUT_OF_MEMORY), \
149 errmsg("out of memory"))); \
152 (errcode(ERRCODE_DUPLICATE_OBJECT), \
153 errmsg("duplicate category name"))); \
154 hentry->catdesc = CATDESC; \
158 typedef struct crosstab_hashent
160 char internal_catname[MAX_CATNAME_LEN];
161 crosstab_cat_desc *catdesc;
165 * normal_rand - return requested number of random values
166 * with a Gaussian (Normal) distribution.
168 * inputs are int numvals, float8 mean, and float8 stddev
169 * returns setof float8
171 PG_FUNCTION_INFO_V1(normal_rand);
173 normal_rand(PG_FUNCTION_ARGS)
175 FuncCallContext *funcctx;
178 normal_rand_fctx *fctx;
183 MemoryContext oldcontext;
185 /* stuff done only on the first call of the function */
186 if (SRF_IS_FIRSTCALL())
188 /* create a function context for cross-call persistence */
189 funcctx = SRF_FIRSTCALL_INIT();
192 * switch to memory context appropriate for multiple function
195 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
197 /* total number of tuples to be returned */
198 funcctx->max_calls = PG_GETARG_UINT32(0);
200 /* allocate memory for user context */
201 fctx = (normal_rand_fctx *) palloc(sizeof(normal_rand_fctx));
204 * Use fctx to keep track of upper and lower bounds from call to
205 * call. It will also be used to carry over the spare value we get
206 * from the Box-Muller algorithm so that we only actually
207 * calculate a new value every other call.
209 fctx->mean = PG_GETARG_FLOAT8(1);
210 fctx->stddev = PG_GETARG_FLOAT8(2);
212 fctx->use_carry = false;
214 funcctx->user_fctx = fctx;
216 MemoryContextSwitchTo(oldcontext);
219 /* stuff done on every call of the function */
220 funcctx = SRF_PERCALL_SETUP();
222 call_cntr = funcctx->call_cntr;
223 max_calls = funcctx->max_calls;
224 fctx = funcctx->user_fctx;
226 stddev = fctx->stddev;
227 carry_val = fctx->carry_val;
228 use_carry = fctx->use_carry;
230 if (call_cntr < max_calls) /* do when there is more left to send */
237 * reset use_carry and use second value obtained on last pass
239 fctx->use_carry = false;
247 /* Get the next two normal values */
248 get_normal_pair(&normval_1, &normval_2);
251 result = mean + (stddev * normval_1);
253 /* and save the second */
254 fctx->carry_val = mean + (stddev * normval_2);
255 fctx->use_carry = true;
258 /* send the result */
259 SRF_RETURN_NEXT(funcctx, Float8GetDatum(result));
262 /* do when there is no more left */
263 SRF_RETURN_DONE(funcctx);
268 * Assigns normally distributed (Gaussian) values to a pair of provided
269 * parameters, with mean 0, standard deviation 1.
271 * This routine implements Algorithm P (Polar method for normal deviates)
272 * from Knuth's _The_Art_of_Computer_Programming_, Volume 2, 3rd ed., pages
273 * 122-126. Knuth cites his source as "The polar method", G. E. P. Box, M. E.
274 * Muller, and G. Marsaglia, _Annals_Math,_Stat._ 29 (1958), 610-611.
278 get_normal_pair(float8 *x1, float8 *x2)
288 u1 = (float8) random() / (float8) MAX_RANDOM_VALUE;
289 u2 = (float8) random() / (float8) MAX_RANDOM_VALUE;
291 v1 = (2.0 * u1) - 1.0;
292 v2 = (2.0 * u2) - 1.0;
294 s = v1 * v1 + v2 * v2;
304 s = sqrt((-2.0 * log(s)) / s);
311 * crosstab - create a crosstab of rowids and values columns from a
312 * SQL statement returning one rowid column, one category column,
313 * and one value column.
315 * e.g. given sql which produces:
318 * ------+-------+-------
329 * <===== values columns =====>
330 * rowid cat1 cat2 cat3 cat4
331 * ------+-------+-------+-------+-------
332 * row1 val1 val2 val3 val4
333 * row2 val5 val6 val7 val8
336 * 1. SQL result must be ordered by 1,2.
337 * 2. The number of values columns depends on the tuple description
338 * of the function's declared return type.
339 * 2. Missing values (i.e. not enough adjacent rows of same rowid to
340 * fill the number of result values columns) are filled in with nulls.
341 * 3. Extra values (i.e. too many adjacent rows of same rowid to fill
342 * the number of result values columns) are skipped.
343 * 4. Rows with all nulls in the values columns are skipped.
345 PG_FUNCTION_INFO_V1(crosstab);
347 crosstab(PG_FUNCTION_ARGS)
349 FuncCallContext *funcctx;
350 TupleDesc ret_tupdesc;
353 TupleTableSlot *slot;
354 AttInMetadata *attinmeta;
355 SPITupleTable *spi_tuptable = NULL;
356 TupleDesc spi_tupdesc;
357 char *lastrowid = NULL;
361 MemoryContext oldcontext;
363 /* stuff done only on the first call of the function */
364 if (SRF_IS_FIRSTCALL())
366 char *sql = GET_STR(PG_GETARG_TEXT_P(0));
367 Oid funcid = fcinfo->flinfo->fn_oid;
370 TupleDesc tupdesc = NULL;
374 /* create a function context for cross-call persistence */
375 funcctx = SRF_FIRSTCALL_INIT();
378 * switch to memory context appropriate for multiple function
381 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
383 /* Connect to SPI manager */
384 if ((ret = SPI_connect()) < 0)
386 elog(ERROR, "crosstab: SPI_connect returned %d", ret);
388 /* Retrieve the desired rows */
389 ret = SPI_exec(sql, 0);
390 proc = SPI_processed;
392 /* Check for qualifying tuples */
393 if ((ret == SPI_OK_SELECT) && (proc > 0))
395 spi_tuptable = SPI_tuptable;
396 spi_tupdesc = spi_tuptable->tupdesc;
399 * The provided SQL query must always return three columns.
401 * 1. rowname the label or identifier for each row in the final
402 * result 2. category the label or identifier for each column
403 * in the final result 3. values the value for each column
404 * in the final result
406 if (spi_tupdesc->natts != 3)
408 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
409 errmsg("invalid source data SQL statement"),
410 errdetail("The provided SQL must return 3 " \
411 " columns; rowid, category, and values.")));
415 /* no qualifying tuples */
417 SRF_RETURN_DONE(funcctx);
420 /* SPI switches context on us, so reset it */
421 MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
423 /* get the typeid that represents our return type */
424 functypeid = get_func_rettype(funcid);
426 /* check typtype to see if we have a predetermined return type */
427 functyptype = get_typtype(functypeid);
429 if (functyptype == 'c')
431 /* Build a tuple description for a functypeid tuple */
432 tupdesc = TypeGetTupleDesc(functypeid, NIL);
434 else if (functyptype == 'p' && functypeid == RECORDOID)
436 if (fcinfo->nargs != 2)
438 (errcode(ERRCODE_SYNTAX_ERROR),
439 errmsg("wrong number of arguments")));
442 int num_categories = PG_GETARG_INT32(1);
444 tupdesc = make_crosstab_tupledesc(spi_tupdesc, num_categories);
449 (errcode(ERRCODE_SYNTAX_ERROR),
450 errmsg("return type must be a row type")));
453 * Check that return tupdesc is compatible with the one we got
454 * from ret_relname, at least based on number and type of
457 if (!compatCrosstabTupleDescs(tupdesc, spi_tupdesc))
459 (errcode(ERRCODE_SYNTAX_ERROR),
460 errmsg("return and sql tuple descriptions are " \
463 /* allocate a slot for a tuple with this tupdesc */
464 slot = TupleDescGetSlot(tupdesc);
466 /* assign slot to function context */
467 funcctx->slot = slot;
470 * Generate attribute metadata needed later to produce tuples from
473 attinmeta = TupleDescGetAttInMetadata(tupdesc);
474 funcctx->attinmeta = attinmeta;
476 /* allocate memory for user context */
477 fctx = (crosstab_fctx *) palloc(sizeof(crosstab_fctx));
480 * Save spi data for use across calls
482 fctx->spi_tuptable = spi_tuptable;
483 fctx->lastrowid = NULL;
484 funcctx->user_fctx = fctx;
486 /* total number of tuples to be returned */
487 funcctx->max_calls = proc;
489 MemoryContextSwitchTo(oldcontext);
492 /* stuff done on every call of the function */
493 funcctx = SRF_PERCALL_SETUP();
496 * initialize per-call variables
498 call_cntr = funcctx->call_cntr;
499 max_calls = funcctx->max_calls;
501 /* return slot for our tuple */
502 slot = funcctx->slot;
504 /* user context info */
505 fctx = (crosstab_fctx *) funcctx->user_fctx;
506 lastrowid = fctx->lastrowid;
507 spi_tuptable = fctx->spi_tuptable;
510 spi_tupdesc = spi_tuptable->tupdesc;
512 /* attribute return type and return tuple description */
513 attinmeta = funcctx->attinmeta;
514 ret_tupdesc = attinmeta->tupdesc;
516 /* the return tuple always must have 1 rowid + num_categories columns */
517 num_categories = ret_tupdesc->natts - 1;
519 if (call_cntr < max_calls) /* do when there is more left to send */
524 bool allnulls = true;
529 values = (char **) palloc((1 + num_categories) * sizeof(char *));
531 /* and make sure it's clear */
532 memset(values, '\0', (1 + num_categories) * sizeof(char *));
535 * now loop through the sql results and assign each value in
536 * sequence to the next category
538 for (i = 0; i < num_categories; i++)
543 /* see if we've gone too far already */
544 if (call_cntr >= max_calls)
547 /* get the next sql result tuple */
548 spi_tuple = spi_tuptable->vals[call_cntr];
550 /* get the rowid from the current sql result tuple */
551 rowid = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
554 * If this is the first pass through the values for this
555 * rowid set it, otherwise make sure it hasn't changed on
556 * us. Also check to see if the rowid is the same as that
557 * of the last tuple sent -- if so, skip this tuple
561 values[0] = pstrdup(rowid);
563 if ((rowid != NULL) && (strcmp(rowid, values[0]) == 0))
565 if ((lastrowid != NULL) && (strcmp(rowid, lastrowid) == 0))
567 else if (allnulls == true)
571 * Get the next category item value, which is alway
572 * attribute number three.
574 * Be careful to sssign the value to the array index
575 * based on which category we are presently
578 values[1 + i] = SPI_getvalue(spi_tuple, spi_tupdesc, 3);
581 * increment the counter since we consume a row for
582 * each category, but not for last pass because the
583 * API will do that for us
585 if (i < (num_categories - 1))
586 call_cntr = ++funcctx->call_cntr;
591 * We'll fill in NULLs for the missing values, but we
592 * need to decrement the counter since this sql result
593 * row doesn't belong to the current output tuple.
595 call_cntr = --funcctx->call_cntr;
603 xpfree(fctx->lastrowid);
605 if (values[0] != NULL)
608 * switch to memory context appropriate for multiple
611 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
613 lastrowid = fctx->lastrowid = pstrdup(values[0]);
614 MemoryContextSwitchTo(oldcontext);
619 /* build the tuple */
620 tuple = BuildTupleFromCStrings(attinmeta, values);
622 /* make the tuple into a datum */
623 result = TupleGetDatum(slot, tuple);
626 for (i = 0; i < num_categories + 1; i++)
627 if (values[i] != NULL)
631 SRF_RETURN_NEXT(funcctx, result);
636 * Skipping this tuple entirely, but we need to advance
637 * the counter like the API would if we had returned one.
639 call_cntr = ++funcctx->call_cntr;
641 /* we'll start over at the top */
644 /* see if we've gone too far already */
645 if (call_cntr >= max_calls)
647 /* release SPI related resources */
649 SRF_RETURN_DONE(funcctx);
655 /* do when there is no more left */
657 /* release SPI related resources */
659 SRF_RETURN_DONE(funcctx);
664 * crosstab_hash - reimplement crosstab as materialized function and
665 * properly deal with missing values (i.e. don't pack remaining
666 * values to the left)
668 * crosstab - create a crosstab of rowids and values columns from a
669 * SQL statement returning one rowid column, one category column,
670 * and one value column.
672 * e.g. given sql which produces:
675 * ------+-------+-------
685 * <===== values columns =====>
686 * rowid cat1 cat2 cat3 cat4
687 * ------+-------+-------+-------+-------
688 * row1 val1 val2 null val4
689 * row2 val5 val6 val7 val8
692 * 1. SQL result must be ordered by 1.
693 * 2. The number of values columns depends on the tuple description
694 * of the function's declared return type.
695 * 2. Missing values (i.e. missing category) are filled in with nulls.
696 * 3. Extra values (i.e. not in category results) are skipped.
698 PG_FUNCTION_INFO_V1(crosstab_hash);
700 crosstab_hash(PG_FUNCTION_ARGS)
702 char *sql = GET_STR(PG_GETARG_TEXT_P(0));
703 char *cats_sql = GET_STR(PG_GETARG_TEXT_P(1));
704 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
706 MemoryContext per_query_ctx;
707 MemoryContext oldcontext;
710 /* check to see if caller supports us returning a tuplestore */
711 if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
713 (errcode(ERRCODE_SYNTAX_ERROR),
714 errmsg("materialize mode required, but it is not " \
715 "allowed in this context")));
717 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
718 oldcontext = MemoryContextSwitchTo(per_query_ctx);
720 /* get the requested return tuple description */
721 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
724 * Check to make sure we have a reasonable tuple descriptor
726 * Note we will attempt to coerce the values into whatever the return
727 * attribute type is and depend on the "in" function to complain if
730 if (tupdesc->natts < 2)
732 (errcode(ERRCODE_SYNTAX_ERROR),
733 errmsg("query-specified return tuple and " \
734 "crosstab function are not compatible")));
736 /* load up the categories hash table */
737 num_categories = load_categories_hash(cats_sql, per_query_ctx);
739 /* let the caller know we're sending back a tuplestore */
740 rsinfo->returnMode = SFRM_Materialize;
742 /* now go build it */
743 rsinfo->setResult = get_crosstab_tuplestore(sql,
749 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
750 * tuples are in our tuplestore and passed back through
751 * rsinfo->setResult. rsinfo->setDesc is set to the tuple description
752 * that we actually used to build our tuples with, so the caller can
753 * verify we did what it was expecting.
755 rsinfo->setDesc = tupdesc;
756 MemoryContextSwitchTo(oldcontext);
762 * load up the categories hash table
765 load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
770 MemoryContext SPIcontext;
771 int num_categories = 0;
773 /* initialize the category hash table */
774 ctl.keysize = MAX_CATNAME_LEN;
775 ctl.entrysize = sizeof(crosstab_HashEnt);
778 * use INIT_CATS, defined above as a guess of how many hash table
779 * entries to create, initially
781 crosstab_HashTable = hash_create("crosstab hash", INIT_CATS, &ctl, HASH_ELEM);
783 /* Connect to SPI manager */
784 if ((ret = SPI_connect()) < 0)
786 elog(ERROR, "load_categories_hash: SPI_connect returned %d", ret);
788 /* Retrieve the category name rows */
789 ret = SPI_exec(cats_sql, 0);
790 num_categories = proc = SPI_processed;
792 /* Check for qualifying tuples */
793 if ((ret == SPI_OK_SELECT) && (proc > 0))
795 SPITupleTable *spi_tuptable = SPI_tuptable;
796 TupleDesc spi_tupdesc = spi_tuptable->tupdesc;
800 * The provided categories SQL query must always return one
801 * column: category - the label or identifier for each column
803 if (spi_tupdesc->natts != 1)
805 (errcode(ERRCODE_SYNTAX_ERROR),
806 errmsg("provided \"categories\" SQL must " \
807 "return 1 column of at least one row")));
809 for (i = 0; i < proc; i++)
811 crosstab_cat_desc *catdesc;
815 /* get the next sql result tuple */
816 spi_tuple = spi_tuptable->vals[i];
818 /* get the category from the current sql result tuple */
819 catname = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
821 SPIcontext = MemoryContextSwitchTo(per_query_ctx);
823 catdesc = (crosstab_cat_desc *) palloc(sizeof(crosstab_cat_desc));
824 catdesc->catname = catname;
827 /* Add the proc description block to the hashtable */
828 crosstab_HashTableInsert(catdesc);
830 MemoryContextSwitchTo(SPIcontext);
835 /* no qualifying tuples */
838 (errcode(ERRCODE_SYNTAX_ERROR),
839 errmsg("provided \"categories\" SQL must " \
840 "return 1 column of at least one row")));
843 if (SPI_finish() != SPI_OK_FINISH)
845 elog(ERROR, "load_categories_hash: SPI_finish() failed");
847 return num_categories;
851 * create and populate the crosstab tuplestore using the provided source query
853 static Tuplestorestate *
854 get_crosstab_tuplestore(char *sql,
857 MemoryContext per_query_ctx)
859 Tuplestorestate *tupstore;
860 AttInMetadata *attinmeta = TupleDescGetAttInMetadata(tupdesc);
865 MemoryContext SPIcontext;
867 /* initialize our tuplestore */
868 tupstore = tuplestore_begin_heap(true, false, SortMem);
870 /* Connect to SPI manager */
871 if ((ret = SPI_connect()) < 0)
873 elog(ERROR, "get_crosstab_tuplestore: SPI_connect returned %d", ret);
875 /* Now retrieve the crosstab source rows */
876 ret = SPI_exec(sql, 0);
877 proc = SPI_processed;
879 /* Check for qualifying tuples */
880 if ((ret == SPI_OK_SELECT) && (proc > 0))
882 SPITupleTable *spi_tuptable = SPI_tuptable;
883 TupleDesc spi_tupdesc = spi_tuptable->tupdesc;
884 int ncols = spi_tupdesc->natts;
886 char *lastrowid = NULL;
892 * The provided SQL query must always return at least three
895 * 1. rowname the label for each row - column 1 in the final result
896 * 2. category the label for each value-column in the final
897 * result 3. value the values used to populate the
900 * If there are more than three columns, the last two are taken as
901 * "category" and "values". The first column is taken as
902 * "rowname". Additional columns (2 thru N-2) are assumed the same
903 * for the same "rowname", and are copied into the result tuple
904 * from the first time we encounter a particular rowname.
908 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
909 errmsg("invalid source data SQL statement"),
910 errdetail("The provided SQL must return 3 " \
911 " columns; rowid, category, and values.")));
913 result_ncols = (ncols - 2) + num_categories;
915 /* Recheck to make sure we tuple descriptor still looks reasonable */
916 if (tupdesc->natts != result_ncols)
918 (errcode(ERRCODE_SYNTAX_ERROR),
919 errmsg("invalid return type"),
920 errdetail("query-specified return " \
921 "tuple has %d columns but crosstab " \
922 "returns %d", tupdesc->natts, result_ncols)));
925 values = (char **) palloc(result_ncols * sizeof(char *));
927 /* and make sure it's clear */
928 memset(values, '\0', result_ncols * sizeof(char *));
930 for (i = 0; i < proc; i++)
933 crosstab_cat_desc *catdesc;
936 /* get the next sql result tuple */
937 spi_tuple = spi_tuptable->vals[i];
939 /* get the rowid from the current sql result tuple */
940 rowid = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
942 /* if rowid is null, skip this tuple entirely */
947 * if we're on a new output row, grab the column values up to
950 if ((lastrowid == NULL) || (strcmp(rowid, lastrowid) != 0))
953 * a new row means we need to flush the old one first,
954 * unless we're on the very first row
956 if (lastrowid != NULL)
959 * switch to appropriate context while storing the
962 SPIcontext = MemoryContextSwitchTo(per_query_ctx);
964 /* rowid changed, flush the previous output row */
965 tuple = BuildTupleFromCStrings(attinmeta, values);
966 tuplestore_puttuple(tupstore, tuple);
967 for (j = 0; j < result_ncols; j++)
970 /* now reset the context */
971 MemoryContextSwitchTo(SPIcontext);
975 for (j = 1; j < ncols - 2; j++)
976 values[j] = SPI_getvalue(spi_tuple, spi_tupdesc, j + 1);
979 /* look up the category and fill in the appropriate column */
980 catname = SPI_getvalue(spi_tuple, spi_tupdesc, ncols - 1);
984 crosstab_HashTableLookup(catname, catdesc);
987 values[catdesc->attidx + ncols - 2] =
988 SPI_getvalue(spi_tuple, spi_tupdesc, ncols);
992 lastrowid = pstrdup(rowid);
995 /* switch to appropriate context while storing the tuple */
996 SPIcontext = MemoryContextSwitchTo(per_query_ctx);
998 /* flush the last output row */
999 tuple = BuildTupleFromCStrings(attinmeta, values);
1000 tuplestore_puttuple(tupstore, tuple);
1002 /* now reset the context */
1003 MemoryContextSwitchTo(SPIcontext);
1008 /* no qualifying tuples */
1012 if (SPI_finish() != SPI_OK_FINISH)
1013 /* internal error */
1014 elog(ERROR, "get_crosstab_tuplestore: SPI_finish() failed");
1016 tuplestore_donestoring(tupstore);
1022 * connectby_text - produce a result set from a hierarchical (parent/child)
1025 * e.g. given table foo:
1027 * keyid parent_keyid pos
1028 * ------+------------+--
1040 * connectby(text relname, text keyid_fld, text parent_keyid_fld
1041 * [, text orderby_fld], text start_with, int max_depth
1042 * [, text branch_delim])
1043 * connectby('foo', 'keyid', 'parent_keyid', 'pos', 'row2', 0, '~') returns:
1045 * keyid parent_id level branch serial
1046 * ------+-----------+--------+-----------------------
1047 * row2 NULL 0 row2 1
1048 * row5 row2 1 row2~row5 2
1049 * row9 row5 2 row2~row5~row9 3
1050 * row4 row2 1 row2~row4 4
1051 * row6 row4 2 row2~row4~row6 5
1052 * row8 row6 3 row2~row4~row6~row8 6
1055 PG_FUNCTION_INFO_V1(connectby_text);
1057 #define CONNECTBY_NCOLS 4
1058 #define CONNECTBY_NCOLS_NOBRANCH 3
1061 connectby_text(PG_FUNCTION_ARGS)
1063 char *relname = GET_STR(PG_GETARG_TEXT_P(0));
1064 char *key_fld = GET_STR(PG_GETARG_TEXT_P(1));
1065 char *parent_key_fld = GET_STR(PG_GETARG_TEXT_P(2));
1066 char *start_with = GET_STR(PG_GETARG_TEXT_P(3));
1067 int max_depth = PG_GETARG_INT32(4);
1068 char *branch_delim = NULL;
1069 bool show_branch = false;
1070 bool show_serial = false;
1071 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1073 AttInMetadata *attinmeta;
1074 MemoryContext per_query_ctx;
1075 MemoryContext oldcontext;
1077 /* check to see if caller supports us returning a tuplestore */
1078 if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
1080 (errcode(ERRCODE_SYNTAX_ERROR),
1081 errmsg("materialize mode required, but it is not " \
1082 "allowed in this context")));
1084 if (fcinfo->nargs == 6)
1086 branch_delim = GET_STR(PG_GETARG_TEXT_P(5));
1090 /* default is no show, tilde for the delimiter */
1091 branch_delim = pstrdup("~");
1093 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1094 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1096 /* get the requested return tuple description */
1097 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1099 /* does it meet our needs */
1100 validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1102 /* OK, use it then */
1103 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1105 /* check to see if caller supports us returning a tuplestore */
1106 if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
1108 (errcode(ERRCODE_SYNTAX_ERROR),
1109 errmsg("materialize mode required, but it is not " \
1110 "allowed in this context")));
1112 /* OK, go to work */
1113 rsinfo->returnMode = SFRM_Materialize;
1114 rsinfo->setResult = connectby(relname,
1125 rsinfo->setDesc = tupdesc;
1127 MemoryContextSwitchTo(oldcontext);
1130 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1131 * tuples are in our tuplestore and passed back through
1132 * rsinfo->setResult. rsinfo->setDesc is set to the tuple description
1133 * that we actually used to build our tuples with, so the caller can
1134 * verify we did what it was expecting.
1139 PG_FUNCTION_INFO_V1(connectby_text_serial);
1141 connectby_text_serial(PG_FUNCTION_ARGS)
1143 char *relname = GET_STR(PG_GETARG_TEXT_P(0));
1144 char *key_fld = GET_STR(PG_GETARG_TEXT_P(1));
1145 char *parent_key_fld = GET_STR(PG_GETARG_TEXT_P(2));
1146 char *orderby_fld = GET_STR(PG_GETARG_TEXT_P(3));
1147 char *start_with = GET_STR(PG_GETARG_TEXT_P(4));
1148 int max_depth = PG_GETARG_INT32(5);
1149 char *branch_delim = NULL;
1150 bool show_branch = false;
1151 bool show_serial = true;
1153 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1155 AttInMetadata *attinmeta;
1156 MemoryContext per_query_ctx;
1157 MemoryContext oldcontext;
1159 /* check to see if caller supports us returning a tuplestore */
1160 if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
1161 elog(ERROR, "connectby: materialize mode required, but it is not "
1162 "allowed in this context");
1164 if (fcinfo->nargs == 7)
1166 branch_delim = GET_STR(PG_GETARG_TEXT_P(6));
1170 /* default is no show, tilde for the delimiter */
1171 branch_delim = pstrdup("~");
1173 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1174 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1176 /* get the requested return tuple description */
1177 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1179 /* does it meet our needs */
1180 validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1182 /* OK, use it then */
1183 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1185 /* check to see if caller supports us returning a tuplestore */
1186 if (!rsinfo->allowedModes & SFRM_Materialize)
1187 elog(ERROR, "connectby requires Materialize mode, but it is not "
1188 "allowed in this context");
1190 /* OK, go to work */
1191 rsinfo->returnMode = SFRM_Materialize;
1192 rsinfo->setResult = connectby(relname,
1203 rsinfo->setDesc = tupdesc;
1205 MemoryContextSwitchTo(oldcontext);
1208 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1209 * tuples are in our tuplestore and passed back through
1210 * rsinfo->setResult. rsinfo->setDesc is set to the tuple description
1211 * that we actually used to build our tuples with, so the caller can
1212 * verify we did what it was expecting.
1219 * connectby - does the real work for connectby_text()
1221 static Tuplestorestate *
1222 connectby(char *relname,
1224 char *parent_key_fld,
1231 MemoryContext per_query_ctx,
1232 AttInMetadata *attinmeta)
1234 Tuplestorestate *tupstore = NULL;
1236 MemoryContext oldcontext;
1240 /* Connect to SPI manager */
1241 if ((ret = SPI_connect()) < 0)
1242 /* internal error */
1243 elog(ERROR, "connectby: SPI_connect returned %d", ret);
1245 /* switch to longer term context to create the tuple store */
1246 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1248 /* initialize our tuplestore */
1249 tupstore = tuplestore_begin_heap(true, false, SortMem);
1251 MemoryContextSwitchTo(oldcontext);
1253 /* now go get the whole tree */
1254 tupstore = build_tuplestore_recursively(key_fld,
1260 start_with, /* current_branch */
1261 0, /* initial level is 0 */
1262 &serial, /* initial serial is 1 */
1275 static Tuplestorestate *
1276 build_tuplestore_recursively(char *key_fld,
1277 char *parent_key_fld,
1288 MemoryContext per_query_ctx,
1289 AttInMetadata *attinmeta,
1290 Tuplestorestate *tupstore)
1292 TupleDesc tupdesc = attinmeta->tupdesc;
1293 MemoryContext oldcontext;
1294 StringInfo sql = makeStringInfo();
1299 if (max_depth > 0 && level > max_depth)
1302 /* Build initial sql statement */
1305 appendStringInfo(sql, "SELECT %s, %s FROM %s WHERE %s = '%s' AND %s IS NOT NULL",
1316 appendStringInfo(sql, "SELECT %s, %s FROM %s WHERE %s = '%s' AND %s IS NOT NULL ORDER BY %s",
1327 /* Retrieve the desired rows */
1328 ret = SPI_exec(sql->data, 0);
1329 proc = SPI_processed;
1331 /* Check for qualifying tuples */
1332 if ((ret == SPI_OK_SELECT) && (proc > 0))
1335 HeapTuple spi_tuple;
1336 SPITupleTable *tuptable = SPI_tuptable;
1337 TupleDesc spi_tupdesc = tuptable->tupdesc;
1340 char *current_key_parent;
1341 char current_level[INT32_STRLEN];
1342 char serial_str[INT32_STRLEN];
1343 char *current_branch;
1345 StringInfo branchstr = NULL;
1346 StringInfo chk_branchstr = NULL;
1347 StringInfo chk_current_key = NULL;
1349 /* start a new branch */
1350 branchstr = makeStringInfo();
1352 /* need these to check for recursion */
1353 chk_branchstr = makeStringInfo();
1354 chk_current_key = makeStringInfo();
1357 values = (char **) palloc((CONNECTBY_NCOLS + serial_column) * sizeof(char *));
1359 values = (char **) palloc((CONNECTBY_NCOLS_NOBRANCH + serial_column) * sizeof(char *));
1361 /* First time through, do a little setup */
1365 * Check that return tupdesc is compatible with the one we got
1366 * from the query, but only at level 0 -- no need to check
1370 if (!compatConnectbyTupleDescs(tupdesc, spi_tupdesc))
1372 (errcode(ERRCODE_SYNTAX_ERROR),
1373 errmsg("invalid return type"),
1374 errdetail("Return and SQL tuple descriptions are " \
1377 /* root value is the one we initially start with */
1378 values[0] = start_with;
1380 /* root value has no parent */
1383 /* root level is 0 */
1384 sprintf(current_level, "%d", level);
1385 values[2] = current_level;
1387 /* root branch is just starting root value */
1389 values[3] = start_with;
1391 /* root starts the serial with 1 */
1394 sprintf(serial_str, "%d", (*serial)++);
1396 values[4] = serial_str;
1398 values[3] = serial_str;
1401 /* construct the tuple */
1402 tuple = BuildTupleFromCStrings(attinmeta, values);
1404 /* switch to long lived context while storing the tuple */
1405 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1408 tuplestore_puttuple(tupstore, tuple);
1410 /* now reset the context */
1411 MemoryContextSwitchTo(oldcontext);
1413 /* increment level */
1417 for (i = 0; i < proc; i++)
1419 /* initialize branch for this pass */
1420 appendStringInfo(branchstr, "%s", branch);
1421 appendStringInfo(chk_branchstr, "%s%s%s", branch_delim, branch, branch_delim);
1423 /* get the next sql result tuple */
1424 spi_tuple = tuptable->vals[i];
1426 /* get the current key and parent */
1427 current_key = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
1428 appendStringInfo(chk_current_key, "%s%s%s", branch_delim, current_key, branch_delim);
1429 current_key_parent = pstrdup(SPI_getvalue(spi_tuple, spi_tupdesc, 2));
1431 /* get the current level */
1432 sprintf(current_level, "%d", level);
1434 /* check to see if this key is also an ancestor */
1435 if (strstr(chk_branchstr->data, chk_current_key->data))
1436 elog(ERROR, "infinite recursion detected");
1438 /* OK, extend the branch */
1439 appendStringInfo(branchstr, "%s%s", branch_delim, current_key);
1440 current_branch = branchstr->data;
1443 values[0] = pstrdup(current_key);
1444 values[1] = current_key_parent;
1445 values[2] = current_level;
1447 values[3] = current_branch;
1450 sprintf(serial_str, "%d", (*serial)++);
1452 values[4] = serial_str;
1454 values[3] = serial_str;
1457 tuple = BuildTupleFromCStrings(attinmeta, values);
1459 xpfree(current_key);
1460 xpfree(current_key_parent);
1462 /* switch to long lived context while storing the tuple */
1463 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1465 /* store the tuple for later use */
1466 tuplestore_puttuple(tupstore, tuple);
1468 /* now reset the context */
1469 MemoryContextSwitchTo(oldcontext);
1471 heap_freetuple(tuple);
1473 /* recurse using current_key_parent as the new start_with */
1474 tupstore = build_tuplestore_recursively(key_fld,
1490 /* reset branch for next pass */
1491 xpfree(branchstr->data);
1492 initStringInfo(branchstr);
1494 xpfree(chk_branchstr->data);
1495 initStringInfo(chk_branchstr);
1497 xpfree(chk_current_key->data);
1498 initStringInfo(chk_current_key);
1506 * Check expected (query runtime) tupdesc suitable for Connectby
1509 validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial)
1511 int serial_column = 0;
1516 /* are there the correct number of columns */
1519 if (tupdesc->natts != (CONNECTBY_NCOLS + serial_column))
1521 (errcode(ERRCODE_SYNTAX_ERROR),
1522 errmsg("invalid return type"),
1523 errdetail("Query-specified return tuple has " \
1524 "wrong number of columns.")));
1528 if (tupdesc->natts != CONNECTBY_NCOLS_NOBRANCH + serial_column)
1530 (errcode(ERRCODE_SYNTAX_ERROR),
1531 errmsg("invalid return type"),
1532 errdetail("Query-specified return tuple has " \
1533 "wrong number of columns.")));
1536 /* check that the types of the first two columns match */
1537 if (tupdesc->attrs[0]->atttypid != tupdesc->attrs[1]->atttypid)
1539 (errcode(ERRCODE_SYNTAX_ERROR),
1540 errmsg("invalid return type"),
1541 errdetail("First two columns must be the same type.")));
1543 /* check that the type of the third column is INT4 */
1544 if (tupdesc->attrs[2]->atttypid != INT4OID)
1546 (errcode(ERRCODE_SYNTAX_ERROR),
1547 errmsg("invalid return type"),
1548 errdetail("Third column must be type %s.",
1549 format_type_be(INT4OID))));
1551 /* check that the type of the fourth column is TEXT if applicable */
1552 if (show_branch && tupdesc->attrs[3]->atttypid != TEXTOID)
1554 (errcode(ERRCODE_SYNTAX_ERROR),
1555 errmsg("invalid return type"),
1556 errdetail("Fourth column must be type %s.",
1557 format_type_be(TEXTOID))));
1559 /* check that the type of the fifth column is INT4 */
1560 if (show_branch && show_serial && tupdesc->attrs[4]->atttypid != INT4OID)
1561 elog(ERROR, "Query-specified return tuple not valid for Connectby: "
1562 "fifth column must be type %s", format_type_be(INT4OID));
1564 /* check that the type of the fifth column is INT4 */
1565 if (!show_branch && show_serial && tupdesc->attrs[3]->atttypid != INT4OID)
1566 elog(ERROR, "Query-specified return tuple not valid for Connectby: "
1567 "fourth column must be type %s", format_type_be(INT4OID));
1569 /* OK, the tupdesc is valid for our purposes */
1573 * Check if spi sql tupdesc and return tupdesc are compatible
1576 compatConnectbyTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
1581 /* check the key_fld types match */
1582 ret_atttypid = ret_tupdesc->attrs[0]->atttypid;
1583 sql_atttypid = sql_tupdesc->attrs[0]->atttypid;
1584 if (ret_atttypid != sql_atttypid)
1586 (errcode(ERRCODE_SYNTAX_ERROR),
1587 errmsg("invalid return type"),
1588 errdetail("SQL key field datatype does " \
1589 "not match return key field datatype.")));
1591 /* check the parent_key_fld types match */
1592 ret_atttypid = ret_tupdesc->attrs[1]->atttypid;
1593 sql_atttypid = sql_tupdesc->attrs[1]->atttypid;
1594 if (ret_atttypid != sql_atttypid)
1596 (errcode(ERRCODE_SYNTAX_ERROR),
1597 errmsg("invalid return type"),
1598 errdetail("SQL parent key field datatype does " \
1599 "not match return parent key field datatype.")));
1601 /* OK, the two tupdescs are compatible for our purposes */
1606 * Check if two tupdescs match in type of attributes
1609 compatCrosstabTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
1612 Form_pg_attribute ret_attr;
1614 Form_pg_attribute sql_attr;
1617 /* check the rowid types match */
1618 ret_atttypid = ret_tupdesc->attrs[0]->atttypid;
1619 sql_atttypid = sql_tupdesc->attrs[0]->atttypid;
1620 if (ret_atttypid != sql_atttypid)
1622 (errcode(ERRCODE_SYNTAX_ERROR),
1623 errmsg("invalid return type"),
1624 errdetail("SQL rowid datatype does not match " \
1625 "return rowid datatype.")));
1628 * - attribute [1] of the sql tuple is the category; no need to check
1629 * it - attribute [2] of the sql tuple should match attributes [1] to
1630 * [natts] of the return tuple
1632 sql_attr = sql_tupdesc->attrs[2];
1633 for (i = 1; i < ret_tupdesc->natts; i++)
1635 ret_attr = ret_tupdesc->attrs[i];
1637 if (ret_attr->atttypid != sql_attr->atttypid)
1641 /* OK, the two tupdescs are compatible for our purposes */
1646 make_crosstab_tupledesc(TupleDesc spi_tupdesc, int num_categories)
1648 Form_pg_attribute sql_attr;
1653 char attname[NAMEDATALEN];
1657 * We need to build a tuple description with one column for the
1658 * rowname, and num_categories columns for the values. Each must be of
1659 * the same type as the corresponding spi result input column.
1661 natts = num_categories + 1;
1662 tupdesc = CreateTemplateTupleDesc(natts, false);
1664 /* first the rowname column */
1667 sql_attr = spi_tupdesc->attrs[0];
1668 sql_atttypid = sql_attr->atttypid;
1670 strcpy(attname, "rowname");
1672 TupleDescInitEntry(tupdesc, attnum, attname, sql_atttypid,
1675 /* now the category values columns */
1676 sql_attr = spi_tupdesc->attrs[2];
1677 sql_atttypid = sql_attr->atttypid;
1679 for (i = 0; i < num_categories; i++)
1683 sprintf(attname, "category_%d", i + 1);
1684 TupleDescInitEntry(tupdesc, attnum, attname, sql_atttypid,