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

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

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

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

◆ CreateTableAsRelExists()

bool CreateTableAsRelExists ( CreateTableAsStmt ctas)

Definition at line 388 of file createas.c.

389 {
390  Oid nspid;
391  Oid oldrelid;
392  ObjectAddress address;
393  IntoClause *into = ctas->into;
394 
396 
397  oldrelid = get_relname_relid(into->rel->relname, nspid);
398  if (OidIsValid(oldrelid))
399  {
400  if (!ctas->if_not_exists)
401  ereport(ERROR,
402  (errcode(ERRCODE_DUPLICATE_TABLE),
403  errmsg("relation \"%s\" already exists",
404  into->rel->relname)));
405 
406  /*
407  * The relation exists and IF NOT EXISTS has been specified.
408  *
409  * If we are in an extension script, insist that the pre-existing
410  * object be a member of the extension, to avoid security risks.
411  */
412  ObjectAddressSet(address, RelationRelationId, oldrelid);
414 
415  /* OK to skip */
416  ereport(NOTICE,
417  (errcode(ERRCODE_DUPLICATE_TABLE),
418  errmsg("relation \"%s\" already exists, skipping",
419  into->rel->relname)));
420  return true;
421  }
422 
423  /* Relation does not exist, it can be created */
424  return false;
425 }
#define OidIsValid(objectId)
Definition: c.h:762
int nspid
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ERROR
Definition: elog.h:39
#define NOTICE
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:149
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1863
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:639
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void checkMembershipInCurrentExtension(const ObjectAddress *object)
Definition: pg_depend.c:257
unsigned int Oid
Definition: postgres_ext.h:31
IntoClause * into
Definition: parsenodes.h:3818
RangeVar * rel
Definition: primnodes.h:148
char * relname
Definition: primnodes.h:82

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

Referenced by ExecCreateTableAs(), and ExplainOneUtility().

◆ ExecCreateTableAs()

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

Definition at line 221 of file createas.c.

224 {
225  Query *query = castNode(Query, stmt->query);
226  IntoClause *into = stmt->into;
227  bool is_matview = (into->viewQuery != NULL);
229  Oid save_userid = InvalidOid;
230  int save_sec_context = 0;
231  int save_nestlevel = 0;
232  ObjectAddress address;
233  List *rewritten;
234  PlannedStmt *plan;
235  QueryDesc *queryDesc;
236 
237  /* Check if the relation exists or not */
239  return InvalidObjectAddress;
240 
241  /*
242  * Create the tuple receiver object and insert info it will need
243  */
245 
246  /*
247  * The contained Query could be a SELECT, or an EXECUTE utility command.
248  * If the latter, we just pass it off to ExecuteQuery.
249  */
250  if (query->commandType == CMD_UTILITY &&
251  IsA(query->utilityStmt, ExecuteStmt))
252  {
253  ExecuteStmt *estmt = castNode(ExecuteStmt, query->utilityStmt);
254 
255  Assert(!is_matview); /* excluded by syntax */
256  ExecuteQuery(pstate, estmt, into, params, dest, qc);
257 
258  /* get object address that intorel_startup saved for us */
259  address = ((DR_intorel *) dest)->reladdr;
260 
261  return address;
262  }
263  Assert(query->commandType == CMD_SELECT);
264 
265  /*
266  * For materialized views, lock down security-restricted operations and
267  * arrange to make GUC variable changes local to this command. This is
268  * not necessary for security, but this keeps the behavior similar to
269  * REFRESH MATERIALIZED VIEW. Otherwise, one could create a materialized
270  * view not possible to refresh.
271  */
272  if (is_matview)
273  {
274  GetUserIdAndSecContext(&save_userid, &save_sec_context);
275  SetUserIdAndSecContext(save_userid,
276  save_sec_context | SECURITY_RESTRICTED_OPERATION);
277  save_nestlevel = NewGUCNestLevel();
278  }
279 
280  if (into->skipData)
281  {
282  /*
283  * If WITH NO DATA was specified, do not go through the rewriter,
284  * planner and executor. Just define the relation using a code path
285  * similar to CREATE VIEW. This avoids dump/restore problems stemming
286  * from running the planner before all dependencies are set up.
287  */
288  address = create_ctas_nodata(query->targetList, into);
289  }
290  else
291  {
292  /*
293  * Parse analysis was done already, but we still have to run the rule
294  * rewriter. We do not do AcquireRewriteLocks: we assume the query
295  * either came straight from the parser, or suitable locks were
296  * acquired by plancache.c.
297  */
298  rewritten = QueryRewrite(query);
299 
300  /* SELECT should never rewrite to more or less than one SELECT query */
301  if (list_length(rewritten) != 1)
302  elog(ERROR, "unexpected rewrite result for %s",
303  is_matview ? "CREATE MATERIALIZED VIEW" :
304  "CREATE TABLE AS SELECT");
305  query = linitial_node(Query, rewritten);
306  Assert(query->commandType == CMD_SELECT);
307 
308  /* plan the query */
309  plan = pg_plan_query(query, pstate->p_sourcetext,
310  CURSOR_OPT_PARALLEL_OK, params);
311 
312  /*
313  * Use a snapshot with an updated command ID to ensure this query sees
314  * results of any previously executed queries. (This could only
315  * matter if the planner executed an allegedly-stable function that
316  * changed the database contents, but let's do it anyway to be
317  * parallel to the EXPLAIN code path.)
318  */
321 
322  /* Create a QueryDesc, redirecting output to our tuple receiver */
323  queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
325  dest, params, queryEnv, 0);
326 
327  /* call ExecutorStart to prepare the plan for execution */
328  ExecutorStart(queryDesc, GetIntoRelEFlags(into));
329 
330  /* run the plan to completion */
331  ExecutorRun(queryDesc, ForwardScanDirection, 0, true);
332 
333  /* save the rowcount if we're given a qc to fill */
334  if (qc)
335  SetQueryCompletion(qc, CMDTAG_SELECT, queryDesc->estate->es_processed);
336 
337  /* get object address that intorel_startup saved for us */
338  address = ((DR_intorel *) dest)->reladdr;
339 
340  /* and clean up */
341  ExecutorFinish(queryDesc);
342  ExecutorEnd(queryDesc);
343 
344  FreeQueryDesc(queryDesc);
345 
347  }
348 
349  if (is_matview)
350  {
351  /* Roll back any GUC changes */
352  AtEOXact_GUC(false, save_nestlevel);
353 
354  /* Restore userid and security context */
355  SetUserIdAndSecContext(save_userid, save_sec_context);
356  }
357 
358  return address;
359 }
void ExecuteQuery(ParseState *pstate, ExecuteStmt *stmt, IntoClause *intoClause, ParamListInfo params, DestReceiver *dest, QueryCompletion *qc)
Definition: prepare.c:147
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:38
bool CreateTableAsRelExists(CreateTableAsStmt *ctas)
Definition: createas.c:388
DestReceiver * CreateIntoRelDestReceiver(IntoClause *intoClause)
Definition: createas.c:435
static ObjectAddress create_ctas_nodata(List *tlist, IntoClause *into)
Definition: createas.c:153
int GetIntoRelEFlags(IntoClause *intoClause)
Definition: createas.c:370
#define elog(elevel,...)
Definition: elog.h:224
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:467
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:407
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:124
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:297
int NewGUCNestLevel(void)
Definition: guc.c:2237
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2264
#define stmt
Definition: indent_codes.h:59
Assert(fmt[strlen(fmt) - 1] !='\n')
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:315
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:635
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:642
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ CMD_UTILITY
Definition: nodes.h:270
@ CMD_SELECT
Definition: nodes.h:265
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
const ObjectAddress InvalidObjectAddress
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3216
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
#define plan(x)
Definition: pg_regress.c:162
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:886
#define InvalidOid
Definition: postgres_ext.h:36
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
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
List * QueryRewrite(Query *parsetree)
@ ForwardScanDirection
Definition: sdir.h:28
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:712
void PopActiveSnapshot(void)
Definition: snapmgr.c:743
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:700
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:770
#define InvalidSnapshot
Definition: snapshot.h:123
uint64 es_processed
Definition: execnodes.h:669
bool skipData
Definition: primnodes.h:156
Definition: pg_list.h:54
const char * p_sourcetext
Definition: parse_node.h:193
EState * estate
Definition: execdesc.h:48
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
List * targetList
Definition: parsenodes.h:190

References Assert(), AtEOXact_GUC(), castNode, CMD_SELECT, CMD_UTILITY, Query::commandType, 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(), InvalidObjectAddress, InvalidOid, InvalidSnapshot, IsA, linitial_node, list_length(), NewGUCNestLevel(), ParseState::p_sourcetext, pg_plan_query(), plan, PopActiveSnapshot(), PushCopiedSnapshot(), QueryRewrite(), SECURITY_RESTRICTED_OPERATION, SetQueryCompletion(), SetUserIdAndSecContext(), IntoClause::skipData, stmt, Query::targetList, UpdateActiveSnapshotCommandId(), and Query::utilityStmt.

Referenced by ProcessUtilitySlow().

◆ GetIntoRelEFlags()

int GetIntoRelEFlags ( IntoClause intoClause)

Definition at line 370 of file createas.c.

371 {
372  int flags = 0;
373 
374  if (intoClause->skipData)
375  flags |= EXEC_FLAG_WITH_NO_DATA;
376 
377  return flags;
378 }
#define EXEC_FLAG_WITH_NO_DATA
Definition: executor.h:71

References EXEC_FLAG_WITH_NO_DATA, and IntoClause::skipData.

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