{
DestReceiver pub; /* publicly-known function pointers */
EState *estate; /* EState we are working with */
+ DestReceiver *origdest; /* QueryDesc's original receiver */
Relation rel; /* Relation to write to */
int hi_options; /* heap_insert performance options */
BulkInsertState bistate; /* bulk insert state */
/*
* Now replace the query's DestReceiver with one for SELECT INTO
*/
- queryDesc->dest = CreateDestReceiver(DestIntoRel);
- myState = (DR_intorel *) queryDesc->dest;
+ myState = (DR_intorel *) CreateDestReceiver(DestIntoRel);
Assert(myState->pub.mydest == DestIntoRel);
myState->estate = estate;
+ myState->origdest = queryDesc->dest;
myState->rel = intoRelationDesc;
+ queryDesc->dest = (DestReceiver *) myState;
+
/*
* We can skip WAL-logging the insertions, unless PITR or streaming
* replication is in use. We can skip the FSM in any case.
{
DR_intorel *myState = (DR_intorel *) queryDesc->dest;
- /* OpenIntoRel might never have gotten called */
- if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
+ /*
+ * OpenIntoRel might never have gotten called, and we also want to guard
+ * against double destruction.
+ */
+ if (myState && myState->pub.mydest == DestIntoRel)
{
FreeBulkInsertState(myState->bistate);
/* close rel, but keep lock until commit */
heap_close(myState->rel, NoLock);
- myState->rel = NULL;
+ /* restore the receiver belonging to executor's caller */
+ queryDesc->dest = myState->origdest;
+
+ /* might as well invoke my destructor */
+ intorel_destroy((DestReceiver *) myState);
}
}
drop cascades to table selinto_schema.tmp2
drop cascades to table selinto_schema.tmp3
DROP USER selinto_user;
+--
+-- CREATE TABLE AS/SELECT INTO as last command in a SQL function
+-- have been known to cause problems
+--
+CREATE FUNCTION make_table() RETURNS VOID
+AS $$
+ CREATE TABLE created_table AS SELECT * FROM int8_tbl;
+$$ LANGUAGE SQL;
+SELECT make_table();
+ make_table
+------------
+
+(1 row)
+
+SELECT * FROM created_table;
+ q1 | q2
+------------------+-------------------
+ 123 | 456
+ 123 | 4567890123456789
+ 4567890123456789 | 123
+ 4567890123456789 | 4567890123456789
+ 4567890123456789 | -4567890123456789
+(5 rows)
+
+DROP TABLE created_table;
DROP SCHEMA selinto_schema CASCADE;
DROP USER selinto_user;
+
+--
+-- CREATE TABLE AS/SELECT INTO as last command in a SQL function
+-- have been known to cause problems
+--
+CREATE FUNCTION make_table() RETURNS VOID
+AS $$
+ CREATE TABLE created_table AS SELECT * FROM int8_tbl;
+$$ LANGUAGE SQL;
+
+SELECT make_table();
+
+SELECT * FROM created_table;
+
+DROP TABLE created_table;