2 * contrib/tablefunc/tablefunc.c
7 * Sample to demonstrate C functions which return setof scalar
9 * Joe Conway <mail@joeconway.com>
11 * Nabil Sayegh <postgresql@e-trolley.de>
13 * Copyright (c) 2002-2022, PostgreSQL Global Development Group
15 * Permission to use, copy, modify, and distribute this software and its
16 * documentation for any purpose, without fee, and without a written agreement
17 * is hereby granted, provided that the above copyright notice and this
18 * paragraph and the following two paragraphs appear in all copies.
20 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
21 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
22 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
23 * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
24 * POSSIBILITY OF SUCH DAMAGE.
26 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
27 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
28 * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
29 * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
30 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
37 #include "access/htup_details.h"
38 #include "catalog/pg_type.h"
39 #include "common/pg_prng.h"
40 #include "executor/spi.h"
42 #include "lib/stringinfo.h"
43 #include "miscadmin.h"
44 #include "tablefunc.h"
45 #include "utils/builtins.h"
49 static HTAB
*load_categories_hash(char *cats_sql
, MemoryContext per_query_ctx
);
50 static Tuplestorestate
*get_crosstab_tuplestore(char *sql
,
54 static void validateConnectbyTupleDesc(TupleDesc td
, bool show_branch
, bool show_serial
);
55 static bool compatCrosstabTupleDescs(TupleDesc ret_tupdesc
, TupleDesc sql_tupdesc
);
56 static void compatConnectbyTupleDescs(TupleDesc ret_tupdesc
, TupleDesc sql_tupdesc
);
57 static void get_normal_pair(float8
*x1
, float8
*x2
);
58 static Tuplestorestate
*connectby(char *relname
,
67 MemoryContext per_query_ctx
,
69 AttInMetadata
*attinmeta
);
70 static void build_tuplestore_recursively(char *key_fld
,
82 MemoryContext per_query_ctx
,
83 AttInMetadata
*attinmeta
,
84 Tuplestorestate
*tupstore
);
88 float8 mean
; /* mean of the distribution */
89 float8 stddev
; /* stddev of the distribution */
90 float8 carry_val
; /* hold second generated value */
91 bool use_carry
; /* use second generated value */
94 #define xpfree(var_) \
103 #define xpstrdup(tgtvar_, srcvar_) \
106 tgtvar_ = pstrdup(srcvar_); \
111 #define xstreq(tgtvar_, srcvar_) \
112 (((tgtvar_ == NULL) && (srcvar_ == NULL)) || \
113 ((tgtvar_ != NULL) && (srcvar_ != NULL) && (strcmp(tgtvar_, srcvar_) == 0)))
115 /* sign, 10 digits, '\0' */
116 #define INT32_STRLEN 12
118 /* stored info for a crosstab category */
119 typedef struct crosstab_cat_desc
121 char *catname
; /* full category name */
122 uint64 attidx
; /* zero based */
125 #define MAX_CATNAME_LEN NAMEDATALEN
128 #define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC) \
130 crosstab_HashEnt *hentry; char key[MAX_CATNAME_LEN]; \
132 MemSet(key, 0, MAX_CATNAME_LEN); \
133 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
134 hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
135 key, HASH_FIND, NULL); \
137 CATDESC = hentry->catdesc; \
142 #define crosstab_HashTableInsert(HASHTAB, CATDESC) \
144 crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
146 MemSet(key, 0, MAX_CATNAME_LEN); \
147 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
148 hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
149 key, HASH_ENTER, &found); \
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())
190 /* create a function context for cross-call persistence */
191 funcctx
= SRF_FIRSTCALL_INIT();
194 * switch to memory context appropriate for multiple function calls
196 oldcontext
= MemoryContextSwitchTo(funcctx
->multi_call_memory_ctx
);
198 /* total number of tuples to be returned */
199 num_tuples
= PG_GETARG_INT32(0);
202 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
203 errmsg("number of rows cannot be negative")));
204 funcctx
->max_calls
= num_tuples
;
206 /* allocate memory for user context */
207 fctx
= (normal_rand_fctx
*) palloc(sizeof(normal_rand_fctx
));
210 * Use fctx to keep track of upper and lower bounds from call to call.
211 * It will also be used to carry over the spare value we get from the
212 * Box-Muller algorithm so that we only actually calculate a new value
215 fctx
->mean
= PG_GETARG_FLOAT8(1);
216 fctx
->stddev
= PG_GETARG_FLOAT8(2);
218 fctx
->use_carry
= false;
220 funcctx
->user_fctx
= fctx
;
222 MemoryContextSwitchTo(oldcontext
);
225 /* stuff done on every call of the function */
226 funcctx
= SRF_PERCALL_SETUP();
228 call_cntr
= funcctx
->call_cntr
;
229 max_calls
= funcctx
->max_calls
;
230 fctx
= funcctx
->user_fctx
;
232 stddev
= fctx
->stddev
;
233 carry_val
= fctx
->carry_val
;
234 use_carry
= fctx
->use_carry
;
236 if (call_cntr
< max_calls
) /* do when there is more left to send */
243 * reset use_carry and use second value obtained on last pass
245 fctx
->use_carry
= false;
253 /* Get the next two normal values */
254 get_normal_pair(&normval_1
, &normval_2
);
257 result
= mean
+ (stddev
* normval_1
);
259 /* and save the second */
260 fctx
->carry_val
= mean
+ (stddev
* normval_2
);
261 fctx
->use_carry
= true;
264 /* send the result */
265 SRF_RETURN_NEXT(funcctx
, Float8GetDatum(result
));
268 /* do when there is no more left */
269 SRF_RETURN_DONE(funcctx
);
274 * Assigns normally distributed (Gaussian) values to a pair of provided
275 * parameters, with mean 0, standard deviation 1.
277 * This routine implements Algorithm P (Polar method for normal deviates)
278 * from Knuth's _The_Art_of_Computer_Programming_, Volume 2, 3rd ed., pages
279 * 122-126. Knuth cites his source as "The polar method", G. E. P. Box, M. E.
280 * Muller, and G. Marsaglia, _Annals_Math,_Stat._ 29 (1958), 610-611.
284 get_normal_pair(float8
*x1
, float8
*x2
)
294 u1
= pg_prng_double(&pg_global_prng_state
);
295 u2
= pg_prng_double(&pg_global_prng_state
);
297 v1
= (2.0 * u1
) - 1.0;
298 v2
= (2.0 * u2
) - 1.0;
300 s
= v1
* v1
+ v2
* v2
;
310 s
= sqrt((-2.0 * log(s
)) / s
);
317 * crosstab - create a crosstab of rowids and values columns from a
318 * SQL statement returning one rowid column, one category column,
319 * and one value column.
321 * e.g. given sql which produces:
324 * ------+-------+-------
335 * <===== values columns =====>
336 * rowid cat1 cat2 cat3 cat4
337 * ------+-------+-------+-------+-------
338 * row1 val1 val2 val3 val4
339 * row2 val5 val6 val7 val8
342 * 1. SQL result must be ordered by 1,2.
343 * 2. The number of values columns depends on the tuple description
344 * of the function's declared return type. The return type's columns
345 * must match the datatypes of the SQL query's result. The datatype
346 * of the category column can be anything, however.
347 * 3. Missing values (i.e. not enough adjacent rows of same rowid to
348 * fill the number of result values columns) are filled in with nulls.
349 * 4. Extra values (i.e. too many adjacent rows of same rowid to fill
350 * the number of result values columns) are skipped.
351 * 5. Rows with all nulls in the values columns are skipped.
353 PG_FUNCTION_INFO_V1(crosstab
);
355 crosstab(PG_FUNCTION_ARGS
)
357 char *sql
= text_to_cstring(PG_GETARG_TEXT_PP(0));
358 ReturnSetInfo
*rsinfo
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
359 Tuplestorestate
*tupstore
;
363 AttInMetadata
*attinmeta
;
364 SPITupleTable
*spi_tuptable
;
365 TupleDesc spi_tupdesc
;
370 MemoryContext per_query_ctx
;
371 MemoryContext oldcontext
;
375 /* check to see if caller supports us returning a tuplestore */
376 if (rsinfo
== NULL
|| !IsA(rsinfo
, ReturnSetInfo
))
378 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
379 errmsg("set-valued function called in context that cannot accept a set")));
380 if (!(rsinfo
->allowedModes
& SFRM_Materialize
))
382 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
383 errmsg("materialize mode required, but it is not allowed in this context")));
385 per_query_ctx
= rsinfo
->econtext
->ecxt_per_query_memory
;
387 /* Connect to SPI manager */
388 if ((ret
= SPI_connect()) < 0)
390 elog(ERROR
, "crosstab: SPI_connect returned %d", ret
);
392 /* Retrieve the desired rows */
393 ret
= SPI_execute(sql
, true, 0);
394 proc
= SPI_processed
;
396 /* If no qualifying tuples, fall out early */
397 if (ret
!= SPI_OK_SELECT
|| proc
== 0)
400 rsinfo
->isDone
= ExprEndResult
;
404 spi_tuptable
= SPI_tuptable
;
405 spi_tupdesc
= spi_tuptable
->tupdesc
;
408 * The provided SQL query must always return three columns.
411 * the label or identifier for each row in the final result
413 * the label or identifier for each column in the final result
415 * the value for each column in the final result
418 if (spi_tupdesc
->natts
!= 3)
420 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
421 errmsg("invalid source data SQL statement"),
422 errdetail("The provided SQL must return 3 "
423 "columns: rowid, category, and values.")));
425 /* get a tuple descriptor for our result type */
426 switch (get_call_result_type(fcinfo
, NULL
, &tupdesc
))
428 case TYPEFUNC_COMPOSITE
:
431 case TYPEFUNC_RECORD
:
432 /* failed to determine actual type of RECORD */
434 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
435 errmsg("function returning record called in context "
436 "that cannot accept type record")));
439 /* result type isn't composite */
441 (errcode(ERRCODE_DATATYPE_MISMATCH
),
442 errmsg("return type must be a row type")));
447 * Check that return tupdesc is compatible with the data we got from SPI,
448 * at least based on number and type of attributes
450 if (!compatCrosstabTupleDescs(tupdesc
, spi_tupdesc
))
452 (errcode(ERRCODE_SYNTAX_ERROR
),
453 errmsg("return and sql tuple descriptions are " \
457 * switch to long-lived memory context
459 oldcontext
= MemoryContextSwitchTo(per_query_ctx
);
461 /* make sure we have a persistent copy of the result tupdesc */
462 tupdesc
= CreateTupleDescCopy(tupdesc
);
464 /* initialize our tuplestore in long-lived context */
466 tuplestore_begin_heap(rsinfo
->allowedModes
& SFRM_Materialize_Random
,
469 MemoryContextSwitchTo(oldcontext
);
472 * Generate attribute metadata needed later to produce tuples from raw C
475 attinmeta
= TupleDescGetAttInMetadata(tupdesc
);
477 /* total number of tuples to be examined */
480 /* the return tuple always must have 1 rowid + num_categories columns */
481 num_categories
= tupdesc
->natts
- 1;
486 for (call_cntr
= 0; call_cntr
< max_calls
; call_cntr
++)
488 bool skip_tuple
= false;
491 /* allocate and zero space */
492 values
= (char **) palloc0((1 + num_categories
) * sizeof(char *));
495 * now loop through the sql results and assign each value in sequence
496 * to the next category
498 for (i
= 0; i
< num_categories
; i
++)
503 /* see if we've gone too far already */
504 if (call_cntr
>= max_calls
)
507 /* get the next sql result tuple */
508 spi_tuple
= spi_tuptable
->vals
[call_cntr
];
510 /* get the rowid from the current sql result tuple */
511 rowid
= SPI_getvalue(spi_tuple
, spi_tupdesc
, 1);
514 * If this is the first pass through the values for this rowid,
515 * set the first column to rowid
519 xpstrdup(values
[0], rowid
);
522 * Check to see if the rowid is the same as that of the last
523 * tuple sent -- if so, skip this tuple entirely
525 if (!firstpass
&& xstreq(lastrowid
, rowid
))
534 * If rowid hasn't changed on us, continue building the output
537 if (xstreq(rowid
, values
[0]))
540 * Get the next category item value, which is always attribute
543 * Be careful to assign the value to the array index based on
544 * which category we are presently processing.
546 values
[1 + i
] = SPI_getvalue(spi_tuple
, spi_tupdesc
, 3);
549 * increment the counter since we consume a row for each
550 * category, but not for last pass because the outer loop will
553 if (i
< (num_categories
- 1))
560 * We'll fill in NULLs for the missing values, but we need to
561 * decrement the counter since this sql result row doesn't
562 * belong to the current output tuple.
574 /* build the tuple and store it */
575 tuple
= BuildTupleFromCStrings(attinmeta
, values
);
576 tuplestore_puttuple(tupstore
, tuple
);
577 heap_freetuple(tuple
);
580 /* Remember current rowid */
582 xpstrdup(lastrowid
, values
[0]);
586 for (i
= 0; i
< num_categories
+ 1; i
++)
587 if (values
[i
] != NULL
)
592 /* let the caller know we're sending back a tuplestore */
593 rsinfo
->returnMode
= SFRM_Materialize
;
594 rsinfo
->setResult
= tupstore
;
595 rsinfo
->setDesc
= tupdesc
;
597 /* release SPI related resources (and return to caller's context) */
604 * crosstab_hash - reimplement crosstab as materialized function and
605 * properly deal with missing values (i.e. don't pack remaining
606 * values to the left)
608 * crosstab - create a crosstab of rowids and values columns from a
609 * SQL statement returning one rowid column, one category column,
610 * and one value column.
612 * e.g. given sql which produces:
615 * ------+-------+-------
625 * <===== values columns =====>
626 * rowid cat1 cat2 cat3 cat4
627 * ------+-------+-------+-------+-------
628 * row1 val1 val2 null val4
629 * row2 val5 val6 val7 val8
632 * 1. SQL result must be ordered by 1.
633 * 2. The number of values columns depends on the tuple description
634 * of the function's declared return type.
635 * 3. Missing values (i.e. missing category) are filled in with nulls.
636 * 4. Extra values (i.e. not in category results) are skipped.
638 PG_FUNCTION_INFO_V1(crosstab_hash
);
640 crosstab_hash(PG_FUNCTION_ARGS
)
642 char *sql
= text_to_cstring(PG_GETARG_TEXT_PP(0));
643 char *cats_sql
= text_to_cstring(PG_GETARG_TEXT_PP(1));
644 ReturnSetInfo
*rsinfo
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
646 MemoryContext per_query_ctx
;
647 MemoryContext oldcontext
;
650 /* check to see if caller supports us returning a tuplestore */
651 if (rsinfo
== NULL
|| !IsA(rsinfo
, ReturnSetInfo
))
653 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
654 errmsg("set-valued function called in context that cannot accept a set")));
655 if (!(rsinfo
->allowedModes
& SFRM_Materialize
) ||
656 rsinfo
->expectedDesc
== NULL
)
658 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
659 errmsg("materialize mode required, but it is not allowed in this context")));
661 per_query_ctx
= rsinfo
->econtext
->ecxt_per_query_memory
;
662 oldcontext
= MemoryContextSwitchTo(per_query_ctx
);
664 /* get the requested return tuple description */
665 tupdesc
= CreateTupleDescCopy(rsinfo
->expectedDesc
);
668 * Check to make sure we have a reasonable tuple descriptor
670 * Note we will attempt to coerce the values into whatever the return
671 * attribute type is and depend on the "in" function to complain if
674 if (tupdesc
->natts
< 2)
676 (errcode(ERRCODE_SYNTAX_ERROR
),
677 errmsg("query-specified return tuple and " \
678 "crosstab function are not compatible")));
680 /* load up the categories hash table */
681 crosstab_hash
= load_categories_hash(cats_sql
, per_query_ctx
);
683 /* let the caller know we're sending back a tuplestore */
684 rsinfo
->returnMode
= SFRM_Materialize
;
686 /* now go build it */
687 rsinfo
->setResult
= get_crosstab_tuplestore(sql
,
690 rsinfo
->allowedModes
& SFRM_Materialize_Random
);
693 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
694 * tuples are in our tuplestore and passed back through rsinfo->setResult.
695 * rsinfo->setDesc is set to the tuple description that we actually used
696 * to build our tuples with, so the caller can verify we did what it was
699 rsinfo
->setDesc
= tupdesc
;
700 MemoryContextSwitchTo(oldcontext
);
706 * load up the categories hash table
709 load_categories_hash(char *cats_sql
, MemoryContext per_query_ctx
)
715 MemoryContext SPIcontext
;
717 /* initialize the category hash table */
718 ctl
.keysize
= MAX_CATNAME_LEN
;
719 ctl
.entrysize
= sizeof(crosstab_HashEnt
);
720 ctl
.hcxt
= per_query_ctx
;
723 * use INIT_CATS, defined above as a guess of how many hash table entries
724 * to create, initially
726 crosstab_hash
= hash_create("crosstab hash",
729 HASH_ELEM
| HASH_STRINGS
| HASH_CONTEXT
);
731 /* Connect to SPI manager */
732 if ((ret
= SPI_connect()) < 0)
734 elog(ERROR
, "load_categories_hash: SPI_connect returned %d", ret
);
736 /* Retrieve the category name rows */
737 ret
= SPI_execute(cats_sql
, true, 0);
738 proc
= SPI_processed
;
740 /* Check for qualifying tuples */
741 if ((ret
== SPI_OK_SELECT
) && (proc
> 0))
743 SPITupleTable
*spi_tuptable
= SPI_tuptable
;
744 TupleDesc spi_tupdesc
= spi_tuptable
->tupdesc
;
748 * The provided categories SQL query must always return one column:
749 * category - the label or identifier for each column
751 if (spi_tupdesc
->natts
!= 1)
753 (errcode(ERRCODE_SYNTAX_ERROR
),
754 errmsg("provided \"categories\" SQL must " \
755 "return 1 column of at least one row")));
757 for (i
= 0; i
< proc
; i
++)
759 crosstab_cat_desc
*catdesc
;
763 /* get the next sql result tuple */
764 spi_tuple
= spi_tuptable
->vals
[i
];
766 /* get the category from the current sql result tuple */
767 catname
= SPI_getvalue(spi_tuple
, spi_tupdesc
, 1);
770 (errcode(ERRCODE_SYNTAX_ERROR
),
771 errmsg("provided \"categories\" SQL must " \
772 "not return NULL values")));
774 SPIcontext
= MemoryContextSwitchTo(per_query_ctx
);
776 catdesc
= (crosstab_cat_desc
*) palloc(sizeof(crosstab_cat_desc
));
777 catdesc
->catname
= catname
;
780 /* Add the proc description block to the hashtable */
781 crosstab_HashTableInsert(crosstab_hash
, catdesc
);
783 MemoryContextSwitchTo(SPIcontext
);
787 if (SPI_finish() != SPI_OK_FINISH
)
789 elog(ERROR
, "load_categories_hash: SPI_finish() failed");
791 return crosstab_hash
;
795 * create and populate the crosstab tuplestore using the provided source query
797 static Tuplestorestate
*
798 get_crosstab_tuplestore(char *sql
,
803 Tuplestorestate
*tupstore
;
804 int num_categories
= hash_get_num_entries(crosstab_hash
);
805 AttInMetadata
*attinmeta
= TupleDescGetAttInMetadata(tupdesc
);
811 /* initialize our tuplestore (while still in query context!) */
812 tupstore
= tuplestore_begin_heap(randomAccess
, false, work_mem
);
814 /* Connect to SPI manager */
815 if ((ret
= SPI_connect()) < 0)
817 elog(ERROR
, "get_crosstab_tuplestore: SPI_connect returned %d", ret
);
819 /* Now retrieve the crosstab source rows */
820 ret
= SPI_execute(sql
, true, 0);
821 proc
= SPI_processed
;
823 /* Check for qualifying tuples */
824 if ((ret
== SPI_OK_SELECT
) && (proc
> 0))
826 SPITupleTable
*spi_tuptable
= SPI_tuptable
;
827 TupleDesc spi_tupdesc
= spi_tuptable
->tupdesc
;
828 int ncols
= spi_tupdesc
->natts
;
830 char *lastrowid
= NULL
;
831 bool firstpass
= true;
836 if (num_categories
== 0)
838 /* no qualifying category tuples */
840 (errcode(ERRCODE_SYNTAX_ERROR
),
841 errmsg("provided \"categories\" SQL must " \
842 "return 1 column of at least one row")));
846 * The provided SQL query must always return at least three columns:
848 * 1. rowname the label for each row - column 1 in the final result
849 * 2. category the label for each value-column in the final result 3.
850 * value the values used to populate the value-columns
852 * If there are more than three columns, the last two are taken as
853 * "category" and "values". The first column is taken as "rowname".
854 * Additional columns (2 thru N-2) are assumed the same for the same
855 * "rowname", and are copied into the result tuple from the first time
856 * we encounter a particular rowname.
860 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
861 errmsg("invalid source data SQL statement"),
862 errdetail("The provided SQL must return 3 " \
863 " columns; rowid, category, and values.")));
865 result_ncols
= (ncols
- 2) + num_categories
;
867 /* Recheck to make sure we tuple descriptor still looks reasonable */
868 if (tupdesc
->natts
!= result_ncols
)
870 (errcode(ERRCODE_SYNTAX_ERROR
),
871 errmsg("invalid return type"),
872 errdetail("Query-specified return " \
873 "tuple has %d columns but crosstab " \
874 "returns %d.", tupdesc
->natts
, result_ncols
)));
876 /* allocate space and make sure it's clear */
877 values
= (char **) palloc0(result_ncols
* sizeof(char *));
879 for (i
= 0; i
< proc
; i
++)
882 crosstab_cat_desc
*catdesc
;
885 /* get the next sql result tuple */
886 spi_tuple
= spi_tuptable
->vals
[i
];
888 /* get the rowid from the current sql result tuple */
889 rowid
= SPI_getvalue(spi_tuple
, spi_tupdesc
, 1);
892 * if we're on a new output row, grab the column values up to
895 if (firstpass
|| !xstreq(lastrowid
, rowid
))
898 * a new row means we need to flush the old one first, unless
899 * we're on the very first row
903 /* rowid changed, flush the previous output row */
904 tuple
= BuildTupleFromCStrings(attinmeta
, values
);
906 tuplestore_puttuple(tupstore
, tuple
);
908 for (j
= 0; j
< result_ncols
; j
++)
913 for (j
= 1; j
< ncols
- 2; j
++)
914 values
[j
] = SPI_getvalue(spi_tuple
, spi_tupdesc
, j
+ 1);
916 /* we're no longer on the first pass */
920 /* look up the category and fill in the appropriate column */
921 catname
= SPI_getvalue(spi_tuple
, spi_tupdesc
, ncols
- 1);
925 crosstab_HashTableLookup(crosstab_hash
, catname
, catdesc
);
928 values
[catdesc
->attidx
+ ncols
- 2] =
929 SPI_getvalue(spi_tuple
, spi_tupdesc
, ncols
);
933 xpstrdup(lastrowid
, rowid
);
936 /* flush the last output row */
937 tuple
= BuildTupleFromCStrings(attinmeta
, values
);
939 tuplestore_puttuple(tupstore
, tuple
);
942 if (SPI_finish() != SPI_OK_FINISH
)
944 elog(ERROR
, "get_crosstab_tuplestore: SPI_finish() failed");
950 * connectby_text - produce a result set from a hierarchical (parent/child)
953 * e.g. given table foo:
955 * keyid parent_keyid pos
956 * ------+------------+--
968 * connectby(text relname, text keyid_fld, text parent_keyid_fld
969 * [, text orderby_fld], text start_with, int max_depth
970 * [, text branch_delim])
971 * connectby('foo', 'keyid', 'parent_keyid', 'pos', 'row2', 0, '~') returns:
973 * keyid parent_id level branch serial
974 * ------+-----------+--------+-----------------------
976 * row5 row2 1 row2~row5 2
977 * row9 row5 2 row2~row5~row9 3
978 * row4 row2 1 row2~row4 4
979 * row6 row4 2 row2~row4~row6 5
980 * row8 row6 3 row2~row4~row6~row8 6
983 PG_FUNCTION_INFO_V1(connectby_text
);
985 #define CONNECTBY_NCOLS 4
986 #define CONNECTBY_NCOLS_NOBRANCH 3
989 connectby_text(PG_FUNCTION_ARGS
)
991 char *relname
= text_to_cstring(PG_GETARG_TEXT_PP(0));
992 char *key_fld
= text_to_cstring(PG_GETARG_TEXT_PP(1));
993 char *parent_key_fld
= text_to_cstring(PG_GETARG_TEXT_PP(2));
994 char *start_with
= text_to_cstring(PG_GETARG_TEXT_PP(3));
995 int max_depth
= PG_GETARG_INT32(4);
996 char *branch_delim
= NULL
;
997 bool show_branch
= false;
998 bool show_serial
= false;
999 ReturnSetInfo
*rsinfo
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
1001 AttInMetadata
*attinmeta
;
1002 MemoryContext per_query_ctx
;
1003 MemoryContext oldcontext
;
1005 /* check to see if caller supports us returning a tuplestore */
1006 if (rsinfo
== NULL
|| !IsA(rsinfo
, ReturnSetInfo
))
1008 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1009 errmsg("set-valued function called in context that cannot accept a set")));
1010 if (!(rsinfo
->allowedModes
& SFRM_Materialize
) ||
1011 rsinfo
->expectedDesc
== NULL
)
1013 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1014 errmsg("materialize mode required, but it is not allowed in this context")));
1016 if (fcinfo
->nargs
== 6)
1018 branch_delim
= text_to_cstring(PG_GETARG_TEXT_PP(5));
1022 /* default is no show, tilde for the delimiter */
1023 branch_delim
= pstrdup("~");
1025 per_query_ctx
= rsinfo
->econtext
->ecxt_per_query_memory
;
1026 oldcontext
= MemoryContextSwitchTo(per_query_ctx
);
1028 /* get the requested return tuple description */
1029 tupdesc
= CreateTupleDescCopy(rsinfo
->expectedDesc
);
1031 /* does it meet our needs */
1032 validateConnectbyTupleDesc(tupdesc
, show_branch
, show_serial
);
1034 /* OK, use it then */
1035 attinmeta
= TupleDescGetAttInMetadata(tupdesc
);
1037 /* OK, go to work */
1038 rsinfo
->returnMode
= SFRM_Materialize
;
1039 rsinfo
->setResult
= connectby(relname
,
1049 rsinfo
->allowedModes
& SFRM_Materialize_Random
,
1051 rsinfo
->setDesc
= tupdesc
;
1053 MemoryContextSwitchTo(oldcontext
);
1056 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1057 * tuples are in our tuplestore and passed back through rsinfo->setResult.
1058 * rsinfo->setDesc is set to the tuple description that we actually used
1059 * to build our tuples with, so the caller can verify we did what it was
1065 PG_FUNCTION_INFO_V1(connectby_text_serial
);
1067 connectby_text_serial(PG_FUNCTION_ARGS
)
1069 char *relname
= text_to_cstring(PG_GETARG_TEXT_PP(0));
1070 char *key_fld
= text_to_cstring(PG_GETARG_TEXT_PP(1));
1071 char *parent_key_fld
= text_to_cstring(PG_GETARG_TEXT_PP(2));
1072 char *orderby_fld
= text_to_cstring(PG_GETARG_TEXT_PP(3));
1073 char *start_with
= text_to_cstring(PG_GETARG_TEXT_PP(4));
1074 int max_depth
= PG_GETARG_INT32(5);
1075 char *branch_delim
= NULL
;
1076 bool show_branch
= false;
1077 bool show_serial
= true;
1078 ReturnSetInfo
*rsinfo
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
1080 AttInMetadata
*attinmeta
;
1081 MemoryContext per_query_ctx
;
1082 MemoryContext oldcontext
;
1084 /* check to see if caller supports us returning a tuplestore */
1085 if (rsinfo
== NULL
|| !IsA(rsinfo
, ReturnSetInfo
))
1087 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1088 errmsg("set-valued function called in context that cannot accept a set")));
1089 if (!(rsinfo
->allowedModes
& SFRM_Materialize
) ||
1090 rsinfo
->expectedDesc
== NULL
)
1092 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1093 errmsg("materialize mode required, but it is not allowed in this context")));
1095 if (fcinfo
->nargs
== 7)
1097 branch_delim
= text_to_cstring(PG_GETARG_TEXT_PP(6));
1101 /* default is no show, tilde for the delimiter */
1102 branch_delim
= pstrdup("~");
1104 per_query_ctx
= rsinfo
->econtext
->ecxt_per_query_memory
;
1105 oldcontext
= MemoryContextSwitchTo(per_query_ctx
);
1107 /* get the requested return tuple description */
1108 tupdesc
= CreateTupleDescCopy(rsinfo
->expectedDesc
);
1110 /* does it meet our needs */
1111 validateConnectbyTupleDesc(tupdesc
, show_branch
, show_serial
);
1113 /* OK, use it then */
1114 attinmeta
= TupleDescGetAttInMetadata(tupdesc
);
1116 /* OK, go to work */
1117 rsinfo
->returnMode
= SFRM_Materialize
;
1118 rsinfo
->setResult
= connectby(relname
,
1128 rsinfo
->allowedModes
& SFRM_Materialize_Random
,
1130 rsinfo
->setDesc
= tupdesc
;
1132 MemoryContextSwitchTo(oldcontext
);
1135 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1136 * tuples are in our tuplestore and passed back through rsinfo->setResult.
1137 * rsinfo->setDesc is set to the tuple description that we actually used
1138 * to build our tuples with, so the caller can verify we did what it was
1146 * connectby - does the real work for connectby_text()
1148 static Tuplestorestate
*
1149 connectby(char *relname
,
1151 char *parent_key_fld
,
1158 MemoryContext per_query_ctx
,
1160 AttInMetadata
*attinmeta
)
1162 Tuplestorestate
*tupstore
= NULL
;
1164 MemoryContext oldcontext
;
1168 /* Connect to SPI manager */
1169 if ((ret
= SPI_connect()) < 0)
1170 /* internal error */
1171 elog(ERROR
, "connectby: SPI_connect returned %d", ret
);
1173 /* switch to longer term context to create the tuple store */
1174 oldcontext
= MemoryContextSwitchTo(per_query_ctx
);
1176 /* initialize our tuplestore */
1177 tupstore
= tuplestore_begin_heap(randomAccess
, false, work_mem
);
1179 MemoryContextSwitchTo(oldcontext
);
1181 /* now go get the whole tree */
1182 build_tuplestore_recursively(key_fld
,
1188 start_with
, /* current_branch */
1189 0, /* initial level is 0 */
1190 &serial
, /* initial serial is 1 */
1204 build_tuplestore_recursively(char *key_fld
,
1205 char *parent_key_fld
,
1216 MemoryContext per_query_ctx
,
1217 AttInMetadata
*attinmeta
,
1218 Tuplestorestate
*tupstore
)
1220 TupleDesc tupdesc
= attinmeta
->tupdesc
;
1227 char *current_key_parent
;
1228 char current_level
[INT32_STRLEN
];
1229 char serial_str
[INT32_STRLEN
];
1230 char *current_branch
;
1233 if (max_depth
> 0 && level
> max_depth
)
1236 initStringInfo(&sql
);
1238 /* Build initial sql statement */
1241 appendStringInfo(&sql
, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s",
1246 quote_literal_cstr(start_with
),
1247 key_fld
, key_fld
, parent_key_fld
);
1252 appendStringInfo(&sql
, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s ORDER BY %s",
1257 quote_literal_cstr(start_with
),
1258 key_fld
, key_fld
, parent_key_fld
,
1264 values
= (char **) palloc((CONNECTBY_NCOLS
+ serial_column
) * sizeof(char *));
1266 values
= (char **) palloc((CONNECTBY_NCOLS_NOBRANCH
+ serial_column
) * sizeof(char *));
1268 /* First time through, do a little setup */
1271 /* root value is the one we initially start with */
1272 values
[0] = start_with
;
1274 /* root value has no parent */
1277 /* root level is 0 */
1278 sprintf(current_level
, "%d", level
);
1279 values
[2] = current_level
;
1281 /* root branch is just starting root value */
1283 values
[3] = start_with
;
1285 /* root starts the serial with 1 */
1288 sprintf(serial_str
, "%d", (*serial
)++);
1290 values
[4] = serial_str
;
1292 values
[3] = serial_str
;
1295 /* construct the tuple */
1296 tuple
= BuildTupleFromCStrings(attinmeta
, values
);
1299 tuplestore_puttuple(tupstore
, tuple
);
1301 /* increment level */
1305 /* Retrieve the desired rows */
1306 ret
= SPI_execute(sql
.data
, true, 0);
1307 proc
= SPI_processed
;
1309 /* Check for qualifying tuples */
1310 if ((ret
== SPI_OK_SELECT
) && (proc
> 0))
1312 HeapTuple spi_tuple
;
1313 SPITupleTable
*tuptable
= SPI_tuptable
;
1314 TupleDesc spi_tupdesc
= tuptable
->tupdesc
;
1316 StringInfoData branchstr
;
1317 StringInfoData chk_branchstr
;
1318 StringInfoData chk_current_key
;
1321 * Check that return tupdesc is compatible with the one we got from
1324 compatConnectbyTupleDescs(tupdesc
, spi_tupdesc
);
1326 initStringInfo(&branchstr
);
1327 initStringInfo(&chk_branchstr
);
1328 initStringInfo(&chk_current_key
);
1330 for (i
= 0; i
< proc
; i
++)
1332 /* initialize branch for this pass */
1333 appendStringInfoString(&branchstr
, branch
);
1334 appendStringInfo(&chk_branchstr
, "%s%s%s", branch_delim
, branch
, branch_delim
);
1336 /* get the next sql result tuple */
1337 spi_tuple
= tuptable
->vals
[i
];
1339 /* get the current key (might be NULL) */
1340 current_key
= SPI_getvalue(spi_tuple
, spi_tupdesc
, 1);
1342 /* get the parent key (might be NULL) */
1343 current_key_parent
= SPI_getvalue(spi_tuple
, spi_tupdesc
, 2);
1345 /* get the current level */
1346 sprintf(current_level
, "%d", level
);
1348 /* check to see if this key is also an ancestor */
1351 appendStringInfo(&chk_current_key
, "%s%s%s",
1352 branch_delim
, current_key
, branch_delim
);
1353 if (strstr(chk_branchstr
.data
, chk_current_key
.data
))
1355 (errcode(ERRCODE_INVALID_RECURSION
),
1356 errmsg("infinite recursion detected")));
1359 /* OK, extend the branch */
1361 appendStringInfo(&branchstr
, "%s%s", branch_delim
, current_key
);
1362 current_branch
= branchstr
.data
;
1365 values
[0] = current_key
;
1366 values
[1] = current_key_parent
;
1367 values
[2] = current_level
;
1369 values
[3] = current_branch
;
1372 sprintf(serial_str
, "%d", (*serial
)++);
1374 values
[4] = serial_str
;
1376 values
[3] = serial_str
;
1379 tuple
= BuildTupleFromCStrings(attinmeta
, values
);
1381 /* store the tuple for later use */
1382 tuplestore_puttuple(tupstore
, tuple
);
1384 heap_freetuple(tuple
);
1386 /* recurse using current_key as the new start_with */
1388 build_tuplestore_recursively(key_fld
,
1404 xpfree(current_key
);
1405 xpfree(current_key_parent
);
1407 /* reset branch for next pass */
1408 resetStringInfo(&branchstr
);
1409 resetStringInfo(&chk_branchstr
);
1410 resetStringInfo(&chk_current_key
);
1413 xpfree(branchstr
.data
);
1414 xpfree(chk_branchstr
.data
);
1415 xpfree(chk_current_key
.data
);
1420 * Check expected (query runtime) tupdesc suitable for Connectby
1423 validateConnectbyTupleDesc(TupleDesc td
, bool show_branch
, bool show_serial
)
1425 int serial_column
= 0;
1430 /* are there the correct number of columns */
1433 if (td
->natts
!= (CONNECTBY_NCOLS
+ serial_column
))
1435 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1436 errmsg("invalid return type"),
1437 errdetail("Query-specified return tuple has " \
1438 "wrong number of columns.")));
1442 if (td
->natts
!= CONNECTBY_NCOLS_NOBRANCH
+ serial_column
)
1444 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1445 errmsg("invalid return type"),
1446 errdetail("Query-specified return tuple has " \
1447 "wrong number of columns.")));
1450 /* check that the types of the first two columns match */
1451 if (TupleDescAttr(td
, 0)->atttypid
!= TupleDescAttr(td
, 1)->atttypid
)
1453 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1454 errmsg("invalid return type"),
1455 errdetail("First two columns must be the same type.")));
1457 /* check that the type of the third column is INT4 */
1458 if (TupleDescAttr(td
, 2)->atttypid
!= INT4OID
)
1460 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1461 errmsg("invalid return type"),
1462 errdetail("Third column must be type %s.",
1463 format_type_be(INT4OID
))));
1465 /* check that the type of the fourth column is TEXT if applicable */
1466 if (show_branch
&& TupleDescAttr(td
, 3)->atttypid
!= TEXTOID
)
1468 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1469 errmsg("invalid return type"),
1470 errdetail("Fourth column must be type %s.",
1471 format_type_be(TEXTOID
))));
1473 /* check that the type of the fifth column is INT4 */
1474 if (show_branch
&& show_serial
&&
1475 TupleDescAttr(td
, 4)->atttypid
!= INT4OID
)
1477 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1478 errmsg("query-specified return tuple not valid for Connectby: "
1479 "fifth column must be type %s",
1480 format_type_be(INT4OID
))));
1482 /* check that the type of the fourth column is INT4 */
1483 if (!show_branch
&& show_serial
&&
1484 TupleDescAttr(td
, 3)->atttypid
!= INT4OID
)
1486 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1487 errmsg("query-specified return tuple not valid for Connectby: "
1488 "fourth column must be type %s",
1489 format_type_be(INT4OID
))));
1491 /* OK, the tupdesc is valid for our purposes */
1495 * Check if spi sql tupdesc and return tupdesc are compatible
1498 compatConnectbyTupleDescs(TupleDesc ret_tupdesc
, TupleDesc sql_tupdesc
)
1502 int32 ret_atttypmod
;
1503 int32 sql_atttypmod
;
1506 * Result must have at least 2 columns.
1508 if (sql_tupdesc
->natts
< 2)
1510 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1511 errmsg("invalid return type"),
1512 errdetail("Query must return at least two columns.")));
1515 * These columns must match the result type indicated by the calling
1518 ret_atttypid
= TupleDescAttr(ret_tupdesc
, 0)->atttypid
;
1519 sql_atttypid
= TupleDescAttr(sql_tupdesc
, 0)->atttypid
;
1520 ret_atttypmod
= TupleDescAttr(ret_tupdesc
, 0)->atttypmod
;
1521 sql_atttypmod
= TupleDescAttr(sql_tupdesc
, 0)->atttypmod
;
1522 if (ret_atttypid
!= sql_atttypid
||
1523 (ret_atttypmod
>= 0 && ret_atttypmod
!= sql_atttypmod
))
1525 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1526 errmsg("invalid return type"),
1527 errdetail("SQL key field type %s does " \
1528 "not match return key field type %s.",
1529 format_type_with_typemod(ret_atttypid
, ret_atttypmod
),
1530 format_type_with_typemod(sql_atttypid
, sql_atttypmod
))));
1532 ret_atttypid
= TupleDescAttr(ret_tupdesc
, 1)->atttypid
;
1533 sql_atttypid
= TupleDescAttr(sql_tupdesc
, 1)->atttypid
;
1534 ret_atttypmod
= TupleDescAttr(ret_tupdesc
, 1)->atttypmod
;
1535 sql_atttypmod
= TupleDescAttr(sql_tupdesc
, 1)->atttypmod
;
1536 if (ret_atttypid
!= sql_atttypid
||
1537 (ret_atttypmod
>= 0 && ret_atttypmod
!= sql_atttypmod
))
1539 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1540 errmsg("invalid return type"),
1541 errdetail("SQL parent key field type %s does " \
1542 "not match return parent key field type %s.",
1543 format_type_with_typemod(ret_atttypid
, ret_atttypmod
),
1544 format_type_with_typemod(sql_atttypid
, sql_atttypmod
))));
1546 /* OK, the two tupdescs are compatible for our purposes */
1550 * Check if two tupdescs match in type of attributes
1553 compatCrosstabTupleDescs(TupleDesc ret_tupdesc
, TupleDesc sql_tupdesc
)
1556 Form_pg_attribute ret_attr
;
1558 Form_pg_attribute sql_attr
;
1561 if (ret_tupdesc
->natts
< 2 ||
1562 sql_tupdesc
->natts
< 3)
1565 /* check the rowid types match */
1566 ret_atttypid
= TupleDescAttr(ret_tupdesc
, 0)->atttypid
;
1567 sql_atttypid
= TupleDescAttr(sql_tupdesc
, 0)->atttypid
;
1568 if (ret_atttypid
!= sql_atttypid
)
1570 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1571 errmsg("invalid return type"),
1572 errdetail("SQL rowid datatype does not match " \
1573 "return rowid datatype.")));
1576 * - attribute [1] of the sql tuple is the category; no need to check it -
1577 * attribute [2] of the sql tuple should match attributes [1] to [natts]
1578 * of the return tuple
1580 sql_attr
= TupleDescAttr(sql_tupdesc
, 2);
1581 for (i
= 1; i
< ret_tupdesc
->natts
; i
++)
1583 ret_attr
= TupleDescAttr(ret_tupdesc
, i
);
1585 if (ret_attr
->atttypid
!= sql_attr
->atttypid
)
1589 /* OK, the two tupdescs are compatible for our purposes */