pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Andres Freund <andres@anarazel.de>
To: pgsql-hackers@postgresql.org
To: Tom Lane <tgl@sss.pgh.pa.us>
Subject: Re: Implement targetlist SRFs using ROWS FROM() (was Changed SRF in targetlist handling)
Date: Sat, 27 Aug 2016 14:48:29 -0700
Message-ID: <20160827214829.zo2dfb5jaikii5nw@alap3.anarazel.de> (raw)
In-Reply-To: <20160822214023.aaxz5l4igypowyri@alap3.anarazel.de>
References: <20160523005327.v2tr7obytitxcnna@alap3.anarazel.de>
	<20160822214023.aaxz5l4igypowyri@alap3.anarazel.de>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-hackers>

Hi,

Attached is a significantly updated patch series (see the mail one up
for details about what this is, I don't want to quote it in its
entirety).

There's still some corner cases (DISTINCT + SRF, UNION/INTERSECT with
SRF) to test / implement and a good bit of code cleanup to do. But
feature wise it's pretty much complete.

It currently consists of the following patches:

0001-Add-some-more-targetlist-srf-tests.patch
  Add some test.

0002-Shore-up-some-weird-corner-cases-for-targetlist-SRFs.patch
  Forbid UPDATE ... SET foo = SRF() and ORDER BY / GROUP BY containing
  SRFs that would change the number of returned rows.  Without the
  latter e.g. SELECT 1 ORDER BY generate_series(1,10); returns 10 rows.

0003-Avoid-materializing-SRFs-in-the-FROM-list.patch
  To avoid performance regressions from moving SRFM_ValuePerCall SRFs to
  ROWS FROM, nodeFunctionscan.c needs to support not materializing
  output.

  In my present patch I've *ripped out* the support for materialization
  in nodeFunctionscan.c entirely. That means that rescans referencing
  volatile functions can change their behaviour (if a function is
  rescanned, without having it's parameters changed), and that native
  backward scan support is gone.  I don't think that's actually an issue.

  This temporarily duplicates a bit of code from execQual.c, but that's
  removed again in 0006.

0004-Allow-ROWS-FROM-to-return-functions-as-single-record.patch
  To allow transforming SELECT record_srf(); nodeFunctionscan.c needs to
  learn to return the result as a record.  I chose
  ROWS FROM (record_srf() AS ()) as the syntax for that. It doesn't
  necessarily have to be SQL exposed, but it does make testing easier.

0005-Basic-implementation-of-targetlist-SRFs-via-ROWS-FRO.patch
  Convert all targetlist SRFs to ROWS FROM() expression, referencing the
  original query (without the SRFs) via a subquery.

  Note that this changes the behaviour of queries in a few cases. Namely
  the "least-common-multiple" behaviour of targetlist SRFs is gone, a
  function can now accept multiple set returning functions as input, SRF
  references in COALESCE / CASE are evaluated a bit more "eagerly". The
  last one I have to think a bit more about.

0006-Remove-unused-code-related-to-targetlist-SRFs.patch
  Now that there's no targetlist SRFs at execution time anymore, rip out
  executor and planner code related to that.  There's possibly more, but
  that's what I could find in a couple passes of searching around.

  This actually speeds up tpch-h queries by roughly 4% for me.


My next steps are to work on cleaning up the code a bit more, and
increase the regression coverage.

Input is greatly welcome.

Greetings,

Andres Freund

-- 
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Attachments: download all (6 files, .tar.gz)

0001-Add-some-more-targetlist-srf-tests.patch (text/x-patch, 10.5K) download From ec5658a5723281bc48d649313ca37507a45f1ca3 Mon Sep 17 00:00:00 2001 From: Andres Freund <andres@anarazel.de> Date: Wed, 3 Aug 2016 18:29:42 -0700 Subject: [PATCH 1/6] Add some more targetlist srf tests. --- src/test/regress/expected/tsrf.out | 214 +++++++++++++++++++++++++++++++++++++ src/test/regress/parallel_schedule | 2 +- src/test/regress/serial_schedule | 1 + src/test/regress/sql/tsrf.sql | 67 ++++++++++++ 4 files changed, 283 insertions(+), 1 deletion(-) create mode 100644 src/test/regress/expected/tsrf.out create mode 100644 src/test/regress/sql/tsrf.sql diff --git a/src/test/regress/expected/tsrf.out b/src/test/regress/expected/tsrf.out new file mode 100644 index 0000000..e4e6059 --- /dev/null +++ b/src/test/regress/expected/tsrf.out @@ -0,0 +1,214 @@ +-- +-- tsrf - targetlist set returning function tests +-- +-- simple srf +SELECT generate_series(1, 3); + generate_series +----------------- + 1 + 2 + 3 +(3 rows) + +-- parallel iteration +SELECT generate_series(1, 3), generate_series(3,5); + generate_series | generate_series +-----------------+----------------- + 1 | 3 + 2 | 4 + 3 | 5 +(3 rows) + +-- parallel iteration, different number of rows +SELECT generate_series(1, 2), generate_series(1,4); + generate_series | generate_series +-----------------+----------------- + 1 | 1 + 2 | 2 + 1 | 3 + 2 | 4 +(4 rows) + +-- srf, with SRF argument +SELECT generate_series(1, generate_series(1, 3)); + generate_series +----------------- + 1 + 1 + 2 + 1 + 2 + 3 +(6 rows) + +-- srf, with two SRF arguments +SELECT generate_series(generate_series(1,3), generate_series(2, 4)); +ERROR: functions and operators can take at most one set argument +CREATE TABLE few(id int, dataa text, datab text); +INSERT INTO few VALUES(1, 'a', 'foo'),(2, 'a', 'bar'),(3, 'b', 'bar'); +-- SRF output order of sorting is maintained, if SRF is not referenced +SELECT few.id, generate_series(1,3) g FROM few ORDER BY id DESC; + id | g +----+--- + 3 | 1 + 3 | 2 + 3 | 3 + 2 | 1 + 2 | 2 + 2 | 3 + 1 | 1 + 1 | 2 + 1 | 3 +(9 rows) + +-- but SRFs can be referenced in sort +SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, g DESC; + id | g +----+--- + 1 | 3 + 1 | 2 + 1 | 1 + 2 | 3 + 2 | 2 + 2 | 1 + 3 | 3 + 3 | 2 + 3 | 1 +(9 rows) + +SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, generate_series(1,3) DESC; + id | g +----+--- + 1 | 3 + 1 | 2 + 1 | 1 + 2 | 3 + 2 | 2 + 2 | 1 + 3 | 3 + 3 | 2 + 3 | 1 +(9 rows) + +-- it's weird to have ORDER BYs that increase the number of results +SELECT few.id FROM few ORDER BY id, generate_series(1,3) DESC; + id +---- + 1 + 1 + 1 + 2 + 2 + 2 + 3 + 3 + 3 +(9 rows) + +-- SRFs are computed after aggregation +SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa; + dataa | count | min | max | unnest +-------+-------+-----+-----+-------- + a | 1 | 1 | 1 | 1 + a | 1 | 1 | 1 | 1 + a | 1 | 1 | 1 | 3 +(3 rows) + +-- unless referenced in GROUP BY clause +SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa, unnest('{1,1,3}'::int[]); + dataa | count | min | max | unnest +-------+-------+-----+-----+-------- + a | 2 | 1 | 1 | 1 + a | 1 | 1 | 1 | 3 +(2 rows) + +SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa, 5; + dataa | count | min | max | unnest +-------+-------+-----+-----+-------- + a | 2 | 1 | 1 | 1 + a | 1 | 1 | 1 | 3 +(2 rows) + +-- it's weird to GROUP BYs that increase the number of results +SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa; + dataa | count | min | max +-------+-------+-----+----- + b | 1 | 3 | 3 + a | 2 | 1 | 2 +(2 rows) + +SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa, unnest('{1,1,3}'::int[]); + dataa | count | min | max +-------+-------+-----+----- + b | 2 | 3 | 3 + a | 4 | 1 | 2 + b | 1 | 3 | 3 + a | 2 | 1 | 2 +(4 rows) + +-- SRFs are computed after window functions +SELECT id,lag(id) OVER(), count(*) OVER(), generate_series(1,3) FROM few; + id | lag | count | generate_series +----+-----+-------+----------------- + 1 | | 3 | 1 + 1 | | 3 | 2 + 1 | | 3 | 3 + 2 | 1 | 3 | 1 + 2 | 1 | 3 | 2 + 2 | 1 | 3 | 3 + 3 | 2 | 3 | 1 + 3 | 2 | 3 | 2 + 3 | 2 | 3 | 3 +(9 rows) + +-- sorting + grouping +SELECT few.dataa, count(*), min(id), max(id), generate_series(1,3) FROM few GROUP BY few.dataa ORDER BY 5; + dataa | count | min | max | generate_series +-------+-------+-----+-----+----------------- + b | 1 | 3 | 3 | 1 + a | 2 | 1 | 2 | 1 + b | 1 | 3 | 3 | 2 + a | 2 | 1 | 2 | 2 + b | 1 | 3 | 3 | 3 + a | 2 | 1 | 2 | 3 +(6 rows) + +-- grouping sets are a bit special, they produce NULLs in columns not actually NULL +SELECT dataa, datab b, count(*) FROM few GROUP BY CUBE(dataa, datab) ORDER BY 1,2,3; + dataa | b | count +-------+-----+------- + a | bar | 1 + a | foo | 1 + a | | 2 + b | bar | 1 + b | | 1 + | bar | 2 + | foo | 1 + | | 3 +(8 rows) + +-- data modification +CREATE TABLE fewmore AS SELECT generate_series(1,3) AS data; +INSERT INTO fewmore VALUES(generate_series(4,5)); +SELECT * FROM fewmore; + data +------ + 1 + 2 + 3 + 4 + 5 +(5 rows) + +-- nonsensically that seems to be allowed +UPDATE fewmore SET data = generate_series(4,9); +-- SRFs are now allowed in RETURNING +INSERT INTO fewmore VALUES(1) RETURNING generate_series(1,3); +ERROR: set-valued function called in context that cannot accept a set +-- nor aggregate arguments +SELECT count(generate_series(1,3)) FROM few; +ERROR: set-valued function called in context that cannot accept a set +-- nor proper VALUES +VALUES(1, generate_series(1,2)); +ERROR: set-valued function called in context that cannot accept a set +-- test DISTINCT ON, LIMIT/OFFSET, correlated subqueries diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule index 1cb5dfc..4135aae 100644 --- a/src/test/regress/parallel_schedule +++ b/src/test/regress/parallel_schedule @@ -92,7 +92,7 @@ test: brin gin gist spgist privileges init_privs security_label collate matview test: alter_generic alter_operator misc psql async dbsize misc_functions # rules cannot run concurrently with any test that creates a view -test: rules psql_crosstab amutils +test: rules psql_crosstab amutils tsrf # run by itself so it can run parallel workers test: select_parallel diff --git a/src/test/regress/serial_schedule b/src/test/regress/serial_schedule index 8958d8c..93b4f00 100644 --- a/src/test/regress/serial_schedule +++ b/src/test/regress/serial_schedule @@ -127,6 +127,7 @@ test: rules test: psql_crosstab test: select_parallel test: amutils +test: tsrf test: select_views test: portals_p2 test: foreign_key diff --git a/src/test/regress/sql/tsrf.sql b/src/test/regress/sql/tsrf.sql new file mode 100644 index 0000000..0ef41ab --- /dev/null +++ b/src/test/regress/sql/tsrf.sql @@ -0,0 +1,67 @@ +-- +-- tsrf - targetlist set returning function tests +-- + +-- simple srf +SELECT generate_series(1, 3); + +-- parallel iteration +SELECT generate_series(1, 3), generate_series(3,5); + +-- parallel iteration, different number of rows +SELECT generate_series(1, 2), generate_series(1,4); + +-- srf, with SRF argument +SELECT generate_series(1, generate_series(1, 3)); + +-- srf, with two SRF arguments +SELECT generate_series(generate_series(1,3), generate_series(2, 4)); + +CREATE TABLE few(id int, dataa text, datab text); +INSERT INTO few VALUES(1, 'a', 'foo'),(2, 'a', 'bar'),(3, 'b', 'bar'); + +-- SRF output order of sorting is maintained, if SRF is not referenced +SELECT few.id, generate_series(1,3) g FROM few ORDER BY id DESC; + +-- but SRFs can be referenced in sort +SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, g DESC; +SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, generate_series(1,3) DESC; + +-- it's weird to have ORDER BYs that increase the number of results +SELECT few.id FROM few ORDER BY id, generate_series(1,3) DESC; + +-- SRFs are computed after aggregation +SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa; +-- unless referenced in GROUP BY clause +SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa, unnest('{1,1,3}'::int[]); +SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa, 5; + +-- it's weird to GROUP BYs that increase the number of results +SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa; +SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa, unnest('{1,1,3}'::int[]); + +-- SRFs are computed after window functions +SELECT id,lag(id) OVER(), count(*) OVER(), generate_series(1,3) FROM few; + +-- sorting + grouping +SELECT few.dataa, count(*), min(id), max(id), generate_series(1,3) FROM few GROUP BY few.dataa ORDER BY 5; + +-- grouping sets are a bit special, they produce NULLs in columns not actually NULL +SELECT dataa, datab b, count(*) FROM few GROUP BY CUBE(dataa, datab) ORDER BY 1,2,3; + +-- data modification +CREATE TABLE fewmore AS SELECT generate_series(1,3) AS data; +INSERT INTO fewmore VALUES(generate_series(4,5)); +SELECT * FROM fewmore; + +-- nonsensically that seems to be allowed +UPDATE fewmore SET data = generate_series(4,9); + +-- SRFs are now allowed in RETURNING +INSERT INTO fewmore VALUES(1) RETURNING generate_series(1,3); +-- nor aggregate arguments +SELECT count(generate_series(1,3)) FROM few; +-- nor proper VALUES +VALUES(1, generate_series(1,2)); + +-- test DISTINCT ON, LIMIT/OFFSET, correlated subqueries -- 2.9.3
0002-Shore-up-some-weird-corner-cases-for-targetlist-SRFs.patch (text/x-patch, 7.8K) download From 4dc1c9e5014c9fb421cd9ecd24200d5668ff651f Mon Sep 17 00:00:00 2001 From: Andres Freund <andres@anarazel.de> Date: Sat, 27 Aug 2016 12:36:13 -0700 Subject: [PATCH 2/6] Shore up some weird corner cases for targetlist SRFs. --- src/backend/executor/README | 13 +++++-------- src/backend/parser/analyze.c | 8 ++++++++ src/backend/parser/parse_clause.c | 7 +++++++ src/test/regress/expected/tsrf.out | 36 ++++++++++++------------------------ src/test/regress/sql/tsrf.sql | 6 +++--- 5 files changed, 35 insertions(+), 35 deletions(-) diff --git a/src/backend/executor/README b/src/backend/executor/README index 8afa1e3..141ddc2 100644 --- a/src/backend/executor/README +++ b/src/backend/executor/README @@ -192,11 +192,8 @@ relations, such as a ValuesScan or FunctionScan. For these, since there is no equivalent of TID, the only practical solution seems to be to include the entire row value in the join output row. -We disallow set-returning functions in the targetlist of SELECT FOR UPDATE, -so as to ensure that at most one tuple can be returned for any particular -set of scan tuples. Otherwise we'd get duplicates due to the original -query returning the same set of scan tuples multiple times. (Note: there -is no explicit prohibition on SRFs in UPDATE, but the net effect will be -that only the first result row of an SRF counts, because all subsequent -rows will result in attempts to re-update an already updated target row. -This is historical behavior and seems not worth changing.) +We disallow set-returning functions in the targetlist of UPDATE and +SELECT FOR UPDATE, so as to ensure that at most one tuple can be +returned for any particular set of scan tuples. Otherwise we'd get +duplicates due to the original query returning the same set of scan +tuples multiple times. diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index eac86cc..cf5bc86 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -2233,6 +2233,14 @@ transformUpdateTargetList(ParseState *pstate, List *origTlist) RelationGetRelationName(pstate->p_target_relation)), parser_errposition(pstate, origTarget->location))); + /* nonsensical, we wouldn't know which of the returned rows to use */ + if (expression_returns_set((Node *) tle->expr)) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("set-valued function called in context that cannot accept a set"), + parser_errposition(pstate, + exprLocation((Node *) tle->expr)))); + updateTargetListEntry(pstate, tle, origTarget->name, attrno, origTarget->indirection, diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c index 751de4b..9b7fcc3 100644 --- a/src/backend/parser/parse_clause.c +++ b/src/backend/parser/parse_clause.c @@ -1794,6 +1794,13 @@ findTargetlistEntrySQL99(ParseState *pstate, Node *node, List **tlist, return tle; } + if (expression_returns_set(expr)) + /* FIXME: decent error message */ + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("GROUP BY / ORDER BY cannot reference set returning function not present in target list"), + parser_errposition(pstate, exprLocation(expr)))); + /* * If no matches, construct a new target entry which is appended to the * end of the target list. This target is given resjunk = TRUE so that it diff --git a/src/test/regress/expected/tsrf.out b/src/test/regress/expected/tsrf.out index e4e6059..f520a91 100644 --- a/src/test/regress/expected/tsrf.out +++ b/src/test/regress/expected/tsrf.out @@ -90,21 +90,11 @@ SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, generate_series(1,3) 3 | 1 (9 rows) --- it's weird to have ORDER BYs that increase the number of results +-- it's weird to have ORDER BYs that increase the number of results (error) SELECT few.id FROM few ORDER BY id, generate_series(1,3) DESC; - id ----- - 1 - 1 - 1 - 2 - 2 - 2 - 3 - 3 - 3 -(9 rows) - +ERROR: GROUP BY / ORDER BY cannot reference set returning function not present in target list +LINE 1: SELECT few.id FROM few ORDER BY id, generate_series(1,3) DES... + ^ -- SRFs are computed after aggregation SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa; dataa | count | min | max | unnest @@ -129,7 +119,7 @@ SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few a | 1 | 1 | 1 | 3 (2 rows) --- it's weird to GROUP BYs that increase the number of results +-- it's weird to GROUP BYs that increase the number of results (2nd is an error) SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa; dataa | count | min | max -------+-------+-----+----- @@ -138,14 +128,9 @@ SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa; (2 rows) SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa, unnest('{1,1,3}'::int[]); - dataa | count | min | max --------+-------+-----+----- - b | 2 | 3 | 3 - a | 4 | 1 | 2 - b | 1 | 3 | 3 - a | 2 | 1 | 2 -(4 rows) - +ERROR: GROUP BY / ORDER BY cannot reference set returning function not present in target list +LINE 1: ...*), min(id), max(id) FROM few GROUP BY few.dataa, unnest('{1... + ^ -- SRFs are computed after window functions SELECT id,lag(id) OVER(), count(*) OVER(), generate_series(1,3) FROM few; id | lag | count | generate_series @@ -200,8 +185,11 @@ SELECT * FROM fewmore; 5 (5 rows) --- nonsensically that seems to be allowed +-- it'd not be clear which value to use for the update (error) UPDATE fewmore SET data = generate_series(4,9); +ERROR: set-valued function called in context that cannot accept a set +LINE 1: UPDATE fewmore SET data = generate_series(4,9); + ^ -- SRFs are now allowed in RETURNING INSERT INTO fewmore VALUES(1) RETURNING generate_series(1,3); ERROR: set-valued function called in context that cannot accept a set diff --git a/src/test/regress/sql/tsrf.sql b/src/test/regress/sql/tsrf.sql index 0ef41ab..b52ec07 100644 --- a/src/test/regress/sql/tsrf.sql +++ b/src/test/regress/sql/tsrf.sql @@ -27,7 +27,7 @@ SELECT few.id, generate_series(1,3) g FROM few ORDER BY id DESC; SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, g DESC; SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, generate_series(1,3) DESC; --- it's weird to have ORDER BYs that increase the number of results +-- it's weird to have ORDER BYs that increase the number of results (error) SELECT few.id FROM few ORDER BY id, generate_series(1,3) DESC; -- SRFs are computed after aggregation @@ -36,7 +36,7 @@ SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa, unnest('{1,1,3}'::int[]); SELECT few.dataa, count(*), min(id), max(id), unnest('{1,1,3}'::int[]) FROM few WHERE few.id = 1 GROUP BY few.dataa, 5; --- it's weird to GROUP BYs that increase the number of results +-- it's weird to GROUP BYs that increase the number of results (2nd is an error) SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa; SELECT few.dataa, count(*), min(id), max(id) FROM few GROUP BY few.dataa, unnest('{1,1,3}'::int[]); @@ -54,7 +54,7 @@ CREATE TABLE fewmore AS SELECT generate_series(1,3) AS data; INSERT INTO fewmore VALUES(generate_series(4,5)); SELECT * FROM fewmore; --- nonsensically that seems to be allowed +-- it'd not be clear which value to use for the update (error) UPDATE fewmore SET data = generate_series(4,9); -- SRFs are now allowed in RETURNING -- 2.9.3
0003-Avoid-materializing-SRFs-in-the-FROM-list.patch (text/x-patch, 48.3K) download From 7f46602167b591943fe35a85739a3a1d901aa3f6 Mon Sep 17 00:00:00 2001 From: Andres Freund <andres@anarazel.de> Date: Thu, 25 Aug 2016 11:10:05 -0700 Subject: [PATCH 3/6] Avoid materializing SRFs in the FROM list. So far SFRM_ValuePerCall (and ones optionally using ValuePerCall) set returning functions have been eagerly materialized when in the from list (i.e. when nodeFunctionscan.c is used). In contrast to that SRFs in the target list support ValuePerCall. The materialization has a significant overhead, in a number of simple example cases more than 2x have been measured. While that's an annoying performance difference on its own, it becomes particularly problematic with the upcoming work to implement targetlist SRFs via ROWS FROM. Thus implement support for querying SFRM_ValuePerCall SRFs without materialization. As supporting backward scans isn't possible without materialization for ValuePerCall, and the complication for conditionally materializing don't seem worthwhile, instead drop backward scanning support for FunctionScan nodes (which will, when necessary, be implemented by the planner by using a Material node). This moves the required support code from execQual.c to nodeFunctionscan.c. While not a clear win now (including requiring some duplication), it becomes more advantageous lateron, when SRF support is removed from execQual.c entirely. It's worthwhile to call out that the removed materialization support implies a behavioural change in cases were some functions in ROWS FROM are dependant on a changed PARAM_EXEC parameter, other's not. Previously only dependent functions were recomputed, now all. TODO: - add some more tests - remove ugly double gotos - add some function header comments --- src/backend/executor/execAmi.c | 2 - src/backend/executor/execQual.c | 381 +---------------- src/backend/executor/nodeFunctionscan.c | 685 +++++++++++++++++++++++++------ src/include/executor/executor.h | 9 +- src/test/regress/expected/pg_lsn.out | 13 +- src/test/regress/expected/plpgsql.out | 2 +- src/test/regress/expected/rangefuncs.out | 8 +- src/test/regress/sql/plpgsql.sql | 2 +- 8 files changed, 584 insertions(+), 518 deletions(-) diff --git a/src/backend/executor/execAmi.c b/src/backend/executor/execAmi.c index 2587ef7..ea2f09e 100644 --- a/src/backend/executor/execAmi.c +++ b/src/backend/executor/execAmi.c @@ -475,7 +475,6 @@ ExecSupportsBackwardScan(Plan *node) case T_SeqScan: case T_TidScan: - case T_FunctionScan: case T_ValuesScan: case T_CteScan: return TargetListSupportsBackwardScan(node->targetlist); @@ -579,7 +578,6 @@ ExecMaterializesOutput(NodeTag plantype) switch (plantype) { case T_Material: - case T_FunctionScan: case T_CteScan: case T_WorkTableScan: case T_Sort: diff --git a/src/backend/executor/execQual.c b/src/backend/executor/execQual.c index 743e7d6..79589d0 100644 --- a/src/backend/executor/execQual.c +++ b/src/backend/executor/execQual.c @@ -91,14 +91,10 @@ static Datum ExecEvalParamExec(ExprState *exprstate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); static Datum ExecEvalParamExtern(ExprState *exprstate, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); -static void init_fcache(Oid foid, Oid input_collation, FuncExprState *fcache, - MemoryContext fcacheCxt, bool needDescForSets); static void ShutdownFuncExpr(Datum arg); static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod, TupleDesc *cache_field, ExprContext *econtext); static void ShutdownTupleDescRef(Datum arg); -static ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo, - List *argList, ExprContext *econtext); static void ExecPrepareTuplestoreResult(FuncExprState *fcache, ExprContext *econtext, Tuplestorestate *resultStore, @@ -1323,11 +1319,11 @@ GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull) } /* - * init_fcache - initialize a FuncExprState node during first use + * ExecInitFcache - initialize a FuncExprState node during first use */ -static void -init_fcache(Oid foid, Oid input_collation, FuncExprState *fcache, - MemoryContext fcacheCxt, bool needDescForSets) +void +ExecInitFcache(Oid foid, Oid input_collation, FuncExprState *fcache, + MemoryContext fcacheCxt, bool needDescForSets) { AclResult aclresult; @@ -1503,7 +1499,7 @@ ShutdownTupleDescRef(Datum arg) /* * Evaluate arguments for a function. */ -static ExprDoneCond +ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo, List *argList, ExprContext *econtext) @@ -2052,353 +2048,6 @@ ExecMakeFunctionResultNoSets(FuncExprState *fcache, } -/* - * ExecMakeTableFunctionResult - * - * Evaluate a table function, producing a materialized result in a Tuplestore - * object. - */ -Tuplestorestate * -ExecMakeTableFunctionResult(ExprState *funcexpr, - ExprContext *econtext, - MemoryContext argContext, - TupleDesc expectedDesc, - bool randomAccess) -{ - Tuplestorestate *tupstore = NULL; - TupleDesc tupdesc = NULL; - Oid funcrettype; - bool returnsTuple; - bool returnsSet = false; - FunctionCallInfoData fcinfo; - PgStat_FunctionCallUsage fcusage; - ReturnSetInfo rsinfo; - HeapTupleData tmptup; - MemoryContext callerContext; - MemoryContext oldcontext; - bool direct_function_call; - bool first_time = true; - - callerContext = CurrentMemoryContext; - - funcrettype = exprType((Node *) funcexpr->expr); - - returnsTuple = type_is_rowtype(funcrettype); - - /* - * Prepare a resultinfo node for communication. We always do this even if - * not expecting a set result, so that we can pass expectedDesc. In the - * generic-expression case, the expression doesn't actually get to see the - * resultinfo, but set it up anyway because we use some of the fields as - * our own state variables. - */ - rsinfo.type = T_ReturnSetInfo; - rsinfo.econtext = econtext; - rsinfo.expectedDesc = expectedDesc; - rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize | SFRM_Materialize_Preferred); - if (randomAccess) - rsinfo.allowedModes |= (int) SFRM_Materialize_Random; - rsinfo.returnMode = SFRM_ValuePerCall; - /* isDone is filled below */ - rsinfo.setResult = NULL; - rsinfo.setDesc = NULL; - - /* - * Normally the passed expression tree will be a FuncExprState, since the - * grammar only allows a function call at the top level of a table - * function reference. However, if the function doesn't return set then - * the planner might have replaced the function call via constant-folding - * or inlining. So if we see any other kind of expression node, execute - * it via the general ExecEvalExpr() code; the only difference is that we - * don't get a chance to pass a special ReturnSetInfo to any functions - * buried in the expression. - */ - if (funcexpr && IsA(funcexpr, FuncExprState) && - IsA(funcexpr->expr, FuncExpr)) - { - FuncExprState *fcache = (FuncExprState *) funcexpr; - ExprDoneCond argDone; - - /* - * This path is similar to ExecMakeFunctionResult. - */ - direct_function_call = true; - - /* - * Initialize function cache if first time through - */ - if (fcache->func.fn_oid == InvalidOid) - { - FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; - - init_fcache(func->funcid, func->inputcollid, fcache, - econtext->ecxt_per_query_memory, false); - } - returnsSet = fcache->func.fn_retset; - InitFunctionCallInfoData(fcinfo, &(fcache->func), - list_length(fcache->args), - fcache->fcinfo_data.fncollation, - NULL, (Node *) &rsinfo); - - /* - * Evaluate the function's argument list. - * - * We can't do this in the per-tuple context: the argument values - * would disappear when we reset that context in the inner loop. And - * the caller's CurrentMemoryContext is typically a query-lifespan - * context, so we don't want to leak memory there. We require the - * caller to pass a separate memory context that can be used for this, - * and can be reset each time through to avoid bloat. - */ - MemoryContextReset(argContext); - oldcontext = MemoryContextSwitchTo(argContext); - argDone = ExecEvalFuncArgs(&fcinfo, fcache->args, econtext); - MemoryContextSwitchTo(oldcontext); - - /* We don't allow sets in the arguments of the table function */ - if (argDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("set-valued function called in context that cannot accept a set"))); - - /* - * If function is strict, and there are any NULL arguments, skip - * calling the function and act like it returned NULL (or an empty - * set, in the returns-set case). - */ - if (fcache->func.fn_strict) - { - int i; - - for (i = 0; i < fcinfo.nargs; i++) - { - if (fcinfo.argnull[i]) - goto no_function_result; - } - } - } - else - { - /* Treat funcexpr as a generic expression */ - direct_function_call = false; - InitFunctionCallInfoData(fcinfo, NULL, 0, InvalidOid, NULL, NULL); - } - - /* - * Switch to short-lived context for calling the function or expression. - */ - MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); - - /* - * Loop to handle the ValuePerCall protocol (which is also the same - * behavior needed in the generic ExecEvalExpr path). - */ - for (;;) - { - Datum result; - - CHECK_FOR_INTERRUPTS(); - - /* - * reset per-tuple memory context before each call of the function or - * expression. This cleans up any local memory the function may leak - * when called. - */ - ResetExprContext(econtext); - - /* Call the function or expression one time */ - if (direct_function_call) - { - pgstat_init_function_usage(&fcinfo, &fcusage); - - fcinfo.isnull = false; - rsinfo.isDone = ExprSingleResult; - result = FunctionCallInvoke(&fcinfo); - - pgstat_end_function_usage(&fcusage, - rsinfo.isDone != ExprMultipleResult); - } - else - { - result = ExecEvalExpr(funcexpr, econtext, - &fcinfo.isnull, &rsinfo.isDone); - } - - /* Which protocol does function want to use? */ - if (rsinfo.returnMode == SFRM_ValuePerCall) - { - /* - * Check for end of result set. - */ - if (rsinfo.isDone == ExprEndResult) - break; - - /* - * If first time through, build tuplestore for result. For a - * scalar function result type, also make a suitable tupdesc. - */ - if (first_time) - { - oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory); - tupstore = tuplestore_begin_heap(randomAccess, false, work_mem); - rsinfo.setResult = tupstore; - if (!returnsTuple) - { - tupdesc = CreateTemplateTupleDesc(1, false); - TupleDescInitEntry(tupdesc, - (AttrNumber) 1, - "column", - funcrettype, - -1, - 0); - rsinfo.setDesc = tupdesc; - } - MemoryContextSwitchTo(oldcontext); - } - - /* - * Store current resultset item. - */ - if (returnsTuple) - { - if (!fcinfo.isnull) - { - HeapTupleHeader td = DatumGetHeapTupleHeader(result); - - if (tupdesc == NULL) - { - /* - * This is the first non-NULL result from the - * function. Use the type info embedded in the - * rowtype Datum to look up the needed tupdesc. Make - * a copy for the query. - */ - oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory); - tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td), - HeapTupleHeaderGetTypMod(td)); - rsinfo.setDesc = tupdesc; - MemoryContextSwitchTo(oldcontext); - } - else - { - /* - * Verify all later returned rows have same subtype; - * necessary in case the type is RECORD. - */ - if (HeapTupleHeaderGetTypeId(td) != tupdesc->tdtypeid || - HeapTupleHeaderGetTypMod(td) != tupdesc->tdtypmod) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("rows returned by function are not all of the same row type"))); - } - - /* - * tuplestore_puttuple needs a HeapTuple not a bare - * HeapTupleHeader, but it doesn't need all the fields. - */ - tmptup.t_len = HeapTupleHeaderGetDatumLength(td); - tmptup.t_data = td; - - tuplestore_puttuple(tupstore, &tmptup); - } - else - { - /* - * NULL result from a tuple-returning function; expand it - * to a row of all nulls. We rely on the expectedDesc to - * form such rows. (Note: this would be problematic if - * tuplestore_putvalues saved the tdtypeid/tdtypmod from - * the provided descriptor, since that might not match - * what we get from the function itself. But it doesn't.) - */ - int natts = expectedDesc->natts; - bool *nullflags; - - nullflags = (bool *) palloc(natts * sizeof(bool)); - memset(nullflags, true, natts * sizeof(bool)); - tuplestore_putvalues(tupstore, expectedDesc, NULL, nullflags); - } - } - else - { - /* Scalar-type case: just store the function result */ - tuplestore_putvalues(tupstore, tupdesc, &result, &fcinfo.isnull); - } - - /* - * Are we done? - */ - if (rsinfo.isDone != ExprMultipleResult) - break; - } - else if (rsinfo.returnMode == SFRM_Materialize) - { - /* check we're on the same page as the function author */ - if (!first_time || rsinfo.isDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED), - errmsg("table-function protocol for materialize mode was not followed"))); - /* Done evaluating the set result */ - break; - } - else - ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED), - errmsg("unrecognized table-function returnMode: %d", - (int) rsinfo.returnMode))); - - first_time = false; - } - -no_function_result: - - /* - * If we got nothing from the function (ie, an empty-set or NULL result), - * we have to create the tuplestore to return, and if it's a - * non-set-returning function then insert a single all-nulls row. As - * above, we depend on the expectedDesc to manufacture the dummy row. - */ - if (rsinfo.setResult == NULL) - { - MemoryContextSwitchTo(econtext->ecxt_per_query_memory); - tupstore = tuplestore_begin_heap(randomAccess, false, work_mem); - rsinfo.setResult = tupstore; - if (!returnsSet) - { - int natts = expectedDesc->natts; - bool *nullflags; - - MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); - nullflags = (bool *) palloc(natts * sizeof(bool)); - memset(nullflags, true, natts * sizeof(bool)); - tuplestore_putvalues(tupstore, expectedDesc, NULL, nullflags); - } - } - - /* - * If function provided a tupdesc, cross-check it. We only really need to - * do this for functions returning RECORD, but might as well do it always. - */ - if (rsinfo.setDesc) - { - tupledesc_match(expectedDesc, rsinfo.setDesc); - - /* - * If it is a dynamically-allocated TupleDesc, free it: it is - * typically allocated in a per-query context, so we must avoid - * leaking it across multiple usages. - */ - if (rsinfo.setDesc->tdrefcount == -1) - FreeTupleDesc(rsinfo.setDesc); - } - - MemoryContextSwitchTo(callerContext); - - /* All done, pass back the tuplestore */ - return rsinfo.setResult; -} - - /* ---------------------------------------------------------------- * ExecEvalFunc * ExecEvalOper @@ -2422,8 +2071,8 @@ ExecEvalFunc(FuncExprState *fcache, FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; /* Initialize function lookup info */ - init_fcache(func->funcid, func->inputcollid, fcache, - econtext->ecxt_per_query_memory, true); + ExecInitFcache(func->funcid, func->inputcollid, fcache, + econtext->ecxt_per_query_memory, true); /* * We need to invoke ExecMakeFunctionResult if either the function itself @@ -2457,8 +2106,8 @@ ExecEvalOper(FuncExprState *fcache, OpExpr *op = (OpExpr *) fcache->xprstate.expr; /* Initialize function lookup info */ - init_fcache(op->opfuncid, op->inputcollid, fcache, - econtext->ecxt_per_query_memory, true); + ExecInitFcache(op->opfuncid, op->inputcollid, fcache, + econtext->ecxt_per_query_memory, true); /* * We need to invoke ExecMakeFunctionResult if either the function itself @@ -2511,8 +2160,8 @@ ExecEvalDistinct(FuncExprState *fcache, { DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr; - init_fcache(op->opfuncid, op->inputcollid, fcache, - econtext->ecxt_per_query_memory, true); + ExecInitFcache(op->opfuncid, op->inputcollid, fcache, + econtext->ecxt_per_query_memory, true); Assert(!fcache->func.fn_retset); } @@ -2588,8 +2237,8 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, */ if (sstate->fxprstate.func.fn_oid == InvalidOid) { - init_fcache(opexpr->opfuncid, opexpr->inputcollid, &sstate->fxprstate, - econtext->ecxt_per_query_memory, true); + ExecInitFcache(opexpr->opfuncid, opexpr->inputcollid, &sstate->fxprstate, + econtext->ecxt_per_query_memory, true); Assert(!sstate->fxprstate.func.fn_retset); } @@ -3850,8 +3499,8 @@ ExecEvalNullIf(FuncExprState *nullIfExpr, { NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr; - init_fcache(op->opfuncid, op->inputcollid, nullIfExpr, - econtext->ecxt_per_query_memory, true); + ExecInitFcache(op->opfuncid, op->inputcollid, nullIfExpr, + econtext->ecxt_per_query_memory, true); Assert(!nullIfExpr->func.fn_retset); } diff --git a/src/backend/executor/nodeFunctionscan.c b/src/backend/executor/nodeFunctionscan.c index a03f6e7..4885f75 100644 --- a/src/backend/executor/nodeFunctionscan.c +++ b/src/backend/executor/nodeFunctionscan.c @@ -22,12 +22,20 @@ */ #include "postgres.h" +#include "access/htup_details.h" #include "catalog/pg_type.h" #include "executor/nodeFunctionscan.h" #include "funcapi.h" +#include "miscadmin.h" #include "nodes/nodeFuncs.h" +#include "parser/parse_coerce.h" +#include "pgstat.h" #include "utils/builtins.h" +#include "utils/expandeddatum.h" +#include "utils/lsyscache.h" +#include "utils/typcache.h" #include "utils/memutils.h" +#include "utils/tuplestore.h" /* @@ -39,12 +47,19 @@ typedef struct FunctionScanPerFuncState TupleDesc tupdesc; /* desc of the function result type */ int colcount; /* expected number of result columns */ Tuplestorestate *tstore; /* holds the function result set */ - int64 rowcount; /* # of rows in result set, -1 if not known */ TupleTableSlot *func_slot; /* function result slot (or NULL) */ + bool started; + bool returnsTuple; + FunctionCallInfoData fcinfo; + ReturnSetInfo rsinfo; } FunctionScanPerFuncState; static TupleTableSlot *FunctionNext(FunctionScanState *node); - +static void ExecBeginFunctionResult(FunctionScanState *node, + FunctionScanPerFuncState *perfunc); +static void ExecNextFunctionResult(FunctionScanState *node, + FunctionScanPerFuncState *perfunc); +static void tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc); /* ---------------------------------------------------------------- * Scan Support @@ -63,7 +78,6 @@ FunctionNext(FunctionScanState *node) ScanDirection direction; TupleTableSlot *scanslot; bool alldone; - int64 oldpos; int funcno; int att; @@ -74,59 +88,39 @@ FunctionNext(FunctionScanState *node) direction = estate->es_direction; scanslot = node->ss.ss_ScanTupleSlot; + Assert(ScanDirectionIsForward(direction)); + if (node->simple) { /* * Fast path for the trivial case: the function return type and scan * result type are the same, so we fetch the function result straight - * into the scan result slot. No need to update ordinality or - * rowcounts either. + * into the scan result slot. No need to update ordinality either. */ - Tuplestorestate *tstore = node->funcstates[0].tstore; + FunctionScanPerFuncState *fs = &node->funcstates[0]; /* - * If first time through, read all tuples from function and put them - * in a tuplestore. Subsequent calls just fetch tuples from - * tuplestore. + * If first time through, call the SRF. Subsequent calls read from a + * tuplestore (for SFRM_Materialize) or call the function again (if + * SFRM_ValuePerCall). */ - if (tstore == NULL) - { - node->funcstates[0].tstore = tstore = - ExecMakeTableFunctionResult(node->funcstates[0].funcexpr, - node->ss.ps.ps_ExprContext, - node->argcontext, - node->funcstates[0].tupdesc, - node->eflags & EXEC_FLAG_BACKWARD); + if (!fs->started) + ExecBeginFunctionResult(node, fs); + else + ExecNextFunctionResult(node, fs); - /* - * paranoia - cope if the function, which may have constructed the - * tuplestore itself, didn't leave it pointing at the start. This - * call is fast, so the overhead shouldn't be an issue. - */ - tuplestore_rescan(tstore); - } + scanslot = fs->func_slot; - /* - * Get the next tuple from tuplestore. - */ - (void) tuplestore_gettupleslot(tstore, - ScanDirectionIsForward(direction), - false, - scanslot); return scanslot; } /* - * Increment or decrement ordinal counter before checking for end-of-data, - * so that we can move off either end of the result by 1 (and no more than - * 1) without losing correct count. See PortalRunSelect for why we can - * assume that we won't be called repeatedly in the end-of-data state. + * Increment ordinal counter before checking for end-of-data, so that we + * can move off the end of the result by 1 (and no more than 1) without + * losing correct count. See PortalRunSelect for why we can assume that + * we won't be called repeatedly in the end-of-data state. */ - oldpos = node->ordinal; - if (ScanDirectionIsForward(direction)) - node->ordinal++; - else - node->ordinal--; + node->ordinal++; /* * Main loop over functions. @@ -144,55 +138,18 @@ FunctionNext(FunctionScanState *node) int i; /* - * If first time through, read all tuples from function and put them - * in a tuplestore. Subsequent calls just fetch tuples from - * tuplestore. + * If first time through, call the SRF. Subsequent calls read from a + * tuplestore (for SFRM_Materialize) or call the function again (if + * SFRM_ValuePerCall). */ - if (fs->tstore == NULL) - { - fs->tstore = - ExecMakeTableFunctionResult(fs->funcexpr, - node->ss.ps.ps_ExprContext, - node->argcontext, - fs->tupdesc, - node->eflags & EXEC_FLAG_BACKWARD); - - /* - * paranoia - cope if the function, which may have constructed the - * tuplestore itself, didn't leave it pointing at the start. This - * call is fast, so the overhead shouldn't be an issue. - */ - tuplestore_rescan(fs->tstore); - } - - /* - * Get the next tuple from tuplestore. - * - * If we have a rowcount for the function, and we know the previous - * read position was out of bounds, don't try the read. This allows - * backward scan to work when there are mixed row counts present. - */ - if (fs->rowcount != -1 && fs->rowcount < oldpos) - ExecClearTuple(fs->func_slot); + if (!fs->started) + ExecBeginFunctionResult(node, fs); else - (void) tuplestore_gettupleslot(fs->tstore, - ScanDirectionIsForward(direction), - false, - fs->func_slot); + ExecNextFunctionResult(node, fs); if (TupIsNull(fs->func_slot)) { /* - * If we ran out of data for this function in the forward - * direction then we now know how many rows it returned. We need - * to know this in order to handle backwards scans. The row count - * we store is actually 1+ the actual number, because we have to - * position the tuplestore 1 off its end sometimes. - */ - if (ScanDirectionIsForward(direction) && fs->rowcount == -1) - fs->rowcount = node->ordinal; - - /* * populate the result cols with nulls */ for (i = 0; i < fs->colcount; i++) @@ -307,21 +264,12 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) scanstate->ordinality = node->funcordinality; scanstate->nfuncs = nfuncs; - if (nfuncs == 1 && !node->funcordinality) - scanstate->simple = true; - else + if (nfuncs > 1 || node->funcordinality) scanstate->simple = false; + else + scanstate->simple = true; - /* - * Ordinal 0 represents the "before the first row" position. - * - * We need to track ordinal position even when not adding an ordinality - * column to the result, in order to handle backwards scanning properly - * with multiple functions with different result sizes. (We can't position - * any individual function's tuplestore any more than 1 place beyond its - * end, so when scanning backwards, we need to know when to start - * including the function in the scan again.) - */ + /* ordinal 0 represents the "before the first row" position */ scanstate->ordinal = 0; /* @@ -367,11 +315,12 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) /* * Don't allocate the tuplestores; the actual calls to the functions - * do that. NULL means that we have not called the function yet (or - * need to call it again after a rescan). + * do that if necessary. started = false means that we have not + * called the function yet (or need to call it again after a rescan). */ fs->tstore = NULL; - fs->rowcount = -1; + fs->started = false; + fs->rsinfo.setDesc = NULL; /* * Now determine if the function returns a simple or composite type, @@ -390,6 +339,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) Assert(tupdesc->natts >= colcount); /* Must copy it out of typcache for safety */ tupdesc = CreateTupleDescCopy(tupdesc); + fs->returnsTuple = true; } else if (functypclass == TYPEFUNC_SCALAR) { @@ -404,6 +354,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) TupleDescInitEntryCollation(tupdesc, (AttrNumber) 1, exprCollation(funcexpr)); + fs->returnsTuple = false; } else if (functypclass == TYPEFUNC_RECORD) { @@ -418,6 +369,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) * case it doesn't.) */ BlessTupleDesc(tupdesc); + fs->returnsTuple = true; } else { @@ -439,7 +391,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) ExecSetSlotDescriptor(fs->func_slot, fs->tupdesc); } else - fs->func_slot = NULL; + fs->func_slot = scanstate->ss.ss_ScanTupleSlot; natts += colcount; i++; @@ -500,11 +452,13 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) ExecAssignScanProjectionInfo(&scanstate->ss); /* - * Create a memory context that ExecMakeTableFunctionResult can use to - * evaluate function arguments in. We can't use the per-tuple context for - * this because it gets reset too often; but we don't want to leak - * evaluation results into the query-lifespan context either. We just - * need one context, because we evaluate each function separately. + * Create a memory context that is used to evaluate function arguments in. + * We can't use the per-tuple context for this because it gets reset too + * often; but we don't want to leak evaluation results into the + * query-lifespan context either. We currently just use one context for + * all functions, they're evaluated at the same time anyway - most of the + * time creating separate contexts would use more memory, than being able + * to reset separately would save. */ scanstate->argcontext = AllocSetContextCreate(CurrentMemoryContext, "Table function arguments", @@ -564,58 +518,523 @@ ExecEndFunctionScan(FunctionScanState *node) void ExecReScanFunctionScan(FunctionScanState *node) { - FunctionScan *scan = (FunctionScan *) node->ss.ps.plan; - int i; - Bitmapset *chgparam = node->ss.ps.chgParam; + int i; ExecClearTuple(node->ss.ps.ps_ResultTupleSlot); + for (i = 0; i < node->nfuncs; i++) { FunctionScanPerFuncState *fs = &node->funcstates[i]; if (fs->func_slot) ExecClearTuple(fs->func_slot); + + if (node->funcstates[i].tstore != NULL) + { + tuplestore_end(node->funcstates[i].tstore); + node->funcstates[i].tstore = NULL; + } + + /* + * If it is a dynamically-allocated TupleDesc, free it: it is + * typically allocated in a per-query context, so we must avoid + * leaking it across multiple usages. + */ + if (fs->rsinfo.setDesc && fs->rsinfo.setDesc->tdrefcount == -1) + { + FreeTupleDesc(fs->rsinfo.setDesc); + fs->rsinfo.setDesc = NULL; + } + + fs->started = false; } ExecScanReScan(&node->ss); + /* Reset ordinality counter */ + node->ordinal = 0; +} + + +static void +ExecBeginFunctionResult(FunctionScanState *node, + FunctionScanPerFuncState *perfunc) +{ + bool returnsSet = false; + MemoryContext callerContext; + MemoryContext oldcontext; + bool direct_function_call; + ExprContext *econtext = node->ss.ps.ps_ExprContext; + ExprState *funcexpr = perfunc->funcexpr; + Datum result; + + callerContext = CurrentMemoryContext; + + Assert(perfunc->tupdesc != NULL); + /* - * Here we have a choice whether to drop the tuplestores (and recompute - * the function outputs) or just rescan them. We must recompute if an - * expression contains changed parameters, else we rescan. - * - * XXX maybe we should recompute if the function is volatile? But in - * general the executor doesn't conditionalize its actions on that. + * Prepare a resultinfo node for communication. We always do this even if + * not expecting a set result, so that we can pass expectedDesc. In the + * generic-expression case, the expression doesn't actually get to see the + * resultinfo, but set it up anyway because we use some of the fields as + * our own state variables. */ - if (chgparam) + perfunc->rsinfo.type = T_ReturnSetInfo; + perfunc->rsinfo.econtext = econtext; + perfunc->rsinfo.expectedDesc = perfunc->tupdesc; + perfunc->rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize); + perfunc->rsinfo.returnMode = SFRM_ValuePerCall; + /* isDone is filled below */ + perfunc->rsinfo.setResult = NULL; + perfunc->rsinfo.setDesc = NULL; + perfunc->tstore = NULL; + + perfunc->started = true; + + /* + * Normally the passed expression tree will be a FuncExprState, since the + * grammar only allows a function call at the top level of a table + * function reference. However, if the function doesn't return set then + * the planner might have replaced the function call via constant-folding + * or inlining. So if we see any other kind of expression node, execute + * it via the general ExecEvalExpr() code; the only difference is that we + * don't get a chance to pass a special ReturnSetInfo to any functions + * buried in the expression. + */ + if (funcexpr && IsA(funcexpr, FuncExprState) && + IsA(funcexpr->expr, FuncExpr)) { - ListCell *lc; + FuncExprState *fcache = (FuncExprState *) funcexpr; + ExprDoneCond argDone; - i = 0; - foreach(lc, scan->functions) + /* + * This path is similar to ExecMakeFunctionResult. + */ + direct_function_call = true; + + /* + * Initialize function cache if first time through + */ + if (fcache->func.fn_oid == InvalidOid) { - RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); + FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; - if (bms_overlap(chgparam, rtfunc->funcparams)) + ExecInitFcache(func->funcid, func->inputcollid, fcache, + econtext->ecxt_per_query_memory, false); + } + returnsSet = fcache->func.fn_retset; + InitFunctionCallInfoData(perfunc->fcinfo, &(fcache->func), + list_length(fcache->args), + fcache->fcinfo_data.fncollation, + NULL, (Node *) &perfunc->rsinfo); + + /* + * Evaluate the function's argument list. + * + * We can't do this in the per-tuple context: the argument values + * would disappear when we reset that context in the inner loop. And + * the caller's CurrentMemoryContext is typically a query-lifespan + * context, so we don't want to leak memory there. We require the + * caller to pass a separate memory context that can be used for this, + * and can be reset each time the node is re-scanned. + */ + oldcontext = MemoryContextSwitchTo(node->argcontext); + argDone = ExecEvalFuncArgs(&perfunc->fcinfo, fcache->args, econtext); + MemoryContextSwitchTo(oldcontext); + + /* We don't allow sets in the arguments of the table function */ + if (argDone != ExprSingleResult) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("set-valued function called in context that cannot accept a set"))); + + /* + * If function is strict, and there are any NULL arguments, skip + * calling the function and act like it returned NULL (or an empty + * set, in the returns-set case). + */ + if (fcache->func.fn_strict) + { + int i; + + for (i = 0; i < perfunc->fcinfo.nargs; i++) { - if (node->funcstates[i].tstore != NULL) - { - tuplestore_end(node->funcstates[i].tstore); - node->funcstates[i].tstore = NULL; - } - node->funcstates[i].rowcount = -1; + if (perfunc->fcinfo.argnull[i]) + goto no_function_result; } - i++; + } + } + else + { + /* Treat funcexpr as a generic expression */ + direct_function_call = false; + InitFunctionCallInfoData(perfunc->fcinfo, NULL, 0, InvalidOid, NULL, NULL); + } + + /* + * Switch to short-lived context for calling the function or expression. + */ + MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); + + /* + * reset per-tuple memory context before each call of the function or + * expression. This cleans up any local memory the function may leak + * when called. + */ + ResetExprContext(econtext); + + /* Call the function or expression one time */ + if (direct_function_call) + { + PgStat_FunctionCallUsage fcusage; + + pgstat_init_function_usage(&perfunc->fcinfo, &fcusage); + + perfunc->fcinfo.isnull = false; + perfunc->rsinfo.isDone = ExprSingleResult; + result = FunctionCallInvoke(&perfunc->fcinfo); + + pgstat_end_function_usage(&fcusage, + perfunc->rsinfo.isDone != ExprMultipleResult); + } + else + { + perfunc->rsinfo.isDone = ExprSingleResult; + result = ExecEvalExpr(funcexpr, econtext, + &perfunc->fcinfo.isnull, NULL); + + /* done after this, will use SFRM_ValuePerCall branch below */ + } + + /* Which protocol does function want to use? */ + if (perfunc->rsinfo.returnMode == SFRM_ValuePerCall) + { + /* + * Check for end of result set. + */ + if (perfunc->rsinfo.isDone == ExprEndResult) + goto no_function_result; + + /* + * Store current resultset item. + */ + if (perfunc->returnsTuple) + { + if (!perfunc->fcinfo.isnull) + { + HeapTupleHeader td = DatumGetHeapTupleHeader(result); + HeapTupleData tmptup; + + if (perfunc->rsinfo.setDesc == NULL) + { + /* + * This is the first non-NULL result from the + * function. Use the type info embedded in the + * rowtype Datum to look up the needed tupdesc. Make + * a copy for the query. + */ + oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory); + perfunc->rsinfo.setDesc = + lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td), + HeapTupleHeaderGetTypMod(td)); + MemoryContextSwitchTo(oldcontext); + + /* + * Cross-check tupdesc. We only really need to do this + * for functions returning RECORD, but might as well do it + * always. + */ + tupledesc_match(perfunc->tupdesc, perfunc->rsinfo.setDesc); + } + + tmptup.t_len = HeapTupleHeaderGetDatumLength(td); + tmptup.t_data = td; + + ExecStoreTuple(&tmptup, perfunc->func_slot, InvalidBuffer, false); + /* materializing handles expanded and toasted datums */ + /* XXX: would be nice if this could be optimized away */ + ExecMaterializeSlot(perfunc->func_slot); + } + else + { + /* + * NULL result from a tuple-returning function; expand it + * to a row of all nulls. + */ + ExecStoreAllNullTuple(perfunc->func_slot); + } + } + else + { + /* + * Scalar-type case: just store the function result + */ + ExecClearTuple(perfunc->func_slot); + perfunc->func_slot->tts_values[0] = result; + perfunc->func_slot->tts_isnull[0] = perfunc->fcinfo.isnull; + ExecStoreVirtualTuple(perfunc->func_slot); + + /* materializing handles expanded and toasted datums */ + ExecMaterializeSlot(perfunc->func_slot); + } + } + else if (perfunc->rsinfo.returnMode == SFRM_Materialize) + { + EState *estate; + ScanDirection direction; + + estate = node->ss.ps.state; + direction = estate->es_direction; + + /* check we're on the same page as the function author */ + if (perfunc->rsinfo.isDone != ExprSingleResult) + ereport(ERROR, + (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED), + errmsg("table-function protocol for materialize mode was not followed"))); + + if (perfunc->rsinfo.setResult != NULL) + { + perfunc->tstore = perfunc->rsinfo.setResult; + + /* + * paranoia - cope if the function, which may have constructed the + * tuplestore itself, didn't leave it pointing at the start. This + * call is fast, so the overhead shouldn't be an issue. + */ + tuplestore_rescan(perfunc->rsinfo.setResult); + + /* + * If function provided a tupdesc, cross-check it. We only really need to + * do this for functions returning RECORD, but might as well do it always. + */ + if (perfunc->rsinfo.setDesc) + { + tupledesc_match(perfunc->tupdesc, perfunc->rsinfo.setDesc); + + /* + * If it is a dynamically-allocated TupleDesc, free it: it is + * typically allocated in a per-query context, so we must avoid + * leaking it across multiple usages. + */ + if (perfunc->rsinfo.setDesc->tdrefcount == -1) + { + FreeTupleDesc(perfunc->rsinfo.setDesc); + perfunc->rsinfo.setDesc = NULL; + } + } + + /* and return first row */ + (void) tuplestore_gettupleslot(perfunc->rsinfo.setResult, + ScanDirectionIsForward(direction), + false, + perfunc->func_slot); + } + } + else + ereport(ERROR, + (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED), + errmsg("unrecognized table-function returnMode: %d", + (int) perfunc->rsinfo.returnMode))); + goto done; + +no_function_result: + MemoryContextSwitchTo(callerContext); + + /* + * If we got nothing from the function (ie, an empty-set or NULL + * result), we have to manufacture a result. I.e. if it's a + * non-set-returning function then return a single all-nulls row. + */ + perfunc->rsinfo.isDone = ExprEndResult; + if (returnsSet) + ExecClearTuple(perfunc->func_slot); + else + ExecStoreAllNullTuple(perfunc->func_slot); +done: + MemoryContextSwitchTo(callerContext); +} + +static void +ExecNextFunctionResult(FunctionScanState *node, + FunctionScanPerFuncState *perfunc) +{ + EState *estate; + ScanDirection direction; + MemoryContext callerContext; + ExprContext *econtext = node->ss.ps.ps_ExprContext; + + estate = node->ss.ps.state; + direction = estate->es_direction; + + callerContext = CurrentMemoryContext; + + if (perfunc->tstore) + { + (void) tuplestore_gettupleslot(perfunc->tstore, + ScanDirectionIsForward(direction), + false, + perfunc->func_slot); + } + else if (perfunc->rsinfo.isDone == ExprSingleResult || + perfunc->rsinfo.isDone == ExprEndResult) + { + ExecClearTuple(perfunc->func_slot); + } + else + { + Datum result; + PgStat_FunctionCallUsage fcusage; + ExprState *funcexpr PG_USED_FOR_ASSERTS_ONLY = perfunc->funcexpr; + + /* ensure called in a sane context */ + Assert(funcexpr && IsA(funcexpr, FuncExprState) && + IsA(funcexpr->expr, FuncExpr)); + Assert(perfunc->rsinfo.returnMode == SFRM_ValuePerCall); + + /* + * Switch to short-lived context for calling the function or expression. + */ + MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); + + /* next call in percall mode */ + pgstat_init_function_usage(&perfunc->fcinfo, &fcusage); + + perfunc->fcinfo.isnull = false; + perfunc->rsinfo.isDone = ExprSingleResult; + result = FunctionCallInvoke(&perfunc->fcinfo); + + pgstat_end_function_usage(&fcusage, + perfunc->rsinfo.isDone != ExprMultipleResult); + + Assert(perfunc->rsinfo.returnMode == SFRM_ValuePerCall); + + if (perfunc->rsinfo.isDone == ExprEndResult) + { + ExecClearTuple(perfunc->func_slot); + goto out; + } + + if (perfunc->returnsTuple) + { + if (!perfunc->fcinfo.isnull) + { + HeapTupleHeader td = DatumGetHeapTupleHeader(result); + HeapTupleData tmptup; + TupleDesc tupdesc; + + if (perfunc->rsinfo.setDesc == NULL) + { + MemoryContext oldcontext; + + /* + * This is the first non-NULL result from the + * function. Use the type info embedded in the + * rowtype Datum to look up the needed tupdesc. Make + * a copy for the query. + */ + oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory); + perfunc->rsinfo.setDesc = + lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td), + HeapTupleHeaderGetTypMod(td)); + MemoryContextSwitchTo(oldcontext); + + /* + * Cross-check tupdesc. We only really need to do this + * for functions returning RECORD, but might as well do it + * always. + */ + tupledesc_match(perfunc->tupdesc, perfunc->rsinfo.setDesc); + } + + tupdesc = perfunc->rsinfo.setDesc; + + /* + * Verify all later returned rows have same subtype; + * necessary in case the type is RECORD. + */ + if (HeapTupleHeaderGetTypeId(td) != tupdesc->tdtypeid || + HeapTupleHeaderGetTypMod(td) != tupdesc->tdtypmod) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("rows returned by function are not all of the same row type"))); + + tmptup.t_len = HeapTupleHeaderGetDatumLength(td); + tmptup.t_data = td; + + ExecStoreTuple(&tmptup, perfunc->func_slot, InvalidBuffer, false); + /* materializing handles expanded and toasted datums */ + /* XXX: would be nice if this could be optimized away */ + ExecMaterializeSlot(perfunc->func_slot); + } + else + { + ExecStoreAllNullTuple(perfunc->func_slot); + } + } + else + { + /* Scalar-type case: just store the function result */ + ExecClearTuple(perfunc->func_slot); + perfunc->func_slot->tts_values[0] = result; + perfunc->func_slot->tts_isnull[0] = perfunc->fcinfo.isnull; + ExecStoreVirtualTuple(perfunc->func_slot); + + /* materializing handles expanded and toasted datums */ + ExecMaterializeSlot(perfunc->func_slot); } } - /* Reset ordinality counter */ - node->ordinal = 0; +out: + MemoryContextSwitchTo(callerContext); +} - /* Make sure we rewind any remaining tuplestores */ - for (i = 0; i < node->nfuncs; i++) + +/* + * Check that function result tuple type (src_tupdesc) matches or can + * be considered to match what the query expects (dst_tupdesc). If + * they don't match, ereport. + * + * We really only care about number of attributes and data type. + * Also, we can ignore type mismatch on columns that are dropped in the + * destination type, so long as the physical storage matches. This is + * helpful in some cases involving out-of-date cached plans. + */ +static void +tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc) +{ + int i; + + if (dst_tupdesc->natts != src_tupdesc->natts) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("function return row and query-specified return row do not match"), + errdetail_plural("Returned row contains %d attribute, but query expects %d.", + "Returned row contains %d attributes, but query expects %d.", + src_tupdesc->natts, + src_tupdesc->natts, dst_tupdesc->natts))); + + for (i = 0; i < dst_tupdesc->natts; i++) { - if (node->funcstates[i].tstore != NULL) - tuplestore_rescan(node->funcstates[i].tstore); + Form_pg_attribute dattr = dst_tupdesc->attrs[i]; + Form_pg_attribute sattr = src_tupdesc->attrs[i]; + + if (IsBinaryCoercible(sattr->atttypid, dattr->atttypid)) + continue; /* no worries */ + if (!dattr->attisdropped) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("function return row and query-specified return row do not match"), + errdetail("Returned type %s at ordinal position %d, but query expects %s.", + format_type_be(sattr->atttypid), + i + 1, + format_type_be(dattr->atttypid)))); + + if (dattr->attlen != sattr->attlen || + dattr->attalign != sattr->attalign) + ereport(ERROR, + (errcode(ERRCODE_DATATYPE_MISMATCH), + errmsg("function return row and query-specified return row do not match"), + errdetail("Physical storage mismatch on dropped attribute at ordinal position %d.", + i + 1))); } } diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h index 39521ed..7f11285 100644 --- a/src/include/executor/executor.h +++ b/src/include/executor/executor.h @@ -234,14 +234,13 @@ extern Datum GetAttributeByNum(HeapTupleHeader tuple, AttrNumber attrno, bool *isNull); extern Datum GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull); -extern Tuplestorestate *ExecMakeTableFunctionResult(ExprState *funcexpr, - ExprContext *econtext, - MemoryContext argContext, - TupleDesc expectedDesc, - bool randomAccess); extern Datum ExecEvalExprSwitchContext(ExprState *expression, ExprContext *econtext, bool *isNull, ExprDoneCond *isDone); +extern ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo, + List *argList, ExprContext *econtext); extern ExprState *ExecInitExpr(Expr *node, PlanState *parent); +extern void ExecInitFcache(Oid foid, Oid input_collation, FuncExprState *fcache, + MemoryContext fcacheCxt, bool needDescForSets); extern ExprState *ExecPrepareExpr(Expr *node, EState *estate); extern bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull); extern int ExecTargetListLength(List *targetlist); diff --git a/src/test/regress/expected/pg_lsn.out b/src/test/regress/expected/pg_lsn.out index 2854cfd..5ed0089 100644 --- a/src/test/regress/expected/pg_lsn.out +++ b/src/test/regress/expected/pg_lsn.out @@ -79,14 +79,15 @@ SELECT DISTINCT (i || '/' || j)::pg_lsn f -> HashAggregate Group Key: ((((i.i)::text || '/'::text) || (j.j)::text))::pg_lsn -> Nested Loop - -> Function Scan on generate_series k - -> Materialize - -> Nested Loop + -> Nested Loop + -> Function Scan on generate_series i + Filter: (i <= 10) + -> Materialize -> Function Scan on generate_series j Filter: ((j > 0) AND (j <= 10)) - -> Function Scan on generate_series i - Filter: (i <= 10) -(12 rows) + -> Materialize + -> Function Scan on generate_series k +(13 rows) SELECT DISTINCT (i || '/' || j)::pg_lsn f FROM generate_series(1, 10) i, diff --git a/src/test/regress/expected/plpgsql.out b/src/test/regress/expected/plpgsql.out index a2c36e4..40fd285 100644 --- a/src/test/regress/expected/plpgsql.out +++ b/src/test/regress/expected/plpgsql.out @@ -3562,7 +3562,7 @@ select * from sc_test(); create or replace function sc_test() returns setof integer as $$ declare - c cursor for select * from generate_series(1, 10); + c scroll cursor for select * from generate_series(1, 10); x integer; begin open c; diff --git a/src/test/regress/expected/rangefuncs.out b/src/test/regress/expected/rangefuncs.out index f06cfa4..a6496fc 100644 --- a/src/test/regress/expected/rangefuncs.out +++ b/src/test/regress/expected/rangefuncs.out @@ -1109,9 +1109,9 @@ SELECT * FROM (VALUES (1),(2),(3)) v(r), ROWS FROM( foo_sql(11,11), foo_mat(10+r 1 | 11 | 1 | 11 | 1 1 | | | 12 | 2 1 | | | 13 | 3 - 2 | 11 | 1 | 12 | 4 + 2 | 11 | 2 | 12 | 4 2 | | | 13 | 5 - 3 | 11 | 1 | 13 | 6 + 3 | 11 | 3 | 13 | 6 (6 rows) SELECT setval('foo_rescan_seq1',1,false),setval('foo_rescan_seq2',1,false); @@ -1126,9 +1126,9 @@ SELECT * FROM (VALUES (1),(2),(3)) v(r), ROWS FROM( foo_sql(10+r,13), foo_mat(11 1 | 11 | 1 | 11 | 1 1 | 12 | 2 | | 1 | 13 | 3 | | - 2 | 12 | 4 | 11 | 1 + 2 | 12 | 4 | 11 | 2 2 | 13 | 5 | | - 3 | 13 | 6 | 11 | 1 + 3 | 13 | 6 | 11 | 3 (6 rows) SELECT setval('foo_rescan_seq1',1,false),setval('foo_rescan_seq2',1,false); diff --git a/src/test/regress/sql/plpgsql.sql b/src/test/regress/sql/plpgsql.sql index 776f229..2d358bb 100644 --- a/src/test/regress/sql/plpgsql.sql +++ b/src/test/regress/sql/plpgsql.sql @@ -2952,7 +2952,7 @@ select * from sc_test(); create or replace function sc_test() returns setof integer as $$ declare - c cursor for select * from generate_series(1, 10); + c scroll cursor for select * from generate_series(1, 10); x integer; begin open c; -- 2.9.3
0004-Allow-ROWS-FROM-to-return-functions-as-single-record.patch (text/x-patch, 46.3K) download From 39b7ee10f7a5e13826bd77e7f9bb07c8a0d92653 Mon Sep 17 00:00:00 2001 From: Andres Freund <andres@anarazel.de> Date: Fri, 26 Aug 2016 16:19:58 -0700 Subject: [PATCH 4/6] Allow ROWS FROM to return functions as single record column. Using an empty AS list inside ROWS FROM (e.g. SELECT * FROM ROWS FROM(aclexplode('{=r/andres}') AS ())), previously not permitted by the grammar, now returns the results of the function as a single record/composite field. This is primarily interesting to allow for the conversion of SELECT record_returning_srf(); into ROWS FROM. Without a facility like this there'd be no way to do that for functions returning record, and it'd be more complicated for composite returning functions. Todo: - cleanup code a bit, move some of the changes to previous commit --- src/backend/executor/nodeFunctionscan.c | 267 ++++++++++++++++++++++--------- src/backend/nodes/copyfuncs.c | 16 ++ src/backend/nodes/equalfuncs.c | 14 ++ src/backend/nodes/outfuncs.c | 14 ++ src/backend/nodes/readfuncs.c | 1 + src/backend/optimizer/util/clauses.c | 4 + src/backend/parser/gram.y | 43 +++-- src/backend/parser/parse_clause.c | 18 +-- src/backend/parser/parse_relation.c | 66 +++++++- src/include/nodes/nodes.h | 1 + src/include/nodes/parsenodes.h | 21 ++- src/include/nodes/pg_list.h | 9 ++ src/include/parser/parse_relation.h | 1 + src/test/regress/expected/rangefuncs.out | 85 ++++++++++ src/test/regress/sql/rangefuncs.sql | 18 +++ 15 files changed, 468 insertions(+), 110 deletions(-) diff --git a/src/backend/executor/nodeFunctionscan.c b/src/backend/executor/nodeFunctionscan.c index 4885f75..1da4fde 100644 --- a/src/backend/executor/nodeFunctionscan.c +++ b/src/backend/executor/nodeFunctionscan.c @@ -44,12 +44,15 @@ typedef struct FunctionScanPerFuncState { ExprState *funcexpr; /* state of the expression being evaluated */ - TupleDesc tupdesc; /* desc of the function result type */ int colcount; /* expected number of result columns */ Tuplestorestate *tstore; /* holds the function result set */ TupleTableSlot *func_slot; /* function result slot (or NULL) */ + TupleDesc func_desc; /* desc of the function result type */ + TupleTableSlot *scan_slot; /* function result slot (or NULL) */ + TupleDesc scan_desc; /* tupdesc for returning a tuple as one col */ bool started; bool returnsTuple; + bool toRecord; FunctionCallInfoData fcinfo; ReturnSetInfo rsinfo; } FunctionScanPerFuncState; @@ -109,7 +112,7 @@ FunctionNext(FunctionScanState *node) else ExecNextFunctionResult(node, fs); - scanslot = fs->func_slot; + scanslot = fs->scan_slot; return scanslot; } @@ -125,7 +128,7 @@ FunctionNext(FunctionScanState *node) /* * Main loop over functions. * - * We fetch the function results into func_slots (which match the function + * We fetch the function results into scan_slots (which match the function * return types), and then copy the values to scanslot (which matches the * scan result type), setting the ordinal column (if any) as well. */ @@ -147,7 +150,7 @@ FunctionNext(FunctionScanState *node) else ExecNextFunctionResult(node, fs); - if (TupIsNull(fs->func_slot)) + if (TupIsNull(fs->scan_slot)) { /* * populate the result cols with nulls @@ -164,12 +167,12 @@ FunctionNext(FunctionScanState *node) /* * we have a result, so just copy it to the result cols. */ - slot_getallattrs(fs->func_slot); + slot_getallattrs(fs->scan_slot); for (i = 0; i < fs->colcount; i++) { - scanslot->tts_values[att] = fs->func_slot->tts_values[i]; - scanslot->tts_isnull[att] = fs->func_slot->tts_isnull[i]; + scanslot->tts_values[att] = fs->scan_slot->tts_values[i]; + scanslot->tts_isnull[att] = fs->scan_slot->tts_isnull[i]; att++; } @@ -309,7 +312,6 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) FunctionScanPerFuncState *fs = &scanstate->funcstates[i]; TypeFuncClass functypclass; Oid funcrettype; - TupleDesc tupdesc; fs->funcexpr = ExecInitExpr((Expr *) funcexpr, (PlanState *) scanstate); @@ -321,6 +323,11 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) fs->tstore = NULL; fs->started = false; fs->rsinfo.setDesc = NULL; + fs->toRecord = false; + fs->scan_desc = NULL; + fs->func_desc = NULL; + fs->scan_slot = NULL; + fs->func_slot = NULL; /* * Now determine if the function returns a simple or composite type, @@ -330,45 +337,77 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) */ functypclass = get_expr_result_type(funcexpr, &funcrettype, - &tupdesc); + &fs->func_desc); - if (functypclass == TYPEFUNC_COMPOSITE) + if (rtfunc->funcasrecord) { - /* Composite data type, e.g. a table's row type */ - Assert(tupdesc); - Assert(tupdesc->natts >= colcount); - /* Must copy it out of typcache for safety */ - tupdesc = CreateTupleDescCopy(tupdesc); - fs->returnsTuple = true; - } - else if (functypclass == TYPEFUNC_SCALAR) - { - /* Base data type, i.e. scalar */ - tupdesc = CreateTemplateTupleDesc(1, false); - TupleDescInitEntry(tupdesc, + /* + * Returning a composite / record type as one column, instead of + * split up. Need to compute two tuple descs: One to pass to the + * function (important when return type is determined in catalog), + * and one specifying what is eventually returned to the user. + */ + Assert(functypclass == TYPEFUNC_COMPOSITE || + functypclass == TYPEFUNC_RECORD); + + /* + * fs->func_desc contains what the function returns, if known, + * scan_desc what we make it return + */ + if (fs->func_desc) + fs->func_desc = CreateTupleDescCopy(fs->func_desc); + fs->scan_desc = CreateTemplateTupleDesc(1, false); + TupleDescInitEntry(fs->scan_desc, (AttrNumber) 1, NULL, /* don't care about the name here */ funcrettype, -1, 0); - TupleDescInitEntryCollation(tupdesc, + TupleDescInitEntryCollation(fs->scan_desc, (AttrNumber) 1, exprCollation(funcexpr)); + fs->toRecord = true; + fs->returnsTuple = true; + } + else if (functypclass == TYPEFUNC_COMPOSITE) + { + /* Composite data type, e.g. a table's row type */ + Assert(fs->func_desc); + Assert(fs->func_desc->natts >= colcount); + /* Must copy it out of typcache for safety */ + fs->func_desc = CreateTupleDescCopy(fs->func_desc); + fs->scan_desc = fs->func_desc; + fs->returnsTuple = true; + } + else if (functypclass == TYPEFUNC_SCALAR) + { + /* Base data type, i.e. scalar */ + fs->func_desc = CreateTemplateTupleDesc(1, false); + TupleDescInitEntry(fs->func_desc, + (AttrNumber) 1, + NULL, /* don't care about the name here */ + funcrettype, + -1, + 0); + TupleDescInitEntryCollation(fs->func_desc, + (AttrNumber) 1, + exprCollation(funcexpr)); + fs->scan_desc = fs->func_desc; fs->returnsTuple = false; } else if (functypclass == TYPEFUNC_RECORD) { - tupdesc = BuildDescFromLists(rtfunc->funccolnames, - rtfunc->funccoltypes, - rtfunc->funccoltypmods, - rtfunc->funccolcollations); - + fs->func_desc = BuildDescFromLists(rtfunc->funccolnames, + rtfunc->funccoltypes, + rtfunc->funccoltypmods, + rtfunc->funccolcollations); /* * For RECORD results, make sure a typmod has been assigned. (The * function should do this for itself, but let's cover things in * case it doesn't.) */ - BlessTupleDesc(tupdesc); + BlessTupleDesc(fs->func_desc); + fs->scan_desc = fs->func_desc; fs->returnsTuple = true; } else @@ -377,7 +416,6 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) elog(ERROR, "function in FROM has unsupported return type"); } - fs->tupdesc = tupdesc; fs->colcount = colcount; /* @@ -387,11 +425,11 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) */ if (!scanstate->simple) { - fs->func_slot = ExecInitExtraTupleSlot(estate); - ExecSetSlotDescriptor(fs->func_slot, fs->tupdesc); + fs->scan_slot = ExecInitExtraTupleSlot(estate); + ExecSetSlotDescriptor(fs->scan_slot, fs->scan_desc); } else - fs->func_slot = scanstate->ss.ss_ScanTupleSlot; + fs->scan_slot = scanstate->ss.ss_ScanTupleSlot; natts += colcount; i++; @@ -406,7 +444,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) */ if (scanstate->simple) { - scan_tupdesc = CreateTupleDescCopy(scanstate->funcstates[0].tupdesc); + scan_tupdesc = CreateTupleDescCopy(scanstate->funcstates[0].scan_desc); scan_tupdesc->tdtypeid = RECORDOID; scan_tupdesc->tdtypmod = -1; } @@ -421,7 +459,7 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) for (i = 0; i < nfuncs; i++) { - TupleDesc tupdesc = scanstate->funcstates[i].tupdesc; + TupleDesc tupdesc = scanstate->funcstates[i].scan_desc; int colcount = scanstate->funcstates[i].colcount; int j; @@ -498,6 +536,8 @@ ExecEndFunctionScan(FunctionScanState *node) { FunctionScanPerFuncState *fs = &node->funcstates[i]; + if (fs->scan_slot) + ExecClearTuple(fs->scan_slot); if (fs->func_slot) ExecClearTuple(fs->func_slot); @@ -526,6 +566,8 @@ ExecReScanFunctionScan(FunctionScanState *node) { FunctionScanPerFuncState *fs = &node->funcstates[i]; + if (fs->scan_slot) + ExecClearTuple(fs->scan_slot); if (fs->func_slot) ExecClearTuple(fs->func_slot); @@ -570,7 +612,7 @@ ExecBeginFunctionResult(FunctionScanState *node, callerContext = CurrentMemoryContext; - Assert(perfunc->tupdesc != NULL); + Assert(perfunc->scan_desc != NULL); /* * Prepare a resultinfo node for communication. We always do this even if @@ -581,7 +623,7 @@ ExecBeginFunctionResult(FunctionScanState *node, */ perfunc->rsinfo.type = T_ReturnSetInfo; perfunc->rsinfo.econtext = econtext; - perfunc->rsinfo.expectedDesc = perfunc->tupdesc; + perfunc->rsinfo.expectedDesc = perfunc->func_desc; perfunc->rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize); perfunc->rsinfo.returnMode = SFRM_ValuePerCall; /* isDone is filled below */ @@ -718,7 +760,7 @@ ExecBeginFunctionResult(FunctionScanState *node, /* * Store current resultset item. */ - if (perfunc->returnsTuple) + if (perfunc->returnsTuple && !perfunc->toRecord) { if (!perfunc->fcinfo.isnull) { @@ -744,16 +786,16 @@ ExecBeginFunctionResult(FunctionScanState *node, * for functions returning RECORD, but might as well do it * always. */ - tupledesc_match(perfunc->tupdesc, perfunc->rsinfo.setDesc); + tupledesc_match(perfunc->scan_desc, perfunc->rsinfo.setDesc); } tmptup.t_len = HeapTupleHeaderGetDatumLength(td); tmptup.t_data = td; - ExecStoreTuple(&tmptup, perfunc->func_slot, InvalidBuffer, false); + ExecStoreTuple(&tmptup, perfunc->scan_slot, InvalidBuffer, false); /* materializing handles expanded and toasted datums */ /* XXX: would be nice if this could be optimized away */ - ExecMaterializeSlot(perfunc->func_slot); + ExecMaterializeSlot(perfunc->scan_slot); } else { @@ -761,7 +803,7 @@ ExecBeginFunctionResult(FunctionScanState *node, * NULL result from a tuple-returning function; expand it * to a row of all nulls. */ - ExecStoreAllNullTuple(perfunc->func_slot); + ExecStoreAllNullTuple(perfunc->scan_slot); } } else @@ -769,13 +811,13 @@ ExecBeginFunctionResult(FunctionScanState *node, /* * Scalar-type case: just store the function result */ - ExecClearTuple(perfunc->func_slot); - perfunc->func_slot->tts_values[0] = result; - perfunc->func_slot->tts_isnull[0] = perfunc->fcinfo.isnull; - ExecStoreVirtualTuple(perfunc->func_slot); + ExecClearTuple(perfunc->scan_slot); + perfunc->scan_slot->tts_values[0] = result; + perfunc->scan_slot->tts_isnull[0] = perfunc->fcinfo.isnull; + ExecStoreVirtualTuple(perfunc->scan_slot); /* materializing handles expanded and toasted datums */ - ExecMaterializeSlot(perfunc->func_slot); + ExecMaterializeSlot(perfunc->scan_slot); } } else if (perfunc->rsinfo.returnMode == SFRM_Materialize) @@ -809,25 +851,70 @@ ExecBeginFunctionResult(FunctionScanState *node, */ if (perfunc->rsinfo.setDesc) { - tupledesc_match(perfunc->tupdesc, perfunc->rsinfo.setDesc); + if (!perfunc->toRecord) + tupledesc_match(perfunc->scan_desc, perfunc->rsinfo.setDesc); + else if (perfunc->func_desc) + tupledesc_match(perfunc->func_desc, perfunc->rsinfo.setDesc); + } - /* - * If it is a dynamically-allocated TupleDesc, free it: it is - * typically allocated in a per-query context, so we must avoid - * leaking it across multiple usages. - */ - if (perfunc->rsinfo.setDesc->tdrefcount == -1) + if (!perfunc->toRecord) + { + /* and return first row */ + (void) tuplestore_gettupleslot(perfunc->rsinfo.setResult, + ScanDirectionIsForward(direction), + false, + perfunc->scan_slot); + } + else + { + + if (perfunc->func_slot == NULL) { - FreeTupleDesc(perfunc->rsinfo.setDesc); - perfunc->rsinfo.setDesc = NULL; + MemoryContext oldcontext; + TupleDesc slotDesc; + + oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory); + + /* don't assume slotDesc is long-lived */ + if (perfunc->rsinfo.setDesc) + slotDesc = CreateTupleDescCopy(perfunc->rsinfo.setDesc); + else if (perfunc->func_desc) + slotDesc = perfunc->func_desc; + else + Assert(false); + + perfunc->func_slot = MakeSingleTupleTableSlot(slotDesc); + MemoryContextSwitchTo(oldcontext); + } + + (void) tuplestore_gettupleslot(perfunc->rsinfo.setResult, + ScanDirectionIsForward(direction), + false, + perfunc->func_slot); + + ExecClearTuple(perfunc->scan_slot); + if (!TupIsNull(perfunc->func_slot)) + { + perfunc->scan_slot->tts_values[0] = + ExecFetchSlotTupleDatum(perfunc->func_slot); + perfunc->scan_slot->tts_isnull[0] = false; + ExecStoreVirtualTuple(perfunc->scan_slot); + /* materializing handles expanded and toasted datums */ + ExecMaterializeSlot(perfunc->scan_slot); } } - /* and return first row */ - (void) tuplestore_gettupleslot(perfunc->rsinfo.setResult, - ScanDirectionIsForward(direction), - false, - perfunc->func_slot); + /* + * If it is a dynamically-allocated TupleDesc, free it: it is + * typically allocated in a per-query context, so we want to avoid + * leaking it across multiple usages. + */ + if (perfunc->rsinfo.setDesc && + perfunc->rsinfo.setDesc->tdrefcount == -1) + { + FreeTupleDesc(perfunc->rsinfo.setDesc); + perfunc->rsinfo.setDesc = NULL; + } } } else @@ -847,9 +934,9 @@ no_function_result: */ perfunc->rsinfo.isDone = ExprEndResult; if (returnsSet) - ExecClearTuple(perfunc->func_slot); + ExecClearTuple(perfunc->scan_slot); else - ExecStoreAllNullTuple(perfunc->func_slot); + ExecStoreAllNullTuple(perfunc->scan_slot); done: MemoryContextSwitchTo(callerContext); } @@ -870,15 +957,37 @@ ExecNextFunctionResult(FunctionScanState *node, if (perfunc->tstore) { - (void) tuplestore_gettupleslot(perfunc->tstore, - ScanDirectionIsForward(direction), - false, - perfunc->func_slot); + if (!perfunc->toRecord) + { + /* and return first row */ + (void) tuplestore_gettupleslot(perfunc->rsinfo.setResult, + ScanDirectionIsForward(direction), + false, + perfunc->scan_slot); + } + else + { + (void) tuplestore_gettupleslot(perfunc->rsinfo.setResult, + ScanDirectionIsForward(direction), + false, + perfunc->func_slot); + + ExecClearTuple(perfunc->scan_slot); + if (!TupIsNull(perfunc->func_slot)) + { + perfunc->scan_slot->tts_values[0] = + ExecFetchSlotTupleDatum(perfunc->func_slot); + perfunc->scan_slot->tts_isnull[0] = false; + ExecStoreVirtualTuple(perfunc->scan_slot); + /* materializing handles expanded and toasted datums */ + ExecMaterializeSlot(perfunc->scan_slot); + } + } } else if (perfunc->rsinfo.isDone == ExprSingleResult || perfunc->rsinfo.isDone == ExprEndResult) { - ExecClearTuple(perfunc->func_slot); + ExecClearTuple(perfunc->scan_slot); } else { @@ -910,11 +1019,11 @@ ExecNextFunctionResult(FunctionScanState *node, if (perfunc->rsinfo.isDone == ExprEndResult) { - ExecClearTuple(perfunc->func_slot); + ExecClearTuple(perfunc->scan_slot); goto out; } - if (perfunc->returnsTuple) + if (perfunc->returnsTuple && !perfunc->toRecord) { if (!perfunc->fcinfo.isnull) { @@ -943,7 +1052,7 @@ ExecNextFunctionResult(FunctionScanState *node, * for functions returning RECORD, but might as well do it * always. */ - tupledesc_match(perfunc->tupdesc, perfunc->rsinfo.setDesc); + tupledesc_match(perfunc->scan_desc, perfunc->rsinfo.setDesc); } tupdesc = perfunc->rsinfo.setDesc; @@ -961,26 +1070,26 @@ ExecNextFunctionResult(FunctionScanState *node, tmptup.t_len = HeapTupleHeaderGetDatumLength(td); tmptup.t_data = td; - ExecStoreTuple(&tmptup, perfunc->func_slot, InvalidBuffer, false); + ExecStoreTuple(&tmptup, perfunc->scan_slot, InvalidBuffer, false); /* materializing handles expanded and toasted datums */ /* XXX: would be nice if this could be optimized away */ - ExecMaterializeSlot(perfunc->func_slot); + ExecMaterializeSlot(perfunc->scan_slot); } else { - ExecStoreAllNullTuple(perfunc->func_slot); + ExecStoreAllNullTuple(perfunc->scan_slot); } } else { /* Scalar-type case: just store the function result */ - ExecClearTuple(perfunc->func_slot); - perfunc->func_slot->tts_values[0] = result; - perfunc->func_slot->tts_isnull[0] = perfunc->fcinfo.isnull; - ExecStoreVirtualTuple(perfunc->func_slot); + ExecClearTuple(perfunc->scan_slot); + perfunc->scan_slot->tts_values[0] = result; + perfunc->scan_slot->tts_isnull[0] = perfunc->fcinfo.isnull; + ExecStoreVirtualTuple(perfunc->scan_slot); /* materializing handles expanded and toasted datums */ - ExecMaterializeSlot(perfunc->func_slot); + ExecMaterializeSlot(perfunc->scan_slot); } } diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c index 1877fb4..292ab6c 100644 --- a/src/backend/nodes/copyfuncs.c +++ b/src/backend/nodes/copyfuncs.c @@ -2183,6 +2183,7 @@ _copyRangeTblFunction(const RangeTblFunction *from) COPY_NODE_FIELD(funccoltypmods); COPY_NODE_FIELD(funccolcollations); COPY_BITMAPSET_FIELD(funcparams); + COPY_SCALAR_FIELD(funcasrecord); return newnode; } @@ -2556,6 +2557,18 @@ _copyRangeFunction(const RangeFunction *from) return newnode; } +static RangeFunctionElem * +_copyRangeFunctionElem(const RangeFunctionElem *from) +{ + RangeFunctionElem *newnode = makeNode(RangeFunctionElem); + + COPY_SCALAR_FIELD(asrecord); + COPY_NODE_FIELD(func); + COPY_NODE_FIELD(coldeflist); + + return newnode; +} + static RangeTableSample * _copyRangeTableSample(const RangeTableSample *from) { @@ -5016,6 +5029,9 @@ copyObject(const void *from) case T_RangeFunction: retval = _copyRangeFunction(from); break; + case T_RangeFunctionElem: + retval = _copyRangeFunctionElem(from); + break; case T_RangeTableSample: retval = _copyRangeTableSample(from); break; diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c index 448e1a9..f69dc8e 100644 --- a/src/backend/nodes/equalfuncs.c +++ b/src/backend/nodes/equalfuncs.c @@ -2339,6 +2339,16 @@ _equalRangeFunction(const RangeFunction *a, const RangeFunction *b) } static bool +_equalRangeFunctionElem(const RangeFunctionElem *a, const RangeFunctionElem *b) +{ + COMPARE_NODE_FIELD(func); + COMPARE_NODE_FIELD(coldeflist); + COMPARE_SCALAR_FIELD(asrecord); + + return true; +} + +static bool _equalRangeTableSample(const RangeTableSample *a, const RangeTableSample *b) { COMPARE_NODE_FIELD(relation); @@ -2484,6 +2494,7 @@ _equalRangeTblFunction(const RangeTblFunction *a, const RangeTblFunction *b) COMPARE_NODE_FIELD(funccoltypmods); COMPARE_NODE_FIELD(funccolcollations); COMPARE_BITMAPSET_FIELD(funcparams); + COMPARE_SCALAR_FIELD(funcasrecord); return true; } @@ -3314,6 +3325,9 @@ equal(const void *a, const void *b) case T_RangeFunction: retval = _equalRangeFunction(a, b); break; + case T_RangeFunctionElem: + retval = _equalRangeFunctionElem(a, b); + break; case T_RangeTableSample: retval = _equalRangeTableSample(a, b); break; diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c index 29b7712..bea295b 100644 --- a/src/backend/nodes/outfuncs.c +++ b/src/backend/nodes/outfuncs.c @@ -2879,6 +2879,7 @@ _outRangeTblFunction(StringInfo str, const RangeTblFunction *node) WRITE_NODE_FIELD(funccoltypmods); WRITE_NODE_FIELD(funccolcollations); WRITE_BITMAPSET_FIELD(funcparams); + WRITE_BOOL_FIELD(funcasrecord); } static void @@ -3148,6 +3149,16 @@ _outRangeFunction(StringInfo str, const RangeFunction *node) } static void +_outRangeFunctionElem(StringInfo str, const RangeFunctionElem *node) +{ + WRITE_NODE_TYPE("RANGEFUNCTIONELEM"); + + WRITE_NODE_FIELD(func); + WRITE_BOOL_FIELD(coldeflist); + WRITE_BOOL_FIELD(asrecord); +} + +static void _outRangeTableSample(StringInfo str, const RangeTableSample *node) { WRITE_NODE_TYPE("RANGETABLESAMPLE"); @@ -3840,6 +3851,9 @@ outNode(StringInfo str, const void *obj) case T_RangeFunction: _outRangeFunction(str, obj); break; + case T_RangeFunctionElem: + _outRangeFunctionElem(str, obj); + break; case T_RangeTableSample: _outRangeTableSample(str, obj); break; diff --git a/src/backend/nodes/readfuncs.c b/src/backend/nodes/readfuncs.c index 6f9a81e..70bb73d 100644 --- a/src/backend/nodes/readfuncs.c +++ b/src/backend/nodes/readfuncs.c @@ -1357,6 +1357,7 @@ _readRangeTblFunction(void) READ_NODE_FIELD(funccoltypmods); READ_NODE_FIELD(funccolcollations); READ_BITMAPSET_FIELD(funcparams); + READ_BOOL_FIELD(funcasrecord); READ_DONE(); } diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 4496fde..3830bc9 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -4828,6 +4828,10 @@ inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte) return NULL; rtfunc = (RangeTblFunction *) linitial(rte->functions); + /* Fail if the function returns as record - we don't implement that here. */ + if (rtfunc->funcasrecord) + return NULL; + if (!IsA(rtfunc->funcexpr, FuncExpr)) return NULL; fexpr = (FuncExpr *) rtfunc->funcexpr; diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index cb5cfc4..183403f 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -441,11 +441,11 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query); a_expr b_expr c_expr AexprConst indirection_el opt_slice_bound columnref in_expr having_clause func_table array_expr ExclusionWhereClause -%type <list> rowsfrom_item rowsfrom_list opt_col_def_list +%type <list> rowsfrom_list %type <boolean> opt_ordinality %type <list> ExclusionConstraintList ExclusionConstraintElem %type <list> func_arg_list -%type <node> func_arg_expr +%type <node> func_arg_expr rowsfrom_item %type <list> row explicit_row implicit_row type_list array_expr_list %type <node> case_expr case_arg when_clause case_default %type <list> when_clause_list @@ -10980,10 +10980,17 @@ opt_repeatable_clause: func_table: func_expr_windowless opt_ordinality { RangeFunction *n = makeNode(RangeFunction); + RangeFunctionElem *e = makeNode(RangeFunctionElem); + n->lateral = false; n->ordinality = $2; n->is_rowsfrom = false; - n->functions = list_make1(list_make2($1, NIL)); + n->functions = list_make1(e); + + e->func = $1; + e->coldeflist = NIL; + e->asrecord = false; + /* alias and coldeflist are set by table_ref production */ $$ = (Node *) n; } @@ -10999,8 +11006,30 @@ func_table: func_expr_windowless opt_ordinality } ; -rowsfrom_item: func_expr_windowless opt_col_def_list - { $$ = list_make2($1, $2); } +rowsfrom_item: func_expr_windowless AS '(' TableFuncElementList ')' + { + RangeFunctionElem *n = makeNode(RangeFunctionElem); + n->func = $1; + n->coldeflist = $4; + n->asrecord = false; + $$ = (Node *) n; + } + | func_expr_windowless AS '(' ')' + { + RangeFunctionElem *n = makeNode(RangeFunctionElem); + n->func = $1; + n->coldeflist = NIL; + n->asrecord = true; + $$ = (Node *) n; + } + | func_expr_windowless + { + RangeFunctionElem *n = makeNode(RangeFunctionElem); + n->func = $1; + n->coldeflist = NIL; + n->asrecord = false; + $$ = (Node *) n; + } ; rowsfrom_list: @@ -11008,10 +11037,6 @@ rowsfrom_list: | rowsfrom_list ',' rowsfrom_item { $$ = lappend($1, $3); } ; -opt_col_def_list: AS '(' TableFuncElementList ')' { $$ = $3; } - | /*EMPTY*/ { $$ = NIL; } - ; - opt_ordinality: WITH_LA ORDINALITY { $$ = true; } | /*EMPTY*/ { $$ = false; } ; diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c index 9b7fcc3..e40954c 100644 --- a/src/backend/parser/parse_clause.c +++ b/src/backend/parser/parse_clause.c @@ -533,6 +533,7 @@ transformRangeFunction(ParseState *pstate, RangeFunction *r) List *funcexprs = NIL; List *funcnames = NIL; List *coldeflists = NIL; + List *asrecordlist = NIL; bool is_lateral; RangeTblEntry *rte; ListCell *lc; @@ -567,14 +568,9 @@ transformRangeFunction(ParseState *pstate, RangeFunction *r) */ foreach(lc, r->functions) { - List *pair = (List *) lfirst(lc); - Node *fexpr; - List *coldeflist; - - /* Disassemble the function-call/column-def-list pairs */ - Assert(list_length(pair) == 2); - fexpr = (Node *) linitial(pair); - coldeflist = (List *) lsecond(pair); + RangeFunctionElem *elem = (RangeFunctionElem *) lfirst(lc); + Node *fexpr = elem->func; + List *coldeflist = elem->coldeflist; /* * If we find a function call unnest() with more than one argument and @@ -630,6 +626,8 @@ transformRangeFunction(ParseState *pstate, RangeFunction *r) /* coldeflist is empty, so no error is possible */ coldeflists = lappend(coldeflists, coldeflist); + + asrecordlist = lappend_int(asrecordlist, false); } continue; /* done with this function item */ } @@ -651,6 +649,8 @@ transformRangeFunction(ParseState *pstate, RangeFunction *r) exprLocation((Node *) r->coldeflist)))); coldeflists = lappend(coldeflists, coldeflist); + + asrecordlist = lappend_int(asrecordlist, elem->asrecord); } pstate->p_lateral_active = false; @@ -713,7 +713,7 @@ transformRangeFunction(ParseState *pstate, RangeFunction *r) */ rte = addRangeTableEntryForFunction(pstate, funcnames, funcexprs, coldeflists, - r, is_lateral, true); + asrecordlist, r, is_lateral, true); return rte; } diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 1e3ecbc..0d92a00 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -1382,6 +1382,7 @@ addRangeTableEntryForFunction(ParseState *pstate, List *funcnames, List *funcexprs, List *coldeflists, + List *asrecordlist, RangeFunction *rangefunc, bool lateral, bool inFromCl) @@ -1395,7 +1396,8 @@ addRangeTableEntryForFunction(ParseState *pstate, TupleDesc tupdesc; ListCell *lc1, *lc2, - *lc3; + *lc3, + *lc4; int i; int j; int funcno; @@ -1429,11 +1431,12 @@ addRangeTableEntryForFunction(ParseState *pstate, totalatts = 0; funcno = 0; - forthree(lc1, funcexprs, lc2, funcnames, lc3, coldeflists) + forfour(lc1, funcexprs, lc2, funcnames, lc3, coldeflists, lc4, asrecordlist) { Node *funcexpr = (Node *) lfirst(lc1); char *funcname = (char *) lfirst(lc2); List *coldeflist = (List *) lfirst(lc3); + int asrecord = lfirst_int(lc4); RangeTblFunction *rtfunc = makeNode(RangeTblFunction); TypeFuncClass functypclass; Oid funcrettype; @@ -1445,6 +1448,7 @@ addRangeTableEntryForFunction(ParseState *pstate, rtfunc->funccoltypmods = NIL; rtfunc->funccolcollations = NIL; rtfunc->funcparams = NULL; /* not set until planning */ + rtfunc->funcasrecord = asrecord; /* * Now determine if the function returns a simple or composite type. @@ -1453,6 +1457,15 @@ addRangeTableEntryForFunction(ParseState *pstate, &funcrettype, &tupdesc); + if (asrecord && functypclass != TYPEFUNC_RECORD && functypclass != TYPEFUNC_COMPOSITE) + { + ereport(ERROR, + (errcode(ERRCODE_SYNTAX_ERROR), + errmsg("only composite and \"record\" returning functions can be returned as record"), + parser_errposition(pstate, + exprLocation(funcexpr)))); + } + /* * A coldeflist is required if the function returns RECORD and hasn't * got a predetermined record type, and is prohibited otherwise. @@ -1466,16 +1479,26 @@ addRangeTableEntryForFunction(ParseState *pstate, parser_errposition(pstate, exprLocation((Node *) coldeflist)))); } - else + else if (functypclass == TYPEFUNC_RECORD && !asrecord) { - if (functypclass == TYPEFUNC_RECORD) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("a column definition list is required for functions returning \"record\""), parser_errposition(pstate, exprLocation(funcexpr)))); } - if (functypclass == TYPEFUNC_COMPOSITE) + if (asrecord) + { + tupdesc = CreateTemplateTupleDesc(1, false); + TupleDescInitEntry(tupdesc, + (AttrNumber) 1, + chooseScalarFunctionAlias(funcexpr, funcname, + alias, nfuncs), + funcrettype, + -1, + 0); + } + else if (functypclass == TYPEFUNC_COMPOSITE) { /* Composite data type, e.g. a table's row type */ Assert(tupdesc); @@ -2052,7 +2075,29 @@ expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, functypclass = get_expr_result_type(rtfunc->funcexpr, &funcrettype, &tupdesc); - if (functypclass == TYPEFUNC_COMPOSITE) + + if (rtfunc->funcasrecord) + { + /* Base data type, i.e. scalar */ + if (colnames) + *colnames = lappend(*colnames, + list_nth(rte->eref->colnames, + atts_done)); + + if (colvars) + { + Var *varnode; + + varnode = makeVar(rtindex, atts_done + 1, + funcrettype, -1, + exprCollation(rtfunc->funcexpr), + sublevels_up); + varnode->location = location; + + *colvars = lappend(*colvars, varnode); + } + } + else if (functypclass == TYPEFUNC_COMPOSITE) { /* Composite data type, e.g. a table's row type */ Assert(tupdesc); @@ -2585,7 +2630,14 @@ get_rte_attribute_type(RangeTblEntry *rte, AttrNumber attnum, &funcrettype, &tupdesc); - if (functypclass == TYPEFUNC_COMPOSITE) + if (rtfunc->funcasrecord) + { + /* XXX */ + *vartype = funcrettype; + *vartypmod = -1; + *varcollid = exprCollation(rtfunc->funcexpr); + } + else if (functypclass == TYPEFUNC_COMPOSITE) { /* Composite data type, e.g. a table's row type */ Form_pg_attribute att_tup; diff --git a/src/include/nodes/nodes.h b/src/include/nodes/nodes.h index 2f7efa8..7d7bd91 100644 --- a/src/include/nodes/nodes.h +++ b/src/include/nodes/nodes.h @@ -427,6 +427,7 @@ typedef enum NodeTag T_WindowDef, T_RangeSubselect, T_RangeFunction, + T_RangeFunctionElem, T_RangeTableSample, T_TypeName, T_ColumnDef, diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index 1481fff..f26e651 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -522,12 +522,9 @@ typedef struct RangeSubselect /* * RangeFunction - function call appearing in a FROM clause * - * functions is a List because we use this to represent the construct - * ROWS FROM(func1(...), func2(...), ...). Each element of this list is a - * two-element sublist, the first element being the untransformed function - * call tree, and the second element being a possibly-empty list of ColumnDef - * nodes representing any columndef list attached to that function within the - * ROWS FROM() syntax. + * functions is a List because we use this to represent the construct ROWS + * FROM(func1(...), func2(...), ...). Each element of this list a + * RangeFunctionElem pointer. * * alias and coldeflist represent any alias and/or columndef list attached * at the top level. (We disallow coldeflist appearing both here and @@ -546,6 +543,17 @@ typedef struct RangeFunction } RangeFunction; /* + * RangeFunctionElem - individual function call in RangeFunction + */ +typedef struct RangeFunctionElem +{ + NodeTag type; + Node *func; /* untransformed function call */ + List *coldeflist; /* optional coldef list inside ROWS FROM */ + bool asrecord; /* record returned as one column */ +} RangeFunctionElem; + +/* * RangeTableSample - TABLESAMPLE appearing in a raw FROM clause * * This node, appearing only in raw parse trees, represents @@ -902,6 +910,7 @@ typedef struct RangeTblFunction List *funccolcollations; /* OID list of column collation OIDs */ /* This is set during planning for use by the executor: */ Bitmapset *funcparams; /* PARAM_EXEC Param IDs affecting this func */ + bool funcasrecord; /* return results as a single record column */ } RangeTblFunction; /* diff --git a/src/include/nodes/pg_list.h b/src/include/nodes/pg_list.h index 77b50ff..b6b57c1 100644 --- a/src/include/nodes/pg_list.h +++ b/src/include/nodes/pg_list.h @@ -185,6 +185,15 @@ list_length(const List *l) (cell1) != NULL && (cell2) != NULL && (cell3) != NULL; \ (cell1) = lnext(cell1), (cell2) = lnext(cell2), (cell3) = lnext(cell3)) +/* + * fortfour - + * the same for four lists + */ +#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4) \ + for ((cell1) = list_head(list1), (cell2) = list_head(list2), (cell3) = list_head(list3), (cell4) = list_head(list4); \ + (cell1) != NULL && (cell2) != NULL && (cell3) != NULL && (cell4) != NULL; \ + (cell1) = lnext(cell1), (cell2) = lnext(cell2), (cell3) = lnext(cell3), (cell4) = lnext(cell4)) + extern List *lappend(List *list, void *datum); extern List *lappend_int(List *list, int datum); extern List *lappend_oid(List *list, Oid datum); diff --git a/src/include/parser/parse_relation.h b/src/include/parser/parse_relation.h index 3ef3d7b..90af146 100644 --- a/src/include/parser/parse_relation.h +++ b/src/include/parser/parse_relation.h @@ -80,6 +80,7 @@ extern RangeTblEntry *addRangeTableEntryForFunction(ParseState *pstate, List *funcnames, List *funcexprs, List *coldeflists, + List *asrecordlist, RangeFunction *rangefunc, bool lateral, bool inFromCl); diff --git a/src/test/regress/expected/rangefuncs.out b/src/test/regress/expected/rangefuncs.out index a6496fc..249dc67 100644 --- a/src/test/regress/expected/rangefuncs.out +++ b/src/test/regress/expected/rangefuncs.out @@ -369,6 +369,10 @@ SELECT * FROM getfoo1(1) WITH ORDINALITY AS t1(v,o); 1 | 1 (1 row) +SELECT * FROM ROWS FROM( getfoo1(1) AS ()) AS t1; -- error, not a composite / record +ERROR: only composite and "record" returning functions can be returned as record +LINE 1: SELECT * FROM ROWS FROM( getfoo1(1) AS ()) AS t1; + ^ CREATE VIEW vw_getfoo AS SELECT * FROM getfoo1(1); SELECT * FROM vw_getfoo; getfoo1 @@ -401,6 +405,10 @@ SELECT * FROM getfoo2(1) WITH ORDINALITY AS t1(v,o); 1 | 2 (2 rows) +SELECT * FROM ROWS FROM( getfoo2(1) AS ()) AS t1; -- error, not a composite / record +ERROR: only composite and "record" returning functions can be returned as record +LINE 1: SELECT * FROM ROWS FROM( getfoo2(1) AS ()) AS t1; + ^ CREATE VIEW vw_getfoo AS SELECT * FROM getfoo2(1); SELECT * FROM vw_getfoo; getfoo2 @@ -435,6 +443,10 @@ SELECT * FROM getfoo3(1) WITH ORDINALITY AS t1(v,o); Ed | 2 (2 rows) +SELECT * FROM ROWS FROM( getfoo3(1) AS ()) AS t1; -- error, not a composite / record +ERROR: only composite and "record" returning functions can be returned as record +LINE 1: SELECT * FROM ROWS FROM( getfoo3(1) AS ()) AS t1; + ^ CREATE VIEW vw_getfoo AS SELECT * FROM getfoo3(1); SELECT * FROM vw_getfoo; getfoo3 @@ -461,12 +473,24 @@ SELECT * FROM getfoo4(1) AS t1; 1 | 1 | Joe (1 row) +SELECT * FROM ROWS FROM( getfoo4(1) AS ()) AS t1; + t1 +----------- + (1,1,Joe) +(1 row) + SELECT * FROM getfoo4(1) WITH ORDINALITY AS t1(a,b,c,o); a | b | c | o ---+---+-----+--- 1 | 1 | Joe | 1 (1 row) +SELECT * FROM ROWS FROM( getfoo4(1) AS ()) WITH ORDINALITY AS t1(abc,o); + abc | o +-----------+--- + (1,1,Joe) | 1 +(1 row) + CREATE VIEW vw_getfoo AS SELECT * FROM getfoo4(1); SELECT * FROM vw_getfoo; fooid | foosubid | fooname @@ -492,6 +516,13 @@ SELECT * FROM getfoo5(1) AS t1; 1 | 2 | Ed (2 rows) +SELECT * FROM ROWS FROM(getfoo5(1) AS ()) AS t1; + t1 +----------- + (1,1,Joe) + (1,2,Ed) +(2 rows) + SELECT * FROM getfoo5(1) WITH ORDINALITY AS t1(a,b,c,o); a | b | c | o ---+---+-----+--- @@ -499,6 +530,13 @@ SELECT * FROM getfoo5(1) WITH ORDINALITY AS t1(a,b,c,o); 1 | 2 | Ed | 2 (2 rows) +SELECT * FROM ROWS FROM(getfoo5(1) AS ()) WITH ORDINALITY AS t1(abc,o); + abc | o +-----------+--- + (1,1,Joe) | 1 + (1,2,Ed) | 2 +(2 rows) + CREATE VIEW vw_getfoo AS SELECT * FROM getfoo5(1); SELECT * FROM vw_getfoo; fooid | foosubid | fooname @@ -525,12 +563,24 @@ SELECT * FROM getfoo6(1) AS t1(fooid int, foosubid int, fooname text); 1 | 1 | Joe (1 row) +SELECT * FROM ROWS FROM( getfoo6(1) AS ()) AS t1; + t1 +----------- + (1,1,Joe) +(1 row) + SELECT * FROM ROWS FROM( getfoo6(1) AS (fooid int, foosubid int, fooname text) ) WITH ORDINALITY; fooid | foosubid | fooname | ordinality -------+----------+---------+------------ 1 | 1 | Joe | 1 (1 row) +SELECT * FROM ROWS FROM( getfoo6(1) AS ()) WITH ORDINALITY; + getfoo6 | ordinality +-----------+------------ + (1,1,Joe) | 1 +(1 row) + CREATE VIEW vw_getfoo AS SELECT * FROM getfoo6(1) AS (fooid int, foosubid int, fooname text); SELECT * FROM vw_getfoo; @@ -559,6 +609,13 @@ SELECT * FROM getfoo7(1) AS t1(fooid int, foosubid int, fooname text); 1 | 2 | Ed (2 rows) +SELECT * FROM ROWS FROM( getfoo7(1) AS ()) AS t1; + t1 +----------- + (1,1,Joe) + (1,2,Ed) +(2 rows) + SELECT * FROM ROWS FROM( getfoo7(1) AS (fooid int, foosubid int, fooname text) ) WITH ORDINALITY; fooid | foosubid | fooname | ordinality -------+----------+---------+------------ @@ -566,6 +623,13 @@ SELECT * FROM ROWS FROM( getfoo7(1) AS (fooid int, foosubid int, fooname text) ) 1 | 2 | Ed | 2 (2 rows) +SELECT * FROM ROWS FROM( getfoo7(1) AS ()) WITH ORDINALITY; + getfoo7 | ordinality +-----------+------------ + (1,1,Joe) | 1 + (1,2,Ed) | 2 +(2 rows) + CREATE VIEW vw_getfoo AS SELECT * FROM getfoo7(1) AS (fooid int, foosubid int, fooname text); SELECT * FROM vw_getfoo; @@ -601,6 +665,10 @@ SELECT * FROM getfoo8(1) WITH ORDINALITY AS t1(v,o); 1 | 1 (1 row) +SELECT * FROM ROWS FROM( getfoo8(1) AS ()) AS t1; -- error, not a composite / record +ERROR: only composite and "record" returning functions can be returned as record +LINE 1: SELECT * FROM ROWS FROM( getfoo8(1) AS ()) AS t1; + ^ CREATE VIEW vw_getfoo AS SELECT * FROM getfoo8(1); SELECT * FROM vw_getfoo; getfoo8 @@ -631,6 +699,12 @@ SELECT * FROM getfoo9(1) WITH ORDINALITY AS t1(a,b,c,o); 1 | 1 | Joe | 1 (1 row) +SELECT * FROM ROWS FROM( getfoo9(1) AS ()) AS t1; + t1 +----------- + (1,1,Joe) +(1 row) + CREATE VIEW vw_getfoo AS SELECT * FROM getfoo9(1); SELECT * FROM vw_getfoo; fooid | foosubid | fooname @@ -670,6 +744,17 @@ select * from rows from(getfoo9(1),getfoo8(1), | | | | 1 | 2 | Ed | | | | 1 | 2 | Ed | | | | Ed | 1 | | 2 (2 rows) +select * from rows from(getfoo9(1),getfoo8(1), + getfoo7(1) AS (fooid int, foosubid int, fooname text), + getfoo6(1) AS (), + getfoo5(1),getfoo4(1),getfoo3(1),getfoo2(1),getfoo1(1)) + with ordinality as t1(a,b,c,d,e,f,g,h,k,l,m,o,p,q,r,s,t,u); + a | b | c | d | e | f | g | h | k | l | m | o | p | q | r | s | t | u +---+---+-----+---+---+---+-----+-----------+---+---+-----+---+---+-----+-----+---+---+--- + 1 | 1 | Joe | 1 | 1 | 1 | Joe | (1,1,Joe) | 1 | 1 | Joe | 1 | 1 | Joe | Joe | 1 | 1 | 1 + | | | | 1 | 2 | Ed | | 1 | 2 | Ed | | | | Ed | 1 | | 2 +(2 rows) + create temporary view vw_foo as select * from rows from(getfoo9(1), getfoo7(1) AS (fooid int, foosubid int, fooname text), diff --git a/src/test/regress/sql/rangefuncs.sql b/src/test/regress/sql/rangefuncs.sql index c8edc55..b43473a 100644 --- a/src/test/regress/sql/rangefuncs.sql +++ b/src/test/regress/sql/rangefuncs.sql @@ -93,6 +93,7 @@ INSERT INTO foo VALUES(2,1,'Mary'); CREATE FUNCTION getfoo1(int) RETURNS int AS 'SELECT $1;' LANGUAGE SQL; SELECT * FROM getfoo1(1) AS t1; SELECT * FROM getfoo1(1) WITH ORDINALITY AS t1(v,o); +SELECT * FROM ROWS FROM( getfoo1(1) AS ()) AS t1; -- error, not a composite / record CREATE VIEW vw_getfoo AS SELECT * FROM getfoo1(1); SELECT * FROM vw_getfoo; DROP VIEW vw_getfoo; @@ -104,6 +105,7 @@ DROP VIEW vw_getfoo; CREATE FUNCTION getfoo2(int) RETURNS setof int AS 'SELECT fooid FROM foo WHERE fooid = $1;' LANGUAGE SQL; SELECT * FROM getfoo2(1) AS t1; SELECT * FROM getfoo2(1) WITH ORDINALITY AS t1(v,o); +SELECT * FROM ROWS FROM( getfoo2(1) AS ()) AS t1; -- error, not a composite / record CREATE VIEW vw_getfoo AS SELECT * FROM getfoo2(1); SELECT * FROM vw_getfoo; DROP VIEW vw_getfoo; @@ -115,6 +117,7 @@ DROP VIEW vw_getfoo; CREATE FUNCTION getfoo3(int) RETURNS setof text AS 'SELECT fooname FROM foo WHERE fooid = $1;' LANGUAGE SQL; SELECT * FROM getfoo3(1) AS t1; SELECT * FROM getfoo3(1) WITH ORDINALITY AS t1(v,o); +SELECT * FROM ROWS FROM( getfoo3(1) AS ()) AS t1; -- error, not a composite / record CREATE VIEW vw_getfoo AS SELECT * FROM getfoo3(1); SELECT * FROM vw_getfoo; DROP VIEW vw_getfoo; @@ -125,7 +128,9 @@ DROP VIEW vw_getfoo; -- sql, proretset = f, prorettype = c CREATE FUNCTION getfoo4(int) RETURNS foo AS 'SELECT * FROM foo WHERE fooid = $1;' LANGUAGE SQL; SELECT * FROM getfoo4(1) AS t1; +SELECT * FROM ROWS FROM( getfoo4(1) AS ()) AS t1; SELECT * FROM getfoo4(1) WITH ORDINALITY AS t1(a,b,c,o); +SELECT * FROM ROWS FROM( getfoo4(1) AS ()) WITH ORDINALITY AS t1(abc,o); CREATE VIEW vw_getfoo AS SELECT * FROM getfoo4(1); SELECT * FROM vw_getfoo; DROP VIEW vw_getfoo; @@ -136,7 +141,9 @@ DROP VIEW vw_getfoo; -- sql, proretset = t, prorettype = c CREATE FUNCTION getfoo5(int) RETURNS setof foo AS 'SELECT * FROM foo WHERE fooid = $1;' LANGUAGE SQL; SELECT * FROM getfoo5(1) AS t1; +SELECT * FROM ROWS FROM(getfoo5(1) AS ()) AS t1; SELECT * FROM getfoo5(1) WITH ORDINALITY AS t1(a,b,c,o); +SELECT * FROM ROWS FROM(getfoo5(1) AS ()) WITH ORDINALITY AS t1(abc,o); CREATE VIEW vw_getfoo AS SELECT * FROM getfoo5(1); SELECT * FROM vw_getfoo; DROP VIEW vw_getfoo; @@ -147,7 +154,9 @@ DROP VIEW vw_getfoo; -- sql, proretset = f, prorettype = record CREATE FUNCTION getfoo6(int) RETURNS RECORD AS 'SELECT * FROM foo WHERE fooid = $1;' LANGUAGE SQL; SELECT * FROM getfoo6(1) AS t1(fooid int, foosubid int, fooname text); +SELECT * FROM ROWS FROM( getfoo6(1) AS ()) AS t1; SELECT * FROM ROWS FROM( getfoo6(1) AS (fooid int, foosubid int, fooname text) ) WITH ORDINALITY; +SELECT * FROM ROWS FROM( getfoo6(1) AS ()) WITH ORDINALITY; CREATE VIEW vw_getfoo AS SELECT * FROM getfoo6(1) AS (fooid int, foosubid int, fooname text); SELECT * FROM vw_getfoo; @@ -161,7 +170,9 @@ DROP VIEW vw_getfoo; -- sql, proretset = t, prorettype = record CREATE FUNCTION getfoo7(int) RETURNS setof record AS 'SELECT * FROM foo WHERE fooid = $1;' LANGUAGE SQL; SELECT * FROM getfoo7(1) AS t1(fooid int, foosubid int, fooname text); +SELECT * FROM ROWS FROM( getfoo7(1) AS ()) AS t1; SELECT * FROM ROWS FROM( getfoo7(1) AS (fooid int, foosubid int, fooname text) ) WITH ORDINALITY; +SELECT * FROM ROWS FROM( getfoo7(1) AS ()) WITH ORDINALITY; CREATE VIEW vw_getfoo AS SELECT * FROM getfoo7(1) AS (fooid int, foosubid int, fooname text); SELECT * FROM vw_getfoo; @@ -176,6 +187,7 @@ DROP VIEW vw_getfoo; CREATE FUNCTION getfoo8(int) RETURNS int AS 'DECLARE fooint int; BEGIN SELECT fooid into fooint FROM foo WHERE fooid = $1; RETURN fooint; END;' LANGUAGE plpgsql; SELECT * FROM getfoo8(1) AS t1; SELECT * FROM getfoo8(1) WITH ORDINALITY AS t1(v,o); +SELECT * FROM ROWS FROM( getfoo8(1) AS ()) AS t1; -- error, not a composite / record CREATE VIEW vw_getfoo AS SELECT * FROM getfoo8(1); SELECT * FROM vw_getfoo; DROP VIEW vw_getfoo; @@ -187,6 +199,7 @@ DROP VIEW vw_getfoo; CREATE FUNCTION getfoo9(int) RETURNS foo AS 'DECLARE footup foo%ROWTYPE; BEGIN SELECT * into footup FROM foo WHERE fooid = $1; RETURN footup; END;' LANGUAGE plpgsql; SELECT * FROM getfoo9(1) AS t1; SELECT * FROM getfoo9(1) WITH ORDINALITY AS t1(a,b,c,o); +SELECT * FROM ROWS FROM( getfoo9(1) AS ()) AS t1; CREATE VIEW vw_getfoo AS SELECT * FROM getfoo9(1); SELECT * FROM vw_getfoo; DROP VIEW vw_getfoo; @@ -206,6 +219,11 @@ select * from rows from(getfoo9(1),getfoo8(1), getfoo6(1) AS (fooid int, foosubid int, fooname text), getfoo5(1),getfoo4(1),getfoo3(1),getfoo2(1),getfoo1(1)) with ordinality as t1(a,b,c,d,e,f,g,h,i,j,k,l,m,o,p,q,r,s,t,u); +select * from rows from(getfoo9(1),getfoo8(1), + getfoo7(1) AS (fooid int, foosubid int, fooname text), + getfoo6(1) AS (), + getfoo5(1),getfoo4(1),getfoo3(1),getfoo2(1),getfoo1(1)) + with ordinality as t1(a,b,c,d,e,f,g,h,k,l,m,o,p,q,r,s,t,u); create temporary view vw_foo as select * from rows from(getfoo9(1), -- 2.9.3
0005-Basic-implementation-of-targetlist-SRFs-via-ROWS-FRO.patch (text/x-patch, 42.8K) download From f18baaeb55803c179e54a4c592532ed27cf8a815 Mon Sep 17 00:00:00 2001 From: Andres Freund <andres@anarazel.de> Date: Fri, 29 Jul 2016 18:51:02 -0700 Subject: [PATCH 5/6] Basic implementation of targetlist SRFs via ROWS FROM. --- src/backend/executor/execQual.c | 7 + src/backend/nodes/copyfuncs.c | 2 + src/backend/nodes/equalfuncs.c | 2 + src/backend/nodes/outfuncs.c | 2 + src/backend/nodes/readfuncs.c | 2 + src/backend/optimizer/plan/initsplan.c | 4 + src/backend/optimizer/plan/planner.c | 8 + src/backend/optimizer/prep/prepjointree.c | 4 + src/backend/optimizer/util/clauses.c | 549 ++++++++++++++++++++++++++++++ src/backend/parser/analyze.c | 10 + src/backend/parser/parse_func.c | 5 + src/backend/parser/parse_oper.c | 5 + src/include/nodes/parsenodes.h | 6 +- src/include/optimizer/clauses.h | 2 + src/include/parser/parse_node.h | 1 + src/test/regress/expected/aggregates.out | 21 +- src/test/regress/expected/limit.out | 72 ++-- src/test/regress/expected/portals.out | 12 +- src/test/regress/expected/rangefuncs.out | 10 +- src/test/regress/expected/subselect.out | 29 +- src/test/regress/expected/tsrf.out | 15 +- src/test/regress/expected/union.out | 8 +- src/test/regress/output/misc.source | 18 +- 23 files changed, 716 insertions(+), 78 deletions(-) diff --git a/src/backend/executor/execQual.c b/src/backend/executor/execQual.c index 79589d0..d9e2797 100644 --- a/src/backend/executor/execQual.c +++ b/src/backend/executor/execQual.c @@ -2074,6 +2074,13 @@ ExecEvalFunc(FuncExprState *fcache, ExecInitFcache(func->funcid, func->inputcollid, fcache, econtext->ecxt_per_query_memory, true); + if (fcache->func.fn_retset) + { + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("set-valued function called in context that cannot accept a set"))); + } + /* * We need to invoke ExecMakeFunctionResult if either the function itself * or any of its input expressions can return a set. Otherwise, invoke diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c index 292ab6c..589fc27 100644 --- a/src/backend/nodes/copyfuncs.c +++ b/src/backend/nodes/copyfuncs.c @@ -2167,6 +2167,7 @@ _copyRangeTblEntry(const RangeTblEntry *from) COPY_BITMAPSET_FIELD(insertedCols); COPY_BITMAPSET_FIELD(updatedCols); COPY_NODE_FIELD(securityQuals); + COPY_NODE_FIELD(deps); return newnode; } @@ -2749,6 +2750,7 @@ _copyQuery(const Query *from) COPY_SCALAR_FIELD(hasModifyingCTE); COPY_SCALAR_FIELD(hasForUpdate); COPY_SCALAR_FIELD(hasRowSecurity); + COPY_SCALAR_FIELD(hasTargetSRF); COPY_NODE_FIELD(cteList); COPY_NODE_FIELD(rtable); COPY_NODE_FIELD(jointree); diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c index f69dc8e..b24e623 100644 --- a/src/backend/nodes/equalfuncs.c +++ b/src/backend/nodes/equalfuncs.c @@ -927,6 +927,7 @@ _equalQuery(const Query *a, const Query *b) COMPARE_SCALAR_FIELD(hasModifyingCTE); COMPARE_SCALAR_FIELD(hasForUpdate); COMPARE_SCALAR_FIELD(hasRowSecurity); + COMPARE_SCALAR_FIELD(hasTargetSRF); COMPARE_NODE_FIELD(cteList); COMPARE_NODE_FIELD(rtable); COMPARE_NODE_FIELD(jointree); @@ -2480,6 +2481,7 @@ _equalRangeTblEntry(const RangeTblEntry *a, const RangeTblEntry *b) COMPARE_BITMAPSET_FIELD(insertedCols); COMPARE_BITMAPSET_FIELD(updatedCols); COMPARE_NODE_FIELD(securityQuals); + COMPARE_NODE_FIELD(deps); return true; } diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c index bea295b..86cd575 100644 --- a/src/backend/nodes/outfuncs.c +++ b/src/backend/nodes/outfuncs.c @@ -2688,6 +2688,7 @@ _outQuery(StringInfo str, const Query *node) WRITE_BOOL_FIELD(hasModifyingCTE); WRITE_BOOL_FIELD(hasForUpdate); WRITE_BOOL_FIELD(hasRowSecurity); + WRITE_BOOL_FIELD(hasTargetSRF); WRITE_NODE_FIELD(cteList); WRITE_NODE_FIELD(rtable); WRITE_NODE_FIELD(jointree); @@ -2865,6 +2866,7 @@ _outRangeTblEntry(StringInfo str, const RangeTblEntry *node) WRITE_BITMAPSET_FIELD(insertedCols); WRITE_BITMAPSET_FIELD(updatedCols); WRITE_NODE_FIELD(securityQuals); + WRITE_NODE_FIELD(deps); } static void diff --git a/src/backend/nodes/readfuncs.c b/src/backend/nodes/readfuncs.c index 70bb73d..174b02f 100644 --- a/src/backend/nodes/readfuncs.c +++ b/src/backend/nodes/readfuncs.c @@ -244,6 +244,7 @@ _readQuery(void) READ_BOOL_FIELD(hasModifyingCTE); READ_BOOL_FIELD(hasForUpdate); READ_BOOL_FIELD(hasRowSecurity); + READ_BOOL_FIELD(hasTargetSRF); READ_NODE_FIELD(cteList); READ_NODE_FIELD(rtable); READ_NODE_FIELD(jointree); @@ -1338,6 +1339,7 @@ _readRangeTblEntry(void) READ_BITMAPSET_FIELD(insertedCols); READ_BITMAPSET_FIELD(updatedCols); READ_NODE_FIELD(securityQuals); + READ_NODE_FIELD(deps); READ_DONE(); } diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index 84ce6b3..ada34cc 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -339,6 +339,10 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) return; /* keep compiler quiet */ } + /* DIRTY hack time, add dependency for targetlist SRFs */ + vars = list_concat(vars, + pull_vars_of_level((Node *) rte->deps, 0)); + if (vars == NIL) return; /* nothing to do */ diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 174210b..986c92b 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -505,6 +505,14 @@ subquery_planner(PlannerGlobal *glob, Query *parse, root->non_recursive_path = NULL; /* + * Convert SRFs in targetlist into FUNCTION rtes. As this, if applicable, + * will move the main portion of the query into a subselect, this has to + * be done early on in subquery_planner(). + */ + if (parse->hasTargetSRF) + unsrfify(root); + + /* * If there is a WITH list, process each WITH query and build an initplan * SubPlan structure for it. */ diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index a334f15..0e06a98 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -1982,6 +1982,10 @@ replace_vars_in_jointree(Node *jtnode, Assert(false); break; } + + rte->deps = (List *) + pullup_replace_vars((Node *) rte->deps, + context); } } } diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 3830bc9..9c502bd 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -36,6 +36,7 @@ #include "optimizer/cost.h" #include "optimizer/planmain.h" #include "optimizer/prep.h" +#include "optimizer/tlist.h" #include "optimizer/var.h" #include "parser/analyze.h" #include "parser/parse_agg.h" @@ -95,6 +96,30 @@ typedef struct char max_interesting; /* worst proparallel hazard of interest */ } max_parallel_hazard_context; +typedef struct unsrfify_context +{ + PlannerInfo *root; + /* query being converted */ + Query *outer_query; + /* created subquery */ + Query *inner_query; + /* RT index of the above */ + Index subquery_rti; + + /* targetlist of the new subquery */ + List *subquery_tlist; + List *subquery_colnames; + + /* RTE for the currently generated function RTE */ + RangeTblEntry *currte; + Index currti; /* and it's RT index */ + /* current column number in function RTE */ + int coloff; + + /* current target's resname during expression iteration */ + char *current_resname; +} unsrfify_context; + static bool contain_agg_clause_walker(Node *node, void *context); static bool get_agg_clause_costs_walker(Node *node, get_agg_clause_costs_context *context); @@ -2390,6 +2415,530 @@ rowtype_field_matches(Oid rowtypeid, int fieldnum, return true; } +/* + * Push down expression into the subquery, return resno of targetlist entry. + */ +static int +unsrfify_push_expr_to_subquery(Expr *expr, Index sortgroupref, + unsrfify_context *context) +{ + ListCell *tc; + int resno = 1; + char *resname = context->current_resname; + TargetEntry *new_te; + + /* + * Check whether we already moved this expression to subquery, if so, + * reuse. + */ + foreach(tc, context->subquery_tlist) + { + TargetEntry *te = (TargetEntry *) lfirst(tc); + Expr *oldexpr = te->expr; + + if (equal(oldexpr, expr)) + { + if (sortgroupref > 0) + { + if (te->ressortgroupref != sortgroupref && + te->ressortgroupref > 0) + { + /* FIXME: might happen with duplicate expressions? */ + elog(ERROR, "non-unique ressortgroupref?"); + } + else + { + te->ressortgroupref = sortgroupref; + return resno; + } + } + return resno; + } + resno++; + } + + /* XXX */ + if (!resname) + resname = "..."; + + Assert(resno == list_length(context->subquery_tlist) + 1); + + new_te = makeTargetEntry((Expr *) copyObject(expr), + resno, resname , false); + new_te->ressortgroupref = sortgroupref; + context->subquery_tlist = lappend(context->subquery_tlist, new_te); + context->subquery_colnames = lappend(context->subquery_colnames, + makeString(context->current_resname)); + + return resno; +} + +/* + * Change target list to reference subquery. + * + * TargetEntry's that dont't contain a set returning function are pushed down + * entirely, others are modified to have relevant expressions refer to (new) + * entries in the subquery targetlist. + */ +static Node * +unsrfify_reference_subquery_mutator(Node *node, unsrfify_context *context) +{ + check_stack_depth(); + + if (node == NULL) + return NULL; + + switch (nodeTag(node)) + { + case T_TargetEntry: + { + TargetEntry *te = (TargetEntry *) node; + + /* + * Note that we're intentionally pushing down sortgrouprefs, + * that way grouping et al will work. It's more than a bit + * debatable though to do this unconditionally: We'll + * currently end up with sortgrouprefs in both top-level and + * subquery. + */ + + /* XXX: naming here isn't great */ + if (!te->resname) + context->current_resname = "..."; + else + context->current_resname = pstrdup(te->resname); + + /* if expression doesn't return set, push down entirely */ + if (!expression_returns_set((Node *) te->expr)) + { + AttrNumber resno = + unsrfify_push_expr_to_subquery(te->expr, + te->ressortgroupref, + context); + te = flatCopyTargetEntry(te); + + te->expr = (Expr *) makeVar(context->subquery_rti, + resno, + exprType((Node *) te->expr), + exprTypmod((Node *) te->expr), + exprCollation((Node *) te->expr), + 0); + } + else + { + te = (TargetEntry *) + expression_tree_mutator((Node *) te, + unsrfify_reference_subquery_mutator, + (void *) context); + } + + context->current_resname = NULL; + return (Node *) te; + } + break; + /* Anything additional? */ + case T_Var: + case T_Aggref: + case T_GroupingFunc: + case T_WindowFunc: + case T_Param /* ? */: + /* + * Vars, aggrefs, groupingfuncs, ... come from the subquery in + * which the main query is being moved. For each reference in the + * main targetlist - containing the reference to the SRF and such + * - move the underlying clause as a separate TargetEntry into the + * subquery, and reference that. + * + * Note that varlevelsup for expressions in the subquery is later + * adjusted with IncrementVarSublevelsUp, together with the other + * expressions in the subquery. + */ + { + AttrNumber resno = + unsrfify_push_expr_to_subquery((Expr *) node, 0, context); + + return (Node *) makeVar(context->subquery_rti, + resno, + exprType(node), + exprTypmod(node), + exprCollation(node), + 0); + } + return node; + default: + break; + } + + return expression_tree_mutator(node, unsrfify_reference_subquery_mutator, + (void *) context); +} + +static Node * +unsrfify_implement_srfs_mutator(Node *node, unsrfify_context *context) +{ + check_stack_depth(); + + if (node == NULL) + return NULL; + switch (nodeTag(node)) + { + case T_OpExpr: + { + OpExpr *expr = (OpExpr *) node; + + if (expr->opretset) + { + /* + * TODO: Hrmpf, implement. And why is there not a single + * test for this :( + */ + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("XXX: SETOF record returning operators are not supported"))); + } + } + break; + + case T_FuncExpr: + { + FuncExpr *expr = (FuncExpr *) node; + + /* + * For set returning functions, move them to the current + * level's ROWS FROM expression, and add a Var referencing + * that expressions result. + */ + if (expr->funcretset) + { + RangeTblEntry *old_currte; + Index old_currti; + int old_coloff; + + /* + * Process set-returning arguments to set-returning + * functions as a separate ROWS FROM expression, again + * laterally joined to this. + */ + old_currte = context->currte; + old_currti = context->currti; + old_coloff = context->coloff; + + context->currte = NULL; + context->currti = 0; + context->coloff = 0; + + expr->args = (List *) + expression_tree_mutator((Node *) expr->args, + unsrfify_implement_srfs_mutator, + (void *) context); + context->currte = old_currte; + context->currti = old_currti; + context->coloff = old_coloff; + + } + else + { + expr->args = (List *) + expression_tree_mutator((Node *) expr->args, + unsrfify_implement_srfs_mutator, + (void *) context); + } + + if (expr->funcretset) + { + RangeTblEntry *rte; + RangeTblFunction *rtfunc; + RangeTblRef *rtf; + Index rti; + Oid funcrettype; + /* FIXME: used in places it shouldn't */ + char *funcname = get_func_name(expr->funcid); + bool asrecord; + + funcrettype = exprType(node); + + asrecord = type_is_rowtype(funcrettype); + + if (context->currte == NULL) + { + Alias *eref; + + rte = makeNode(RangeTblEntry); + rte->rtekind = RTE_FUNCTION; + rte->lateral = true; + rte->inh = false; + rte->inFromCl = true; + + eref = makeAlias(funcname, NIL); + + rte->eref = eref; + + rte->funcordinality = false; + + /* + * DIRTY hack time: add LATERAL dependency to the + * subquery containing the original query. That forces + * the planner to evaluate the subquery first + * (i.e. nestloop subquery to SRF, not the other way + * round), persisting the output ordering of the SRF. + */ + rte->deps = list_make1(makeVar(context->subquery_rti, 0, RECORDOID, -1, InvalidOid, 0)); + + context->outer_query->rtable = + lappend(context->outer_query->rtable, rte); + + rti = list_length(context->outer_query->rtable); + + rtf = makeNode(RangeTblRef); + rtf->rtindex = rti; + + context->outer_query->jointree->fromlist = + lappend(context->outer_query->jointree->fromlist, rtf); + + context->currte = rte; + context->currti = rti; + } + else + { + rte = context->currte; + rti = context->currti; + } + + /* add SRF RTE */ + rtfunc = makeNode(RangeTblFunction); + rtfunc->funcexpr = (Node *) expr; + rtfunc->funccolcount = 1; + rtfunc->funcasrecord = asrecord; + + rte->functions = lappend(rte->functions, rtfunc); + + rte->eref->colnames = lappend(rte->eref->colnames, + makeString(funcname)); + + /* replace reference to RTE */ + return (Node *) makeVar(rti, + ++context->coloff, + funcrettype, + exprTypmod(node), + expr->funccollid, + 0); + } + } + break; + default: + break; + } + + return expression_tree_mutator(node, unsrfify_implement_srfs_mutator, + (void *) context); +} + +/* + * Implement set-returning-functions in the targetlist using ROWS FROM() in + * the from list. + */ +void +unsrfify(PlannerInfo *root) +{ + unsrfify_context context; + Query *outer_query = root->parse; + List *outerOldTlist = root->parse->targetList; + bool sortContainsSRF = false; + bool groupContainsSRF = false; + Query *inner_query; + RangeTblEntry *rte; + RangeTblRef *rtf; + ListCell *lc; + + /* skip work if targetlist doesn't contain an SRF */ + if (!expression_returns_set((Node *) root->parse->targetList)) + { + return; + } + + Assert(outer_query->commandType != CMD_UPDATE); + + inner_query = makeNode(Query); + rte = makeNode(RangeTblEntry); + rtf = makeNode(RangeTblRef); + + memset(&context, 0, sizeof(context)); + context.root = root; + context.outer_query = outer_query; + context.inner_query = inner_query; + + /* check whether sorting has to be performed before/after SRF processing */ + foreach(lc, root->parse->sortClause) + { + SortGroupClause *sgc = lfirst(lc); + Node *sortExpr = get_sortgroupclause_expr(sgc, root->parse->targetList); + + if (expression_returns_set(sortExpr)) + { + sortContainsSRF = true; + break; + } + } + + /* check whether sorting has to be performed before/after SRF processing */ + foreach(lc, root->parse->groupClause) + { + SortGroupClause *sgc = lfirst(lc); + Node *groupExpr = get_sortgroupclause_expr(sgc, root->parse->targetList); + + if (expression_returns_set(groupExpr)) + { + groupContainsSRF = true; + break; + } + } + + /* + * Move main query processing into a subquery. Otherwise aggregates will + * possibly process more rows, due to the SRF expanding the result set. We + * could perform this work conditionally, but that seems like an + * unnecessary complication. + * + * If the query has an order-by, but that order-by does not reference SRF + * output, then SRF expansion should happen after the sort, for two + * reasons: Firstly, to process fewer rows. Secondly, to have less + * confusing results, if the output of the SRF are sorted. + */ + rte->rtekind = RTE_SUBQUERY; + rte->subquery = inner_query; + rte->security_barrier = false; + context.subquery_rti = list_length(outer_query->rtable) + 1; + rtf->rtindex = context.subquery_rti; + + inner_query->commandType = CMD_SELECT; + inner_query->querySource = QSRC_TARGETLIST_SRF; + inner_query->canSetTag = true; + + /* + * Copy the range-table, without resetting it on the outside. If the outer + * query is a data-modifying one, resultRelation needs to point to the + * actually modified table. XXX: But that doesn't work at all for + * UPDATEs, because there expand_targetlist() will add Vars pointing to + * the result relation. + */ + inner_query->rtable = copyObject(outer_query->rtable); + + inner_query->jointree = outer_query->jointree; + + /* + * Transfer group / window computation to child, unless referencing SRF + * output. + */ + if (!groupContainsSRF) + { + inner_query->hasAggs = outer_query->hasAggs; + outer_query->hasAggs = false; /* moved to subquery */ + } + else + { + inner_query->hasAggs = false; + } + + inner_query->hasWindowFuncs = outer_query->hasWindowFuncs; /* FIXME */ + outer_query->hasWindowFuncs = false; + + /* can still be present in outer query */ + inner_query->hasSubLinks = outer_query->hasSubLinks; + + /* + * CTEs stay on outer level, IncrementVarSublevelsUp adjusts ctelevelsup. + */ + inner_query->hasRecursive = false; + inner_query->hasModifyingCTE = false; + + inner_query->hasForUpdate = false; + + inner_query->hasRowSecurity = outer_query->hasRowSecurity; + + /* we've expanded everything */ + outer_query->hasTargetSRF = false; + + outer_query->rtable = lappend(outer_query->rtable, rte); + + outer_query->jointree = makeFromExpr(list_make1(rtf), NULL); + + /* targetlist is set later */ + + /* not modifying */ + inner_query->onConflict = NULL; + inner_query->returningList = NIL; + + /* + * Transfer group / window related clauses to child, unless referencing + * SRF output. + */ + if (!groupContainsSRF && list_length(outer_query->groupClause) > 0) + { + inner_query->groupClause = outer_query->groupClause; + outer_query->groupClause = NIL; + } + + inner_query->groupingSets = outer_query->groupingSets; + outer_query->groupingSets = NIL; + + inner_query->havingQual = outer_query->havingQual; + outer_query->havingQual = NULL; + + inner_query->windowClause = outer_query->windowClause; + outer_query->windowClause = NIL; + + /* DISTINCT [ON] is computed outside */ + + /* sort is computed in sub query, unless referencing SRF output */ + /* XXX: what about combinations with DISTINCT? */ + if (!sortContainsSRF && list_length(outer_query->sortClause) > 0) + { + inner_query->sortClause = outer_query->sortClause; + outer_query->sortClause = NIL; + } + + + /* limit is processed after SRF expansion */ + + /* XXX: where should row marks be processed? */ + + /* XXX: where should set operations be processed? */ + inner_query->setOperations = outer_query->setOperations; + outer_query->setOperations = NULL; + + /* constraints should stay on top level */ + + /* XXX: where should WITH CHECK options be processed? */ + + /* + * Update the outer query's targetlist to reference subquery for all + * Vars, Aggs and such. + */ + outer_query->targetList = (List *) + unsrfify_reference_subquery_mutator((Node *) outerOldTlist, + &context); + /* + * Now convert all targetlist SRFs into FUNCTION RTEs. + */ + outer_query->targetList = (List *) + unsrfify_implement_srfs_mutator((Node *) outer_query->targetList, + &context); + + + rte->eref = makeAlias("srf", context.subquery_colnames); + + inner_query->targetList = context.subquery_tlist; + + /* + * varlevelsup for expression not local to the query (i.e. varlevelsup > + * 0) have to be increased by one, to adjust for the additional layer of + * subquery added. Do so after the above processing populating the + * subselect's targetlist, to avoid having to deal with varlevelsup in + * multiple places. + */ + IncrementVarSublevelsUp((Node *) inner_query, 1, 1); +} + /*-------------------- * eval_const_expressions diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index cf5bc86..f81db37 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -418,6 +418,7 @@ transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt) qry->hasSubLinks = pstate->p_hasSubLinks; qry->hasWindowFuncs = pstate->p_hasWindowFuncs; qry->hasAggs = pstate->p_hasAggs; + qry->hasTargetSRF = pstate->p_hasTargetSRF; if (pstate->p_hasAggs) parseCheckAggregates(pstate, qry); @@ -820,6 +821,7 @@ transformInsertStmt(ParseState *pstate, InsertStmt *stmt) qry->jointree = makeFromExpr(pstate->p_joinlist, NULL); qry->hasSubLinks = pstate->p_hasSubLinks; + qry->hasTargetSRF = pstate->p_hasTargetSRF; assign_query_collations(pstate, qry); @@ -1232,6 +1234,7 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt) qry->hasSubLinks = pstate->p_hasSubLinks; qry->hasWindowFuncs = pstate->p_hasWindowFuncs; qry->hasAggs = pstate->p_hasAggs; + qry->hasTargetSRF = pstate->p_hasTargetSRF; if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual) parseCheckAggregates(pstate, qry); @@ -1463,6 +1466,11 @@ transformValuesClause(ParseState *pstate, SelectStmt *stmt) qry->hasSubLinks = pstate->p_hasSubLinks; + if (pstate->p_hasTargetSRF) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("set-valued function called in context that cannot accept a set"))); + assign_query_collations(pstate, qry); return qry; @@ -1692,6 +1700,7 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt) qry->hasSubLinks = pstate->p_hasSubLinks; qry->hasWindowFuncs = pstate->p_hasWindowFuncs; qry->hasAggs = pstate->p_hasAggs; + qry->hasTargetSRF = pstate->p_hasTargetSRF; if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual) parseCheckAggregates(pstate, qry); @@ -2171,6 +2180,7 @@ transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt) qry->jointree = makeFromExpr(pstate->p_joinlist, qual); qry->hasSubLinks = pstate->p_hasSubLinks; + qry->hasTargetSRF = pstate->p_hasTargetSRF; assign_query_collations(pstate, qry); diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c index 61af484..770903d 100644 --- a/src/backend/parser/parse_func.c +++ b/src/backend/parser/parse_func.c @@ -625,6 +625,11 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, exprLocation((Node *) llast(fargs))))); } + if (retset) + { + pstate->p_hasTargetSRF = true; + } + /* build the appropriate output structure */ if (fdresult == FUNCDETAIL_NORMAL) { diff --git a/src/backend/parser/parse_oper.c b/src/backend/parser/parse_oper.c index e913d05..0a1a0f1 100644 --- a/src/backend/parser/parse_oper.c +++ b/src/backend/parser/parse_oper.c @@ -841,6 +841,11 @@ make_op(ParseState *pstate, List *opname, Node *ltree, Node *rtree, ReleaseSysCache(tup); + if (result->opretset) + { + pstate->p_hasTargetSRF = true; + } + return (Expr *) result; } diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h index f26e651..969db8c 100644 --- a/src/include/nodes/parsenodes.h +++ b/src/include/nodes/parsenodes.h @@ -32,7 +32,8 @@ typedef enum QuerySource QSRC_PARSER, /* added by parse analysis (now unused) */ QSRC_INSTEAD_RULE, /* added by unconditional INSTEAD rule */ QSRC_QUAL_INSTEAD_RULE, /* added by conditional INSTEAD rule */ - QSRC_NON_INSTEAD_RULE /* added by non-INSTEAD rule */ + QSRC_NON_INSTEAD_RULE, /* added by non-INSTEAD rule */ + QSRC_TARGETLIST_SRF /* added by targetlist SRF processing */ } QuerySource; /* Sort ordering options for ORDER BY and CREATE INDEX */ @@ -122,6 +123,7 @@ typedef struct Query bool hasModifyingCTE; /* has INSERT/UPDATE/DELETE in WITH */ bool hasForUpdate; /* FOR [KEY] UPDATE/SHARE was specified */ bool hasRowSecurity; /* rewriter has applied some RLS policy */ + bool hasTargetSRF; /* has SRF in target list */ List *cteList; /* WITH list (of CommonTableExpr's) */ @@ -879,6 +881,8 @@ typedef struct RangeTblEntry Bitmapset *insertedCols; /* columns needing INSERT permission */ Bitmapset *updatedCols; /* columns needing UPDATE permission */ List *securityQuals; /* any security barrier quals to apply */ + + List *deps; } RangeTblEntry; /* diff --git a/src/include/optimizer/clauses.h b/src/include/optimizer/clauses.h index 9abef37..7fb5005 100644 --- a/src/include/optimizer/clauses.h +++ b/src/include/optimizer/clauses.h @@ -79,6 +79,8 @@ extern int NumRelids(Node *clause); extern void CommuteOpExpr(OpExpr *clause); extern void CommuteRowCompareExpr(RowCompareExpr *clause); +extern void unsrfify(PlannerInfo *root); + extern Node *eval_const_expressions(PlannerInfo *root, Node *node); extern Node *estimate_expression_value(PlannerInfo *root, Node *node); diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index e3e359c..c0eec33 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -152,6 +152,7 @@ struct ParseState bool p_hasWindowFuncs; bool p_hasSubLinks; bool p_hasModifyingCTE; + bool p_hasTargetSRF; bool p_is_insert; bool p_locked_from_parent; Relation p_target_relation; diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out index 45208a6..b791572 100644 --- a/src/test/regress/expected/aggregates.out +++ b/src/test/regress/expected/aggregates.out @@ -814,16 +814,19 @@ select max(unique2) from tenk1 order by max(unique2)+1; explain (costs off) select max(unique2), generate_series(1,3) as g from tenk1 order by g desc; - QUERY PLAN ---------------------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------------------------------- Sort - Sort Key: (generate_series(1, 3)) DESC - InitPlan 1 (returns $0) - -> Limit - -> Index Only Scan Backward using tenk1_unique2 on tenk1 - Index Cond: (unique2 IS NOT NULL) - -> Result -(7 rows) + Sort Key: generate_series.generate_series DESC + -> Nested Loop + -> Subquery Scan on srf + -> Result + InitPlan 1 (returns $0) + -> Limit + -> Index Only Scan Backward using tenk1_unique2 on tenk1 + Index Cond: (unique2 IS NOT NULL) + -> Function Scan on generate_series +(10 rows) select max(unique2), generate_series(1,3) as g from tenk1 order by g desc; max | g diff --git a/src/test/regress/expected/limit.out b/src/test/regress/expected/limit.out index 9c3eecf..45f0c38 100644 --- a/src/test/regress/expected/limit.out +++ b/src/test/regress/expected/limit.out @@ -208,13 +208,20 @@ select currval('testseq'); explain (verbose, costs off) select unique1, unique2, generate_series(1,10) from tenk1 order by unique2 limit 7; - QUERY PLAN ----------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------------------- Limit - Output: unique1, unique2, (generate_series(1, 10)) - -> Index Scan using tenk1_unique2 on public.tenk1 - Output: unique1, unique2, generate_series(1, 10) -(4 rows) + Output: srf.unique1, srf.unique2, generate_series.generate_series + -> Nested Loop + Output: srf.unique1, srf.unique2, generate_series.generate_series + -> Subquery Scan on srf + Output: srf.unique1, srf.unique2, srf.* + -> Index Scan using tenk1_unique2 on public.tenk1 + Output: tenk1.unique1, tenk1.unique2 + -> Function Scan on pg_catalog.generate_series + Output: generate_series.generate_series + Function Call: generate_series(1, 10) +(11 rows) select unique1, unique2, generate_series(1,10) from tenk1 order by unique2 limit 7; @@ -232,18 +239,23 @@ select unique1, unique2, generate_series(1,10) explain (verbose, costs off) select unique1, unique2, generate_series(1,10) from tenk1 order by tenthous limit 7; - QUERY PLAN --------------------------------------------------------------------- + QUERY PLAN +-------------------------------------------------------------------------------------- Limit - Output: unique1, unique2, (generate_series(1, 10)), tenthous - -> Result - Output: unique1, unique2, generate_series(1, 10), tenthous - -> Sort - Output: unique1, unique2, tenthous - Sort Key: tenk1.tenthous - -> Seq Scan on public.tenk1 - Output: unique1, unique2, tenthous -(9 rows) + Output: srf.unique1, srf.unique2, generate_series.generate_series, srf."..." + -> Nested Loop + Output: srf.unique1, srf.unique2, generate_series.generate_series, srf."..." + -> Subquery Scan on srf + Output: srf.unique1, srf.unique2, srf."...", srf.* + -> Sort + Output: tenk1.unique1, tenk1.unique2, tenk1.tenthous + Sort Key: tenk1.tenthous + -> Seq Scan on public.tenk1 + Output: tenk1.unique1, tenk1.unique2, tenk1.tenthous + -> Function Scan on pg_catalog.generate_series + Output: generate_series.generate_series + Function Call: generate_series(1, 10) +(14 rows) select unique1, unique2, generate_series(1,10) from tenk1 order by tenthous limit 7; @@ -261,11 +273,12 @@ select unique1, unique2, generate_series(1,10) -- use of random() is to keep planner from folding the expressions together explain (verbose, costs off) select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2; - QUERY PLAN ------------------------------------------------------------------------------------------------------- - Result - Output: generate_series(0, 2), generate_series(((random() * '0.1'::double precision))::integer, 2) -(2 rows) + QUERY PLAN +------------------------------------------------------------------------------------------------------------- + Function Scan on generate_series + Output: generate_series.generate_series, generate_series.generate_series_1 + Function Call: generate_series(0, 2), generate_series(((random() * '0.1'::double precision))::integer, 2) +(3 rows) select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2; s1 | s2 @@ -278,14 +291,15 @@ select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2; explain (verbose, costs off) select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2 order by s2 desc; - QUERY PLAN ------------------------------------------------------------------------------------------------------------- + QUERY PLAN +------------------------------------------------------------------------------------------------------------------- Sort - Output: (generate_series(0, 2)), (generate_series(((random() * '0.1'::double precision))::integer, 2)) - Sort Key: (generate_series(((random() * '0.1'::double precision))::integer, 2)) DESC - -> Result - Output: generate_series(0, 2), generate_series(((random() * '0.1'::double precision))::integer, 2) -(5 rows) + Output: generate_series.generate_series, generate_series.generate_series_1 + Sort Key: generate_series.generate_series_1 DESC + -> Function Scan on generate_series + Output: generate_series.generate_series, generate_series.generate_series_1 + Function Call: generate_series(0, 2), generate_series(((random() * '0.1'::double precision))::integer, 2) +(6 rows) select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2 order by s2 desc; diff --git a/src/test/regress/expected/portals.out b/src/test/regress/expected/portals.out index 3ae918a..7530bb8 100644 --- a/src/test/regress/expected/portals.out +++ b/src/test/regress/expected/portals.out @@ -1320,16 +1320,16 @@ fetch backward all in c1; rollback; begin; explain (costs off) declare c2 cursor for select generate_series(1,3) as g; - QUERY PLAN ------------- - Result + QUERY PLAN +---------------------------------- + Function Scan on generate_series (1 row) explain (costs off) declare c2 scroll cursor for select generate_series(1,3) as g; - QUERY PLAN --------------- + QUERY PLAN +---------------------------------------- Materialize - -> Result + -> Function Scan on generate_series (2 rows) declare c2 scroll cursor for select generate_series(1,3) as g; diff --git a/src/test/regress/expected/rangefuncs.out b/src/test/regress/expected/rangefuncs.out index 249dc67..635aa50 100644 --- a/src/test/regress/expected/rangefuncs.out +++ b/src/test/regress/expected/rangefuncs.out @@ -2080,12 +2080,10 @@ SELECT *, END) FROM (VALUES (1,''), (2,'0000000049404'), (3,'FROM 10000000876')) v(id, str); - id | str | lower -----+------------------+------------------ - 1 | | - 2 | 0000000049404 | 49404 - 3 | FROM 10000000876 | from 10000000876 -(3 rows) + id | str | lower +----+---------------+------- + 2 | 0000000049404 | 49404 +(1 row) -- check whole-row-Var handling in nested lateral functions (bug #11703) create function extractq2(t int8_tbl) returns int8 as $$ diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index 0fc93d9..569784d 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -807,24 +807,31 @@ select * from int4_tbl where explain (verbose, costs off) select * from int4_tbl o where (f1, f1) in (select f1, generate_series(1,2) / 10 g from int4_tbl i group by f1); - QUERY PLAN ----------------------------------------------------------------- - Hash Semi Join + QUERY PLAN +---------------------------------------------------------------------------- + Nested Loop Semi Join Output: o.f1 - Hash Cond: (o.f1 = "ANY_subquery".f1) + Join Filter: (o.f1 = "ANY_subquery".f1) -> Seq Scan on public.int4_tbl o Output: o.f1 - -> Hash + -> Materialize Output: "ANY_subquery".f1, "ANY_subquery".g -> Subquery Scan on "ANY_subquery" Output: "ANY_subquery".f1, "ANY_subquery".g Filter: ("ANY_subquery".f1 = "ANY_subquery".g) - -> HashAggregate - Output: i.f1, (generate_series(1, 2) / 10) - Group Key: i.f1 - -> Seq Scan on public.int4_tbl i - Output: i.f1 -(15 rows) + -> Nested Loop + Output: srf.f1, (generate_series.generate_series / 10) + -> Subquery Scan on srf + Output: srf.f1, srf.* + -> HashAggregate + Output: i.f1 + Group Key: i.f1 + -> Seq Scan on public.int4_tbl i + Output: i.f1 + -> Function Scan on pg_catalog.generate_series + Output: generate_series.generate_series + Function Call: generate_series(1, 2) +(22 rows) select * from int4_tbl o where (f1, f1) in (select f1, generate_series(1,2) / 10 g from int4_tbl i group by f1); diff --git a/src/test/regress/expected/tsrf.out b/src/test/regress/expected/tsrf.out index f520a91..4a7ab6d 100644 --- a/src/test/regress/expected/tsrf.out +++ b/src/test/regress/expected/tsrf.out @@ -25,8 +25,8 @@ SELECT generate_series(1, 2), generate_series(1,4); -----------------+----------------- 1 | 1 2 | 2 - 1 | 3 - 2 | 4 + | 3 + | 4 (4 rows) -- srf, with SRF argument @@ -43,7 +43,16 @@ SELECT generate_series(1, generate_series(1, 3)); -- srf, with two SRF arguments SELECT generate_series(generate_series(1,3), generate_series(2, 4)); -ERROR: functions and operators can take at most one set argument + generate_series +----------------- + 1 + 2 + 2 + 3 + 3 + 4 +(6 rows) + CREATE TABLE few(id int, dataa text, datab text); INSERT INTO few VALUES(1, 'a', 'foo'),(2, 'a', 'bar'),(3, 'b', 'bar'); -- SRF output order of sorting is maintained, if SRF is not referenced diff --git a/src/test/regress/expected/union.out b/src/test/regress/expected/union.out index 016571b..04e9765 100644 --- a/src/test/regress/expected/union.out +++ b/src/test/regress/expected/union.out @@ -622,16 +622,16 @@ SELECT * FROM SELECT 2 AS t, 4 AS x) ss WHERE x < 4 ORDER BY x; - QUERY PLAN --------------------------------------------------------- + QUERY PLAN +--------------------------------------------------------------- Sort Sort Key: ss.x -> Subquery Scan on ss Filter: (ss.x < 4) -> HashAggregate - Group Key: (1), (generate_series(1, 10)) + Group Key: (1), generate_series.generate_series -> Append - -> Result + -> Function Scan on generate_series -> Result (9 rows) diff --git a/src/test/regress/output/misc.source b/src/test/regress/output/misc.source index 5c88aad..d8d87cf 100644 --- a/src/test/regress/output/misc.source +++ b/src/test/regress/output/misc.source @@ -511,7 +511,7 @@ SELECT p.name, name(p.hobbies), name(equipment(p.hobbies)) FROM ONLY person p; name | name | name -------+-------------+--------------- mike | posthacking | advil - mike | posthacking | peet's coffee + mike | | peet's coffee joe | basketball | hightops sally | basketball | hightops (4 rows) @@ -523,11 +523,11 @@ SELECT p.name, name(p.hobbies), name(equipment(p.hobbies)) FROM person* p; name | name | name -------+-------------+--------------- mike | posthacking | advil - mike | posthacking | peet's coffee + mike | | peet's coffee joe | basketball | hightops sally | basketball | hightops jeff | posthacking | advil - jeff | posthacking | peet's coffee + jeff | | peet's coffee (6 rows) -- @@ -538,7 +538,7 @@ SELECT name(equipment(p.hobbies)), p.name, name(p.hobbies) FROM ONLY person p; name | name | name ---------------+-------+------------- advil | mike | posthacking - peet's coffee | mike | posthacking + peet's coffee | mike | hightops | joe | basketball hightops | sally | basketball (4 rows) @@ -547,18 +547,18 @@ SELECT (p.hobbies).equipment.name, p.name, name(p.hobbies) FROM person* p; name | name | name ---------------+-------+------------- advil | mike | posthacking - peet's coffee | mike | posthacking + peet's coffee | mike | hightops | joe | basketball hightops | sally | basketball advil | jeff | posthacking - peet's coffee | jeff | posthacking + peet's coffee | jeff | (6 rows) SELECT (p.hobbies).equipment.name, name(p.hobbies), p.name FROM ONLY person p; name | name | name ---------------+-------------+------- advil | posthacking | mike - peet's coffee | posthacking | mike + peet's coffee | | mike hightops | basketball | joe hightops | basketball | sally (4 rows) @@ -567,11 +567,11 @@ SELECT name(equipment(p.hobbies)), name(p.hobbies), p.name FROM person* p; name | name | name ---------------+-------------+------- advil | posthacking | mike - peet's coffee | posthacking | mike + peet's coffee | | mike hightops | basketball | joe hightops | basketball | sally advil | posthacking | jeff - peet's coffee | posthacking | jeff + peet's coffee | | jeff (6 rows) SELECT user_relns() AS user_relns -- 2.9.3
0006-Remove-unused-code-related-to-targetlist-SRFs.patch (text/x-patch, 138.0K) download From d38013a7e9d49dd7b1e9c6c2b22c9906945e7010 Mon Sep 17 00:00:00 2001 From: Andres Freund <andres@anarazel.de> Date: Thu, 25 Aug 2016 11:24:49 -0700 Subject: [PATCH 6/6] Remove unused code related to targetlist SRFs. --- src/backend/catalog/index.c | 3 +- src/backend/commands/copy.c | 2 +- src/backend/commands/prepare.c | 3 +- src/backend/commands/tablecmds.c | 3 +- src/backend/commands/typecmds.c | 2 +- src/backend/executor/execAmi.c | 42 +- src/backend/executor/execQual.c | 1174 ++++------------------------- src/backend/executor/execScan.c | 30 +- src/backend/executor/execUtils.c | 6 - src/backend/executor/nodeAgg.c | 52 +- src/backend/executor/nodeBitmapHeapscan.c | 2 - src/backend/executor/nodeCtescan.c | 2 - src/backend/executor/nodeCustom.c | 2 - src/backend/executor/nodeForeignscan.c | 2 - src/backend/executor/nodeFunctionscan.c | 16 +- src/backend/executor/nodeGather.c | 25 +- src/backend/executor/nodeGroup.c | 42 +- src/backend/executor/nodeHash.c | 2 +- src/backend/executor/nodeHashjoin.c | 52 +- src/backend/executor/nodeIndexonlyscan.c | 2 - src/backend/executor/nodeIndexscan.c | 11 +- src/backend/executor/nodeLimit.c | 19 +- src/backend/executor/nodeMergejoin.c | 59 +- src/backend/executor/nodeModifyTable.c | 4 +- src/backend/executor/nodeNestloop.c | 41 +- src/backend/executor/nodeResult.c | 33 +- src/backend/executor/nodeSamplescan.c | 8 +- src/backend/executor/nodeSeqscan.c | 2 - src/backend/executor/nodeSubplan.c | 31 +- src/backend/executor/nodeSubqueryscan.c | 2 - src/backend/executor/nodeTidscan.c | 8 +- src/backend/executor/nodeValuesscan.c | 5 +- src/backend/executor/nodeWindowAgg.c | 58 +- src/backend/executor/nodeWorktablescan.c | 2 - src/backend/optimizer/plan/planner.c | 119 +-- src/backend/optimizer/util/clauses.c | 46 +- src/backend/optimizer/util/predtest.c | 2 +- src/backend/utils/adt/domains.c | 2 +- src/backend/utils/adt/xml.c | 4 +- src/include/executor/executor.h | 13 +- src/include/nodes/execnodes.h | 16 +- src/include/optimizer/clauses.h | 1 - src/pl/plpgsql/src/pl_exec.c | 5 +- 43 files changed, 284 insertions(+), 1671 deletions(-) diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index b0b43cf..fd82855 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1788,8 +1788,7 @@ FormIndexDatum(IndexInfo *indexInfo, elog(ERROR, "wrong number of index expressions"); iDatum = ExecEvalExprSwitchContext((ExprState *) lfirst(indexpr_item), GetPerTupleExprContext(estate), - &isNull, - NULL); + &isNull); indexpr_item = lnext(indexpr_item); } values[i] = iDatum; diff --git a/src/backend/commands/copy.c b/src/backend/commands/copy.c index f45b330..28466ac 100644 --- a/src/backend/commands/copy.c +++ b/src/backend/commands/copy.c @@ -3172,7 +3172,7 @@ NextCopyFrom(CopyState cstate, ExprContext *econtext, Assert(CurrentMemoryContext == econtext->ecxt_per_tuple_memory); values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext, - &nulls[defmap[i]], NULL); + &nulls[defmap[i]]); } return true; diff --git a/src/backend/commands/prepare.c b/src/backend/commands/prepare.c index cec37ce..451c8d5 100644 --- a/src/backend/commands/prepare.c +++ b/src/backend/commands/prepare.c @@ -404,8 +404,7 @@ EvaluateParams(PreparedStatement *pstmt, List *params, prm->pflags = PARAM_FLAG_CONST; prm->value = ExecEvalExprSwitchContext(n, GetPerTupleExprContext(estate), - &prm->isnull, - NULL); + &prm->isnull); i++; } diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 86e9814..92e468d 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -4151,8 +4151,7 @@ ATRewriteTable(AlteredTableInfo *tab, Oid OIDNewHeap, LOCKMODE lockmode) values[ex->attnum - 1] = ExecEvalExpr(ex->exprstate, econtext, - &isnull[ex->attnum - 1], - NULL); + &isnull[ex->attnum - 1]); } /* diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c index ce04211..755af68 100644 --- a/src/backend/commands/typecmds.c +++ b/src/backend/commands/typecmds.c @@ -2741,7 +2741,7 @@ validateDomainConstraint(Oid domainoid, char *ccbin) conResult = ExecEvalExprSwitchContext(exprstate, econtext, - &isNull, NULL); + &isNull); if (!isNull && !DatumGetBool(conResult)) { diff --git a/src/backend/executor/execAmi.c b/src/backend/executor/execAmi.c index ea2f09e..959d27a 100644 --- a/src/backend/executor/execAmi.c +++ b/src/backend/executor/execAmi.c @@ -58,7 +58,6 @@ #include "utils/syscache.h" -static bool TargetListSupportsBackwardScan(List *targetlist); static bool IndexSupportsBackwardScan(Oid indexid); @@ -119,7 +118,7 @@ ExecReScan(PlanState *node) UpdateChangedParamSet(node->righttree, node->chgParam); } - /* Shut down any SRFs in the plan node's targetlist */ + /* Call expression callbacks */ if (node->ps_ExprContext) ReScanExprContext(node->ps_ExprContext); @@ -455,8 +454,7 @@ ExecSupportsBackwardScan(Plan *node) { case T_Result: if (outerPlan(node) != NULL) - return ExecSupportsBackwardScan(outerPlan(node)) && - TargetListSupportsBackwardScan(node->targetlist); + return ExecSupportsBackwardScan(outerPlan(node)); else return false; @@ -473,12 +471,6 @@ ExecSupportsBackwardScan(Plan *node) return true; } - case T_SeqScan: - case T_TidScan: - case T_ValuesScan: - case T_CteScan: - return TargetListSupportsBackwardScan(node->targetlist); - case T_SampleScan: /* Simplify life for tablesample methods by disallowing this */ return false; @@ -487,35 +479,33 @@ ExecSupportsBackwardScan(Plan *node) return false; case T_IndexScan: - return IndexSupportsBackwardScan(((IndexScan *) node)->indexid) && - TargetListSupportsBackwardScan(node->targetlist); + return IndexSupportsBackwardScan(((IndexScan *) node)->indexid); case T_IndexOnlyScan: - return IndexSupportsBackwardScan(((IndexOnlyScan *) node)->indexid) && - TargetListSupportsBackwardScan(node->targetlist); + return IndexSupportsBackwardScan(((IndexOnlyScan *) node)->indexid); case T_SubqueryScan: - return ExecSupportsBackwardScan(((SubqueryScan *) node)->subplan) && - TargetListSupportsBackwardScan(node->targetlist); + return ExecSupportsBackwardScan(((SubqueryScan *) node)->subplan); case T_CustomScan: { uint32 flags = ((CustomScan *) node)->flags; - if ((flags & CUSTOMPATH_SUPPORT_BACKWARD_SCAN) && - TargetListSupportsBackwardScan(node->targetlist)) + if (flags & CUSTOMPATH_SUPPORT_BACKWARD_SCAN) return true; } return false; + case T_SeqScan: + case T_TidScan: + case T_ValuesScan: + case T_CteScan: case T_Material: case T_Sort: - /* these don't evaluate tlist */ return true; case T_LockRows: case T_Limit: - /* these don't evaluate tlist */ return ExecSupportsBackwardScan(outerPlan(node)); default: @@ -524,18 +514,6 @@ ExecSupportsBackwardScan(Plan *node) } /* - * If the tlist contains set-returning functions, we can't support backward - * scan, because the TupFromTlist code is direction-ignorant. - */ -static bool -TargetListSupportsBackwardScan(List *targetlist) -{ - if (expression_returns_set((Node *) targetlist)) - return false; - return true; -} - -/* * An IndexScan or IndexOnlyScan node supports backward scan only if the * index's AM does. */ diff --git a/src/backend/executor/execQual.c b/src/backend/executor/execQual.c index d9e2797..1bdc0ac 100644 --- a/src/backend/executor/execQual.c +++ b/src/backend/executor/execQual.c @@ -64,127 +64,115 @@ /* static function decls */ static Datum ExecEvalArrayRef(ArrayRefExprState *astate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static bool isAssignmentIndirectionExpr(ExprState *exprstate); static Datum ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalWindowFunc(WindowFuncExprState *wfunc, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalScalarVar(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalScalarVarFast(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalWholeRowVar(WholeRowVarExprState *wrvstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalWholeRowFast(WholeRowVarExprState *wrvstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalWholeRowSlow(WholeRowVarExprState *wrvstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalConst(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalParamExec(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalParamExtern(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); -static void ShutdownFuncExpr(Datum arg); -static TupleDesc get_cached_rowtype(Oid type_id, int32 typmod, - TupleDesc *cache_field, ExprContext *econtext); + bool *isNull); static void ShutdownTupleDescRef(Datum arg); -static void ExecPrepareTuplestoreResult(FuncExprState *fcache, - ExprContext *econtext, - Tuplestorestate *resultStore, - TupleDesc resultDesc); -static void tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc); -static Datum ExecMakeFunctionResult(FuncExprState *fcache, - ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone); static Datum ExecMakeFunctionResultNoSets(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalCaseTestExpr(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalRow(RowExprState *rstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalRowCompare(RowCompareExprState *rstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalSQLValueFunction(ExprState *svfExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalNullIf(FuncExprState *nullIfExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalNullTest(NullTestState *nstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalBooleanTest(GenericExprState *bstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalCoerceToDomainValue(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalFieldSelect(FieldSelectState *fstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalFieldStore(FieldStoreState *fstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalRelabelType(GenericExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalCoerceViaIO(CoerceViaIOState *iostate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalArrayCoerceExpr(ArrayCoerceExprState *astate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalCurrentOfExpr(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); static Datum ExecEvalGroupingFuncExpr(GroupingFuncExprState *gstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); + bool *isNull); /* ---------------------------------------------------------------- @@ -195,8 +183,7 @@ static Datum ExecEvalGroupingFuncExpr(GroupingFuncExprState *gstate, * Each of the following routines having the signature * Datum ExecEvalFoo(ExprState *expression, * ExprContext *econtext, - * bool *isNull, - * ExprDoneCond *isDone); + * bool *isNull); * is responsible for evaluating one type or subtype of ExprState node. * They are normally called via the ExecEvalExpr macro, which makes use of * the function pointer set up when the ExprState node was built by @@ -220,22 +207,6 @@ static Datum ExecEvalGroupingFuncExpr(GroupingFuncExprState *gstate, * return value: Datum value of result * *isNull: set to TRUE if result is NULL (actual return value is * meaningless if so); set to FALSE if non-null result - * *isDone: set to indicator of set-result status - * - * A caller that can only accept a singleton (non-set) result should pass - * NULL for isDone; if the expression computes a set result then an error - * will be reported via ereport. If the caller does pass an isDone pointer - * then *isDone is set to one of these three states: - * ExprSingleResult singleton result (not a set) - * ExprMultipleResult return value is one element of a set - * ExprEndResult there are no more elements in the set - * When ExprMultipleResult is returned, the caller should invoke - * ExecEvalExpr() repeatedly until ExprEndResult is returned. ExprEndResult - * is returned after the last real set element. For convenience isNull will - * always be set TRUE when ExprEndResult is returned, but this should not be - * taken as indicating a NULL element of the set. Note that these return - * conventions allow us to distinguish among a singleton NULL, a NULL element - * of a set, and an empty set. * * The caller should already have switched into the temporary memory * context econtext->ecxt_per_tuple_memory. The convenience entry point @@ -260,8 +231,7 @@ static Datum ExecEvalGroupingFuncExpr(GroupingFuncExprState *gstate, static Datum ExecEvalArrayRef(ArrayRefExprState *astate, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { ArrayRef *arrayRef = (ArrayRef *) astate->xprstate.expr; Datum array_source; @@ -278,8 +248,7 @@ ExecEvalArrayRef(ArrayRefExprState *astate, array_source = ExecEvalExpr(astate->refexpr, econtext, - isNull, - isDone); + isNull); /* * If refexpr yields NULL, and it's a fetch, then result is NULL. In the @@ -287,8 +256,6 @@ ExecEvalArrayRef(ArrayRefExprState *astate, */ if (*isNull) { - if (isDone && *isDone == ExprEndResult) - return (Datum) NULL; /* end of set result */ if (!isAssignment) return (Datum) NULL; } @@ -314,8 +281,7 @@ ExecEvalArrayRef(ArrayRefExprState *astate, upper.indx[i++] = DatumGetInt32(ExecEvalExpr(eltstate, econtext, - &eisnull, - NULL)); + &eisnull)); /* If any index expr yields NULL, result is NULL or error */ if (eisnull) { @@ -350,8 +316,7 @@ ExecEvalArrayRef(ArrayRefExprState *astate, lower.indx[j++] = DatumGetInt32(ExecEvalExpr(eltstate, econtext, - &eisnull, - NULL)); + &eisnull)); /* If any index expr yields NULL, result is NULL or error */ if (eisnull) { @@ -438,8 +403,7 @@ ExecEvalArrayRef(ArrayRefExprState *astate, */ sourceData = ExecEvalExpr(astate->refassgnexpr, econtext, - &eisnull, - NULL); + &eisnull); econtext->caseValue_datum = save_datum; econtext->caseValue_isNull = save_isNull; @@ -542,11 +506,8 @@ isAssignmentIndirectionExpr(ExprState *exprstate) */ static Datum ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { - if (isDone) - *isDone = ExprSingleResult; - if (econtext->ecxt_aggvalues == NULL) /* safety check */ elog(ERROR, "no aggregates in this expression context"); @@ -563,11 +524,8 @@ ExecEvalAggref(AggrefExprState *aggref, ExprContext *econtext, */ static Datum ExecEvalWindowFunc(WindowFuncExprState *wfunc, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { - if (isDone) - *isDone = ExprSingleResult; - if (econtext->ecxt_aggvalues == NULL) /* safety check */ elog(ERROR, "no window functions in this expression context"); @@ -588,15 +546,12 @@ ExecEvalWindowFunc(WindowFuncExprState *wfunc, ExprContext *econtext, */ static Datum ExecEvalScalarVar(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Var *variable = (Var *) exprstate->expr; TupleTableSlot *slot; AttrNumber attnum; - if (isDone) - *isDone = ExprSingleResult; - /* Get the input slot and attribute number we want */ switch (variable->varno) { @@ -677,15 +632,12 @@ ExecEvalScalarVar(ExprState *exprstate, ExprContext *econtext, */ static Datum ExecEvalScalarVarFast(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Var *variable = (Var *) exprstate->expr; TupleTableSlot *slot; AttrNumber attnum; - if (isDone) - *isDone = ExprSingleResult; - /* Get the input slot and attribute number we want */ switch (variable->varno) { @@ -725,7 +677,7 @@ ExecEvalScalarVarFast(ExprState *exprstate, ExprContext *econtext, */ static Datum ExecEvalWholeRowVar(WholeRowVarExprState *wrvstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Var *variable = (Var *) wrvstate->xprstate.expr; TupleTableSlot *slot; @@ -733,9 +685,6 @@ ExecEvalWholeRowVar(WholeRowVarExprState *wrvstate, ExprContext *econtext, MemoryContext oldcontext; bool needslow = false; - if (isDone) - *isDone = ExprSingleResult; - /* This was checked by ExecInitExpr */ Assert(variable->varattno == InvalidAttrNumber); @@ -941,7 +890,7 @@ ExecEvalWholeRowVar(WholeRowVarExprState *wrvstate, ExprContext *econtext, /* Fetch the value */ return (*wrvstate->xprstate.evalfunc) ((ExprState *) wrvstate, econtext, - isNull, isDone); + isNull); } /* ---------------------------------------------------------------- @@ -952,14 +901,12 @@ ExecEvalWholeRowVar(WholeRowVarExprState *wrvstate, ExprContext *econtext, */ static Datum ExecEvalWholeRowFast(WholeRowVarExprState *wrvstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Var *variable = (Var *) wrvstate->xprstate.expr; TupleTableSlot *slot; HeapTupleHeader dtuple; - if (isDone) - *isDone = ExprSingleResult; *isNull = false; /* Get the input slot we want */ @@ -1008,7 +955,7 @@ ExecEvalWholeRowFast(WholeRowVarExprState *wrvstate, ExprContext *econtext, */ static Datum ExecEvalWholeRowSlow(WholeRowVarExprState *wrvstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Var *variable = (Var *) wrvstate->xprstate.expr; TupleTableSlot *slot; @@ -1018,8 +965,6 @@ ExecEvalWholeRowSlow(WholeRowVarExprState *wrvstate, ExprContext *econtext, HeapTupleHeader dtuple; int i; - if (isDone) - *isDone = ExprSingleResult; *isNull = false; /* Get the input slot we want */ @@ -1097,13 +1042,10 @@ ExecEvalWholeRowSlow(WholeRowVarExprState *wrvstate, ExprContext *econtext, */ static Datum ExecEvalConst(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Const *con = (Const *) exprstate->expr; - if (isDone) - *isDone = ExprSingleResult; - *isNull = con->constisnull; return con->constvalue; } @@ -1116,15 +1058,12 @@ ExecEvalConst(ExprState *exprstate, ExprContext *econtext, */ static Datum ExecEvalParamExec(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Param *expression = (Param *) exprstate->expr; int thisParamId = expression->paramid; ParamExecData *prm; - if (isDone) - *isDone = ExprSingleResult; - /* * PARAM_EXEC params (internal executor parameters) are stored in the * ecxt_param_exec_vals array, and can be accessed by array index. @@ -1149,15 +1088,12 @@ ExecEvalParamExec(ExprState *exprstate, ExprContext *econtext, */ static Datum ExecEvalParamExtern(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Param *expression = (Param *) exprstate->expr; int thisParamId = expression->paramid; ParamListInfo paramInfo = econtext->ecxt_param_list_info; - if (isDone) - *isDone = ExprSingleResult; - /* * PARAM_EXTERN parameters must be sought in ecxt_param_list_info. */ @@ -1323,7 +1259,7 @@ GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull) */ void ExecInitFcache(Oid foid, Oid input_collation, FuncExprState *fcache, - MemoryContext fcacheCxt, bool needDescForSets) + MemoryContext fcacheCxt) { AclResult aclresult; @@ -1356,88 +1292,9 @@ ExecInitFcache(Oid foid, Oid input_collation, FuncExprState *fcache, list_length(fcache->args), input_collation, NULL, NULL); - /* If function returns set, prepare expected tuple descriptor */ - if (fcache->func.fn_retset && needDescForSets) - { - TypeFuncClass functypclass; - Oid funcrettype; - TupleDesc tupdesc; - MemoryContext oldcontext; - - functypclass = get_expr_result_type(fcache->func.fn_expr, - &funcrettype, - &tupdesc); - - /* Must save tupdesc in fcache's context */ - oldcontext = MemoryContextSwitchTo(fcacheCxt); - - if (functypclass == TYPEFUNC_COMPOSITE) - { - /* Composite data type, e.g. a table's row type */ - Assert(tupdesc); - /* Must copy it out of typcache for safety */ - fcache->funcResultDesc = CreateTupleDescCopy(tupdesc); - fcache->funcReturnsTuple = true; - } - else if (functypclass == TYPEFUNC_SCALAR) - { - /* Base data type, i.e. scalar */ - tupdesc = CreateTemplateTupleDesc(1, false); - TupleDescInitEntry(tupdesc, - (AttrNumber) 1, - NULL, - funcrettype, - -1, - 0); - fcache->funcResultDesc = tupdesc; - fcache->funcReturnsTuple = false; - } - else if (functypclass == TYPEFUNC_RECORD) - { - /* This will work if function doesn't need an expectedDesc */ - fcache->funcResultDesc = NULL; - fcache->funcReturnsTuple = true; - } - else - { - /* Else, we will fail if function needs an expectedDesc */ - fcache->funcResultDesc = NULL; - } - - MemoryContextSwitchTo(oldcontext); - } - else - fcache->funcResultDesc = NULL; - /* Initialize additional state */ fcache->funcResultStore = NULL; fcache->funcResultSlot = NULL; - fcache->setArgsValid = false; - fcache->shutdown_reg = false; -} - -/* - * callback function in case a FuncExpr returning a set needs to be shut down - * before it has been run to completion - */ -static void -ShutdownFuncExpr(Datum arg) -{ - FuncExprState *fcache = (FuncExprState *) DatumGetPointer(arg); - - /* If we have a slot, make sure it's let go of any tuplestore pointer */ - if (fcache->funcResultSlot) - ExecClearTuple(fcache->funcResultSlot); - - /* Release any open tuplestore */ - if (fcache->funcResultStore) - tuplestore_end(fcache->funcResultStore); - fcache->funcResultStore = NULL; - - /* Clear any active set-argument state */ - fcache->setArgsValid = false; - - /* execUtils will deregister the callback... */ fcache->shutdown_reg = false; } @@ -1499,500 +1356,38 @@ ShutdownTupleDescRef(Datum arg) /* * Evaluate arguments for a function. */ -ExprDoneCond +void ExecEvalFuncArgs(FunctionCallInfo fcinfo, List *argList, ExprContext *econtext) { - ExprDoneCond argIsDone; int i; ListCell *arg; - argIsDone = ExprSingleResult; /* default assumption */ - i = 0; foreach(arg, argList) { ExprState *argstate = (ExprState *) lfirst(arg); - ExprDoneCond thisArgIsDone; fcinfo->arg[i] = ExecEvalExpr(argstate, econtext, - &fcinfo->argnull[i], - &thisArgIsDone); - - if (thisArgIsDone != ExprSingleResult) - { - /* - * We allow only one argument to have a set value; we'd need much - * more complexity to keep track of multiple set arguments (cf. - * ExecTargetList) and it doesn't seem worth it. - */ - if (argIsDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("functions and operators can take at most one set argument"))); - argIsDone = thisArgIsDone; - } + &fcinfo->argnull[i]); i++; } Assert(i == fcinfo->nargs); - - return argIsDone; -} - -/* - * ExecPrepareTuplestoreResult - * - * Subroutine for ExecMakeFunctionResult: prepare to extract rows from a - * tuplestore function result. We must set up a funcResultSlot (unless - * already done in a previous call cycle) and verify that the function - * returned the expected tuple descriptor. - */ -static void -ExecPrepareTuplestoreResult(FuncExprState *fcache, - ExprContext *econtext, - Tuplestorestate *resultStore, - TupleDesc resultDesc) -{ - fcache->funcResultStore = resultStore; - - if (fcache->funcResultSlot == NULL) - { - /* Create a slot so we can read data out of the tuplestore */ - TupleDesc slotDesc; - MemoryContext oldcontext; - - oldcontext = MemoryContextSwitchTo(fcache->func.fn_mcxt); - - /* - * If we were not able to determine the result rowtype from context, - * and the function didn't return a tupdesc, we have to fail. - */ - if (fcache->funcResultDesc) - slotDesc = fcache->funcResultDesc; - else if (resultDesc) - { - /* don't assume resultDesc is long-lived */ - slotDesc = CreateTupleDescCopy(resultDesc); - } - else - { - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("function returning setof record called in " - "context that cannot accept type record"))); - slotDesc = NULL; /* keep compiler quiet */ - } - - fcache->funcResultSlot = MakeSingleTupleTableSlot(slotDesc); - MemoryContextSwitchTo(oldcontext); - } - - /* - * If function provided a tupdesc, cross-check it. We only really need to - * do this for functions returning RECORD, but might as well do it always. - */ - if (resultDesc) - { - if (fcache->funcResultDesc) - tupledesc_match(fcache->funcResultDesc, resultDesc); - - /* - * If it is a dynamically-allocated TupleDesc, free it: it is - * typically allocated in a per-query context, so we must avoid - * leaking it across multiple usages. - */ - if (resultDesc->tdrefcount == -1) - FreeTupleDesc(resultDesc); - } - - /* Register cleanup callback if we didn't already */ - if (!fcache->shutdown_reg) - { - RegisterExprContextCallback(econtext, - ShutdownFuncExpr, - PointerGetDatum(fcache)); - fcache->shutdown_reg = true; - } -} - -/* - * Check that function result tuple type (src_tupdesc) matches or can - * be considered to match what the query expects (dst_tupdesc). If - * they don't match, ereport. - * - * We really only care about number of attributes and data type. - * Also, we can ignore type mismatch on columns that are dropped in the - * destination type, so long as the physical storage matches. This is - * helpful in some cases involving out-of-date cached plans. - */ -static void -tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc) -{ - int i; - - if (dst_tupdesc->natts != src_tupdesc->natts) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("function return row and query-specified return row do not match"), - errdetail_plural("Returned row contains %d attribute, but query expects %d.", - "Returned row contains %d attributes, but query expects %d.", - src_tupdesc->natts, - src_tupdesc->natts, dst_tupdesc->natts))); - - for (i = 0; i < dst_tupdesc->natts; i++) - { - Form_pg_attribute dattr = dst_tupdesc->attrs[i]; - Form_pg_attribute sattr = src_tupdesc->attrs[i]; - - if (IsBinaryCoercible(sattr->atttypid, dattr->atttypid)) - continue; /* no worries */ - if (!dattr->attisdropped) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("function return row and query-specified return row do not match"), - errdetail("Returned type %s at ordinal position %d, but query expects %s.", - format_type_be(sattr->atttypid), - i + 1, - format_type_be(dattr->atttypid)))); - - if (dattr->attlen != sattr->attlen || - dattr->attalign != sattr->attalign) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("function return row and query-specified return row do not match"), - errdetail("Physical storage mismatch on dropped attribute at ordinal position %d.", - i + 1))); - } -} - -/* - * ExecMakeFunctionResult - * - * Evaluate the arguments to a function and then the function itself. - * init_fcache is presumed already run on the FuncExprState. - * - * This function handles the most general case, wherein the function or - * one of its arguments can return a set. - */ -static Datum -ExecMakeFunctionResult(FuncExprState *fcache, - ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) -{ - List *arguments; - Datum result; - FunctionCallInfo fcinfo; - PgStat_FunctionCallUsage fcusage; - ReturnSetInfo rsinfo; /* for functions returning sets */ - ExprDoneCond argDone; - bool hasSetArg; - int i; - -restart: - - /* Guard against stack overflow due to overly complex expressions */ - check_stack_depth(); - - /* - * If a previous call of the function returned a set result in the form of - * a tuplestore, continue reading rows from the tuplestore until it's - * empty. - */ - if (fcache->funcResultStore) - { - Assert(isDone); /* it was provided before ... */ - if (tuplestore_gettupleslot(fcache->funcResultStore, true, false, - fcache->funcResultSlot)) - { - *isDone = ExprMultipleResult; - if (fcache->funcReturnsTuple) - { - /* We must return the whole tuple as a Datum. */ - *isNull = false; - return ExecFetchSlotTupleDatum(fcache->funcResultSlot); - } - else - { - /* Extract the first column and return it as a scalar. */ - return slot_getattr(fcache->funcResultSlot, 1, isNull); - } - } - /* Exhausted the tuplestore, so clean up */ - tuplestore_end(fcache->funcResultStore); - fcache->funcResultStore = NULL; - /* We are done unless there was a set-valued argument */ - if (!fcache->setHasSetArg) - { - *isDone = ExprEndResult; - *isNull = true; - return (Datum) 0; - } - /* If there was, continue evaluating the argument values */ - Assert(!fcache->setArgsValid); - } - - /* - * arguments is a list of expressions to evaluate before passing to the - * function manager. We skip the evaluation if it was already done in the - * previous call (ie, we are continuing the evaluation of a set-valued - * function). Otherwise, collect the current argument values into fcinfo. - */ - fcinfo = &fcache->fcinfo_data; - arguments = fcache->args; - if (!fcache->setArgsValid) - { - argDone = ExecEvalFuncArgs(fcinfo, arguments, econtext); - if (argDone == ExprEndResult) - { - /* input is an empty set, so return an empty set. */ - *isNull = true; - if (isDone) - *isDone = ExprEndResult; - else - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("set-valued function called in context that cannot accept a set"))); - return (Datum) 0; - } - hasSetArg = (argDone != ExprSingleResult); - } - else - { - /* Re-use callinfo from previous evaluation */ - hasSetArg = fcache->setHasSetArg; - /* Reset flag (we may set it again below) */ - fcache->setArgsValid = false; - } - - /* - * Now call the function, passing the evaluated parameter values. - */ - if (fcache->func.fn_retset || hasSetArg) - { - /* - * We need to return a set result. Complain if caller not ready to - * accept one. - */ - if (isDone == NULL) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("set-valued function called in context that cannot accept a set"))); - - /* - * Prepare a resultinfo node for communication. If the function - * doesn't itself return set, we don't pass the resultinfo to the - * function, but we need to fill it in anyway for internal use. - */ - if (fcache->func.fn_retset) - fcinfo->resultinfo = (Node *) &rsinfo; - rsinfo.type = T_ReturnSetInfo; - rsinfo.econtext = econtext; - rsinfo.expectedDesc = fcache->funcResultDesc; - rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize); - /* note we do not set SFRM_Materialize_Random or _Preferred */ - rsinfo.returnMode = SFRM_ValuePerCall; - /* isDone is filled below */ - rsinfo.setResult = NULL; - rsinfo.setDesc = NULL; - - /* - * This loop handles the situation where we have both a set argument - * and a set-valued function. Once we have exhausted the function's - * value(s) for a particular argument value, we have to get the next - * argument value and start the function over again. We might have to - * do it more than once, if the function produces an empty result set - * for a particular input value. - */ - for (;;) - { - /* - * If function is strict, and there are any NULL arguments, skip - * calling the function (at least for this set of args). - */ - bool callit = true; - - if (fcache->func.fn_strict) - { - for (i = 0; i < fcinfo->nargs; i++) - { - if (fcinfo->argnull[i]) - { - callit = false; - break; - } - } - } - - if (callit) - { - pgstat_init_function_usage(fcinfo, &fcusage); - - fcinfo->isnull = false; - rsinfo.isDone = ExprSingleResult; - result = FunctionCallInvoke(fcinfo); - *isNull = fcinfo->isnull; - *isDone = rsinfo.isDone; - - pgstat_end_function_usage(&fcusage, - rsinfo.isDone != ExprMultipleResult); - } - else if (fcache->func.fn_retset) - { - /* for a strict SRF, result for NULL is an empty set */ - result = (Datum) 0; - *isNull = true; - *isDone = ExprEndResult; - } - else - { - /* for a strict non-SRF, result for NULL is a NULL */ - result = (Datum) 0; - *isNull = true; - *isDone = ExprSingleResult; - } - - /* Which protocol does function want to use? */ - if (rsinfo.returnMode == SFRM_ValuePerCall) - { - if (*isDone != ExprEndResult) - { - /* - * Got a result from current argument. If function itself - * returns set, save the current argument values to re-use - * on the next call. - */ - if (fcache->func.fn_retset && - *isDone == ExprMultipleResult) - { - fcache->setHasSetArg = hasSetArg; - fcache->setArgsValid = true; - /* Register cleanup callback if we didn't already */ - if (!fcache->shutdown_reg) - { - RegisterExprContextCallback(econtext, - ShutdownFuncExpr, - PointerGetDatum(fcache)); - fcache->shutdown_reg = true; - } - } - - /* - * Make sure we say we are returning a set, even if the - * function itself doesn't return sets. - */ - if (hasSetArg) - *isDone = ExprMultipleResult; - break; - } - } - else if (rsinfo.returnMode == SFRM_Materialize) - { - /* check we're on the same page as the function author */ - if (rsinfo.isDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED), - errmsg("table-function protocol for materialize mode was not followed"))); - if (rsinfo.setResult != NULL) - { - /* prepare to return values from the tuplestore */ - ExecPrepareTuplestoreResult(fcache, econtext, - rsinfo.setResult, - rsinfo.setDesc); - /* remember whether we had set arguments */ - fcache->setHasSetArg = hasSetArg; - /* loop back to top to start returning from tuplestore */ - goto restart; - } - /* if setResult was left null, treat it as empty set */ - *isDone = ExprEndResult; - *isNull = true; - result = (Datum) 0; - } - else - ereport(ERROR, - (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED), - errmsg("unrecognized table-function returnMode: %d", - (int) rsinfo.returnMode))); - - /* Else, done with this argument */ - if (!hasSetArg) - break; /* input not a set, so done */ - - /* Re-eval args to get the next element of the input set */ - argDone = ExecEvalFuncArgs(fcinfo, arguments, econtext); - - if (argDone != ExprMultipleResult) - { - /* End of argument set, so we're done. */ - *isNull = true; - *isDone = ExprEndResult; - result = (Datum) 0; - break; - } - - /* - * If we reach here, loop around to run the function on the new - * argument. - */ - } - } - else - { - /* - * Non-set case: much easier. - * - * In common cases, this code path is unreachable because we'd have - * selected ExecMakeFunctionResultNoSets instead. However, it's - * possible to get here if an argument sometimes produces set results - * and sometimes scalar results. For example, a CASE expression might - * call a set-returning function in only some of its arms. - */ - if (isDone) - *isDone = ExprSingleResult; - - /* - * If function is strict, and there are any NULL arguments, skip - * calling the function and return NULL. - */ - if (fcache->func.fn_strict) - { - for (i = 0; i < fcinfo->nargs; i++) - { - if (fcinfo->argnull[i]) - { - *isNull = true; - return (Datum) 0; - } - } - } - - pgstat_init_function_usage(fcinfo, &fcusage); - - fcinfo->isnull = false; - result = FunctionCallInvoke(fcinfo); - *isNull = fcinfo->isnull; - - pgstat_end_function_usage(&fcusage, true); - } - - return result; } /* * ExecMakeFunctionResultNoSets * - * Simplified version of ExecMakeFunctionResult that can only handle - * non-set cases. Hand-tuned for speed. + * Portion of ExecMakeFunctionResult that does not need initialization. + * Hand-tuned for speed. */ static Datum ExecMakeFunctionResultNoSets(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { ListCell *arg; Datum result; @@ -2003,9 +1398,6 @@ ExecMakeFunctionResultNoSets(FuncExprState *fcache, /* Guard against stack overflow due to overly complex expressions */ check_stack_depth(); - if (isDone) - *isDone = ExprSingleResult; - /* inlined, simplified version of ExecEvalFuncArgs */ fcinfo = &fcache->fcinfo_data; i = 0; @@ -2015,8 +1407,7 @@ ExecMakeFunctionResultNoSets(FuncExprState *fcache, fcinfo->arg[i] = ExecEvalExpr(argstate, econtext, - &fcinfo->argnull[i], - NULL); + &fcinfo->argnull[i]); i++; } @@ -2064,15 +1455,14 @@ ExecMakeFunctionResultNoSets(FuncExprState *fcache, static Datum ExecEvalFunc(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { /* This is called only the first time through */ FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; /* Initialize function lookup info */ ExecInitFcache(func->funcid, func->inputcollid, fcache, - econtext->ecxt_per_query_memory, true); + econtext->ecxt_per_query_memory); if (fcache->func.fn_retset) { @@ -2081,22 +1471,9 @@ ExecEvalFunc(FuncExprState *fcache, errmsg("set-valued function called in context that cannot accept a set"))); } - /* - * We need to invoke ExecMakeFunctionResult if either the function itself - * or any of its input expressions can return a set. Otherwise, invoke - * ExecMakeFunctionResultNoSets. In either case, change the evalfunc - * pointer to go directly there on subsequent uses. - */ - if (fcache->func.fn_retset || expression_returns_set((Node *) func->args)) - { - fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult; - return ExecMakeFunctionResult(fcache, econtext, isNull, isDone); - } - else - { - fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets; - return ExecMakeFunctionResultNoSets(fcache, econtext, isNull, isDone); - } + /* Change the evalfunc pointer, to skip the above initialization. */ + fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets; + return ExecMakeFunctionResultNoSets(fcache, econtext, isNull); } /* ---------------------------------------------------------------- @@ -2106,32 +1483,25 @@ ExecEvalFunc(FuncExprState *fcache, static Datum ExecEvalOper(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { /* This is called only the first time through */ OpExpr *op = (OpExpr *) fcache->xprstate.expr; /* Initialize function lookup info */ ExecInitFcache(op->opfuncid, op->inputcollid, fcache, - econtext->ecxt_per_query_memory, true); + econtext->ecxt_per_query_memory); - /* - * We need to invoke ExecMakeFunctionResult if either the function itself - * or any of its input expressions can return a set. Otherwise, invoke - * ExecMakeFunctionResultNoSets. In either case, change the evalfunc - * pointer to go directly there on subsequent uses. - */ - if (fcache->func.fn_retset || expression_returns_set((Node *) op->args)) + if (fcache->func.fn_retset) { - fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResult; - return ExecMakeFunctionResult(fcache, econtext, isNull, isDone); - } - else - { - fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets; - return ExecMakeFunctionResultNoSets(fcache, econtext, isNull, isDone); + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("set-valued function called in context that cannot accept a set"))); } + + /* Change the evalfunc pointer, to skip the above initialization. */ + fcache->xprstate.evalfunc = (ExprStateEvalFunc) ExecMakeFunctionResultNoSets; + return ExecMakeFunctionResultNoSets(fcache, econtext, isNull); } /* ---------------------------------------------------------------- @@ -2148,17 +1518,13 @@ ExecEvalOper(FuncExprState *fcache, static Datum ExecEvalDistinct(FuncExprState *fcache, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { Datum result; FunctionCallInfo fcinfo; - ExprDoneCond argDone; - /* Set default values for result flags: non-null, not a set result */ + /* Set non-null as default */ *isNull = false; - if (isDone) - *isDone = ExprSingleResult; /* * Initialize function cache if first time through @@ -2168,7 +1534,7 @@ ExecEvalDistinct(FuncExprState *fcache, DistinctExpr *op = (DistinctExpr *) fcache->xprstate.expr; ExecInitFcache(op->opfuncid, op->inputcollid, fcache, - econtext->ecxt_per_query_memory, true); + econtext->ecxt_per_query_memory); Assert(!fcache->func.fn_retset); } @@ -2176,11 +1542,7 @@ ExecEvalDistinct(FuncExprState *fcache, * Evaluate arguments */ fcinfo = &fcache->fcinfo_data; - argDone = ExecEvalFuncArgs(fcinfo, fcache->args, econtext); - if (argDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("IS DISTINCT FROM does not support set arguments"))); + ExecEvalFuncArgs(fcinfo, fcache->args, econtext); Assert(fcinfo->nargs == 2); if (fcinfo->argnull[0] && fcinfo->argnull[1]) @@ -2216,7 +1578,7 @@ ExecEvalDistinct(FuncExprState *fcache, static Datum ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) sstate->fxprstate.xprstate.expr; bool useOr = opexpr->useOr; @@ -2225,7 +1587,6 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, Datum result; bool resultnull; FunctionCallInfo fcinfo; - ExprDoneCond argDone; int i; int16 typlen; bool typbyval; @@ -2234,10 +1595,8 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, bits8 *bitmap; int bitmask; - /* Set default values for result flags: non-null, not a set result */ + /* Set non-null as default */ *isNull = false; - if (isDone) - *isDone = ExprSingleResult; /* * Initialize function cache if first time through @@ -2245,7 +1604,7 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, if (sstate->fxprstate.func.fn_oid == InvalidOid) { ExecInitFcache(opexpr->opfuncid, opexpr->inputcollid, &sstate->fxprstate, - econtext->ecxt_per_query_memory, true); + econtext->ecxt_per_query_memory); Assert(!sstate->fxprstate.func.fn_retset); } @@ -2253,11 +1612,7 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, * Evaluate arguments */ fcinfo = &sstate->fxprstate.fcinfo_data; - argDone = ExecEvalFuncArgs(fcinfo, sstate->fxprstate.args, econtext); - if (argDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("op ANY/ALL (array) does not support set arguments"))); + ExecEvalFuncArgs(fcinfo, sstate->fxprstate.args, econtext); Assert(fcinfo->nargs == 2); /* @@ -2403,15 +1758,12 @@ ExecEvalScalarArrayOp(ScalarArrayOpExprState *sstate, */ static Datum ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { ExprState *clause = linitial(notclause->args); Datum expr_value; - if (isDone) - *isDone = ExprSingleResult; - - expr_value = ExecEvalExpr(clause, econtext, isNull, NULL); + expr_value = ExecEvalExpr(clause, econtext, isNull); /* * if the expression evaluates to null, then we just cascade the null back @@ -2433,15 +1785,12 @@ ExecEvalNot(BoolExprState *notclause, ExprContext *econtext, */ static Datum ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { List *clauses = orExpr->args; ListCell *clause; bool AnyNull; - if (isDone) - *isDone = ExprSingleResult; - AnyNull = false; /* @@ -2462,7 +1811,7 @@ ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, ExprState *clausestate = (ExprState *) lfirst(clause); Datum clause_value; - clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL); + clause_value = ExecEvalExpr(clausestate, econtext, isNull); /* * if we have a non-null true result, then return it. @@ -2484,15 +1833,12 @@ ExecEvalOr(BoolExprState *orExpr, ExprContext *econtext, */ static Datum ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { List *clauses = andExpr->args; ListCell *clause; bool AnyNull; - if (isDone) - *isDone = ExprSingleResult; - AnyNull = false; /* @@ -2509,7 +1855,7 @@ ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, ExprState *clausestate = (ExprState *) lfirst(clause); Datum clause_value; - clause_value = ExecEvalExpr(clausestate, econtext, isNull, NULL); + clause_value = ExecEvalExpr(clausestate, econtext, isNull); /* * if we have a non-null false result, then return it. @@ -2535,7 +1881,7 @@ ExecEvalAnd(BoolExprState *andExpr, ExprContext *econtext, static Datum ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) cstate->xprstate.expr; HeapTuple result; @@ -2543,7 +1889,7 @@ ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate, HeapTupleHeader tuple; HeapTupleData tmptup; - tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull, isDone); + tupDatum = ExecEvalExpr(cstate->arg, econtext, isNull); /* this test covers the isDone exception too: */ if (*isNull) @@ -2619,16 +1965,13 @@ ExecEvalConvertRowtype(ConvertRowtypeExprState *cstate, */ static Datum ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { List *clauses = caseExpr->args; ListCell *clause; Datum save_datum; bool save_isNull; - if (isDone) - *isDone = ExprSingleResult; - /* * If there's a test expression, we have to evaluate it and save the value * where the CaseTestExpr placeholders can find it. We must save and @@ -2652,8 +1995,7 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, econtext->caseValue_datum = ExecEvalExpr(caseExpr->arg, econtext, - &arg_isNull, - NULL); + &arg_isNull); econtext->caseValue_isNull = arg_isNull; } @@ -2670,8 +2012,7 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, clause_value = ExecEvalExpr(wclause->expr, econtext, - &clause_isNull, - NULL); + &clause_isNull); /* * if we have a true test, then we return the result, since the case @@ -2684,8 +2025,7 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, econtext->caseValue_isNull = save_isNull; return ExecEvalExpr(wclause->result, econtext, - isNull, - isDone); + isNull); } } @@ -2696,8 +2036,7 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, { return ExecEvalExpr(caseExpr->defresult, econtext, - isNull, - isDone); + isNull); } *isNull = true; @@ -2712,10 +2051,8 @@ ExecEvalCase(CaseExprState *caseExpr, ExprContext *econtext, static Datum ExecEvalCaseTestExpr(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { - if (isDone) - *isDone = ExprSingleResult; *isNull = econtext->caseValue_isNull; return econtext->caseValue_datum; } @@ -2732,17 +2069,13 @@ ExecEvalCaseTestExpr(ExprState *exprstate, static Datum ExecEvalGroupingFuncExpr(GroupingFuncExprState *gstate, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { int result = 0; int attnum = 0; Bitmapset *grouped_cols = gstate->aggstate->grouped_cols; ListCell *lc; - if (isDone) - *isDone = ExprSingleResult; - *isNull = false; foreach(lc, (gstate->clauses)) @@ -2764,7 +2097,7 @@ ExecEvalGroupingFuncExpr(GroupingFuncExprState *gstate, */ static Datum ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { ArrayExpr *arrayExpr = (ArrayExpr *) astate->xprstate.expr; ArrayType *result; @@ -2774,10 +2107,8 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, int dims[MAXDIM]; int lbs[MAXDIM]; - /* Set default values for result flags: non-null, not a set result */ + /* Set default values for result flags: non-null */ *isNull = false; - if (isDone) - *isDone = ExprSingleResult; if (!arrayExpr->multidims) { @@ -2802,7 +2133,7 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, { ExprState *e = (ExprState *) lfirst(element); - dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i], NULL); + dvalues[i] = ExecEvalExpr(e, econtext, &dnulls[i]); i++; } @@ -2852,7 +2183,7 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, ArrayType *array; int this_ndims; - arraydatum = ExecEvalExpr(e, econtext, &eisnull, NULL); + arraydatum = ExecEvalExpr(e, econtext, &eisnull); /* temporarily ignore null subarrays */ if (eisnull) { @@ -2991,7 +2322,7 @@ ExecEvalArray(ArrayExprState *astate, ExprContext *econtext, static Datum ExecEvalRow(RowExprState *rstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { HeapTuple tuple; Datum *values; @@ -3000,10 +2331,8 @@ ExecEvalRow(RowExprState *rstate, ListCell *arg; int i; - /* Set default values for result flags: non-null, not a set result */ + /* Set default values for result flag: non-null */ *isNull = false; - if (isDone) - *isDone = ExprSingleResult; /* Allocate workspace */ natts = rstate->tupdesc->natts; @@ -3019,7 +2348,7 @@ ExecEvalRow(RowExprState *rstate, { ExprState *e = (ExprState *) lfirst(arg); - values[i] = ExecEvalExpr(e, econtext, &isnull[i], NULL); + values[i] = ExecEvalExpr(e, econtext, &isnull[i]); i++; } @@ -3038,7 +2367,7 @@ ExecEvalRow(RowExprState *rstate, static Datum ExecEvalRowCompare(RowCompareExprState *rstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { bool result; RowCompareType rctype = ((RowCompareExpr *) rstate->xprstate.expr)->rctype; @@ -3047,8 +2376,6 @@ ExecEvalRowCompare(RowCompareExprState *rstate, ListCell *r; int i; - if (isDone) - *isDone = ExprSingleResult; *isNull = true; /* until we get a result */ i = 0; @@ -3062,9 +2389,9 @@ ExecEvalRowCompare(RowCompareExprState *rstate, rstate->collations[i], NULL, NULL); locfcinfo.arg[0] = ExecEvalExpr(le, econtext, - &locfcinfo.argnull[0], NULL); + &locfcinfo.argnull[0]); locfcinfo.arg[1] = ExecEvalExpr(re, econtext, - &locfcinfo.argnull[1], NULL); + &locfcinfo.argnull[1]); if (rstate->funcs[i].fn_strict && (locfcinfo.argnull[0] || locfcinfo.argnull[1])) return (Datum) 0; /* force NULL result */ @@ -3108,20 +2435,17 @@ ExecEvalRowCompare(RowCompareExprState *rstate, */ static Datum ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { ListCell *arg; - if (isDone) - *isDone = ExprSingleResult; - /* Simply loop through until something NOT NULL is found */ foreach(arg, coalesceExpr->args) { ExprState *e = (ExprState *) lfirst(arg); Datum value; - value = ExecEvalExpr(e, econtext, isNull, NULL); + value = ExecEvalExpr(e, econtext, isNull); if (!*isNull) return value; } @@ -3137,7 +2461,7 @@ ExecEvalCoalesce(CoalesceExprState *coalesceExpr, ExprContext *econtext, */ static Datum ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Datum result = (Datum) 0; MinMaxExpr *minmax = (MinMaxExpr *) minmaxExpr->xprstate.expr; @@ -3146,8 +2470,6 @@ ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext, FunctionCallInfoData locfcinfo; ListCell *arg; - if (isDone) - *isDone = ExprSingleResult; *isNull = true; /* until we get a result */ InitFunctionCallInfoData(locfcinfo, &minmaxExpr->cfunc, 2, @@ -3162,7 +2484,7 @@ ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext, bool valueIsNull; int32 cmpresult; - value = ExecEvalExpr(e, econtext, &valueIsNull, NULL); + value = ExecEvalExpr(e, econtext, &valueIsNull); if (valueIsNull) continue; /* ignore NULL inputs */ @@ -3198,14 +2520,12 @@ ExecEvalMinMax(MinMaxExprState *minmaxExpr, ExprContext *econtext, static Datum ExecEvalSQLValueFunction(ExprState *svfExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Datum result = (Datum) 0; SQLValueFunction *svf = (SQLValueFunction *) svfExpr->expr; FunctionCallInfoData fcinfo; - if (isDone) - *isDone = ExprSingleResult; *isNull = false; /* @@ -3266,7 +2586,7 @@ ExecEvalSQLValueFunction(ExprState *svfExpr, */ static Datum ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { XmlExpr *xexpr = (XmlExpr *) xmlExpr->xprstate.expr; Datum value; @@ -3274,8 +2594,6 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, ListCell *arg; ListCell *narg; - if (isDone) - *isDone = ExprSingleResult; *isNull = true; /* until we get a result */ switch (xexpr->op) @@ -3288,7 +2606,7 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, { ExprState *e = (ExprState *) lfirst(arg); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (!isnull) values = lappend(values, DatumGetPointer(value)); } @@ -3313,7 +2631,7 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, ExprState *e = (ExprState *) lfirst(arg); char *argname = strVal(lfirst(narg)); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (!isnull) { appendStringInfo(&buf, "<%s>%s</%s>", @@ -3356,13 +2674,13 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, Assert(list_length(xmlExpr->args) == 2); e = (ExprState *) linitial(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) return (Datum) 0; data = DatumGetTextP(value); e = (ExprState *) lsecond(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) /* probably can't happen */ return (Datum) 0; preserve_whitespace = DatumGetBool(value); @@ -3386,7 +2704,7 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, if (xmlExpr->args) { e = (ExprState *) linitial(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) arg = NULL; else @@ -3413,20 +2731,20 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, Assert(list_length(xmlExpr->args) == 3); e = (ExprState *) linitial(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) return (Datum) 0; data = DatumGetXmlP(value); e = (ExprState *) lsecond(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) version = NULL; else version = DatumGetTextP(value); e = (ExprState *) lthird(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); standalone = DatumGetInt32(value); *isNull = false; @@ -3445,7 +2763,7 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, Assert(list_length(xmlExpr->args) == 1); e = (ExprState *) linitial(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) return (Datum) 0; @@ -3463,7 +2781,7 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, Assert(list_length(xmlExpr->args) == 1); e = (ExprState *) linitial(xmlExpr->args); - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) return (Datum) 0; else @@ -3490,14 +2808,10 @@ ExecEvalXml(XmlExprState *xmlExpr, ExprContext *econtext, static Datum ExecEvalNullIf(FuncExprState *nullIfExpr, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Datum result; FunctionCallInfo fcinfo; - ExprDoneCond argDone; - - if (isDone) - *isDone = ExprSingleResult; /* * Initialize function cache if first time through @@ -3507,7 +2821,7 @@ ExecEvalNullIf(FuncExprState *nullIfExpr, NullIfExpr *op = (NullIfExpr *) nullIfExpr->xprstate.expr; ExecInitFcache(op->opfuncid, op->inputcollid, nullIfExpr, - econtext->ecxt_per_query_memory, true); + econtext->ecxt_per_query_memory); Assert(!nullIfExpr->func.fn_retset); } @@ -3515,11 +2829,7 @@ ExecEvalNullIf(FuncExprState *nullIfExpr, * Evaluate arguments */ fcinfo = &nullIfExpr->fcinfo_data; - argDone = ExecEvalFuncArgs(fcinfo, nullIfExpr->args, econtext); - if (argDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_DATATYPE_MISMATCH), - errmsg("NULLIF does not support set arguments"))); + ExecEvalFuncArgs(fcinfo, nullIfExpr->args, econtext); Assert(fcinfo->nargs == 2); /* if either argument is NULL they can't be equal */ @@ -3549,16 +2859,12 @@ ExecEvalNullIf(FuncExprState *nullIfExpr, static Datum ExecEvalNullTest(NullTestState *nstate, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { NullTest *ntest = (NullTest *) nstate->xprstate.expr; Datum result; - result = ExecEvalExpr(nstate->arg, econtext, isNull, isDone); - - if (isDone && *isDone == ExprEndResult) - return result; /* nothing to check */ + result = ExecEvalExpr(nstate->arg, econtext, isNull); if (ntest->argisrow && !(*isNull)) { @@ -3658,16 +2964,12 @@ ExecEvalNullTest(NullTestState *nstate, static Datum ExecEvalBooleanTest(GenericExprState *bstate, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { BooleanTest *btest = (BooleanTest *) bstate->xprstate.expr; Datum result; - result = ExecEvalExpr(bstate->arg, econtext, isNull, isDone); - - if (isDone && *isDone == ExprEndResult) - return result; /* nothing to check */ + result = ExecEvalExpr(bstate->arg, econtext, isNull); switch (btest->booltesttype) { @@ -3743,16 +3045,13 @@ ExecEvalBooleanTest(GenericExprState *bstate, */ static Datum ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { CoerceToDomain *ctest = (CoerceToDomain *) cstate->xprstate.expr; Datum result; ListCell *l; - result = ExecEvalExpr(cstate->arg, econtext, isNull, isDone); - - if (isDone && *isDone == ExprEndResult) - return result; /* nothing to check */ + result = ExecEvalExpr(cstate->arg, econtext, isNull); /* Make sure we have up-to-date constraints */ UpdateDomainConstraintRef(cstate->constraint_ref); @@ -3790,8 +3089,8 @@ ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext, econtext->domainValue_datum = result; econtext->domainValue_isNull = *isNull; - conResult = ExecEvalExpr(con->check_expr, - econtext, &conIsNull, NULL); + conResult = ExecEvalExpr(con->check_expr, econtext, + &conIsNull); if (!conIsNull && !DatumGetBool(conResult)) @@ -3826,10 +3125,8 @@ ExecEvalCoerceToDomain(CoerceToDomainState *cstate, ExprContext *econtext, static Datum ExecEvalCoerceToDomainValue(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { - if (isDone) - *isDone = ExprSingleResult; *isNull = econtext->domainValue_isNull; return econtext->domainValue_datum; } @@ -3843,8 +3140,7 @@ ExecEvalCoerceToDomainValue(ExprState *exprstate, static Datum ExecEvalFieldSelect(FieldSelectState *fstate, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { FieldSelect *fselect = (FieldSelect *) fstate->xprstate.expr; AttrNumber fieldnum = fselect->fieldnum; @@ -3857,7 +3153,7 @@ ExecEvalFieldSelect(FieldSelectState *fstate, Form_pg_attribute attr; HeapTupleData tmptup; - tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone); + tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull); /* this test covers the isDone exception too: */ if (*isNull) @@ -3922,8 +3218,7 @@ ExecEvalFieldSelect(FieldSelectState *fstate, static Datum ExecEvalFieldStore(FieldStoreState *fstate, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { FieldStore *fstore = (FieldStore *) fstate->xprstate.expr; HeapTuple tuple; @@ -3936,10 +3231,7 @@ ExecEvalFieldStore(FieldStoreState *fstate, ListCell *l1, *l2; - tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull, isDone); - - if (isDone && *isDone == ExprEndResult) - return tupDatum; + tupDatum = ExecEvalExpr(fstate->arg, econtext, isNull); /* Lookup tupdesc if first time through or after rescan */ tupDesc = get_cached_rowtype(fstore->resulttype, -1, @@ -3999,8 +3291,7 @@ ExecEvalFieldStore(FieldStoreState *fstate, values[fieldnum - 1] = ExecEvalExpr(newval, econtext, - &isnull[fieldnum - 1], - NULL); + &isnull[fieldnum - 1]); } econtext->caseValue_datum = save_datum; @@ -4023,9 +3314,9 @@ ExecEvalFieldStore(FieldStoreState *fstate, static Datum ExecEvalRelabelType(GenericExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { - return ExecEvalExpr(exprstate->arg, econtext, isNull, isDone); + return ExecEvalExpr(exprstate->arg, econtext, isNull); } /* ---------------------------------------------------------------- @@ -4037,16 +3328,13 @@ ExecEvalRelabelType(GenericExprState *exprstate, static Datum ExecEvalCoerceViaIO(CoerceViaIOState *iostate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { Datum result; Datum inputval; char *string; - inputval = ExecEvalExpr(iostate->arg, econtext, isNull, isDone); - - if (isDone && *isDone == ExprEndResult) - return inputval; /* nothing to do */ + inputval = ExecEvalExpr(iostate->arg, econtext, isNull); if (*isNull) string = NULL; /* output functions are not called on nulls */ @@ -4071,16 +3359,14 @@ ExecEvalCoerceViaIO(CoerceViaIOState *iostate, static Datum ExecEvalArrayCoerceExpr(ArrayCoerceExprState *astate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) astate->xprstate.expr; Datum result; FunctionCallInfoData locfcinfo; - result = ExecEvalExpr(astate->arg, econtext, isNull, isDone); + result = ExecEvalExpr(astate->arg, econtext, isNull); - if (isDone && *isDone == ExprEndResult) - return result; /* nothing to do */ if (*isNull) return result; /* nothing to do */ @@ -4148,7 +3434,7 @@ ExecEvalArrayCoerceExpr(ArrayCoerceExprState *astate, */ static Datum ExecEvalCurrentOfExpr(ExprState *exprstate, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone) + bool *isNull) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), @@ -4165,14 +3451,13 @@ ExecEvalCurrentOfExpr(ExprState *exprstate, ExprContext *econtext, Datum ExecEvalExprSwitchContext(ExprState *expression, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { Datum retDatum; MemoryContext oldContext; oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); - retDatum = ExecEvalExpr(expression, econtext, isNull, isDone); + retDatum = ExecEvalExpr(expression, econtext, isNull); MemoryContextSwitchTo(oldContext); return retDatum; } @@ -5032,7 +4317,7 @@ ExecQual(List *qual, ExprContext *econtext, bool resultForNull) Datum expr_value; bool isNull; - expr_value = ExecEvalExpr(clause, econtext, &isNull, NULL); + expr_value = ExecEvalExpr(clause, econtext, &isNull); if (isNull) { @@ -5090,17 +4375,9 @@ ExecCleanTargetListLength(List *targetlist) /* * ExecTargetList * Evaluates a targetlist with respect to the given - * expression context. Returns TRUE if we were able to create - * a result, FALSE if we have exhausted a set-valued expression. + * expression context. * * Results are stored into the passed values and isnull arrays. - * The caller must provide an itemIsDone array that persists across calls. - * - * As with ExecEvalExpr, the caller should pass isDone = NULL if not - * prepared to deal with sets of result tuples. Otherwise, a return - * of *isDone = ExprMultipleResult signifies a set element, and a return - * of *isDone = ExprEndResult signifies end of the set of tuple. - * We assume that *isDone has been initialized to ExprSingleResult by caller. * * Since fields of the result tuple might be multiply referenced in higher * plan nodes, we have to force any read/write expanded values to read-only @@ -5109,19 +4386,16 @@ ExecCleanTargetListLength(List *targetlist) * actually-multiply-referenced Vars and insert an expression node that * would do that only where really required. */ -static bool +static void ExecTargetList(List *targetlist, TupleDesc tupdesc, ExprContext *econtext, Datum *values, - bool *isnull, - ExprDoneCond *itemIsDone, - ExprDoneCond *isDone) + bool *isnull) { Form_pg_attribute *att = tupdesc->attrs; MemoryContext oldContext; ListCell *tl; - bool haveDoneSets; /* * Run in short-lived per-tuple context while computing expressions. @@ -5131,8 +4405,6 @@ ExecTargetList(List *targetlist, /* * evaluate all the expressions in the target list */ - haveDoneSets = false; /* any exhausted set exprs in tlist? */ - foreach(tl, targetlist) { GenericExprState *gstate = (GenericExprState *) lfirst(tl); @@ -5141,117 +4413,15 @@ ExecTargetList(List *targetlist, values[resind] = ExecEvalExpr(gstate->arg, econtext, - &isnull[resind], - &itemIsDone[resind]); + &isnull[resind]); values[resind] = MakeExpandedObjectReadOnly(values[resind], isnull[resind], att[resind]->attlen); - - if (itemIsDone[resind] != ExprSingleResult) - { - /* We have a set-valued expression in the tlist */ - if (isDone == NULL) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("set-valued function called in context that cannot accept a set"))); - if (itemIsDone[resind] == ExprMultipleResult) - { - /* we have undone sets in the tlist, set flag */ - *isDone = ExprMultipleResult; - } - else - { - /* we have done sets in the tlist, set flag for that */ - haveDoneSets = true; - } - } - } - - if (haveDoneSets) - { - /* - * note: can't get here unless we verified isDone != NULL - */ - if (*isDone == ExprSingleResult) - { - /* - * all sets are done, so report that tlist expansion is complete. - */ - *isDone = ExprEndResult; - MemoryContextSwitchTo(oldContext); - return false; - } - else - { - /* - * We have some done and some undone sets. Restart the done ones - * so that we can deliver a tuple (if possible). - */ - foreach(tl, targetlist) - { - GenericExprState *gstate = (GenericExprState *) lfirst(tl); - TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr; - AttrNumber resind = tle->resno - 1; - - if (itemIsDone[resind] == ExprEndResult) - { - values[resind] = ExecEvalExpr(gstate->arg, - econtext, - &isnull[resind], - &itemIsDone[resind]); - - values[resind] = MakeExpandedObjectReadOnly(values[resind], - isnull[resind], - att[resind]->attlen); - - if (itemIsDone[resind] == ExprEndResult) - { - /* - * Oh dear, this item is returning an empty set. Guess - * we can't make a tuple after all. - */ - *isDone = ExprEndResult; - break; - } - } - } - - /* - * If we cannot make a tuple because some sets are empty, we still - * have to cycle the nonempty sets to completion, else resources - * will not be released from subplans etc. - * - * XXX is that still necessary? - */ - if (*isDone == ExprEndResult) - { - foreach(tl, targetlist) - { - GenericExprState *gstate = (GenericExprState *) lfirst(tl); - TargetEntry *tle = (TargetEntry *) gstate->xprstate.expr; - AttrNumber resind = tle->resno - 1; - - while (itemIsDone[resind] == ExprMultipleResult) - { - values[resind] = ExecEvalExpr(gstate->arg, - econtext, - &isnull[resind], - &itemIsDone[resind]); - /* no need for MakeExpandedObjectReadOnly */ - } - } - - MemoryContextSwitchTo(oldContext); - return false; - } - } } /* Report success */ MemoryContextSwitchTo(oldContext); - - return true; } /* @@ -5268,7 +4438,7 @@ ExecTargetList(List *targetlist, * result slot. */ TupleTableSlot * -ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone) +ExecProject(ProjectionInfo *projInfo) { TupleTableSlot *slot; ExprContext *econtext; @@ -5285,10 +4455,6 @@ ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone) slot = projInfo->pi_slot; econtext = projInfo->pi_exprContext; - /* Assume single result row until proven otherwise */ - if (isDone) - *isDone = ExprSingleResult; - /* * Clear any former contents of the result slot. This makes it safe for * us to use the slot's Datum/isnull arrays as workspace. (Also, we can @@ -5356,21 +4522,15 @@ ExecProject(ProjectionInfo *projInfo, ExprDoneCond *isDone) } /* - * If there are any generic expressions, evaluate them. It's possible - * that there are set-returning functions in such expressions; if so and - * we have reached the end of the set, we return the result slot, which we - * already marked empty. + * If there are any generic expressions, evaluate them. */ if (projInfo->pi_targetlist) { - if (!ExecTargetList(projInfo->pi_targetlist, - slot->tts_tupleDescriptor, - econtext, - slot->tts_values, - slot->tts_isnull, - projInfo->pi_itemIsDone, - isDone)) - return slot; /* no more result rows, return empty slot */ + ExecTargetList(projInfo->pi_targetlist, + slot->tts_tupleDescriptor, + econtext, + slot->tts_values, + slot->tts_isnull); } /* diff --git a/src/backend/executor/execScan.c b/src/backend/executor/execScan.c index fb0013d..eb224b4 100644 --- a/src/backend/executor/execScan.c +++ b/src/backend/executor/execScan.c @@ -125,8 +125,6 @@ ExecScan(ScanState *node, ExprContext *econtext; List *qual; ProjectionInfo *projInfo; - ExprDoneCond isDone; - TupleTableSlot *resultSlot; /* * Fetch data from node @@ -146,21 +144,6 @@ ExecScan(ScanState *node, } /* - * Check to see if we're still projecting out tuples from a previous scan - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->ps.ps_TupFromTlist) - { - Assert(projInfo); /* can't get here if not projecting */ - resultSlot = ExecProject(projInfo, &isDone); - if (isDone == ExprMultipleResult) - return resultSlot; - /* Done with that source tuple... */ - node->ps.ps_TupFromTlist = false; - } - - /* * Reset per-tuple memory context to free any expression evaluation * storage allocated in the previous tuple cycle. Note this can't happen * until we're done projecting out tuples from a scan tuple. @@ -214,15 +197,9 @@ ExecScan(ScanState *node, { /* * Form a projection tuple, store it in the result tuple slot - * and return it --- unless we find we can project no tuples - * from this scan tuple, in which case continue scan. + * and return it. */ - resultSlot = ExecProject(projInfo, &isDone); - if (isDone != ExprEndResult) - { - node->ps.ps_TupFromTlist = (isDone == ExprMultipleResult); - return resultSlot; - } + return ExecProject(projInfo); } else { @@ -352,9 +329,6 @@ ExecScanReScan(ScanState *node) { EState *estate = node->ps.state; - /* Stop projecting any tuples from SRFs in the targetlist */ - node->ps.ps_TupFromTlist = false; - /* Rescan EvalPlanQual tuple if we're inside an EvalPlanQual recheck */ if (estate->es_epqScanDone != NULL) { diff --git a/src/backend/executor/execUtils.c b/src/backend/executor/execUtils.c index e937cf8..ded073a 100644 --- a/src/backend/executor/execUtils.c +++ b/src/backend/executor/execUtils.c @@ -592,12 +592,6 @@ ExecBuildProjectionInfo(List *targetList, projInfo->pi_numSimpleVars = numSimpleVars; projInfo->pi_directMap = directMap; - if (exprlist == NIL) - projInfo->pi_itemIsDone = NULL; /* not needed */ - else - projInfo->pi_itemIsDone = (ExprDoneCond *) - palloc(len * sizeof(ExprDoneCond)); - return projInfo; } diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c index ce2fc28..f2ba170 100644 --- a/src/backend/executor/nodeAgg.c +++ b/src/backend/executor/nodeAgg.c @@ -859,13 +859,13 @@ advance_aggregates(AggState *aggstate, AggStatePerGroup pergroup) bool isnull; res = ExecEvalExprSwitchContext(filter, aggstate->tmpcontext, - &isnull, NULL); + &isnull); if (isnull || !DatumGetBool(res)) continue; } /* Evaluate the current input expressions for this aggregate */ - slot = ExecProject(pertrans->evalproj, NULL); + slot = ExecProject(pertrans->evalproj); if (pertrans->numSortCols > 0) { @@ -951,7 +951,7 @@ combine_aggregates(AggState *aggstate, AggStatePerGroup pergroup) FunctionCallInfo fcinfo = &pertrans->transfn_fcinfo; /* Evaluate the current input expressions for this aggregate */ - slot = ExecProject(pertrans->evalproj, NULL); + slot = ExecProject(pertrans->evalproj); Assert(slot->tts_nvalid >= 1); /* @@ -1325,8 +1325,7 @@ finalize_aggregate(AggState *aggstate, fcinfo.arg[i] = ExecEvalExpr(expr, aggstate->ss.ps.ps_ExprContext, - &fcinfo.argnull[i], - NULL); + &fcinfo.argnull[i]); anynull |= fcinfo.argnull[i]; i++; } @@ -1566,7 +1565,7 @@ finalize_aggregates(AggState *aggstate, /* * Project the result of a group (whose aggs have already been calculated by * finalize_aggregates). Returns the result slot, or NULL if no row is - * projected (suppressed by qual or by an empty SRF). + * projected (suppressed by qual). */ static TupleTableSlot * project_aggregates(AggState *aggstate) @@ -1579,20 +1578,10 @@ project_aggregates(AggState *aggstate) if (ExecQual(aggstate->ss.ps.qual, econtext, false)) { /* - * Form and return or store a projection tuple using the aggregate - * results and the representative input tuple. + * Form and return projection tuple using the aggregate results and + * the representative input tuple. */ - ExprDoneCond isDone; - TupleTableSlot *result; - - result = ExecProject(aggstate->ss.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - aggstate->ss.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(aggstate->ss.ps.ps_ProjInfo); } else InstrCountFiltered1(aggstate, 1); @@ -1802,27 +1791,6 @@ ExecAgg(AggState *node) { TupleTableSlot *result; - /* - * Check to see if we're still projecting out tuples from a previous agg - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->ss.ps.ps_TupFromTlist) - { - ExprDoneCond isDone; - - result = ExecProject(node->ss.ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return result; - /* Done with that source tuple... */ - node->ss.ps.ps_TupFromTlist = false; - } - - /* - * (We must do the ps_TupFromTlist check first, because in some cases - * agg_done gets set before we emit the final aggregate tuple, and we have - * to finish running SRFs for it.) - */ if (!node->agg_done) { /* Dispatch based on strategy */ @@ -2443,8 +2411,6 @@ ExecInitAgg(Agg *node, EState *estate, int eflags) ExecAssignResultTypeFromTL(&aggstate->ss.ps); ExecAssignProjectionInfo(&aggstate->ss.ps, NULL); - aggstate->ss.ps.ps_TupFromTlist = false; - /* * get the count of aggregates in targetlist and quals */ @@ -3411,8 +3377,6 @@ ExecReScanAgg(AggState *node) node->agg_done = false; - node->ss.ps.ps_TupFromTlist = false; - if (aggnode->aggstrategy == AGG_HASHED) { /* diff --git a/src/backend/executor/nodeBitmapHeapscan.c b/src/backend/executor/nodeBitmapHeapscan.c index 449aacb..16381f6 100644 --- a/src/backend/executor/nodeBitmapHeapscan.c +++ b/src/backend/executor/nodeBitmapHeapscan.c @@ -575,8 +575,6 @@ ExecInitBitmapHeapScan(BitmapHeapScan *node, EState *estate, int eflags) */ ExecAssignExprContext(estate, &scanstate->ss.ps); - scanstate->ss.ps.ps_TupFromTlist = false; - /* * initialize child expressions */ diff --git a/src/backend/executor/nodeCtescan.c b/src/backend/executor/nodeCtescan.c index 3c2f684..1acb166 100644 --- a/src/backend/executor/nodeCtescan.c +++ b/src/backend/executor/nodeCtescan.c @@ -265,8 +265,6 @@ ExecInitCteScan(CteScan *node, EState *estate, int eflags) ExecAssignResultTypeFromTL(&scanstate->ss.ps); ExecAssignScanProjectionInfo(&scanstate->ss); - scanstate->ss.ps.ps_TupFromTlist = false; - return scanstate; } diff --git a/src/backend/executor/nodeCustom.c b/src/backend/executor/nodeCustom.c index 322abca..b465252 100644 --- a/src/backend/executor/nodeCustom.c +++ b/src/backend/executor/nodeCustom.c @@ -48,8 +48,6 @@ ExecInitCustomScan(CustomScan *cscan, EState *estate, int eflags) /* create expression context for node */ ExecAssignExprContext(estate, &css->ss.ps); - css->ss.ps.ps_TupFromTlist = false; - /* initialize child expressions */ css->ss.ps.targetlist = (List *) ExecInitExpr((Expr *) cscan->scan.plan.targetlist, diff --git a/src/backend/executor/nodeForeignscan.c b/src/backend/executor/nodeForeignscan.c index d886aaf..3762843 100644 --- a/src/backend/executor/nodeForeignscan.c +++ b/src/backend/executor/nodeForeignscan.c @@ -152,8 +152,6 @@ ExecInitForeignScan(ForeignScan *node, EState *estate, int eflags) */ ExecAssignExprContext(estate, &scanstate->ss.ps); - scanstate->ss.ps.ps_TupFromTlist = false; - /* * initialize child expressions */ diff --git a/src/backend/executor/nodeFunctionscan.c b/src/backend/executor/nodeFunctionscan.c index 1da4fde..725a5fe 100644 --- a/src/backend/executor/nodeFunctionscan.c +++ b/src/backend/executor/nodeFunctionscan.c @@ -282,8 +282,6 @@ ExecInitFunctionScan(FunctionScan *node, EState *estate, int eflags) */ ExecAssignExprContext(estate, &scanstate->ss.ps); - scanstate->ss.ps.ps_TupFromTlist = false; - /* * tuple table initialization */ @@ -647,7 +645,6 @@ ExecBeginFunctionResult(FunctionScanState *node, IsA(funcexpr->expr, FuncExpr)) { FuncExprState *fcache = (FuncExprState *) funcexpr; - ExprDoneCond argDone; /* * This path is similar to ExecMakeFunctionResult. @@ -662,7 +659,7 @@ ExecBeginFunctionResult(FunctionScanState *node, FuncExpr *func = (FuncExpr *) fcache->xprstate.expr; ExecInitFcache(func->funcid, func->inputcollid, fcache, - econtext->ecxt_per_query_memory, false); + econtext->ecxt_per_query_memory); } returnsSet = fcache->func.fn_retset; InitFunctionCallInfoData(perfunc->fcinfo, &(fcache->func), @@ -681,15 +678,9 @@ ExecBeginFunctionResult(FunctionScanState *node, * and can be reset each time the node is re-scanned. */ oldcontext = MemoryContextSwitchTo(node->argcontext); - argDone = ExecEvalFuncArgs(&perfunc->fcinfo, fcache->args, econtext); + ExecEvalFuncArgs(&perfunc->fcinfo, fcache->args, econtext); MemoryContextSwitchTo(oldcontext); - /* We don't allow sets in the arguments of the table function */ - if (argDone != ExprSingleResult) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("set-valued function called in context that cannot accept a set"))); - /* * If function is strict, and there are any NULL arguments, skip * calling the function and act like it returned NULL (or an empty @@ -742,8 +733,7 @@ ExecBeginFunctionResult(FunctionScanState *node, else { perfunc->rsinfo.isDone = ExprSingleResult; - result = ExecEvalExpr(funcexpr, econtext, - &perfunc->fcinfo.isnull, NULL); + result = ExecEvalExpr(funcexpr, econtext, &perfunc->fcinfo.isnull); /* done after this, will use SFRM_ValuePerCall branch below */ } diff --git a/src/backend/executor/nodeGather.c b/src/backend/executor/nodeGather.c index 438d1b2..51754c8 100644 --- a/src/backend/executor/nodeGather.c +++ b/src/backend/executor/nodeGather.c @@ -99,8 +99,6 @@ ExecInitGather(Gather *node, EState *estate, int eflags) outerNode = outerPlan(node); outerPlanState(gatherstate) = ExecInitNode(outerNode, estate, eflags); - gatherstate->ps.ps_TupFromTlist = false; - /* * Initialize result tuple type and projection info. */ @@ -131,8 +129,6 @@ ExecGather(GatherState *node) TupleTableSlot *fslot = node->funnel_slot; int i; TupleTableSlot *slot; - TupleTableSlot *resultSlot; - ExprDoneCond isDone; ExprContext *econtext; /* @@ -198,20 +194,6 @@ ExecGather(GatherState *node) } /* - * Check to see if we're still projecting out tuples from a previous scan - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->ps.ps_TupFromTlist) - { - resultSlot = ExecProject(node->ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return resultSlot; - /* Done with that source tuple... */ - node->ps.ps_TupFromTlist = false; - } - - /* * Reset per-tuple memory context to free any expression evaluation * storage allocated in the previous tuple cycle. Note we can't do this * until we're done projecting. This will also clear any previous tuple @@ -239,13 +221,8 @@ ExecGather(GatherState *node) * back around for another tuple */ econtext->ecxt_outertuple = slot; - resultSlot = ExecProject(node->ps.ps_ProjInfo, &isDone); - if (isDone != ExprEndResult) - { - node->ps.ps_TupFromTlist = (isDone == ExprMultipleResult); - return resultSlot; - } + return ExecProject(node->ps.ps_ProjInfo); } return slot; diff --git a/src/backend/executor/nodeGroup.c b/src/backend/executor/nodeGroup.c index dcf5175..2f55c70 100644 --- a/src/backend/executor/nodeGroup.c +++ b/src/backend/executor/nodeGroup.c @@ -50,23 +50,6 @@ ExecGroup(GroupState *node) grpColIdx = ((Group *) node->ss.ps.plan)->grpColIdx; /* - * Check to see if we're still projecting out tuples from a previous group - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->ss.ps.ps_TupFromTlist) - { - TupleTableSlot *result; - ExprDoneCond isDone; - - result = ExecProject(node->ss.ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return result; - /* Done with that source tuple... */ - node->ss.ps.ps_TupFromTlist = false; - } - - /* * The ScanTupleSlot holds the (copied) first tuple of each group. */ firsttupleslot = node->ss.ss_ScanTupleSlot; @@ -107,16 +90,7 @@ ExecGroup(GroupState *node) /* * Form and return a projection tuple using the first input tuple. */ - TupleTableSlot *result; - ExprDoneCond isDone; - - result = ExecProject(node->ss.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->ss.ps.ps_TupFromTlist = (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->ss.ps.ps_ProjInfo); } else InstrCountFiltered1(node, 1); @@ -170,16 +144,7 @@ ExecGroup(GroupState *node) /* * Form and return a projection tuple using the first input tuple. */ - TupleTableSlot *result; - ExprDoneCond isDone; - - result = ExecProject(node->ss.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->ss.ps.ps_TupFromTlist = (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->ss.ps.ps_ProjInfo); } else InstrCountFiltered1(node, 1); @@ -246,8 +211,6 @@ ExecInitGroup(Group *node, EState *estate, int eflags) ExecAssignResultTypeFromTL(&grpstate->ss.ps); ExecAssignProjectionInfo(&grpstate->ss.ps, NULL); - grpstate->ss.ps.ps_TupFromTlist = false; - /* * Precompute fmgr lookup data for inner loop */ @@ -283,7 +246,6 @@ ExecReScanGroup(GroupState *node) PlanState *outerPlan = outerPlanState(node); node->grp_done = FALSE; - node->ss.ps.ps_TupFromTlist = false; /* must clear first tuple */ ExecClearTuple(node->ss.ss_ScanTupleSlot); diff --git a/src/backend/executor/nodeHash.c b/src/backend/executor/nodeHash.c index 9ed09a7..e008a51 100644 --- a/src/backend/executor/nodeHash.c +++ b/src/backend/executor/nodeHash.c @@ -963,7 +963,7 @@ ExecHashGetHashValue(HashJoinTable hashtable, /* * Get the join attribute value of the tuple */ - keyval = ExecEvalExpr(keyexpr, econtext, &isNull, NULL); + keyval = ExecEvalExpr(keyexpr, econtext, &isNull); /* * If the attribute is NULL, and the join operator is strict, then diff --git a/src/backend/executor/nodeHashjoin.c b/src/backend/executor/nodeHashjoin.c index 369e666..45c7be2 100644 --- a/src/backend/executor/nodeHashjoin.c +++ b/src/backend/executor/nodeHashjoin.c @@ -66,7 +66,6 @@ ExecHashJoin(HashJoinState *node) List *joinqual; List *otherqual; ExprContext *econtext; - ExprDoneCond isDone; HashJoinTable hashtable; TupleTableSlot *outerTupleSlot; uint32 hashvalue; @@ -83,22 +82,6 @@ ExecHashJoin(HashJoinState *node) econtext = node->js.ps.ps_ExprContext; /* - * Check to see if we're still projecting out tuples from a previous join - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->js.ps.ps_TupFromTlist) - { - TupleTableSlot *result; - - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return result; - /* Done with that source tuple... */ - node->js.ps.ps_TupFromTlist = false; - } - - /* * Reset per-tuple memory context to free any expression evaluation * storage allocated in the previous tuple cycle. Note this can't happen * until we're done projecting out tuples from a join tuple. @@ -315,16 +298,7 @@ ExecHashJoin(HashJoinState *node) if (otherqual == NIL || ExecQual(otherqual, econtext, false)) { - TupleTableSlot *result; - - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -354,16 +328,7 @@ ExecHashJoin(HashJoinState *node) if (otherqual == NIL || ExecQual(otherqual, econtext, false)) { - TupleTableSlot *result; - - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -393,16 +358,7 @@ ExecHashJoin(HashJoinState *node) if (otherqual == NIL || ExecQual(otherqual, econtext, false)) { - TupleTableSlot *result; - - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -586,7 +542,6 @@ ExecInitHashJoin(HashJoin *node, EState *estate, int eflags) /* child Hash node needs to evaluate inner hash keys, too */ ((HashState *) innerPlanState(hjstate))->hashkeys = rclauses; - hjstate->js.ps.ps_TupFromTlist = false; hjstate->hj_JoinState = HJ_BUILD_HASHTABLE; hjstate->hj_MatchedOuter = false; hjstate->hj_OuterNotEmpty = false; @@ -1000,7 +955,6 @@ ExecReScanHashJoin(HashJoinState *node) node->hj_CurSkewBucketNo = INVALID_SKEW_BUCKET_NO; node->hj_CurTuple = NULL; - node->js.ps.ps_TupFromTlist = false; node->hj_MatchedOuter = false; node->hj_FirstOuterTupleSlot = NULL; diff --git a/src/backend/executor/nodeIndexonlyscan.c b/src/backend/executor/nodeIndexonlyscan.c index 4f6f91c..edd45661 100644 --- a/src/backend/executor/nodeIndexonlyscan.c +++ b/src/backend/executor/nodeIndexonlyscan.c @@ -412,8 +412,6 @@ ExecInitIndexOnlyScan(IndexOnlyScan *node, EState *estate, int eflags) */ ExecAssignExprContext(estate, &indexstate->ss.ps); - indexstate->ss.ps.ps_TupFromTlist = false; - /* * initialize child expressions * diff --git a/src/backend/executor/nodeIndexscan.c b/src/backend/executor/nodeIndexscan.c index 3143bd9..d1b1c23 100644 --- a/src/backend/executor/nodeIndexscan.c +++ b/src/backend/executor/nodeIndexscan.c @@ -336,8 +336,7 @@ EvalOrderByExpressions(IndexScanState *node, ExprContext *econtext) node->iss_OrderByValues[i] = ExecEvalExpr(orderby, econtext, - &node->iss_OrderByNulls[i], - NULL); + &node->iss_OrderByNulls[i]); i++; } @@ -590,8 +589,7 @@ ExecIndexEvalRuntimeKeys(ExprContext *econtext, */ scanvalue = ExecEvalExpr(key_expr, econtext, - &isNull, - NULL); + &isNull); if (isNull) { scan_key->sk_argument = scanvalue; @@ -648,8 +646,7 @@ ExecIndexEvalArrayKeys(ExprContext *econtext, */ arraydatum = ExecEvalExpr(array_expr, econtext, - &isNull, - NULL); + &isNull); if (isNull) { result = false; @@ -837,8 +834,6 @@ ExecInitIndexScan(IndexScan *node, EState *estate, int eflags) */ ExecAssignExprContext(estate, &indexstate->ss.ps); - indexstate->ss.ps.ps_TupFromTlist = false; - /* * initialize child expressions * diff --git a/src/backend/executor/nodeLimit.c b/src/backend/executor/nodeLimit.c index faf32e1..0ef9ea5 100644 --- a/src/backend/executor/nodeLimit.c +++ b/src/backend/executor/nodeLimit.c @@ -239,8 +239,7 @@ recompute_limits(LimitState *node) { val = ExecEvalExprSwitchContext(node->limitOffset, econtext, - &isNull, - NULL); + &isNull); /* Interpret NULL offset as no offset */ if (isNull) node->offset = 0; @@ -263,8 +262,7 @@ recompute_limits(LimitState *node) { val = ExecEvalExprSwitchContext(node->limitCount, econtext, - &isNull, - NULL); + &isNull); /* Interpret NULL count as no count (LIMIT ALL) */ if (isNull) { @@ -346,18 +344,11 @@ pass_down_bound(LimitState *node, PlanState *child_node) else if (IsA(child_node, ResultState)) { /* - * An extra consideration here is that if the Result is projecting a - * targetlist that contains any SRFs, we can't assume that every input - * tuple generates an output tuple, so a Sort underneath might need to - * return more than N tuples to satisfy LIMIT N. So we cannot use - * bounded sort. - * * If Result supported qual checking, we'd have to punt on seeing a - * qual, too. Note that having a resconstantqual is not a - * showstopper: if that fails we're not getting any rows at all. + * qual. Note that having a resconstantqual is not a showstopper: if + * that fails we're not getting any rows at all. */ - if (outerPlanState(child_node) && - !expression_returns_set((Node *) child_node->plan->targetlist)) + if (outerPlanState(child_node)) pass_down_bound(node, outerPlanState(child_node)); } } diff --git a/src/backend/executor/nodeMergejoin.c b/src/backend/executor/nodeMergejoin.c index 6db09b8..340a2a9 100644 --- a/src/backend/executor/nodeMergejoin.c +++ b/src/backend/executor/nodeMergejoin.c @@ -313,7 +313,7 @@ MJEvalOuterValues(MergeJoinState *mergestate) MergeJoinClause clause = &mergestate->mj_Clauses[i]; clause->ldatum = ExecEvalExpr(clause->lexpr, econtext, - &clause->lisnull, NULL); + &clause->lisnull); if (clause->lisnull) { /* match is impossible; can we end the join early? */ @@ -360,7 +360,7 @@ MJEvalInnerValues(MergeJoinState *mergestate, TupleTableSlot *innerslot) MergeJoinClause clause = &mergestate->mj_Clauses[i]; clause->rdatum = ExecEvalExpr(clause->rexpr, econtext, - &clause->risnull, NULL); + &clause->risnull); if (clause->risnull) { /* match is impossible; can we end the join early? */ @@ -465,19 +465,10 @@ MJFillOuter(MergeJoinState *node) * qualification succeeded. now form the desired projection tuple and * return the slot containing it. */ - TupleTableSlot *result; - ExprDoneCond isDone; MJ_printf("ExecMergeJoin: returning outer fill tuple\n"); - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -506,19 +497,9 @@ MJFillInner(MergeJoinState *node) * qualification succeeded. now form the desired projection tuple and * return the slot containing it. */ - TupleTableSlot *result; - ExprDoneCond isDone; - MJ_printf("ExecMergeJoin: returning inner fill tuple\n"); - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -642,23 +623,6 @@ ExecMergeJoin(MergeJoinState *node) doFillInner = node->mj_FillInner; /* - * Check to see if we're still projecting out tuples from a previous join - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->js.ps.ps_TupFromTlist) - { - TupleTableSlot *result; - ExprDoneCond isDone; - - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return result; - /* Done with that source tuple... */ - node->js.ps.ps_TupFromTlist = false; - } - - /* * Reset per-tuple memory context to free any expression evaluation * storage allocated in the previous tuple cycle. Note this can't happen * until we're done projecting out tuples from a join tuple. @@ -856,20 +820,9 @@ ExecMergeJoin(MergeJoinState *node) * qualification succeeded. now form the desired * projection tuple and return the slot containing it. */ - TupleTableSlot *result; - ExprDoneCond isDone; - MJ_printf("ExecMergeJoin: returning tuple\n"); - result = ExecProject(node->js.ps.ps_ProjInfo, - &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -1629,7 +1582,6 @@ ExecInitMergeJoin(MergeJoin *node, EState *estate, int eflags) * initialize join state */ mergestate->mj_JoinState = EXEC_MJ_INITIALIZE_OUTER; - mergestate->js.ps.ps_TupFromTlist = false; mergestate->mj_MatchedOuter = false; mergestate->mj_MatchedInner = false; mergestate->mj_OuterTupleSlot = NULL; @@ -1684,7 +1636,6 @@ ExecReScanMergeJoin(MergeJoinState *node) ExecClearTuple(node->mj_MarkedTupleSlot); node->mj_JoinState = EXEC_MJ_INITIALIZE_OUTER; - node->js.ps.ps_TupFromTlist = false; node->mj_MatchedOuter = false; node->mj_MatchedInner = false; node->mj_OuterTupleSlot = NULL; diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index af7b26c..0e6187b 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -175,7 +175,7 @@ ExecProcessReturning(ResultRelInfo *resultRelInfo, econtext->ecxt_outertuple = planSlot; /* Compute the RETURNING expressions */ - return ExecProject(projectReturning, NULL); + return ExecProject(projectReturning); } /* @@ -1216,7 +1216,7 @@ ExecOnConflictUpdate(ModifyTableState *mtstate, } /* Project the new tuple version */ - ExecProject(resultRelInfo->ri_onConflictSetProj, NULL); + ExecProject(resultRelInfo->ri_onConflictSetProj); /* * Note that it is possible that the target tuple has been modified in diff --git a/src/backend/executor/nodeNestloop.c b/src/backend/executor/nodeNestloop.c index 555fa09..5d30e75 100644 --- a/src/backend/executor/nodeNestloop.c +++ b/src/backend/executor/nodeNestloop.c @@ -82,23 +82,6 @@ ExecNestLoop(NestLoopState *node) econtext = node->js.ps.ps_ExprContext; /* - * Check to see if we're still projecting out tuples from a previous join - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->js.ps.ps_TupFromTlist) - { - TupleTableSlot *result; - ExprDoneCond isDone; - - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return result; - /* Done with that source tuple... */ - node->js.ps.ps_TupFromTlist = false; - } - - /* * Reset per-tuple memory context to free any expression evaluation * storage allocated in the previous tuple cycle. Note this can't happen * until we're done projecting out tuples from a join tuple. @@ -201,19 +184,10 @@ ExecNestLoop(NestLoopState *node) * the slot containing the result tuple using * ExecProject(). */ - TupleTableSlot *result; - ExprDoneCond isDone; ENL1_printf("qualification succeeded, projecting tuple"); - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -259,19 +233,10 @@ ExecNestLoop(NestLoopState *node) * qualification was satisfied so we project and return the * slot containing the result tuple using ExecProject(). */ - TupleTableSlot *result; - ExprDoneCond isDone; ENL1_printf("qualification succeeded, projecting tuple"); - result = ExecProject(node->js.ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->js.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; - } + return ExecProject(node->js.ps.ps_ProjInfo); } else InstrCountFiltered2(node, 1); @@ -377,7 +342,6 @@ ExecInitNestLoop(NestLoop *node, EState *estate, int eflags) /* * finally, wipe the current outer tuple clean. */ - nlstate->js.ps.ps_TupFromTlist = false; nlstate->nl_NeedNewOuter = true; nlstate->nl_MatchedOuter = false; @@ -441,7 +405,6 @@ ExecReScanNestLoop(NestLoopState *node) * outer Vars are used as run-time keys... */ - node->js.ps.ps_TupFromTlist = false; node->nl_NeedNewOuter = true; node->nl_MatchedOuter = false; } diff --git a/src/backend/executor/nodeResult.c b/src/backend/executor/nodeResult.c index 4007b76..3901351 100644 --- a/src/backend/executor/nodeResult.c +++ b/src/backend/executor/nodeResult.c @@ -67,10 +67,8 @@ TupleTableSlot * ExecResult(ResultState *node) { TupleTableSlot *outerTupleSlot; - TupleTableSlot *resultSlot; PlanState *outerPlan; ExprContext *econtext; - ExprDoneCond isDone; econtext = node->ps.ps_ExprContext; @@ -92,20 +90,6 @@ ExecResult(ResultState *node) } /* - * Check to see if we're still projecting out tuples from a previous scan - * tuple (because there is a function-returning-set in the projection - * expressions). If so, try to project another one. - */ - if (node->ps.ps_TupFromTlist) - { - resultSlot = ExecProject(node->ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return resultSlot; - /* Done with that source tuple... */ - node->ps.ps_TupFromTlist = false; - } - - /* * Reset per-tuple memory context to free any expression evaluation * storage allocated in the previous tuple cycle. Note this can't happen * until we're done projecting out tuples from a scan tuple. @@ -147,18 +131,8 @@ ExecResult(ResultState *node) node->rs_done = true; } - /* - * form the result tuple using ExecProject(), and return it --- unless - * the projection produces an empty set, in which case we must loop - * back to see if there are more outerPlan tuples. - */ - resultSlot = ExecProject(node->ps.ps_ProjInfo, &isDone); - - if (isDone != ExprEndResult) - { - node->ps.ps_TupFromTlist = (isDone == ExprMultipleResult); - return resultSlot; - } + /* form the result tuple using ExecProject(), and return it */ + return ExecProject(node->ps.ps_ProjInfo); } return NULL; @@ -228,8 +202,6 @@ ExecInitResult(Result *node, EState *estate, int eflags) */ ExecAssignExprContext(estate, &resstate->ps); - resstate->ps.ps_TupFromTlist = false; - /* * tuple table initialization */ @@ -295,7 +267,6 @@ void ExecReScanResult(ResultState *node) { node->rs_done = false; - node->ps.ps_TupFromTlist = false; node->rs_checkqual = (node->resconstantqual == NULL) ? false : true; /* diff --git a/src/backend/executor/nodeSamplescan.c b/src/backend/executor/nodeSamplescan.c index 9ce7c02..64396e1 100644 --- a/src/backend/executor/nodeSamplescan.c +++ b/src/backend/executor/nodeSamplescan.c @@ -188,8 +188,6 @@ ExecInitSampleScan(SampleScan *node, EState *estate, int eflags) */ InitScanRelation(scanstate, estate, eflags); - scanstate->ss.ps.ps_TupFromTlist = false; - /* * Initialize result tuple type and projection info. */ @@ -299,8 +297,7 @@ tablesample_init(SampleScanState *scanstate) params[i] = ExecEvalExprSwitchContext(argstate, econtext, - &isnull, - NULL); + &isnull); if (isnull) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLESAMPLE_ARGUMENT), @@ -312,8 +309,7 @@ tablesample_init(SampleScanState *scanstate) { datum = ExecEvalExprSwitchContext(scanstate->repeatable, econtext, - &isnull, - NULL); + &isnull); if (isnull) ereport(ERROR, (errcode(ERRCODE_INVALID_TABLESAMPLE_REPEAT), diff --git a/src/backend/executor/nodeSeqscan.c b/src/backend/executor/nodeSeqscan.c index 00bf3a5..477dc42 100644 --- a/src/backend/executor/nodeSeqscan.c +++ b/src/backend/executor/nodeSeqscan.c @@ -206,8 +206,6 @@ ExecInitSeqScan(SeqScan *node, EState *estate, int eflags) */ InitScanRelation(scanstate, estate, eflags); - scanstate->ss.ps.ps_TupFromTlist = false; - /* * Initialize result tuple type and projection info. */ diff --git a/src/backend/executor/nodeSubplan.c b/src/backend/executor/nodeSubplan.c index e503494..5800ca8 100644 --- a/src/backend/executor/nodeSubplan.c +++ b/src/backend/executor/nodeSubplan.c @@ -41,12 +41,10 @@ static Datum ExecSubPlan(SubPlanState *node, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone); + bool *isNull); static Datum ExecAlternativeSubPlan(AlternativeSubPlanState *node, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone); + bool *isNull); static Datum ExecHashSubPlan(SubPlanState *node, ExprContext *econtext, bool *isNull); @@ -69,15 +67,12 @@ static bool slotNoNulls(TupleTableSlot *slot); static Datum ExecSubPlan(SubPlanState *node, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { SubPlan *subplan = (SubPlan *) node->xprstate.expr; /* Set default values for result flags: non-null, not a set result */ *isNull = false; - if (isDone) - *isDone = ExprSingleResult; /* Sanity checks */ if (subplan->subLinkType == CTE_SUBLINK) @@ -128,7 +123,7 @@ ExecHashSubPlan(SubPlanState *node, * have to set the econtext to use (hack alert!). */ node->projLeft->pi_exprContext = econtext; - slot = ExecProject(node->projLeft, NULL); + slot = ExecProject(node->projLeft); /* * Note: because we are typically called in a per-tuple context, we have @@ -285,8 +280,7 @@ ExecScanSubPlan(SubPlanState *node, prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar), econtext, - &(prm->isnull), - NULL); + &(prm->isnull)); planstate->chgParam = bms_add_member(planstate->chgParam, paramid); } @@ -403,7 +397,7 @@ ExecScanSubPlan(SubPlanState *node, } rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext, - &rownull, NULL); + &rownull); if (subLinkType == ANY_SUBLINK) { @@ -570,7 +564,7 @@ buildSubPlanHash(SubPlanState *node, ExprContext *econtext) &(prmdata->isnull)); col++; } - slot = ExecProject(node->projRight, NULL); + slot = ExecProject(node->projRight); /* * If result contains any nulls, store separately or not at all. @@ -987,8 +981,7 @@ ExecSetParamPlan(SubPlanState *node, ExprContext *econtext) prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar), econtext, - &(prm->isnull), - NULL); + &(prm->isnull)); planstate->chgParam = bms_add_member(planstate->chgParam, paramid); } @@ -1224,8 +1217,7 @@ ExecInitAlternativeSubPlan(AlternativeSubPlan *asplan, PlanState *parent) static Datum ExecAlternativeSubPlan(AlternativeSubPlanState *node, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone) + bool *isNull) { /* Just pass control to the active subplan */ SubPlanState *activesp = (SubPlanState *) list_nth(node->subplans, @@ -1233,8 +1225,5 @@ ExecAlternativeSubPlan(AlternativeSubPlanState *node, Assert(IsA(activesp, SubPlanState)); - return ExecSubPlan(activesp, - econtext, - isNull, - isDone); + return ExecSubPlan(activesp, econtext, isNull); } diff --git a/src/backend/executor/nodeSubqueryscan.c b/src/backend/executor/nodeSubqueryscan.c index 9bafc62..4de7024 100644 --- a/src/backend/executor/nodeSubqueryscan.c +++ b/src/backend/executor/nodeSubqueryscan.c @@ -138,8 +138,6 @@ ExecInitSubqueryScan(SubqueryScan *node, EState *estate, int eflags) */ subquerystate->subplan = ExecInitNode(node->subplan, estate, eflags); - subquerystate->ss.ps.ps_TupFromTlist = false; - /* * Initialize scan tuple type (needed by ExecAssignScanProjectionInfo) */ diff --git a/src/backend/executor/nodeTidscan.c b/src/backend/executor/nodeTidscan.c index 2604103..e1c736c 100644 --- a/src/backend/executor/nodeTidscan.c +++ b/src/backend/executor/nodeTidscan.c @@ -104,8 +104,7 @@ TidListCreate(TidScanState *tidstate) itemptr = (ItemPointer) DatumGetPointer(ExecEvalExprSwitchContext(exstate, econtext, - &isNull, - NULL)); + &isNull)); if (!isNull && ItemPointerIsValid(itemptr) && ItemPointerGetBlockNumber(itemptr) < nblocks) @@ -133,8 +132,7 @@ TidListCreate(TidScanState *tidstate) exstate = (ExprState *) lsecond(saexstate->fxprstate.args); arraydatum = ExecEvalExprSwitchContext(exstate, econtext, - &isNull, - NULL); + &isNull); if (isNull) continue; itemarray = DatumGetArrayTypeP(arraydatum); @@ -469,8 +467,6 @@ ExecInitTidScan(TidScan *node, EState *estate, int eflags) */ ExecAssignExprContext(estate, &tidstate->ss.ps); - tidstate->ss.ps.ps_TupFromTlist = false; - /* * initialize child expressions */ diff --git a/src/backend/executor/nodeValuesscan.c b/src/backend/executor/nodeValuesscan.c index 9c03f8a..18c8ae9 100644 --- a/src/backend/executor/nodeValuesscan.c +++ b/src/backend/executor/nodeValuesscan.c @@ -140,8 +140,7 @@ ValuesNext(ValuesScanState *node) values[resind] = ExecEvalExpr(estate, econtext, - &isnull[resind], - NULL); + &isnull[resind]); /* * We must force any R/W expanded datums to read-only state, in @@ -272,8 +271,6 @@ ExecInitValuesScan(ValuesScan *node, EState *estate, int eflags) scanstate->exprlists[i++] = (List *) lfirst(vtl); } - scanstate->ss.ps.ps_TupFromTlist = false; - /* * Initialize result tuple type and projection info. */ diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c index d4c88a1..42550c9 100644 --- a/src/backend/executor/nodeWindowAgg.c +++ b/src/backend/executor/nodeWindowAgg.c @@ -256,7 +256,7 @@ advance_windowaggregate(WindowAggState *winstate, if (filter) { bool isnull; - Datum res = ExecEvalExpr(filter, econtext, &isnull, NULL); + Datum res = ExecEvalExpr(filter, econtext, &isnull); if (isnull || !DatumGetBool(res)) { @@ -272,7 +272,7 @@ advance_windowaggregate(WindowAggState *winstate, ExprState *argstate = (ExprState *) lfirst(arg); fcinfo->arg[i] = ExecEvalExpr(argstate, econtext, - &fcinfo->argnull[i], NULL); + &fcinfo->argnull[i]); i++; } @@ -418,7 +418,7 @@ advance_windowaggregate_base(WindowAggState *winstate, if (filter) { bool isnull; - Datum res = ExecEvalExpr(filter, econtext, &isnull, NULL); + Datum res = ExecEvalExpr(filter, econtext, &isnull); if (isnull || !DatumGetBool(res)) { @@ -434,7 +434,7 @@ advance_windowaggregate_base(WindowAggState *winstate, ExprState *argstate = (ExprState *) lfirst(arg); fcinfo->arg[i] = ExecEvalExpr(argstate, econtext, - &fcinfo->argnull[i], NULL); + &fcinfo->argnull[i]); i++; } @@ -1551,15 +1551,12 @@ update_frametailpos(WindowObject winobj, TupleTableSlot *slot) * ExecWindowAgg receives tuples from its outer subplan and * stores them into a tuplestore, then processes window functions. * This node doesn't reduce nor qualify any row so the number of - * returned rows is exactly the same as its outer subplan's result - * (ignoring the case of SRFs in the targetlist, that is). + * returned rows is exactly the same as its outer subplan's result. * ----------------- */ TupleTableSlot * ExecWindowAgg(WindowAggState *winstate) { - TupleTableSlot *result; - ExprDoneCond isDone; ExprContext *econtext; int i; int numfuncs; @@ -1568,23 +1565,6 @@ ExecWindowAgg(WindowAggState *winstate) return NULL; /* - * Check to see if we're still projecting out tuples from a previous - * output tuple (because there is a function-returning-set in the - * projection expressions). If so, try to project another one. - */ - if (winstate->ss.ps.ps_TupFromTlist) - { - TupleTableSlot *result; - ExprDoneCond isDone; - - result = ExecProject(winstate->ss.ps.ps_ProjInfo, &isDone); - if (isDone == ExprMultipleResult) - return result; - /* Done with that source tuple... */ - winstate->ss.ps.ps_TupFromTlist = false; - } - - /* * Compute frame offset values, if any, during first call. */ if (winstate->all_first) @@ -1601,8 +1581,7 @@ ExecWindowAgg(WindowAggState *winstate) Assert(winstate->startOffset != NULL); value = ExecEvalExprSwitchContext(winstate->startOffset, econtext, - &isnull, - NULL); + &isnull); if (isnull) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), @@ -1627,8 +1606,7 @@ ExecWindowAgg(WindowAggState *winstate) Assert(winstate->endOffset != NULL); value = ExecEvalExprSwitchContext(winstate->endOffset, econtext, - &isnull, - NULL); + &isnull); if (isnull) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), @@ -1651,7 +1629,6 @@ ExecWindowAgg(WindowAggState *winstate) winstate->all_first = false; } -restart: if (winstate->buffer == NULL) { /* Initialize for first partition and set current row = 0 */ @@ -1743,17 +1720,8 @@ restart: * evaluated with respect to that row. */ econtext->ecxt_outertuple = winstate->ss.ss_ScanTupleSlot; - result = ExecProject(winstate->ss.ps.ps_ProjInfo, &isDone); - if (isDone == ExprEndResult) - { - /* SRF in tlist returned no rows, so advance to next input tuple */ - goto restart; - } - - winstate->ss.ps.ps_TupFromTlist = - (isDone == ExprMultipleResult); - return result; + return ExecProject(winstate->ss.ps.ps_ProjInfo); } /* ----------------- @@ -1867,8 +1835,6 @@ ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags) ExecAssignResultTypeFromTL(&winstate->ss.ps); ExecAssignProjectionInfo(&winstate->ss.ps, NULL); - winstate->ss.ps.ps_TupFromTlist = false; - /* Set up data for comparing tuples */ if (node->partNumCols > 0) winstate->partEqfunctions = execTuplesMatchPrepare(node->partNumCols, @@ -2061,8 +2027,6 @@ ExecReScanWindowAgg(WindowAggState *node) ExprContext *econtext = node->ss.ps.ps_ExprContext; node->all_done = false; - - node->ss.ps.ps_TupFromTlist = false; node->all_first = true; /* release tuplestore et al */ @@ -2685,7 +2649,7 @@ WinGetFuncArgInPartition(WindowObject winobj, int argno, } econtext->ecxt_outertuple = slot; return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno), - econtext, isnull, NULL); + econtext, isnull); } } @@ -2784,7 +2748,7 @@ WinGetFuncArgInFrame(WindowObject winobj, int argno, } econtext->ecxt_outertuple = slot; return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno), - econtext, isnull, NULL); + econtext, isnull); } } @@ -2814,5 +2778,5 @@ WinGetFuncArgCurrent(WindowObject winobj, int argno, bool *isnull) econtext->ecxt_outertuple = winstate->ss.ss_ScanTupleSlot; return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno), - econtext, isnull, NULL); + econtext, isnull); } diff --git a/src/backend/executor/nodeWorktablescan.c b/src/backend/executor/nodeWorktablescan.c index cfed6e6..dbb8ea3 100644 --- a/src/backend/executor/nodeWorktablescan.c +++ b/src/backend/executor/nodeWorktablescan.c @@ -174,8 +174,6 @@ ExecInitWorkTableScan(WorkTableScan *node, EState *estate, int eflags) */ ExecAssignResultTypeFromTL(&scanstate->ss.ps); - scanstate->ss.ps.ps_TupFromTlist = false; - return scanstate; } diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 986c92b..73862a2 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -151,8 +151,7 @@ static PathTarget *make_window_input_target(PlannerInfo *root, static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist); static PathTarget *make_sort_input_target(PlannerInfo *root, - PathTarget *final_target, - bool *have_postponed_srfs); + PathTarget *final_target); /***************************************************************************** @@ -1443,8 +1442,6 @@ grouping_planner(PlannerInfo *root, bool inheritance_update, int64 offset_est = 0; int64 count_est = 0; double limit_tuples = -1.0; - bool have_postponed_srfs = false; - double tlist_rows; PathTarget *final_target; RelOptInfo *current_rel; RelOptInfo *final_rel; @@ -1710,10 +1707,7 @@ grouping_planner(PlannerInfo *root, bool inheritance_update, * Figure out whether there's a hard limit on the number of rows that * query_planner's result subplan needs to return. Even if we know a * hard limit overall, it doesn't apply if the query has any - * grouping/aggregation operations. (XXX it also doesn't apply if the - * tlist contains any SRFs; but checking for that here seems more - * costly than it's worth, since root->limit_tuples is only used for - * cost estimates, and only in a small number of cases.) + * grouping/aggregation operations. */ if (parse->groupClause || parse->groupingSets || @@ -1757,8 +1751,7 @@ grouping_planner(PlannerInfo *root, bool inheritance_update, */ if (parse->sortClause) sort_input_target = make_sort_input_target(root, - final_target, - &have_postponed_srfs); + final_target); else sort_input_target = final_target; @@ -1915,50 +1908,17 @@ grouping_planner(PlannerInfo *root, bool inheritance_update, /* * If ORDER BY was given, consider ways to implement that, and generate a * new upperrel containing only paths that emit the correct ordering and - * project the correct final_target. We can apply the original - * limit_tuples limit in sort costing here, but only if there are no - * postponed SRFs. + * project the correct final_target. */ if (parse->sortClause) { current_rel = create_ordered_paths(root, current_rel, final_target, - have_postponed_srfs ? -1.0 : limit_tuples); } /* - * If there are set-returning functions in the tlist, scale up the output - * rowcounts of all surviving Paths to account for that. Note that if any - * SRFs appear in sorting or grouping columns, we'll have underestimated - * the numbers of rows passing through earlier steps; but that's such a - * weird usage that it doesn't seem worth greatly complicating matters to - * account for it. - */ - tlist_rows = tlist_returns_set_rows(tlist); - if (tlist_rows > 1) - { - foreach(lc, current_rel->pathlist) - { - Path *path = (Path *) lfirst(lc); - - /* - * We assume that execution costs of the tlist as such were - * already accounted for. However, it still seems appropriate to - * charge something more for the executor's general costs of - * processing the added tuples. The cost is probably less than - * cpu_tuple_cost, though, so we arbitrarily use half of that. - */ - path->total_cost += path->rows * (tlist_rows - 1) * - cpu_tuple_cost / 2; - - path->rows *= tlist_rows; - } - /* No need to run set_cheapest; we're keeping all paths anyway. */ - } - - /* * Now we are prepared to build the final-output upperrel. */ final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL); @@ -4907,20 +4867,12 @@ make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, * * Our current policy is to postpone volatile expressions till after the sort * unconditionally (assuming that that's possible, ie they are in plain tlist - * columns and not ORDER BY/GROUP BY/DISTINCT columns). We also prefer to - * postpone set-returning expressions, because running them beforehand would - * bloat the sort dataset, and because it might cause unexpected output order - * if the sort isn't stable. However there's a constraint on that: all SRFs - * in the tlist should be evaluated at the same plan step, so that they can - * run in sync in ExecTargetList. So if any SRFs are in sort columns, we - * mustn't postpone any SRFs. (Note that in principle that policy should - * probably get applied to the group/window input targetlists too, but we - * have not done that historically.) Lastly, expensive expressions are - * postponed if there is a LIMIT, or if root->tuple_fraction shows that - * partial evaluation of the query is possible (if neither is true, we expect - * to have to evaluate the expressions for every row anyway), or if there are - * any volatile or set-returning expressions (since once we've put in a - * projection at all, it won't cost any more to postpone more stuff). + * columns and not ORDER BY/GROUP BY/DISTINCT columns). Also, expensive + * expressions are postponed if there is a LIMIT, or if root->tuple_fraction + * shows that partial evaluation of the query is possible (if neither is true, + * we expect to have to evaluate the expressions for every row anyway), or if + * there are any volatile or set-returning expressions (since once we've put + * in a projection at all, it won't cost any more to postpone more stuff). * * Another issue that could potentially be considered here is that * evaluating tlist expressions could result in data that's either wider @@ -4944,30 +4896,21 @@ make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, * computed earlier. * * 'final_target' is the query's final target list (in PathTarget form) - * 'have_postponed_srfs' is an output argument, see below * * The result is the PathTarget to be computed by the plan node immediately * below the Sort step (and the Distinct step, if any). This will be * exactly final_target if we decide a projection step wouldn't be helpful. - * - * In addition, *have_postponed_srfs is set to TRUE if we choose to postpone - * any set-returning functions to after the Sort. */ static PathTarget * make_sort_input_target(PlannerInfo *root, - PathTarget *final_target, - bool *have_postponed_srfs) + PathTarget *final_target) { Query *parse = root->parse; PathTarget *input_target; int ncols; - bool *col_is_srf; bool *postpone_col; - bool have_srf; bool have_volatile; bool have_expensive; - bool have_srf_sortcols; - bool postpone_srfs; List *postponable_cols; List *postponable_vars; int i; @@ -4976,13 +4919,10 @@ make_sort_input_target(PlannerInfo *root, /* Shouldn't get here unless query has ORDER BY */ Assert(parse->sortClause); - *have_postponed_srfs = false; /* default result */ - /* Inspect tlist and collect per-column information */ ncols = list_length(final_target->exprs); - col_is_srf = (bool *) palloc0(ncols * sizeof(bool)); postpone_col = (bool *) palloc0(ncols * sizeof(bool)); - have_srf = have_volatile = have_expensive = have_srf_sortcols = false; + have_volatile = have_expensive = false; i = 0; foreach(lc, final_target->exprs) @@ -5000,16 +4940,9 @@ make_sort_input_target(PlannerInfo *root, if (get_pathtarget_sortgroupref(final_target, i) == 0) { /* - * Check for SRF or volatile functions. Check the SRF case first - * because we must know whether we have any postponed SRFs. + * Check for volatile functions. */ - if (expression_returns_set((Node *) expr)) - { - /* We'll decide below whether these are postponable */ - col_is_srf[i] = true; - have_srf = true; - } - else if (contain_volatile_functions((Node *) expr)) + if (contain_volatile_functions((Node *) expr)) { /* Unconditionally postpone */ postpone_col[i] = true; @@ -5038,39 +4971,19 @@ make_sort_input_target(PlannerInfo *root, } } } - else - { - /* For sortgroupref cols, just check if any contain SRFs */ - if (!have_srf_sortcols && - expression_returns_set((Node *) expr)) - have_srf_sortcols = true; - } i++; } /* - * We can postpone SRFs if we have some but none are in sortgroupref cols. - */ - postpone_srfs = (have_srf && !have_srf_sortcols); - - /* * If we don't need a post-sort projection, just return final_target. */ - if (!(postpone_srfs || have_volatile || + if (!(have_volatile || (have_expensive && (parse->limitCount || root->tuple_fraction > 0)))) return final_target; /* - * Report whether the post-sort projection will contain set-returning - * functions. This is important because it affects whether the Sort can - * rely on the query's LIMIT (if any) to bound the number of rows it needs - * to return. - */ - *have_postponed_srfs = postpone_srfs; - - /* * Construct the sort-input target, taking all non-postponable columns and * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in * the postponable ones. @@ -5083,7 +4996,7 @@ make_sort_input_target(PlannerInfo *root, { Expr *expr = (Expr *) lfirst(lc); - if (postpone_col[i] || (postpone_srfs && col_is_srf[i])) + if (postpone_col[i]) postponable_cols = lappend(postponable_cols, expr); else add_column_to_pathtarget(input_target, expr, diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 9c502bd..8f7a8bd 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -807,11 +807,13 @@ find_window_functions_walker(Node *node, WindowFuncLists *lists) * Estimate the number of rows returned by a set-returning expression. * The result is 1 if there are no set-returning functions. * - * We use the product of the rowcount estimates of all the functions in - * the given tree (this corresponds to the behavior of ExecMakeFunctionResult - * for nested set-returning functions). + * We use the product of the rowcount estimates of all the functions in the + * given tree (this corresponds to the behavior of ExecMakeFunctionResult for + * nested set-returning functions). * * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c. + * + * FIXME: This possibly be simplified now that targetlist SRFs are gone. */ double expression_returns_set_rows(Node *clause) @@ -881,40 +883,6 @@ expression_returns_set_rows_walker(Node *node, double *count) (void *) count); } -/* - * tlist_returns_set_rows - * Estimate the number of rows returned by a set-returning targetlist. - * The result is 1 if there are no set-returning functions. - * - * Here, the result is the largest rowcount estimate of any of the tlist's - * expressions, not the product as you would get from naively applying - * expression_returns_set_rows() to the whole tlist. The behavior actually - * implemented by ExecTargetList produces a number of rows equal to the least - * common multiple of the expression rowcounts, so that the product would be - * a worst-case estimate that is typically not realistic. Taking the max as - * we do here is a best-case estimate that might not be realistic either, - * but it's probably closer for typical usages. We don't try to compute the - * actual LCM because we're working with very approximate estimates, so their - * LCM would be unduly noisy. - */ -double -tlist_returns_set_rows(List *tlist) -{ - double result = 1; - ListCell *lc; - - foreach(lc, tlist) - { - TargetEntry *tle = (TargetEntry *) lfirst(lc); - double colresult; - - colresult = expression_returns_set_rows((Node *) tle->expr); - if (result < colresult) - result = colresult; - } - return result; -} - /***************************************************************************** * Subplan clause manipulation @@ -4899,7 +4867,7 @@ inline_function(Oid funcid, Oid result_type, Oid result_collid, /* * Forget it if the function is not SQL-language or has other showstopper - * properties. (The nargs check is just paranoia.) + * properties. (The nargs and retset checks are just paranoia.) */ if (funcform->prolang != SQLlanguageId || funcform->prosecdef || @@ -5287,7 +5255,7 @@ evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, */ const_val = ExecEvalExprSwitchContext(exprstate, GetPerTupleExprContext(estate), - &const_is_null, NULL); + &const_is_null); /* Get info needed about result datatype */ get_typlenbyval(result_type, &resultTypLen, &resultTypByVal); diff --git a/src/backend/optimizer/util/predtest.c b/src/backend/optimizer/util/predtest.c index 2c2efb1..0c59fe8 100644 --- a/src/backend/optimizer/util/predtest.c +++ b/src/backend/optimizer/util/predtest.c @@ -1596,7 +1596,7 @@ operator_predicate_proof(Expr *predicate, Node *clause, bool refute_it) /* And execute it. */ test_result = ExecEvalExprSwitchContext(test_exprstate, GetPerTupleExprContext(estate), - &isNull, NULL); + &isNull); /* Get back to outer memory context */ MemoryContextSwitchTo(oldcontext); diff --git a/src/backend/utils/adt/domains.c b/src/backend/utils/adt/domains.c index 19ee4ce..c568c6c 100644 --- a/src/backend/utils/adt/domains.c +++ b/src/backend/utils/adt/domains.c @@ -164,7 +164,7 @@ domain_check_input(Datum value, bool isnull, DomainIOData *my_extra) conResult = ExecEvalExprSwitchContext(con->check_expr, econtext, - &conIsNull, NULL); + &conIsNull); if (!conIsNull && !DatumGetBool(conResult)) diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c index 7ed5bcb..65bf6ad 100644 --- a/src/backend/utils/adt/xml.c +++ b/src/backend/utils/adt/xml.c @@ -603,7 +603,7 @@ xmlelement(XmlExprState *xmlExpr, ExprContext *econtext) bool isnull; char *str; - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); if (isnull) str = NULL; else @@ -620,7 +620,7 @@ xmlelement(XmlExprState *xmlExpr, ExprContext *econtext) bool isnull; char *str; - value = ExecEvalExpr(e, econtext, &isnull, NULL); + value = ExecEvalExpr(e, econtext, &isnull); /* here we can just forget NULL elements immediately */ if (!isnull) { diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h index 7f11285..79a31a9 100644 --- a/src/include/executor/executor.h +++ b/src/include/executor/executor.h @@ -69,8 +69,8 @@ * now it's just a macro invoking the function pointed to by an ExprState * node. Beware of double evaluation of the ExprState argument! */ -#define ExecEvalExpr(expr, econtext, isNull, isDone) \ - ((*(expr)->evalfunc) (expr, econtext, isNull, isDone)) +#define ExecEvalExpr(expr, econtext, isNull) \ + ((*(expr)->evalfunc) (expr, econtext, isNull)) /* Hook for plugins to get control in ExecutorStart() */ @@ -235,18 +235,17 @@ extern Datum GetAttributeByNum(HeapTupleHeader tuple, AttrNumber attrno, extern Datum GetAttributeByName(HeapTupleHeader tuple, const char *attname, bool *isNull); extern Datum ExecEvalExprSwitchContext(ExprState *expression, ExprContext *econtext, - bool *isNull, ExprDoneCond *isDone); -extern ExprDoneCond ExecEvalFuncArgs(FunctionCallInfo fcinfo, + bool *isNull); +extern void ExecEvalFuncArgs(FunctionCallInfo fcinfo, List *argList, ExprContext *econtext); extern ExprState *ExecInitExpr(Expr *node, PlanState *parent); extern void ExecInitFcache(Oid foid, Oid input_collation, FuncExprState *fcache, - MemoryContext fcacheCxt, bool needDescForSets); + MemoryContext fcacheCxt); extern ExprState *ExecPrepareExpr(Expr *node, EState *estate); extern bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull); extern int ExecTargetListLength(List *targetlist); extern int ExecCleanTargetListLength(List *targetlist); -extern TupleTableSlot *ExecProject(ProjectionInfo *projInfo, - ExprDoneCond *isDone); +extern TupleTableSlot *ExecProject(ProjectionInfo *projInfo); /* * prototypes from functions in execScan.c diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index e7fd7bd..043f969 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -243,7 +243,6 @@ typedef struct ProjectionInfo List *pi_targetlist; ExprContext *pi_exprContext; TupleTableSlot *pi_slot; - ExprDoneCond *pi_itemIsDone; bool pi_directMap; int pi_numSimpleVars; int *pi_varSlotOffsets; @@ -569,8 +568,7 @@ typedef struct ExprState ExprState; typedef Datum (*ExprStateEvalFunc) (ExprState *expression, ExprContext *econtext, - bool *isNull, - ExprDoneCond *isDone); + bool *isNull); struct ExprState { @@ -692,21 +690,13 @@ typedef struct FuncExprState TupleTableSlot *funcResultSlot; /* - * In some cases we need to compute a tuple descriptor for the function's - * output. If so, it's stored here. - */ - TupleDesc funcResultDesc; - bool funcReturnsTuple; /* valid when funcResultDesc isn't - * NULL */ - - /* * setArgsValid is true when we are evaluating a set-returning function * that uses value-per-call mode and we are in the middle of a call * series; we want to pass the same argument values to the function again * (and again, until it returns ExprEndResult). This indicates that * fcinfo_data already contains valid argument data. */ - bool setArgsValid; + bool setArgsValid2; /* * Flag to remember whether we found a set-valued argument to the @@ -1057,8 +1047,6 @@ typedef struct PlanState TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */ ExprContext *ps_ExprContext; /* node's expression-evaluation context */ ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */ - bool ps_TupFromTlist;/* state flag for processing set-valued - * functions in targetlist */ } PlanState; /* ---------------- diff --git a/src/include/optimizer/clauses.h b/src/include/optimizer/clauses.h index 7fb5005..e2d44ce 100644 --- a/src/include/optimizer/clauses.h +++ b/src/include/optimizer/clauses.h @@ -54,7 +54,6 @@ extern bool contain_window_function(Node *clause); extern WindowFuncLists *find_window_functions(Node *clause, Index maxWinRef); extern double expression_returns_set_rows(Node *clause); -extern double tlist_returns_set_rows(List *tlist); extern bool contain_subplans(Node *clause); diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c index f9b3b22..d8905c9 100644 --- a/src/pl/plpgsql/src/pl_exec.c +++ b/src/pl/plpgsql/src/pl_exec.c @@ -5644,8 +5644,7 @@ exec_eval_simple_expr(PLpgSQL_execstate *estate, */ *result = ExecEvalExpr(expr->expr_simple_state, econtext, - isNull, - NULL); + isNull); /* Assorted cleanup */ expr->expr_simple_in_use = false; @@ -6312,7 +6311,7 @@ exec_cast_value(PLpgSQL_execstate *estate, cast_entry->cast_in_use = true; value = ExecEvalExpr(cast_entry->cast_exprstate, econtext, - isnull, NULL); + isnull); cast_entry->cast_in_use = false; -- 2.9.3

view thread (110+ messages)  latest in thread

Message-ID: <20160827214829.zo2dfb5jaikii5nw@alap3.anarazel.de>
Permalink:  ../20160827214829.zo2dfb5jaikii5nw@alap3.anarazel.de/
Also on:    postgresql.org/message-id/20160827214829.zo2dfb5jaikii5nw@alap3.anarazel.de

 ·  · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-hackers@postgresql.org
  Cc: andres@anarazel.de, tgl@sss.pgh.pa.us
  Subject: Re: Implement targetlist SRFs using ROWS FROM() (was Changed SRF in targetlist handling)
  In-Reply-To: <20160827214829.zo2dfb5jaikii5nw@alap3.anarazel.de>
  References: <20160523005327.v2tr7obytitxcnna@alap3.anarazel.de> <20160822214023.aaxz5l4igypowyri@alap3.anarazel.de> <20160827214829.zo2dfb5jaikii5nw@alap3.anarazel.de>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox