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 423 of file createas.c.

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

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

424 {
425  DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
426 
427  self->pub.receiveSlot = intorel_receive;
428  self->pub.rStartup = intorel_startup;
429  self->pub.rShutdown = intorel_shutdown;
430  self->pub.rDestroy = intorel_destroy;
431  self->pub.mydest = DestIntoRel;
432  self->into = intoClause;
433  /* other private fields will be set during intorel_startup */
434 
435  return (DestReceiver *) self;
436 }
static void intorel_shutdown(DestReceiver *self)
Definition: createas.c:614
static bool intorel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: createas.c:582
void * palloc0(Size size)
Definition: mcxt.c:877
static void intorel_destroy(DestReceiver *self)
Definition: createas.c:633
static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: createas.c:442

◆ ExecCreateTableAs()

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

Definition at line 224 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().

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

◆ GetIntoRelEFlags()

int GetIntoRelEFlags ( IntoClause intoClause)

Definition at line 392 of file createas.c.

References EXEC_FLAG_WITH_NO_DATA, EXEC_FLAG_WITH_OIDS, EXEC_FLAG_WITHOUT_OIDS, interpretOidsOption(), IntoClause::options, IntoClause::skipData, and IntoClause::viewQuery.

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

393 {
394  int flags;
395 
396  /*
397  * We need to tell the executor whether it has to produce OIDs or not,
398  * because it doesn't have enough information to do so itself (since we
399  * can't build the target relation until after ExecutorStart).
400  *
401  * Disallow the OIDS option for materialized views.
402  */
403  if (interpretOidsOption(intoClause->options,
404  (intoClause->viewQuery == NULL)))
405  flags = EXEC_FLAG_WITH_OIDS;
406  else
407  flags = EXEC_FLAG_WITHOUT_OIDS;
408 
409  if (intoClause->skipData)
410  flags |= EXEC_FLAG_WITH_NO_DATA;
411 
412  return flags;
413 }
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:65
bool skipData
Definition: primnodes.h:115
#define EXEC_FLAG_WITHOUT_OIDS
Definition: executor.h:64
Node * viewQuery
Definition: primnodes.h:114
List * options
Definition: primnodes.h:111
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:255
#define EXEC_FLAG_WITH_OIDS
Definition: executor.h:63