1 /*-------------------------------------------------------------------------
4 * Contains functions which control the execution of the POSTGRES utility
5 * commands. At one time acted as an interface between the Lisp and C
8 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $Header: /cvsroot/pgsql/src/backend/tcop/utility.c,v 1.137 2002/03/21 23:27:23 tgl Exp $
15 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "catalog/catalog.h"
21 #include "catalog/pg_shadow.h"
22 #include "commands/async.h"
23 #include "commands/cluster.h"
24 #include "commands/command.h"
25 #include "commands/comment.h"
26 #include "commands/copy.h"
27 #include "commands/creatinh.h"
28 #include "commands/dbcommands.h"
29 #include "commands/defrem.h"
30 #include "commands/explain.h"
31 #include "commands/proclang.h"
32 #include "commands/rename.h"
33 #include "commands/sequence.h"
34 #include "commands/trigger.h"
35 #include "commands/user.h"
36 #include "commands/vacuum.h"
37 #include "commands/variable.h"
38 #include "commands/view.h"
39 #include "miscadmin.h"
40 #include "parser/parse.h"
41 #include "parser/parse_clause.h"
42 #include "parser/parse_expr.h"
43 #include "rewrite/rewriteDefine.h"
44 #include "rewrite/rewriteRemove.h"
45 #include "tcop/utility.h"
46 #include "utils/acl.h"
47 #include "utils/syscache.h"
48 #include "utils/temprel.h"
49 #include "access/xlog.h"
52 * Error-checking support for DROP commands
63 static struct kindstrings kindstringarray[] = {
64 {RELKIND_RELATION, "a", "table", "TABLE"},
65 {RELKIND_SEQUENCE, "a", "sequence", "SEQUENCE"},
66 {RELKIND_VIEW, "a", "view", "VIEW"},
67 {RELKIND_INDEX, "an", "index", "INDEX"},
68 {'\0', "a", "???", "???"}
73 DropErrorMsg(char *relname, char wrongkind, char rightkind)
75 struct kindstrings *rentry;
76 struct kindstrings *wentry;
78 for (rentry = kindstringarray; rentry->kind != '\0'; rentry++)
79 if (rentry->kind == rightkind)
81 Assert(rentry->kind != '\0');
83 for (wentry = kindstringarray; wentry->kind != '\0'; wentry++)
84 if (wentry->kind == wrongkind)
86 /* wrongkind could be something we don't have in our table... */
87 if (wentry->kind != '\0')
88 elog(ERROR, "\"%s\" is not %s %s. Use DROP %s to remove %s %s",
89 relname, rentry->indef_article, rentry->name,
90 wentry->command, wentry->indef_article, wentry->name);
92 elog(ERROR, "\"%s\" is not %s %s",
93 relname, rentry->indef_article, rentry->name);
97 CheckDropPermissions(char *name, char rightkind)
99 struct kindstrings *rentry;
101 Form_pg_class classform;
103 for (rentry = kindstringarray; rentry->kind != '\0'; rentry++)
104 if (rentry->kind == rightkind)
106 Assert(rentry->kind != '\0');
108 tuple = SearchSysCache(RELNAME,
109 PointerGetDatum(name),
111 if (!HeapTupleIsValid(tuple))
112 elog(ERROR, "%s \"%s\" does not exist", rentry->name, name);
114 classform = (Form_pg_class) GETSTRUCT(tuple);
116 if (classform->relkind != rightkind)
117 DropErrorMsg(name, classform->relkind, rightkind);
119 if (!pg_class_ownercheck(tuple->t_data->t_oid, GetUserId()))
120 elog(ERROR, "you do not own %s \"%s\"",
123 if (!allowSystemTableMods && IsSystemRelationName(name) &&
124 !is_temp_relname(name))
125 elog(ERROR, "%s \"%s\" is a system %s",
126 rentry->name, name, rentry->name);
128 ReleaseSysCache(tuple);
132 CheckOwnership(char *relname, bool noCatalogs)
136 tuple = SearchSysCache(RELNAME,
137 PointerGetDatum(relname),
139 if (!HeapTupleIsValid(tuple))
140 elog(ERROR, "Relation \"%s\" does not exist", relname);
142 if (!pg_class_ownercheck(tuple->t_data->t_oid, GetUserId()))
143 elog(ERROR, "%s: %s", relname,
144 aclcheck_error_strings[ACLCHECK_NOT_OWNER]);
148 if (!allowSystemTableMods && IsSystemRelationName(relname))
149 elog(ERROR, "relation \"%s\" is a system catalog",
153 ReleaseSysCache(tuple);
159 * general utility function invoker
161 * parsetree: the parse tree for the utility statement
162 * dest: where to send results
163 * completionTag: points to a buffer of size COMPLETION_TAG_BUFSIZE
164 * in which to store a command completion status string.
166 * completionTag is only set nonempty if we want to return a nondefault
167 * status (currently, only used for MOVE/FETCH).
169 * completionTag may be NULL if caller doesn't want a status string.
172 ProcessUtility(Node *parsetree,
179 completionTag[0] = '\0';
181 switch (nodeTag(parsetree))
184 * ******************************** transactions ********************************
187 case T_TransactionStmt:
189 TransactionStmt *stmt = (TransactionStmt *) parsetree;
191 switch (stmt->command)
194 BeginTransactionBlock();
198 EndTransactionBlock();
202 UserAbortTransactionBlock();
209 * ******************************** portal manipulation ********************************
212 case T_ClosePortalStmt:
214 ClosePortalStmt *stmt = (ClosePortalStmt *) parsetree;
216 PerformPortalClose(stmt->portalname, dest);
222 FetchStmt *stmt = (FetchStmt *) parsetree;
223 char *portalName = stmt->portalname;
229 forward = (bool) (stmt->direction == FORWARD);
232 * parser ensures that count is >= 0 and 'fetch ALL' -> 0
235 count = stmt->howMany;
236 PerformPortalFetch(portalName, forward, count,
237 (stmt->ismove) ? None : dest,
243 * relation and attribute manipulation
245 case T_CreateSchemaStmt:
247 CreateSchemaStmt *stmt = (CreateSchemaStmt *) parsetree;
249 CreateSchemaCommand(stmt);
254 DefineRelation((CreateStmt *) parsetree, RELKIND_RELATION);
257 * Let AlterTableCreateToastTable decide if this one needs a
258 * secondary relation too.
260 CommandCounterIncrement();
261 AlterTableCreateToastTable(((CreateStmt *) parsetree)->relation->relname,
267 DropStmt *stmt = (DropStmt *) parsetree;
268 List *args = stmt->objects;
273 relname = ((RangeVar *) lfirst(arg))->relname;
275 switch (stmt->removeType)
278 CheckDropPermissions(relname, RELKIND_RELATION);
279 RemoveRelation(relname);
283 CheckDropPermissions(relname, RELKIND_SEQUENCE);
284 RemoveRelation(relname);
288 CheckDropPermissions(relname, RELKIND_VIEW);
293 CheckDropPermissions(relname, RELKIND_INDEX);
294 RemoveIndex(relname);
298 /* RemoveRewriteRule checks permissions */
299 RemoveRewriteRule(relname);
303 /* RemoveType does its own permissions checks */
308 /* RemoveDomain does its own permissions checks */
309 RemoveDomain(relname, stmt->behavior);
314 * Make sure subsequent loop iterations will see
315 * results of this one; needed if removing multiple
316 * rules for same table, for example.
318 CommandCounterIncrement();
325 relname = ((TruncateStmt *) parsetree)->relation->relname;
326 TruncateRelation(relname);
332 CommentStmt *statement;
334 statement = ((CommentStmt *) parsetree);
336 CommentObject(statement->objtype, statement->objname,
337 statement->objproperty, statement->objlist,
344 CopyStmt *stmt = (CopyStmt *) parsetree;
346 if (stmt->direction != FROM)
349 DoCopy(stmt->relation->relname,
352 (bool) (stmt->direction == FROM),
353 (bool) (stmt->filename == NULL),
356 * null filename means copy to/from stdout/stdin, rather
357 * than to/from a file.
370 RenameStmt *stmt = (RenameStmt *) parsetree;
372 relname = stmt->relation->relname;
373 CheckOwnership(relname, true);
376 * XXX using len == 3 to tell the difference
377 * between "rename rel to newrel" and
378 * "rename att in rel to newatt" will not
379 * work soon because "rename type/operator/rule"
380 * stuff is being added. - cim 10/24/90
382 * [another piece of amuzing but useless anecdote -- ay]
384 if (stmt->column == NULL)
389 * Note: we also rename the "type" tuple corresponding to
392 renamerel(relname, /* old name */
393 stmt->newname); /* new name */
400 renameatt(relname, /* relname */
401 stmt->column, /* old att name */
402 stmt->newname, /* new att name */
403 interpretInhOption(stmt->relation->inhOpt)); /* recursive? */
408 /* various Alter Table forms */
410 case T_AlterTableStmt:
412 AlterTableStmt *stmt = (AlterTableStmt *) parsetree;
415 * Some or all of these functions are recursive to cover
416 * inherited things, so permission checks are done there.
418 switch (stmt->subtype)
420 case 'A': /* ADD COLUMN */
421 AlterTableAddColumn(stmt->relation->relname,
422 interpretInhOption((stmt->relation)->inhOpt),
423 (ColumnDef *) stmt->def);
425 case 'T': /* ALTER COLUMN DEFAULT */
426 AlterTableAlterColumnDefault(stmt->relation->relname,
427 interpretInhOption((stmt->relation)->inhOpt),
431 case 'S': /* ALTER COLUMN STATISTICS */
432 case 'M': /* ALTER COLUMN STORAGE */
433 AlterTableAlterColumnFlags(stmt->relation->relname,
434 interpretInhOption(stmt->relation->inhOpt),
439 case 'D': /* DROP COLUMN */
440 AlterTableDropColumn(stmt->relation->relname,
441 interpretInhOption(stmt->relation->inhOpt),
445 case 'C': /* ADD CONSTRAINT */
446 AlterTableAddConstraint(stmt->relation->relname,
447 interpretInhOption(stmt->relation->inhOpt),
450 case 'X': /* DROP CONSTRAINT */
451 AlterTableDropConstraint(stmt->relation->relname,
452 interpretInhOption(stmt->relation->inhOpt),
456 case 'E': /* CREATE TOAST TABLE */
457 AlterTableCreateToastTable(stmt->relation->relname,
460 case 'U': /* ALTER OWNER */
461 AlterTableOwner(stmt->relation->relname,
465 elog(ERROR, "T_AlterTableStmt: unknown subtype");
474 GrantStmt *stmt = (GrantStmt *) parsetree;
476 ExecuteGrantStmt(stmt);
481 * ******************************** object creation /
482 * destruction ********************************
487 DefineStmt *stmt = (DefineStmt *) parsetree;
489 switch (stmt->defType)
492 DefineOperator(stmt->defname, /* operator name */
493 stmt->definition); /* rest */
496 DefineType(stmt->defname, stmt->definition);
499 DefineAggregate(stmt->defname, /* aggregate name */
500 stmt->definition); /* rest */
506 case T_ViewStmt: /* CREATE VIEW */
508 ViewStmt *stmt = (ViewStmt *) parsetree;
510 DefineView(stmt->view->relname, stmt->query); /* retrieve parsetree */
514 case T_ProcedureStmt: /* CREATE FUNCTION */
515 CreateFunction((ProcedureStmt *) parsetree);
518 case T_IndexStmt: /* CREATE INDEX */
520 IndexStmt *stmt = (IndexStmt *) parsetree;
522 relname = stmt->relation->relname;
523 CheckOwnership(relname, true);
525 DefineIndex(stmt->relation->relname, /* relation */
526 stmt->idxname, /* index name */
527 stmt->accessMethod, /* am name */
528 stmt->indexParams, /* parameters */
531 (Expr *) stmt->whereClause,
536 case T_RuleStmt: /* CREATE RULE */
537 DefineQueryRewrite((RuleStmt *) parsetree);
540 case T_CreateSeqStmt:
541 DefineSequence((CreateSeqStmt *) parsetree);
544 case T_RemoveAggrStmt:
546 RemoveAggrStmt *stmt = (RemoveAggrStmt *) parsetree;
547 char *typename = (char *) NULL;
549 if (stmt->aggtype != NULL)
550 typename = TypeNameToInternalName((TypeName *) stmt->aggtype);
552 RemoveAggregate(stmt->aggname, typename);
556 case T_RemoveFuncStmt:
558 RemoveFuncStmt *stmt = (RemoveFuncStmt *) parsetree;
560 RemoveFunction(stmt->funcname, stmt->args);
564 case T_RemoveOperStmt:
566 RemoveOperStmt *stmt = (RemoveOperStmt *) parsetree;
567 TypeName *typenode1 = (TypeName *) lfirst(stmt->args);
568 TypeName *typenode2 = (TypeName *) lsecond(stmt->args);
569 char *typename1 = (char *) NULL;
570 char *typename2 = (char *) NULL;
572 if (typenode1 != NULL)
573 typename1 = TypeNameToInternalName(typenode1);
574 if (typenode2 != NULL)
575 typename2 = TypeNameToInternalName(typenode2);
577 RemoveOperator(stmt->opname, typename1, typename2);
582 elog(ERROR, "CREATE VERSION is not currently implemented");
587 CreatedbStmt *stmt = (CreatedbStmt *) parsetree;
589 createdb(stmt->dbname, stmt->dbowner,
590 stmt->dbpath, stmt->dbtemplate,
595 case T_AlterDatabaseSetStmt:
596 AlterDatabaseSet((AlterDatabaseSetStmt *)parsetree);
601 DropdbStmt *stmt = (DropdbStmt *) parsetree;
603 dropdb(stmt->dbname);
607 /* Query-level asynchronous notification */
610 NotifyStmt *stmt = (NotifyStmt *) parsetree;
612 Async_Notify(stmt->relation->relname);
618 ListenStmt *stmt = (ListenStmt *) parsetree;
620 Async_Listen(stmt->relation->relname, MyProcPid);
626 UnlistenStmt *stmt = (UnlistenStmt *) parsetree;
628 Async_Unlisten(stmt->relation->relname, MyProcPid);
634 LoadStmt *stmt = (LoadStmt *) parsetree;
636 closeAllVfds(); /* probably not necessary... */
637 load_file(stmt->filename);
643 ClusterStmt *stmt = (ClusterStmt *) parsetree;
645 relname = stmt->relation->relname;
646 CheckOwnership(relname, true);
648 cluster(relname, stmt->indexname);
653 vacuum((VacuumStmt *) parsetree);
658 ExplainStmt *stmt = (ExplainStmt *) parsetree;
660 ExplainQuery(stmt->query, stmt->verbose, stmt->analyze, dest);
668 RecipeStmt *stmt = (RecipeStmt *) parsetree;
675 case T_VariableSetStmt:
677 VariableSetStmt *n = (VariableSetStmt *) parsetree;
679 SetPGVariable(n->name, n->args);
683 case T_VariableShowStmt:
685 VariableShowStmt *n = (VariableShowStmt *) parsetree;
687 GetPGVariable(n->name);
691 case T_VariableResetStmt:
693 VariableResetStmt *n = (VariableResetStmt *) parsetree;
695 ResetPGVariable(n->name);
699 case T_CreateTrigStmt:
700 CreateTrigger((CreateTrigStmt *) parsetree);
704 DropTrigger((DropTrigStmt *) parsetree);
707 case T_CreatePLangStmt:
708 CreateProceduralLanguage((CreatePLangStmt *) parsetree);
711 case T_DropPLangStmt:
712 DropProceduralLanguage((DropPLangStmt *) parsetree);
716 * ******************************** DOMAIN statements ****
718 case T_CreateDomainStmt:
719 DefineDomain((CreateDomainStmt *) parsetree);
723 * ******************************** USER statements ****
725 case T_CreateUserStmt:
726 CreateUser((CreateUserStmt *) parsetree);
729 case T_AlterUserStmt:
730 AlterUser((AlterUserStmt *) parsetree);
733 case T_AlterUserSetStmt:
734 AlterUserSet((AlterUserSetStmt *) parsetree);
738 DropUser((DropUserStmt *) parsetree);
742 LockTableCommand((LockStmt *) parsetree);
745 case T_ConstraintsSetStmt:
746 DeferredTriggerSetState((ConstraintsSetStmt *) parsetree);
749 case T_CreateGroupStmt:
750 CreateGroup((CreateGroupStmt *) parsetree);
753 case T_AlterGroupStmt:
754 AlterGroup((AlterGroupStmt *) parsetree, "ALTER GROUP");
757 case T_DropGroupStmt:
758 DropGroup((DropGroupStmt *) parsetree);
761 case T_CheckPointStmt:
764 elog(ERROR, "permission denied");
765 CreateCheckPoint(false);
771 ReindexStmt *stmt = (ReindexStmt *) parsetree;
773 switch (stmt->reindexType)
776 relname = (char *) stmt->relation->relname;
777 if (IsSystemRelationName(relname))
779 if (!allowSystemTableMods)
780 elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -O -P options",
782 if (!IsIgnoringSystemIndexes())
783 elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -P -O options",
786 CheckOwnership(relname, false);
787 ReindexIndex(relname, stmt->force);
790 relname = (char *) stmt->relation->relname;
791 CheckOwnership(relname, false);
792 ReindexTable(relname, stmt->force);
795 relname = (char *) stmt->name;
796 if (!allowSystemTableMods)
797 elog(ERROR, "must be called under standalone postgres with -O -P options");
798 if (!IsIgnoringSystemIndexes())
799 elog(ERROR, "must be called under standalone postgres with -P -O options");
800 ReindexDatabase(relname, stmt->force, false);
808 elog(ERROR, "ProcessUtility: command #%d unsupported",