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-2000, PostgreSQL, Inc
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $Header: /cvsroot/pgsql/src/backend/tcop/utility.c,v 1.101 2000/11/08 16:31:06 tgl Exp $
15 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "catalog/catalog.h"
21 #include "commands/async.h"
22 #include "commands/cluster.h"
23 #include "commands/command.h"
24 #include "commands/comment.h"
25 #include "commands/copy.h"
26 #include "commands/creatinh.h"
27 #include "commands/dbcommands.h"
28 #include "commands/defrem.h"
29 #include "commands/explain.h"
30 #include "commands/proclang.h"
31 #include "commands/rename.h"
32 #include "commands/sequence.h"
33 #include "commands/trigger.h"
34 #include "commands/user.h"
35 #include "commands/vacuum.h"
36 #include "commands/variable.h"
37 #include "commands/view.h"
38 #include "miscadmin.h"
39 #include "parser/parse.h"
40 #include "parser/parse_expr.h"
41 #include "rewrite/rewriteDefine.h"
42 #include "rewrite/rewriteRemove.h"
43 #include "tcop/utility.h"
44 #include "utils/acl.h"
45 #include "utils/ps_status.h"
46 #include "utils/syscache.h"
47 #include "access/xlog.h"
50 * Error-checking support for DROP commands
60 static struct kindstrings kindstringarray[] = {
61 { RELKIND_RELATION, "a", "table", "TABLE" },
62 { RELKIND_SEQUENCE, "a", "sequence", "SEQUENCE" },
63 { RELKIND_VIEW, "a", "view", "VIEW" },
64 { RELKIND_INDEX, "an", "index", "INDEX" },
65 { '\0', "a", "???", "???" }
70 DropErrorMsg(char* relname, char wrongkind, char rightkind)
72 struct kindstrings *rentry;
73 struct kindstrings *wentry;
75 for (rentry = kindstringarray; rentry->kind != '\0'; rentry++)
76 if (rentry->kind == rightkind)
78 Assert(rentry->kind != '\0');
80 for (wentry = kindstringarray; wentry->kind != '\0'; wentry++)
81 if (wentry->kind == wrongkind)
83 /* wrongkind could be something we don't have in our table... */
84 if (wentry->kind != '\0')
85 elog(ERROR, "\"%s\" is not %s %s. Use DROP %s to remove %s %s",
86 relname, rentry->indef_article, rentry->name,
87 wentry->command, wentry->indef_article, wentry->name);
89 elog(ERROR, "\"%s\" is not %s %s",
90 relname, rentry->indef_article, rentry->name);
94 CheckDropPermissions(char *name, char rightkind)
96 struct kindstrings *rentry;
98 Form_pg_class classform;
100 for (rentry = kindstringarray; rentry->kind != '\0'; rentry++)
101 if (rentry->kind == rightkind)
103 Assert(rentry->kind != '\0');
105 tuple = SearchSysCacheTuple(RELNAME,
106 PointerGetDatum(name),
108 if (!HeapTupleIsValid(tuple))
109 elog(ERROR, "%s \"%s\" does not exist", rentry->name, name);
111 classform = (Form_pg_class) GETSTRUCT(tuple);
113 if (classform->relkind != rightkind)
114 DropErrorMsg(name, classform->relkind, rightkind);
116 if (!pg_ownercheck(GetUserId(), name, RELNAME))
117 elog(ERROR, "you do not own %s \"%s\"",
120 if (!allowSystemTableMods && IsSystemRelationName(name))
121 elog(ERROR, "%s \"%s\" is a system %s",
122 rentry->name, name, rentry->name);
127 * general utility function invoker
131 ProcessUtility(Node *parsetree,
134 char *commandTag = NULL;
138 switch (nodeTag(parsetree))
142 * ******************************** transactions ********************************
145 case T_TransactionStmt:
147 TransactionStmt *stmt = (TransactionStmt *) parsetree;
149 switch (stmt->command)
152 set_ps_display(commandTag = "BEGIN");
153 BeginTransactionBlock();
157 set_ps_display(commandTag = "COMMIT");
158 EndTransactionBlock();
162 set_ps_display(commandTag = "ROLLBACK");
163 UserAbortTransactionBlock();
170 * ******************************** portal manipulation ********************************
173 case T_ClosePortalStmt:
175 ClosePortalStmt *stmt = (ClosePortalStmt *) parsetree;
177 set_ps_display(commandTag = "CLOSE");
179 PerformPortalClose(stmt->portalname, dest);
185 FetchStmt *stmt = (FetchStmt *) parsetree;
186 char *portalName = stmt->portalname;
190 set_ps_display(commandTag = (stmt->ismove) ? "MOVE" : "FETCH");
194 forward = (bool) (stmt->direction == FORWARD);
197 * parser ensures that count is >= 0 and 'fetch ALL' -> 0
200 count = stmt->howMany;
201 PerformPortalFetch(portalName, forward, count, commandTag,
202 (stmt->ismove) ? None : dest); /* /dev/null for MOVE */
207 * ******************************** relation and attribute
208 * manipulation ********************************
212 set_ps_display(commandTag = "CREATE");
214 DefineRelation((CreateStmt *) parsetree, RELKIND_RELATION);
217 * Let AlterTableCreateToastTable decide if this
218 * one needs a secondary relation too.
220 CommandCounterIncrement();
221 AlterTableCreateToastTable(((CreateStmt *)parsetree)->relname,
227 DropStmt *stmt = (DropStmt *) parsetree;
228 List *args = stmt->names;
231 set_ps_display(commandTag = "DROP");
235 relname = strVal(lfirst(arg));
237 switch(stmt->removeType)
240 CheckDropPermissions(relname, RELKIND_RELATION);
241 RemoveRelation(relname);
245 CheckDropPermissions(relname, RELKIND_SEQUENCE);
246 RemoveRelation(relname);
250 CheckDropPermissions(relname, RELKIND_VIEW);
255 CheckDropPermissions(relname, RELKIND_INDEX);
256 RemoveIndex(relname);
261 char *rulename = relname;
264 relationName = RewriteGetRuleEventRel(rulename);
265 aclcheck_result = pg_aclcheck(relationName, GetUserId(), ACL_RU);
266 if (aclcheck_result != ACLCHECK_OK)
267 elog(ERROR, "%s: %s", relationName,
268 aclcheck_error_strings[aclcheck_result]);
269 RemoveRewriteRule(rulename);
274 /* RemoveType does its own permissions checks */
280 * Make sure subsequent loop iterations will see results
281 * of this one; needed if removing multiple rules for
282 * same table, for example.
284 CommandCounterIncrement();
293 set_ps_display(commandTag = "TRUNCATE");
295 relname = ((TruncateStmt *) parsetree)->relName;
296 if (!allowSystemTableMods && IsSystemRelationName(relname))
297 elog(ERROR, "TRUNCATE cannot be used on system tables. '%s' is a system table",
300 /* Grab exclusive lock in preparation for truncate... */
301 rel = heap_openr(relname, AccessExclusiveLock);
302 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
303 elog(ERROR, "TRUNCATE cannot be used on sequences. '%s' is a sequence",
305 if (rel->rd_rel->relkind == RELKIND_VIEW)
306 elog(ERROR, "TRUNCATE cannot be used on views. '%s' is a sequence",
308 heap_close(rel, NoLock);
310 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
311 elog(ERROR, "you do not own class \"%s\"", relname);
312 TruncateRelation(relname);
318 CommentStmt *statement;
320 statement = ((CommentStmt *) parsetree);
322 set_ps_display(commandTag = "COMMENT");
324 CommentObject(statement->objtype, statement->objname,
325 statement->objproperty, statement->objlist,
332 CopyStmt *stmt = (CopyStmt *) parsetree;
334 set_ps_display(commandTag = "COPY");
336 if (stmt->direction != FROM)
339 DoCopy(stmt->relname,
342 (bool) (stmt->direction == FROM),
343 (bool) (stmt->filename == NULL),
346 * null filename means copy to/from stdout/stdin, rather
347 * than to/from a file.
360 RenameStmt *stmt = (RenameStmt *) parsetree;
362 set_ps_display(commandTag = "ALTER");
364 relname = stmt->relname;
365 if (!allowSystemTableMods && IsSystemRelationName(relname))
366 elog(ERROR, "ALTER TABLE: relation \"%s\" is a system catalog",
368 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
369 elog(ERROR, "permission denied");
372 * XXX using len == 3 to tell the difference
373 * between "rename rel to newrel" and
374 * "rename att in rel to newatt" will not
375 * work soon because "rename type/operator/rule"
376 * stuff is being added. - cim 10/24/90
378 * [another piece of amuzing but useless anecdote -- ay]
380 if (stmt->column == NULL)
385 * Note: we also rename the "type" tuple
386 * corresponding to the relation.
389 renamerel(relname, /* old name */
390 stmt->newname); /* new name */
398 renameatt(relname, /* relname */
399 stmt->column, /* old att name */
400 stmt->newname, /* new att name */
401 stmt->inh); /* recursive? */
406 /* various Alter Table forms */
408 case T_AlterTableStmt:
410 AlterTableStmt *stmt = (AlterTableStmt *) parsetree;
412 set_ps_display(commandTag = "ALTER");
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->relname, stmt->inh, (ColumnDef *) stmt->def);
423 case 'T': /* ALTER COLUMN */
424 AlterTableAlterColumn(stmt->relname, stmt->inh, stmt->name, stmt->def);
426 case 'D': /* ALTER DROP */
427 AlterTableDropColumn(stmt->relname, stmt->inh, stmt->name, stmt->behavior);
429 case 'C': /* ADD CONSTRAINT */
430 AlterTableAddConstraint(stmt->relname, stmt->inh, stmt->def);
432 case 'X': /* DROP CONSTRAINT */
433 AlterTableDropConstraint(stmt->relname, stmt->inh, stmt->name, stmt->behavior);
435 case 'E': /* CREATE TOAST TABLE */
436 AlterTableCreateToastTable(stmt->relname, false);
438 case 'U': /* ALTER OWNER */
439 AlterTableOwner(stmt->relname, stmt->name);
442 elog(ERROR, "T_AlterTableStmt: unknown subtype");
449 case T_ChangeACLStmt:
451 ChangeACLStmt *stmt = (ChangeACLStmt *) parsetree;
453 set_ps_display(commandTag = "CHANGE");
455 ExecuteChangeACLStmt(stmt);
460 * ******************************** object creation /
461 * destruction ********************************
466 DefineStmt *stmt = (DefineStmt *) parsetree;
468 set_ps_display(commandTag = "CREATE");
470 switch (stmt->defType)
473 DefineOperator(stmt->defname, /* operator name */
474 stmt->definition); /* rest */
477 DefineType(stmt->defname, stmt->definition);
480 DefineAggregate(stmt->defname, /* aggregate name */
481 stmt->definition); /* rest */
487 case T_ViewStmt: /* CREATE VIEW */
489 ViewStmt *stmt = (ViewStmt *) parsetree;
491 set_ps_display(commandTag = "CREATE");
493 DefineView(stmt->viewname, stmt->query); /* retrieve parsetree */
497 case T_ProcedureStmt: /* CREATE FUNCTION */
498 set_ps_display(commandTag = "CREATE");
500 CreateFunction((ProcedureStmt *) parsetree, dest); /* everything */
503 case T_IndexStmt: /* CREATE INDEX */
505 IndexStmt *stmt = (IndexStmt *) parsetree;
507 set_ps_display(commandTag = "CREATE");
509 DefineIndex(stmt->relname, /* relation name */
510 stmt->idxname, /* index name */
511 stmt->accessMethod, /* am name */
512 stmt->indexParams, /* parameters */
516 (Expr *) stmt->whereClause,
521 case T_RuleStmt: /* CREATE RULE */
523 RuleStmt *stmt = (RuleStmt *) parsetree;
526 relname = stmt->object->relname;
527 aclcheck_result = pg_aclcheck(relname, GetUserId(), ACL_RU);
528 if (aclcheck_result != ACLCHECK_OK)
529 elog(ERROR, "%s: %s", relname, aclcheck_error_strings[aclcheck_result]);
530 set_ps_display(commandTag = "CREATE");
532 DefineQueryRewrite(stmt);
536 case T_CreateSeqStmt:
537 set_ps_display(commandTag = "CREATE");
539 DefineSequence((CreateSeqStmt *) parsetree);
544 ExtendStmt *stmt = (ExtendStmt *) parsetree;
546 set_ps_display(commandTag = "EXTEND");
548 ExtendIndex(stmt->idxname, /* index name */
549 (Expr *) stmt->whereClause, /* where */
554 case T_RemoveAggrStmt:
556 RemoveAggrStmt *stmt = (RemoveAggrStmt *) parsetree;
557 char *typename = (char *) NULL;
559 set_ps_display(commandTag = "DROP");
561 if (stmt->aggtype != NULL)
562 typename = TypeNameToInternalName((TypeName *) stmt->aggtype);
564 RemoveAggregate(stmt->aggname, typename);
568 case T_RemoveFuncStmt:
570 RemoveFuncStmt *stmt = (RemoveFuncStmt *) parsetree;
572 set_ps_display(commandTag = "DROP");
574 RemoveFunction(stmt->funcname, stmt->args);
578 case T_RemoveOperStmt:
580 RemoveOperStmt *stmt = (RemoveOperStmt *) parsetree;
581 TypeName *typenode1 = (TypeName *) lfirst(stmt->args);
582 TypeName *typenode2 = (TypeName *) lsecond(stmt->args);
583 char *typename1 = (char *) NULL;
584 char *typename2 = (char *) NULL;
586 set_ps_display(commandTag = "DROP");
588 if (typenode1 != NULL)
589 typename1 = TypeNameToInternalName(typenode1);
590 if (typenode2 != NULL)
591 typename2 = TypeNameToInternalName(typenode2);
593 RemoveOperator(stmt->opname, typename1, typename2);
598 elog(ERROR, "CREATE VERSION is not currently implemented");
603 CreatedbStmt *stmt = (CreatedbStmt *) parsetree;
605 set_ps_display(commandTag = "CREATE DATABASE");
607 createdb(stmt->dbname, stmt->dbpath, stmt->encoding);
613 DropdbStmt *stmt = (DropdbStmt *) parsetree;
615 set_ps_display(commandTag = "DROP DATABASE");
617 dropdb(stmt->dbname);
621 /* Query-level asynchronous notification */
624 NotifyStmt *stmt = (NotifyStmt *) parsetree;
626 set_ps_display(commandTag = "NOTIFY");
628 Async_Notify(stmt->relname);
634 ListenStmt *stmt = (ListenStmt *) parsetree;
636 set_ps_display(commandTag = "LISTEN");
638 Async_Listen(stmt->relname, MyProcPid);
644 UnlistenStmt *stmt = (UnlistenStmt *) parsetree;
646 set_ps_display(commandTag = "UNLISTEN");
648 Async_Unlisten(stmt->relname, MyProcPid);
653 * ******************************** dynamic loader ********************************
658 LoadStmt *stmt = (LoadStmt *) parsetree;
660 set_ps_display(commandTag = "LOAD");
662 closeAllVfds(); /* probably not necessary... */
663 load_file(stmt->filename);
669 ClusterStmt *stmt = (ClusterStmt *) parsetree;
671 set_ps_display(commandTag = "CLUSTER");
673 relname = stmt->relname;
674 if (IsSystemRelationName(relname))
675 elog(ERROR, "CLUSTER: relation \"%s\" is a system catalog",
677 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
678 elog(ERROR, "permission denied");
680 cluster(relname, stmt->indexname);
685 set_ps_display(commandTag = "VACUUM");
687 vacuum(((VacuumStmt *) parsetree)->vacrel,
688 ((VacuumStmt *) parsetree)->verbose,
689 ((VacuumStmt *) parsetree)->analyze,
690 ((VacuumStmt *) parsetree)->va_spec);
695 ExplainStmt *stmt = (ExplainStmt *) parsetree;
697 set_ps_display(commandTag = "EXPLAIN");
699 ExplainQuery(stmt->query, stmt->verbose, dest);
706 * ******************************** Tioga-related statements *******************************
710 RecipeStmt *stmt = (RecipeStmt *) parsetree;
712 set_ps_display(commandTag = "EXECUTE RECIPE");
720 * ******************************** set variable statements *******************************
722 case T_VariableSetStmt:
724 VariableSetStmt *n = (VariableSetStmt *) parsetree;
726 SetPGVariable(n->name, n->value);
727 set_ps_display(commandTag = "SET VARIABLE");
731 case T_VariableShowStmt:
733 VariableShowStmt *n = (VariableShowStmt *) parsetree;
735 GetPGVariable(n->name);
736 set_ps_display(commandTag = "SHOW VARIABLE");
740 case T_VariableResetStmt:
742 VariableResetStmt *n = (VariableResetStmt *) parsetree;
744 ResetPGVariable(n->name);
745 set_ps_display(commandTag = "RESET VARIABLE");
750 * ******************************** TRIGGER statements *******************************
752 case T_CreateTrigStmt:
753 set_ps_display(commandTag = "CREATE");
755 CreateTrigger((CreateTrigStmt *) parsetree);
759 set_ps_display(commandTag = "DROP");
761 DropTrigger((DropTrigStmt *) parsetree);
765 * ************* PROCEDURAL LANGUAGE statements *****************
767 case T_CreatePLangStmt:
768 set_ps_display(commandTag = "CREATE");
770 CreateProceduralLanguage((CreatePLangStmt *) parsetree);
773 case T_DropPLangStmt:
774 set_ps_display(commandTag = "DROP");
776 DropProceduralLanguage((DropPLangStmt *) parsetree);
780 * ******************************** USER statements ****
783 case T_CreateUserStmt:
784 set_ps_display(commandTag = "CREATE USER");
786 CreateUser((CreateUserStmt *) parsetree);
789 case T_AlterUserStmt:
790 set_ps_display(commandTag = "ALTER USER");
792 AlterUser((AlterUserStmt *) parsetree);
796 set_ps_display(commandTag = "DROP USER");
798 DropUser((DropUserStmt *) parsetree);
802 set_ps_display(commandTag = "LOCK TABLE");
804 LockTableCommand((LockStmt *) parsetree);
807 case T_ConstraintsSetStmt:
808 set_ps_display(commandTag = "SET CONSTRAINTS");
810 DeferredTriggerSetState((ConstraintsSetStmt *) parsetree);
813 case T_CreateGroupStmt:
814 set_ps_display(commandTag = "CREATE GROUP");
816 CreateGroup((CreateGroupStmt *) parsetree);
819 case T_AlterGroupStmt:
820 set_ps_display(commandTag = "ALTER GROUP");
822 AlterGroup((AlterGroupStmt *) parsetree, "ALTER GROUP");
825 case T_DropGroupStmt:
826 set_ps_display(commandTag = "DROP GROUP");
828 DropGroup((DropGroupStmt *) parsetree);
831 case T_CheckPointStmt:
833 set_ps_display(commandTag = "CHECKPOINT");
835 CreateCheckPoint(false);
841 ReindexStmt *stmt = (ReindexStmt *) parsetree;
843 set_ps_display(commandTag = "REINDEX");
845 switch (stmt->reindexType)
848 relname = (char *) stmt->name;
849 if (IsSystemRelationName(relname))
851 if (!allowSystemTableMods && IsSystemRelationName(relname))
852 elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -O -P options",
854 if (!IsIgnoringSystemIndexes())
855 elog(ERROR, "\"%s\" is a system index. call REINDEX under standalone postgres with -P -O options",
858 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
859 elog(ERROR, "%s: %s", relname, aclcheck_error_strings[ACLCHECK_NOT_OWNER]);
860 ReindexIndex(relname, stmt->force);
863 relname = (char *) stmt->name;
864 if (IsSystemRelationName(relname))
866 if (!allowSystemTableMods && IsSystemRelationName(relname))
867 elog(ERROR, "\"%s\" is a system table. call REINDEX under standalone postgres with -O -P options",
869 if (!IsIgnoringSystemIndexes())
870 elog(ERROR, "\"%s\" is a system table. call REINDEX under standalone postgres with -P -O options",
874 if (!pg_ownercheck(GetUserId(), relname, RELNAME))
875 elog(ERROR, "%s: %s", relname, aclcheck_error_strings[ACLCHECK_NOT_OWNER]);
876 ReindexTable(relname, stmt->force);
879 relname = (char *) stmt->name;
880 if (!allowSystemTableMods)
881 elog(ERROR, "must be called under standalone postgres with -O -P options");
882 if (!IsIgnoringSystemIndexes())
883 elog(ERROR, "must be called under standalone postgres with -P -O options");
884 ReindexDatabase(relname, stmt->force, false);
892 * ******************************** default ********************************
896 elog(ERROR, "ProcessUtility: command #%d unsupported",
902 * tell fe/be or whatever that we're done.
905 EndCommand(commandTag, dest);