PostgreSQL Source Code  git master
createas.h File Reference
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 (ParseState *pstate, CreateTableAsStmt *stmt, ParamListInfo params, QueryEnvironment *queryEnv, QueryCompletion *qc)
 
int GetIntoRelEFlags (IntoClause *intoClause)
 
DestReceiverCreateIntoRelDestReceiver (IntoClause *intoClause)
 
bool CreateTableAsRelExists (CreateTableAsStmt *ctas)
 

Function Documentation

◆ CreateIntoRelDestReceiver()

DestReceiver* CreateIntoRelDestReceiver ( IntoClause intoClause)

Definition at line 434 of file createas.c.

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

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

435 {
436  DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
437 
438  self->pub.receiveSlot = intorel_receive;
439  self->pub.rStartup = intorel_startup;
440  self->pub.rShutdown = intorel_shutdown;
441  self->pub.rDestroy = intorel_destroy;
442  self->pub.mydest = DestIntoRel;
443  self->into = intoClause;
444  /* other private fields will be set during intorel_startup */
445 
446  return (DestReceiver *) self;
447 }
static void intorel_shutdown(DestReceiver *self)
Definition: createas.c:608
static bool intorel_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: createas.c:577
void * palloc0(Size size)
Definition: mcxt.c:981
static void intorel_destroy(DestReceiver *self)
Definition: createas.c:628
static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: createas.c:453

◆ CreateTableAsRelExists()

bool CreateTableAsRelExists ( CreateTableAsStmt ctas)

Definition at line 399 of file createas.c.

References ereport, errcode(), errmsg(), ERROR, get_relname_relid(), CreateTableAsStmt::if_not_exists, CreateTableAsStmt::into, NOTICE, RangeVarGetCreationNamespace(), IntoClause::rel, and RangeVar::relname.

Referenced by ExecCreateTableAs(), and ExplainOneUtility().

400 {
401  Oid nspid;
402  IntoClause *into = ctas->into;
403 
404  nspid = RangeVarGetCreationNamespace(into->rel);
405 
406  if (get_relname_relid(into->rel->relname, nspid))
407  {
408  if (!ctas->if_not_exists)
409  ereport(ERROR,
410  (errcode(ERRCODE_DUPLICATE_TABLE),
411  errmsg("relation \"%s\" already exists",
412  into->rel->relname)));
413 
414  /* The relation exists and IF NOT EXISTS has been specified */
415  ereport(NOTICE,
416  (errcode(ERRCODE_DUPLICATE_TABLE),
417  errmsg("relation \"%s\" already exists, skipping",
418  into->rel->relname)));
419  return true;
420  }
421 
422  /* Relation does not exist, it can be created */
423  return false;
424 }
int errcode(int sqlerrcode)
Definition: elog.c:704
unsigned int Oid
Definition: postgres_ext.h:31
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:45
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1829
#define ereport(elevel,...)
Definition: elog.h:155
IntoClause * into
Definition: parsenodes.h:3288
#define NOTICE
Definition: elog.h:37
int errmsg(const char *fmt,...)
Definition: elog.c:915
RangeVar * rel
Definition: primnodes.h:112
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:449

◆ ExecCreateTableAs()

ObjectAddress ExecCreateTableAs ( ParseState pstate,
CreateTableAsStmt stmt,
ParamListInfo  params,
QueryEnvironment queryEnv,
QueryCompletion qc 
)

Definition at line 226 of file createas.c.

References Assert, AtEOXact_GUC(), castNode, CMD_SELECT, CMD_UTILITY, Query::commandType, copyObject, create_ctas_nodata(), CreateIntoRelDestReceiver(), CreateQueryDesc(), CreateTableAsRelExists(), CURSOR_OPT_PARALLEL_OK, generate_unaccent_rules::dest, elog, ERROR, EState::es_processed, QueryDesc::estate, ExecuteQuery(), ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), ForwardScanDirection, FreeQueryDesc(), GetActiveSnapshot(), GetIntoRelEFlags(), GetUserIdAndSecContext(), CreateTableAsStmt::into, InvalidObjectAddress, InvalidOid, InvalidSnapshot, IsA, linitial_node, list_length(), NewGUCNestLevel(), ParseState::p_sourcetext, pg_plan_query(), PopActiveSnapshot(), PushCopiedSnapshot(), CreateTableAsStmt::query, QueryRewrite(), SECURITY_RESTRICTED_OPERATION, SetQueryCompletion(), SetUserIdAndSecContext(), IntoClause::skipData, Query::targetList, 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  /* Check if the relation exists or not */
243  if (CreateTableAsRelExists(stmt))
244  return InvalidObjectAddress;
245 
246  /*
247  * Create the tuple receiver object and insert info it will need
248  */
249  dest = CreateIntoRelDestReceiver(into);
250 
251  /*
252  * The contained Query could be a SELECT, or an EXECUTE utility command.
253  * If the latter, we just pass it off to ExecuteQuery.
254  */
255  if (query->commandType == CMD_UTILITY &&
256  IsA(query->utilityStmt, ExecuteStmt))
257  {
258  ExecuteStmt *estmt = castNode(ExecuteStmt, query->utilityStmt);
259 
260  Assert(!is_matview); /* excluded by syntax */
261  ExecuteQuery(pstate, estmt, into, params, dest, qc);
262 
263  /* get object address that intorel_startup saved for us */
264  address = ((DR_intorel *) dest)->reladdr;
265 
266  return address;
267  }
268  Assert(query->commandType == CMD_SELECT);
269 
270  /*
271  * For materialized views, lock down security-restricted operations and
272  * arrange to make GUC variable changes local to this command. This is
273  * not necessary for security, but this keeps the behavior similar to
274  * REFRESH MATERIALIZED VIEW. Otherwise, one could create a materialized
275  * view not possible to refresh.
276  */
277  if (is_matview)
278  {
279  GetUserIdAndSecContext(&save_userid, &save_sec_context);
280  SetUserIdAndSecContext(save_userid,
281  save_sec_context | SECURITY_RESTRICTED_OPERATION);
282  save_nestlevel = NewGUCNestLevel();
283  }
284 
285  if (into->skipData)
286  {
287  /*
288  * If WITH NO DATA was specified, do not go through the rewriter,
289  * planner and executor. Just define the relation using a code path
290  * similar to CREATE VIEW. This avoids dump/restore problems stemming
291  * from running the planner before all dependencies are set up.
292  */
293  address = create_ctas_nodata(query->targetList, into);
294  }
295  else
296  {
297  /*
298  * Parse analysis was done already, but we still have to run the rule
299  * rewriter. We do not do AcquireRewriteLocks: we assume the query
300  * either came straight from the parser, or suitable locks were
301  * acquired by plancache.c.
302  *
303  * Because the rewriter and planner tend to scribble on the input, we
304  * make a preliminary copy of the source querytree. This prevents
305  * problems in the case that CTAS is in a portal or plpgsql function
306  * and is executed repeatedly. (See also the same hack in EXPLAIN and
307  * PREPARE.)
308  */
309  rewritten = QueryRewrite(copyObject(query));
310 
311  /* SELECT should never rewrite to more or less than one SELECT query */
312  if (list_length(rewritten) != 1)
313  elog(ERROR, "unexpected rewrite result for %s",
314  is_matview ? "CREATE MATERIALIZED VIEW" :
315  "CREATE TABLE AS SELECT");
316  query = linitial_node(Query, rewritten);
317  Assert(query->commandType == CMD_SELECT);
318 
319  /* plan the query */
320  plan = pg_plan_query(query, pstate->p_sourcetext,
321  CURSOR_OPT_PARALLEL_OK, params);
322 
323  /*
324  * Use a snapshot with an updated command ID to ensure this query sees
325  * results of any previously executed queries. (This could only
326  * matter if the planner executed an allegedly-stable function that
327  * changed the database contents, but let's do it anyway to be
328  * parallel to the EXPLAIN code path.)
329  */
332 
333  /* Create a QueryDesc, redirecting output to our tuple receiver */
334  queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
336  dest, params, queryEnv, 0);
337 
338  /* call ExecutorStart to prepare the plan for execution */
339  ExecutorStart(queryDesc, GetIntoRelEFlags(into));
340 
341  /* run the plan to completion */
342  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
343 
344  /* save the rowcount if we're given a qc to fill */
345  if (qc)
346  SetQueryCompletion(qc, CMDTAG_SELECT, queryDesc->estate->es_processed);
347 
348  /* get object address that intorel_startup saved for us */
349  address = ((DR_intorel *) dest)->reladdr;
350 
351  /* and clean up */
352  ExecutorFinish(queryDesc);
353  ExecutorEnd(queryDesc);
354 
355  FreeQueryDesc(queryDesc);
356 
358  }
359 
360  if (is_matview)
361  {
362  /* Roll back any GUC changes */
363  AtEOXact_GUC(false, save_nestlevel);
364 
365  /* Restore userid and security context */
366  SetUserIdAndSecContext(save_userid, save_sec_context);
367  }
368 
369  return address;
370 }
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:728
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
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:588
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
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:177
List * targetList
Definition: parsenodes.h:140
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
int GetIntoRelEFlags(IntoClause *intoClause)
Definition: createas.c:381
#define ERROR
Definition: elog.h:45
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:716
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
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:581
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6008
void ExecuteQuery(ParseState *pstate, ExecuteStmt *stmt, IntoClause *intoClause, ParamListInfo params, DestReceiver *dest, QueryCompletion *qc)
Definition: prepare.c:187
DestReceiver * CreateIntoRelDestReceiver(IntoClause *intoClause)
Definition: createas.c:434
bool CreateTableAsRelExists(CreateTableAsStmt *ctas)
Definition: createas.c:399
const char * p_sourcetext
Definition: parse_node.h:179
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:3288
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:792
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
uint64 es_processed
Definition: execnodes.h:569
static int list_length(const List *l)
Definition: pg_list.h:149
static ObjectAddress create_ctas_nodata(List *tlist, IntoClause *into)
Definition: createas.c:158
int NewGUCNestLevel(void)
Definition: guc.c:5994
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2732
const ObjectAddress InvalidObjectAddress
#define elog(elevel,...)
Definition: elog.h:228
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:858
#define copyObject(obj)
Definition: nodes.h:644
Definition: pg_list.h:50

◆ GetIntoRelEFlags()

int GetIntoRelEFlags ( IntoClause intoClause)

Definition at line 381 of file createas.c.

References EXEC_FLAG_WITH_NO_DATA, and IntoClause::skipData.

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

382 {
383  int flags = 0;
384 
385  if (intoClause->skipData)
386  flags |= EXEC_FLAG_WITH_NO_DATA;
387 
388  return flags;
389 }
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:61
bool skipData
Definition: primnodes.h:119