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.120 2001/10/12 00:07:14 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/ps_status.h"
48 #include "utils/syscache.h"
49 #include "utils/temprel.h"
50 #include "access/xlog.h"
53 * Error-checking support for DROP commands
64 static struct kindstrings kindstringarray[] = {
65 {RELKIND_RELATION, "a", "table", "TABLE"},
66 {RELKIND_SEQUENCE, "a", "sequence", "SEQUENCE"},
67 {RELKIND_VIEW, "a", "view", "VIEW"},
68 {RELKIND_INDEX, "an", "index", "INDEX"},
69 {'\0', "a", "???", "???"}
74 DropErrorMsg(char *relname, char wrongkind, char rightkind)
76 struct kindstrings *rentry;
77 struct kindstrings *wentry;
79 for (rentry = kindstringarray; rentry->kind != '\0'; rentry++)
80 if (rentry->kind == rightkind)
82 Assert(rentry->kind != '\0');
84 for (wentry = kindstringarray; wentry->kind != '\0'; wentry++)
85 if (wentry->kind == wrongkind)
87 /* wrongkind could be something we don't have in our table... */
88 if (wentry->kind != '\0')
89 elog(ERROR, "\"%s\" is not %s %s. Use DROP %s to remove %s %s",
90 relname, rentry->indef_article, rentry->name,
91 wentry->command, wentry->indef_article, wentry->name);
93 elog(ERROR, "\"%s\" is not %s %s",
94 relname, rentry->indef_article, rentry->name);
98 CheckDropPermissions(char *name, char rightkind)
100 struct kindstrings *rentry;
102 Form_pg_class classform;
104 for (rentry = kindstringarray; rentry->kind != '\0'; rentry++)
105 if (rentry->kind == rightkind)
107 Assert(rentry->kind != '\0');
109 tuple = SearchSysCache(RELNAME,
110 PointerGetDatum(name),
112 if (!HeapTupleIsValid(tuple))
113 elog(ERROR, "%s \"%s\" does not exist", rentry->name, name);
115 classform = (Form_pg_class) GETSTRUCT(tuple);
117 if (classform->relkind != rightkind)
118 DropErrorMsg(name, classform->relkind, rightkind);
120 if (!pg_ownercheck(GetUserId(), name, RELNAME))
121 elog(ERROR, "you do not own %s \"%s\"",
124 if (!allowSystemTableMods && IsSystemRelationName(name) &&
125 !is_temp_relname(name))
126 elog(ERROR, "%s \"%s\" is a system %s",
127 rentry->name, name, rentry->name);
129 ReleaseSysCache(tuple);
134 * general utility function invoker
138 ProcessUtility(Node *parsetree,
141 char *commandTag = NULL;
145 switch (nodeTag(parsetree))
149 * ******************************** transactions ********************************
152 case T_TransactionStmt:
154 TransactionStmt *stmt = (TransactionStmt *) parsetree;
156 switch (stmt->command)
159 set_ps_display(commandTag = "BEGIN");
160 BeginTransactionBlock();
164 set_ps_display(commandTag = "COMMIT");
165 EndTransactionBlock();
169 set_ps_display(commandTag = "ROLLBACK");
170 UserAbortTransactionBlock();
177 * ******************************** portal manipulation ********************************
180 case T_ClosePortalStmt:
182 ClosePortalStmt *stmt = (ClosePortalStmt *) parsetree;
184 set_ps_display(commandTag = "CLOSE");
186 PerformPortalClose(stmt->portalname, dest);
192 FetchStmt *stmt = (FetchStmt *) parsetree;
193 char *portalName = stmt->portalname;
197 set_ps_display(commandTag = (stmt->ismove) ? "MOVE" : "FETCH");
201 forward = (bool) (stmt->direction == FORWARD);
204 * parser ensures that count is >= 0 and 'fetch ALL' -> 0
207 count = stmt->howMany;
208 PerformPortalFetch(portalName, forward, count, commandTag,
209 (stmt->ismove) ? None : dest); /* /dev/null for MOVE */
214 * ******************************** relation and attribute
215 * manipulation ********************************
219 set_ps_display(commandTag = "CREATE");
221 DefineRelation((CreateStmt *) parsetree, RELKIND_RELATION);
224 * Let AlterTableCreateToastTable decide if this one needs a
225 * secondary relation too.
227 CommandCounterIncrement();
228 AlterTableCreateToastTable(((CreateStmt *) parsetree)->relname,
234 DropStmt *stmt = (DropStmt *) parsetree;
235 List *args = stmt->names;
238 set_ps_display(commandTag = "DROP");
242 relname = strVal(lfirst(arg));
244 switch (stmt->removeType)
247 CheckDropPermissions(relname, RELKIND_RELATION);
248 RemoveRelation(relname);
252 CheckDropPermissions(relname, RELKIND_SEQUENCE);
253 RemoveRelation(relname);
257 CheckDropPermissions(relname, RELKIND_VIEW);
262 CheckDropPermissions(relname, RELKIND_INDEX);
263 RemoveIndex(relname);
268 char *rulename = relname;
271 relationName = RewriteGetRuleEventRel(rulename);
272 aclcheck_result = pg_aclcheck(relationName, GetUserId(), ACL_RULE);
273 if (aclcheck_result != ACLCHECK_OK)
274 elog(ERROR, "%s: %s", relationName,
275 aclcheck_error_strings[aclcheck_result]);
276 RemoveRewriteRule(rulename);
281 /* RemoveType does its own permissions checks */
287 * Make sure subsequent loop iterations will see
288 * results of this one; needed if removing multiple
289 * rules for same table, for example.
291 CommandCounterIncrement();
300 set_ps_display(commandTag = "TRUNCATE");
302 relname = ((TruncateStmt *) parsetree)->relName;
303 if (!allowSystemTableMods && IsSystemRelationName(relname))
304 elog(ERROR, "TRUNCATE cannot be used on system tables. '%s' is a system table",
307 /* Grab exclusive lock in preparation for truncate... */
308 rel = heap_openr(relname, AccessExclusiveLock);
309 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
310 elog(ERROR, "TRUNCATE cannot be used on sequences. '%s' is a sequence",
312 if (rel->rd_rel->relkind == RELKIND_VIEW)
313 elog(ERROR, "TRUNCATE cannot be used on views. '%s' is a view",
315 heap_close(rel, NoLock);
317 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
318 elog(ERROR, "you do not own class \"%s\"", relname);
319 TruncateRelation(relname);
325 CommentStmt *statement;
327 statement = ((CommentStmt *) parsetree);
329 set_ps_display(commandTag = "COMMENT");
331 CommentObject(statement->objtype, statement->objname,
332 statement->objproperty, statement->objlist,
339 CopyStmt *stmt = (CopyStmt *) parsetree;
341 set_ps_display(commandTag = "COPY");
343 if (stmt->direction != FROM)
346 DoCopy(stmt->relname,
349 (bool) (stmt->direction == FROM),
350 (bool) (stmt->filename == NULL),
353 * null filename means copy to/from stdout/stdin, rather
354 * than to/from a file.
367 RenameStmt *stmt = (RenameStmt *) parsetree;
369 set_ps_display(commandTag = "ALTER");
371 relname = stmt->relname;
372 if (!allowSystemTableMods && IsSystemRelationName(relname))
373 elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
375 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
376 elog(ERROR, "permission denied");
379 * XXX using len == 3 to tell the difference
380 * between "rename rel to newrel" and
381 * "rename att in rel to newatt" will not
382 * work soon because "rename type/operator/rule"
383 * stuff is being added. - cim 10/24/90
385 * [another piece of amuzing but useless anecdote -- ay]
387 if (stmt->column == NULL)
393 * Note: we also rename the "type" tuple corresponding to
396 renamerel(relname, /* old name */
397 stmt->newname); /* new name */
405 renameatt(relname, /* relname */
406 stmt->column, /* old att name */
407 stmt->newname, /* new att name */
408 interpretInhOption(stmt->inhOpt)); /* recursive? */
413 /* various Alter Table forms */
415 case T_AlterTableStmt:
417 AlterTableStmt *stmt = (AlterTableStmt *) parsetree;
419 set_ps_display(commandTag = "ALTER");
422 * Some or all of these functions are recursive to cover
423 * inherited things, so permission checks are done there.
425 switch (stmt->subtype)
427 case 'A': /* ADD COLUMN */
428 AlterTableAddColumn(stmt->relname,
429 interpretInhOption(stmt->inhOpt),
430 (ColumnDef *) stmt->def);
432 case 'T': /* ALTER COLUMN DEFAULT */
433 AlterTableAlterColumnDefault(stmt->relname,
434 interpretInhOption(stmt->inhOpt),
438 case 'S': /* ALTER COLUMN STATISTICS */
439 AlterTableAlterColumnStatistics(stmt->relname,
440 interpretInhOption(stmt->inhOpt),
444 case 'D': /* DROP COLUMN */
445 AlterTableDropColumn(stmt->relname,
446 interpretInhOption(stmt->inhOpt),
450 case 'C': /* ADD CONSTRAINT */
451 AlterTableAddConstraint(stmt->relname,
452 interpretInhOption(stmt->inhOpt),
455 case 'X': /* DROP CONSTRAINT */
456 AlterTableDropConstraint(stmt->relname,
457 interpretInhOption(stmt->inhOpt),
461 case 'E': /* CREATE TOAST TABLE */
462 AlterTableCreateToastTable(stmt->relname,
465 case 'U': /* ALTER OWNER */
466 AlterTableOwner(stmt->relname,
470 elog(ERROR, "T_AlterTableStmt: unknown subtype");
479 GrantStmt *stmt = (GrantStmt *) parsetree;
480 commandTag = stmt->is_grant ? "GRANT" : "REVOKE";
481 set_ps_display(commandTag);
483 ExecuteGrantStmt(stmt);
488 * ******************************** object creation /
489 * destruction ********************************
494 DefineStmt *stmt = (DefineStmt *) parsetree;
496 set_ps_display(commandTag = "CREATE");
498 switch (stmt->defType)
501 DefineOperator(stmt->defname, /* operator name */
502 stmt->definition); /* rest */
505 DefineType(stmt->defname, stmt->definition);
508 DefineAggregate(stmt->defname, /* aggregate name */
509 stmt->definition); /* rest */
515 case T_ViewStmt: /* CREATE VIEW */
517 ViewStmt *stmt = (ViewStmt *) parsetree;
519 set_ps_display(commandTag = "CREATE");
521 DefineView(stmt->viewname, stmt->query); /* retrieve parsetree */
525 case T_ProcedureStmt: /* CREATE FUNCTION */
526 set_ps_display(commandTag = "CREATE");
528 CreateFunction((ProcedureStmt *) parsetree);
531 case T_IndexStmt: /* CREATE INDEX */
533 IndexStmt *stmt = (IndexStmt *) parsetree;
535 set_ps_display(commandTag = "CREATE");
537 DefineIndex(stmt->relname, /* relation name */
538 stmt->idxname, /* index name */
539 stmt->accessMethod, /* am name */
540 stmt->indexParams, /* parameters */
543 (Expr *) stmt->whereClause,
548 case T_RuleStmt: /* CREATE RULE */
550 RuleStmt *stmt = (RuleStmt *) parsetree;
553 relname = stmt->object->relname;
554 aclcheck_result = pg_aclcheck(relname, GetUserId(), ACL_RULE);
555 if (aclcheck_result != ACLCHECK_OK)
556 elog(ERROR, "%s: %s", relname, aclcheck_error_strings[aclcheck_result]);
557 set_ps_display(commandTag = "CREATE");
559 DefineQueryRewrite(stmt);
563 case T_CreateSeqStmt:
564 set_ps_display(commandTag = "CREATE");
566 DefineSequence((CreateSeqStmt *) parsetree);
569 case T_RemoveAggrStmt:
571 RemoveAggrStmt *stmt = (RemoveAggrStmt *) parsetree;
572 char *typename = (char *) NULL;
574 set_ps_display(commandTag = "DROP");
576 if (stmt->aggtype != NULL)
577 typename = TypeNameToInternalName((TypeName *) stmt->aggtype);
579 RemoveAggregate(stmt->aggname, typename);
583 case T_RemoveFuncStmt:
585 RemoveFuncStmt *stmt = (RemoveFuncStmt *) parsetree;
587 set_ps_display(commandTag = "DROP");
589 RemoveFunction(stmt->funcname, stmt->args);
593 case T_RemoveOperStmt:
595 RemoveOperStmt *stmt = (RemoveOperStmt *) parsetree;
596 TypeName *typenode1 = (TypeName *) lfirst(stmt->args);
597 TypeName *typenode2 = (TypeName *) lsecond(stmt->args);
598 char *typename1 = (char *) NULL;
599 char *typename2 = (char *) NULL;
601 set_ps_display(commandTag = "DROP");
603 if (typenode1 != NULL)
604 typename1 = TypeNameToInternalName(typenode1);
605 if (typenode2 != NULL)
606 typename2 = TypeNameToInternalName(typenode2);
608 RemoveOperator(stmt->opname, typename1, typename2);
613 elog(ERROR, "CREATE VERSION is not currently implemented");
618 CreatedbStmt *stmt = (CreatedbStmt *) parsetree;
620 set_ps_display(commandTag = "CREATE DATABASE");
622 createdb(stmt->dbname, stmt->dbpath,
623 stmt->dbtemplate, stmt->encoding);
629 DropdbStmt *stmt = (DropdbStmt *) parsetree;
631 set_ps_display(commandTag = "DROP DATABASE");
633 dropdb(stmt->dbname);
637 /* Query-level asynchronous notification */
640 NotifyStmt *stmt = (NotifyStmt *) parsetree;
642 set_ps_display(commandTag = "NOTIFY");
644 Async_Notify(stmt->relname);
650 ListenStmt *stmt = (ListenStmt *) parsetree;
652 set_ps_display(commandTag = "LISTEN");
654 Async_Listen(stmt->relname, MyProcPid);
660 UnlistenStmt *stmt = (UnlistenStmt *) parsetree;
662 set_ps_display(commandTag = "UNLISTEN");
664 Async_Unlisten(stmt->relname, MyProcPid);
669 * ******************************** dynamic loader ********************************
674 LoadStmt *stmt = (LoadStmt *) parsetree;
676 set_ps_display(commandTag = "LOAD");
678 closeAllVfds(); /* probably not necessary... */
679 load_file(stmt->filename);
685 ClusterStmt *stmt = (ClusterStmt *) parsetree;
687 set_ps_display(commandTag = "CLUSTER");
689 relname = stmt->relname;
690 if (IsSystemRelationName(relname))
691 elog(ERROR, "CLUSTER: relation \"%s\" is a system catalog",
693 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
694 elog(ERROR, "permission denied");
696 cluster(relname, stmt->indexname);
701 if (((VacuumStmt *) parsetree)->vacuum)
702 commandTag = "VACUUM";
704 commandTag = "ANALYZE";
705 set_ps_display(commandTag);
707 vacuum((VacuumStmt *) parsetree);
712 ExplainStmt *stmt = (ExplainStmt *) parsetree;
714 set_ps_display(commandTag = "EXPLAIN");
716 ExplainQuery(stmt->query, stmt->verbose, stmt->analyze, dest);
723 * ******************************** Tioga-related statements *******************************
727 RecipeStmt *stmt = (RecipeStmt *) parsetree;
729 set_ps_display(commandTag = "EXECUTE RECIPE");
737 * ******************************** set variable statements *******************************
739 case T_VariableSetStmt:
741 VariableSetStmt *n = (VariableSetStmt *) parsetree;
743 SetPGVariable(n->name, n->value);
744 set_ps_display(commandTag = "SET VARIABLE");
748 case T_VariableShowStmt:
750 VariableShowStmt *n = (VariableShowStmt *) parsetree;
752 GetPGVariable(n->name);
753 set_ps_display(commandTag = "SHOW VARIABLE");
757 case T_VariableResetStmt:
759 VariableResetStmt *n = (VariableResetStmt *) parsetree;
761 ResetPGVariable(n->name);
762 set_ps_display(commandTag = "RESET VARIABLE");
767 * ******************************** TRIGGER statements *******************************
769 case T_CreateTrigStmt:
770 set_ps_display(commandTag = "CREATE");
772 CreateTrigger((CreateTrigStmt *) parsetree);
776 set_ps_display(commandTag = "DROP");
778 DropTrigger((DropTrigStmt *) parsetree);
782 * ************* PROCEDURAL LANGUAGE statements *****************
784 case T_CreatePLangStmt:
785 set_ps_display(commandTag = "CREATE");
787 CreateProceduralLanguage((CreatePLangStmt *) parsetree);
790 case T_DropPLangStmt:
791 set_ps_display(commandTag = "DROP");
793 DropProceduralLanguage((DropPLangStmt *) parsetree);
797 * ******************************** USER statements ****
800 case T_CreateUserStmt:
801 set_ps_display(commandTag = "CREATE USER");
803 CreateUser((CreateUserStmt *) parsetree);
806 case T_AlterUserStmt:
807 set_ps_display(commandTag = "ALTER USER");
809 AlterUser((AlterUserStmt *) parsetree);
813 set_ps_display(commandTag = "DROP USER");
815 DropUser((DropUserStmt *) parsetree);
819 set_ps_display(commandTag = "LOCK TABLE");
821 LockTableCommand((LockStmt *) parsetree);
824 case T_ConstraintsSetStmt:
825 set_ps_display(commandTag = "SET CONSTRAINTS");
827 DeferredTriggerSetState((ConstraintsSetStmt *) parsetree);
830 case T_CreateGroupStmt:
831 set_ps_display(commandTag = "CREATE GROUP");
833 CreateGroup((CreateGroupStmt *) parsetree);
836 case T_AlterGroupStmt:
837 set_ps_display(commandTag = "ALTER GROUP");
839 AlterGroup((AlterGroupStmt *) parsetree, "ALTER GROUP");
842 case T_DropGroupStmt:
843 set_ps_display(commandTag = "DROP GROUP");
845 DropGroup((DropGroupStmt *) parsetree);
848 case T_CheckPointStmt:
850 set_ps_display(commandTag = "CHECKPOINT");
853 elog(ERROR, "permission denied");
854 CreateCheckPoint(false);
860 ReindexStmt *stmt = (ReindexStmt *) parsetree;
862 set_ps_display(commandTag = "REINDEX");
864 switch (stmt->reindexType)
867 relname = (char *) stmt->name;
868 if (IsSystemRelationName(relname))
870 if (!allowSystemTableMods && IsSystemRelationName(relname))
871 elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -O -P options",
873 if (!IsIgnoringSystemIndexes())
874 elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -P -O options",
877 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
878 elog(ERROR, "%s: %s", relname, aclcheck_error_strings[ACLCHECK_NOT_OWNER]);
879 ReindexIndex(relname, stmt->force);
882 relname = (char *) stmt->name;
883 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
884 elog(ERROR, "%s: %s", relname, aclcheck_error_strings[ACLCHECK_NOT_OWNER]);
885 ReindexTable(relname, stmt->force);
888 relname = (char *) stmt->name;
889 if (!allowSystemTableMods)
890 elog(ERROR, "must be called under standalone postgres with -O -P options");
891 if (!IsIgnoringSystemIndexes())
892 elog(ERROR, "must be called under standalone postgres with -P -O options");
893 ReindexDatabase(relname, stmt->force, false);
901 * ******************************** default ********************************
905 elog(ERROR, "ProcessUtility: command #%d unsupported",
911 * tell fe/be or whatever that we're done.
913 EndCommand(commandTag, dest);