PostgreSQL Source Code  git master
createas.h File Reference
#include "catalog/objectaddress.h"
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "tcop/dest.h"
#include "utils/queryenvironment.h"
Include dependency graph for createas.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ObjectAddress ExecCreateTableAs (CreateTableAsStmt *stmt, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv, char *completionTag)
 
int GetIntoRelEFlags (IntoClause *intoClause)
 
DestReceiverCreateIntoRelDestReceiver (IntoClause *intoClause)
 

Function Documentation

◆ CreateIntoRelDestReceiver()

DestReceiver* CreateIntoRelDestReceiver ( IntoClause intoClause)

Definition at line 412 of file createas.c.

References DestIntoRel, intorel_destroy(), intorel_receive(), intorel_shutdown(), intorel_startup(), and palloc0().

Referenced by CreateDestReceiver(), ExecCreateTableAs(), and ExplainOnePlan().

413 {
414  DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
415 
416  self->pub.receiveSlot = intorel_receive;
417  self->pub.rStartup = intorel_startup;
418  self->pub.rShutdown = intorel_shutdown;
419  self->pub.rDestroy = intorel_destroy;
420  self->pub.mydest = DestIntoRel;
421  self->into = intoClause;
422  /* other private fields will be set during intorel_startup */
423 
424  return (DestReceiver *) self;
425 }
static void intorel_shutdown(DestReceiver *self)
Definition: createas.c:600
static bool intorel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: createas.c:572
void * palloc0(Size size)
Definition: mcxt.c:980
static void intorel_destroy(DestReceiver *self)
Definition: createas.c:617
static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: createas.c:431

◆ ExecCreateTableAs()

ObjectAddress ExecCreateTableAs ( CreateTableAsStmt stmt,
const char *  queryString,
ParamListInfo  params,
QueryEnvironment queryEnv,
char *  completionTag 
)

Definition at line 226 of file createas.c.

References Assert, AtEOXact_GUC(), castNode, CMD_SELECT, CMD_UTILITY, Query::commandType, COMPLETION_TAG_BUFSIZE, copyObject, create_ctas_nodata(), CreateIntoRelDestReceiver(), CreateQueryDesc(), CURSOR_OPT_PARALLEL_OK, generate_unaccent_rules::dest, elog, ereport, errcode(), errmsg(), ERROR, EState::es_processed, QueryDesc::estate, ExecuteQuery(), ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), ForwardScanDirection, FreeQueryDesc(), get_relname_relid(), GetActiveSnapshot(), GetIntoRelEFlags(), GetUserIdAndSecContext(), CreateTableAsStmt::if_not_exists, CreateTableAsStmt::into, InvalidObjectAddress, InvalidOid, InvalidSnapshot, IsA, linitial_node, list_length(), NewGUCNestLevel(), NOTICE, pg_plan_query(), PopActiveSnapshot(), PushCopiedSnapshot(), CreateTableAsStmt::query, QueryRewrite(), RangeVarGetCreationNamespace(), IntoClause::rel, RangeVar::relname, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), IntoClause::skipData, snprintf, Query::targetList, UINT64_FORMAT, UpdateActiveSnapshotCommandId(), Query::utilityStmt, and IntoClause::viewQuery.

Referenced by ProcessUtilitySlow().

229 {
230  Query *query = castNode(Query, stmt->query);
231  IntoClause *into = stmt->into;
232  bool is_matview = (into->viewQuery != NULL);
234  Oid save_userid = InvalidOid;
235  int save_sec_context = 0;
236  int save_nestlevel = 0;
237  ObjectAddress address;
238  List *rewritten;
239  PlannedStmt *plan;
240  QueryDesc *queryDesc;
241 
242  if (stmt->if_not_exists)
243  {
244  Oid nspid;
245 
246  nspid = RangeVarGetCreationNamespace(stmt->into->rel);
247 
248  if (get_relname_relid(stmt->into->rel->relname, nspid))
249  {
250  ereport(NOTICE,
251  (errcode(ERRCODE_DUPLICATE_TABLE),
252  errmsg("relation \"%s\" already exists, skipping",
253  stmt->into->rel->relname)));
254  return InvalidObjectAddress;
255  }
256  }
257 
258  /*
259  * Create the tuple receiver object and insert info it will need
260  */
261  dest = CreateIntoRelDestReceiver(into);
262 
263  /*
264  * The contained Query could be a SELECT, or an EXECUTE utility command.
265  * If the latter, we just pass it off to ExecuteQuery.
266  */
267  if (query->commandType == CMD_UTILITY &&
268  IsA(query->utilityStmt, ExecuteStmt))
269  {
270  ExecuteStmt *estmt = castNode(ExecuteStmt, query->utilityStmt);
271 
272  Assert(!is_matview); /* excluded by syntax */
273  ExecuteQuery(estmt, into, queryString, params, dest, completionTag);
274 
275  /* get object address that intorel_startup saved for us */
276  address = ((DR_intorel *) dest)->reladdr;
277 
278  return address;
279  }
280  Assert(query->commandType == CMD_SELECT);
281 
282  /*
283  * For materialized views, lock down security-restricted operations and
284  * arrange to make GUC variable changes local to this command. This is
285  * not necessary for security, but this keeps the behavior similar to
286  * REFRESH MATERIALIZED VIEW. Otherwise, one could create a materialized
287  * view not possible to refresh.
288  */
289  if (is_matview)
290  {
291  GetUserIdAndSecContext(&save_userid, &save_sec_context);
292  SetUserIdAndSecContext(save_userid,
293  save_sec_context | SECURITY_RESTRICTED_OPERATION);
294  save_nestlevel = NewGUCNestLevel();
295  }
296 
297  if (into->skipData)
298  {
299  /*
300  * If WITH NO DATA was specified, do not go through the rewriter,
301  * planner and executor. Just define the relation using a code path
302  * similar to CREATE VIEW. This avoids dump/restore problems stemming
303  * from running the planner before all dependencies are set up.
304  */
305  address = create_ctas_nodata(query->targetList, into);
306  }
307  else
308  {
309  /*
310  * Parse analysis was done already, but we still have to run the rule
311  * rewriter. We do not do AcquireRewriteLocks: we assume the query
312  * either came straight from the parser, or suitable locks were
313  * acquired by plancache.c.
314  *
315  * Because the rewriter and planner tend to scribble on the input, we
316  * make a preliminary copy of the source querytree. This prevents
317  * problems in the case that CTAS is in a portal or plpgsql function
318  * and is executed repeatedly. (See also the same hack in EXPLAIN and
319  * PREPARE.)
320  */
321  rewritten = QueryRewrite(copyObject(query));
322 
323  /* SELECT should never rewrite to more or less than one SELECT query */
324  if (list_length(rewritten) != 1)
325  elog(ERROR, "unexpected rewrite result for %s",
326  is_matview ? "CREATE MATERIALIZED VIEW" :
327  "CREATE TABLE AS SELECT");
328  query = linitial_node(Query, rewritten);
329  Assert(query->commandType == CMD_SELECT);
330 
331  /* plan the query */
332  plan = pg_plan_query(query, CURSOR_OPT_PARALLEL_OK, params);
333 
334  /*
335  * Use a snapshot with an updated command ID to ensure this query sees
336  * results of any previously executed queries. (This could only
337  * matter if the planner executed an allegedly-stable function that
338  * changed the database contents, but let's do it anyway to be
339  * parallel to the EXPLAIN code path.)
340  */
343 
344  /* Create a QueryDesc, redirecting output to our tuple receiver */
345  queryDesc = CreateQueryDesc(plan, queryString,
347  dest, params, queryEnv, 0);
348 
349  /* call ExecutorStart to prepare the plan for execution */
350  ExecutorStart(queryDesc, GetIntoRelEFlags(into));
351 
352  /* run the plan to completion */
353  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
354 
355  /* save the rowcount if we're given a completionTag to fill */
356  if (completionTag)
357  snprintf(completionTag, COMPLETION_TAG_BUFSIZE,
358  "SELECT " UINT64_FORMAT,
359  queryDesc->estate->es_processed);
360 
361  /* get object address that intorel_startup saved for us */
362  address = ((DR_intorel *) dest)->reladdr;
363 
364  /* and clean up */
365  ExecutorFinish(queryDesc);
366  ExecutorEnd(queryDesc);
367 
368  FreeQueryDesc(queryDesc);
369 
371  }
372 
373  if (is_matview)
374  {
375  /* Roll back any GUC changes */
376  AtEOXact_GUC(false, save_nestlevel);
377 
378  /* Restore userid and security context */
379  SetUserIdAndSecContext(save_userid, save_sec_context);
380  }
381 
382  return address;
383 }
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:783
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * QueryRewrite(Query *parsetree)
EState * estate
Definition: execdesc.h:48
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:300
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:492
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:841
int errcode(int sqlerrcode)
Definition: elog.c:608
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
bool skipData
Definition: primnodes.h:119
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:120
#define linitial_node(type, l)
Definition: pg_list.h:198
void ExecuteQuery(ExecuteStmt *stmt, IntoClause *intoClause, const char *queryString, ParamListInfo params, DestReceiver *dest, char *completionTag)
Definition: prepare.c:200
List * targetList
Definition: parsenodes.h:140
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
char * relname
Definition: primnodes.h:68
int GetIntoRelEFlags(IntoClause *intoClause)
Definition: createas.c:394
#define ERROR
Definition: elog.h:43
Node * viewQuery
Definition: primnodes.h:118
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:771
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:485
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5782
DestReceiver * CreateIntoRelDestReceiver(IntoClause *intoClause)
Definition: createas.c:412
#define ereport(elevel, rest)
Definition: elog.h:141
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402
#define InvalidSnapshot
Definition: snapshot.h:123
#define InvalidOid
Definition: postgres_ext.h:36
IntoClause * into
Definition: parsenodes.h:3241
#define NOTICE
Definition: elog.h:37
CmdType commandType
Definition: parsenodes.h:112
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
#define Assert(condition)
Definition: c.h:739
uint64 es_processed
Definition: execnodes.h:553
static int list_length(const List *l)
Definition: pg_list.h:169
static ObjectAddress create_ctas_nodata(List *tlist, IntoClause *into)
Definition: createas.c:158
int NewGUCNestLevel(void)
Definition: guc.c:5768
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2692
const ObjectAddress InvalidObjectAddress
int errmsg(const char *fmt,...)
Definition: elog.c:822
RangeVar * rel
Definition: primnodes.h:112
#define elog(elevel,...)
Definition: elog.h:228
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50
#define snprintf
Definition: port.h:192
#define UINT64_FORMAT
Definition: c.h:402
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:441
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:855

◆ GetIntoRelEFlags()

int GetIntoRelEFlags ( IntoClause intoClause)

Definition at line 394 of file createas.c.

References EXEC_FLAG_WITH_NO_DATA, and IntoClause::skipData.

Referenced by ExecCreateTableAs(), ExecuteQuery(), and ExplainOnePlan().

395 {
396  int flags = 0;
397 
398  if (intoClause->skipData)
399  flags |= EXEC_FLAG_WITH_NO_DATA;
400 
401  return flags;
402 }
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:61
bool skipData
Definition: primnodes.h:119