1/*-------------------------------------------------------------------------
4 * use rewrite rules to construct views
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/view.c
13 *-------------------------------------------------------------------------
35/*---------------------------------------------------------------------
36 * DefineVirtualRelation
38 * Create a view relation and use the rules system to store the query
41 * EventTriggerAlterTableStart must have been called already.
42 *---------------------------------------------------------------------
54 * create a list of ColumnDef nodes based on the names and types of the
55 * (non-junk) targetlist items from the view's SELECT list.
70 * It's possible that the column is of a collatable type but the
71 * collation could not be resolved, so double-check.
77 (
errcode(ERRCODE_INDETERMINATE_COLLATION),
78 errmsg(
"could not determine which collation to use for view column \"%s\"",
80 errhint(
"Use the COLLATE clause to set the collation explicitly.")));
85 attrList =
lappend(attrList, def);
90 * Look up, check permissions on, and lock the creation namespace; also
91 * check for a preexisting view with the same name. This will also set
92 * relation->relpersistence to RELPERSISTENCE_TEMP if the selected
93 * namespace is temporary.
106 /* Relation is already locked, but we must build a relcache entry. */
109 /* Make sure it *is* a view. */
110 if (rel->
rd_rel->relkind != RELKIND_VIEW)
112 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
113 errmsg(
"\"%s\" is not a view",
116 /* Also check it's not in use already */
120 * Due to the namespace visibility rules for temporary objects, we
121 * should only end up replacing a temporary view with another
122 * temporary view, and similarly for permanent views.
127 * Create a tuple descriptor to compare against the existing view, and
128 * verify that the old column list is an initial prefix of the new
135 * If new attributes have been added, we must add pg_attribute entries
136 * for them. It is convenient (although overkill) to use the ALTER
137 * TABLE ADD COLUMN infrastructure for this.
139 * Note that we must do this before updating the query for the view,
140 * since the rules system requires that the correct view columns be in
141 * place when defining the new rules.
143 * Also note that ALTER TABLE doesn't run parse transformation on
144 * AT_AddColumnToView commands. The ColumnDef we supply must be ready
162 atcmds =
lappend(atcmds, atcmd);
165 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
168 /* Make the new view columns visible */
173 * Update the query for the view.
175 * Note that we must do this before updating the view options, because
176 * the new options may not be compatible with the old view query (for
177 * example if we attempt to add the WITH CHECK OPTION, we require that
178 * the new view be automatically updatable, but the old view may not
183 /* Make the new view query visible */
187 * Update the view's options.
189 * The new options list replaces the existing options list, even if
197 /* EventTriggerAlterTableStart called by ProcessUtilitySlow */
201 * There is very little to do here to update the view's dependencies.
202 * Most view-level dependency relationships, such as those on the
203 * owner, schema, and associated composite type, aren't changing.
204 * Because we don't allow changing type or collation of an existing
205 * view column, those dependencies of the existing columns don't
206 * change either, while the AT_AddColumnToView machinery took care of
207 * adding such dependencies for new view columns. The dependencies of
208 * the view's query could have changed arbitrarily, but that was dealt
209 * with inside StoreViewQuery. What remains is only to check that
210 * view replacement is allowed when we're creating an extension.
217 * Seems okay, so return the OID of the pre-existing view.
229 * Set the parameters for keys/inheritance etc. All of these are
230 * uninteresting for views...
242 * Create the relation (this will error out if there's an existing
243 * view, so we don't need more code to complain if "replace" is
250 /* Make the new view relation visible */
253 /* Store the query for the view */
261 * Verify that the columns associated with proposed new view definition match
262 * the columns of the old view. This is similar to equalRowTypes(), with code
263 * added to generate specific complaints. Also, we allow the new view to have
264 * more columns than the old.
273 (
errcode(ERRCODE_INVALID_TABLE_DEFINITION),
274 errmsg(
"cannot drop columns from view")));
276 for (
i = 0;
i < olddesc->
natts;
i++)
281 /* XXX msg not right, but we don't support DROP COL on view anyway */
282 if (newattr->attisdropped != oldattr->attisdropped)
284 (
errcode(ERRCODE_INVALID_TABLE_DEFINITION),
285 errmsg(
"cannot drop columns from view")));
287 if (strcmp(
NameStr(newattr->attname),
NameStr(oldattr->attname)) != 0)
289 (
errcode(ERRCODE_INVALID_TABLE_DEFINITION),
290 errmsg(
"cannot change name of view column \"%s\" to \"%s\"",
293 errhint(
"Use ALTER VIEW ... RENAME COLUMN ... to change name of view column instead.")));
296 * We cannot allow type, typmod, or collation to change, since these
297 * properties may be embedded in Vars of other views/rules referencing
298 * this one. Other column attributes can be ignored.
300 if (newattr->atttypid != oldattr->atttypid ||
301 newattr->atttypmod != oldattr->atttypmod)
303 (
errcode(ERRCODE_INVALID_TABLE_DEFINITION),
304 errmsg(
"cannot change data type of view column \"%s\" from %s to %s",
309 newattr->atttypmod))));
312 * At this point, attcollations should be both valid or both invalid,
313 * so applying get_collation_name unconditionally should be fine.
315 if (newattr->attcollation != oldattr->attcollation)
317 (
errcode(ERRCODE_INVALID_TABLE_DEFINITION),
318 errmsg(
"cannot change collation of view column \"%s\" from \"%s\" to \"%s\"",
325 * We ignore the constraint fields. The new view desc can't have any
326 * constraints, and the only ones that could be on the old view are
327 * defaults, which we are happy to leave in place.
335 * Set up the ON SELECT rule. Since the query has already been through
336 * parse analysis, we use DefineQueryRewrite() directly.
347 * Someday: automatic ON INSERT, etc
353 * Execute a CREATE VIEW command.
357 int stmt_location,
int stmt_len)
367 * Run parse analysis to convert the raw parse tree to a Query. Note this
368 * also acquires sufficient locks on the source table(s).
378 * The grammar should ensure that the result is a single SELECT Query.
379 * However, it doesn't forbid SELECT INTO, so we have to check for that.
382 elog(
ERROR,
"unexpected parse analysis result");
386 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
387 errmsg(
"views must not contain SELECT INTO")));
389 elog(
ERROR,
"unexpected parse analysis result");
392 * Check for unsupported cases. These tests are redundant with ones in
393 * DefineQueryRewrite(), but that function will complain about a bogus ON
394 * SELECT rule, and we'd rather the message complain about a view.
396 if (viewParse->hasModifyingCTE)
398 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
399 errmsg(
"views must not contain data-modifying statements in WITH")));
402 * If the user specified the WITH CHECK OPTION, add it to the list of
415 * Check that the view is auto-updatable if WITH CHECK OPTION was
418 check_option =
false;
420 foreach(cell,
stmt->options)
424 if (strcmp(defel->
defname,
"check_option") == 0)
429 * If the check option is specified, look to see if the view is actually
430 * auto-updatable or not.
434 const char *view_updatable_error =
437 if (view_updatable_error)
439 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
440 errmsg(
"WITH CHECK OPTION is supported only on automatically updatable views"),
441 errhint(
"%s",
_(view_updatable_error))));
445 * If a list of column names was given, run through and insert these into
446 * the actual query tree. - thomas 2000年03月08日
457 /* junk columns don't get aliases */
461 alist_item =
lnext(
stmt->aliases, alist_item);
462 if (alist_item == NULL)
463 break;
/* done assigning aliases */
466 if (alist_item != NULL)
468 (
errcode(ERRCODE_SYNTAX_ERROR),
469 errmsg(
"CREATE VIEW specifies more column "
470 "names than columns")));
473 /* Unlogged views are not sensible. */
474 if (
stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
476 (
errcode(ERRCODE_SYNTAX_ERROR),
477 errmsg(
"views cannot be unlogged because they do not have storage")));
480 * If the user didn't explicitly ask for a temporary view, check whether
481 * we need one implicitly. We allow TEMP to be inserted automatically as
482 * long as the CREATE command is consistent with that --- no explicit
485 view =
copyObject(
stmt->view);
/* don't corrupt original command */
491 (
errmsg(
"view \"%s\" will be a temporary view",
496 * Create the view relation
498 * NOTE: if it already exists and replace is false, the xact will be
502 stmt->replace,
stmt->options, viewParse);
508 * Use the rules system to store the query for the view.
514 * Now create the rules associated with the view.
#define OidIsValid(objectId)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
Assert(PointerIsAligned(start, uint64))
List * lappend(List *list, void *datum)
#define AccessExclusiveLock
char * get_collation_name(Oid colloid)
bool type_is_collatable(Oid typid)
DefElem * makeDefElem(char *name, Node *arg, int location)
ColumnDef * makeColumnDef(const char *colname, Oid typeOid, int32 typmod, Oid collOid)
char * pstrdup(const char *in)
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Oid exprType(const Node *expr)
int32 exprTypmod(const Node *expr)
Oid exprCollation(const Node *expr)
#define IsA(nodeptr, _type_)
#define ObjectAddressSet(addr, class_id, object_id)
bool isQueryUsingTempRelation(Query *query)
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
FormData_pg_attribute * Form_pg_attribute
static const struct exclude_list_item skip[]
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
#define lfirst_node(type, lc)
static int list_length(const List *l)
static ListCell * list_head(const List *l)
static ListCell * lnext(const List *l, const ListCell *c)
#define RelationGetRelationName(relation)
ObjectAddress DefineQueryRewrite(const char *rulename, Oid event_relid, Node *event_qual, CmdType event_type, bool is_instead, bool replace, List *action)
const char * view_query_is_auto_updatable(Query *viewquery, bool check_cols)
#define ViewSelectRuleName
void relation_close(Relation relation, LOCKMODE lockmode)
Relation relation_open(Oid relationId, LOCKMODE lockmode)
TupleDesc BuildDescForRelation(const List *columns)
void CheckTableNotInUse(Relation rel, const char *stmt)
ObjectAddress DefineRelation(CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
String * makeString(char *str)
static ObjectAddress DefineVirtualRelation(RangeVar *relation, List *tlist, bool replace, List *options, Query *viewParse)
static void checkViewColumns(TupleDesc newdesc, TupleDesc olddesc)
static void DefineViewRules(Oid viewOid, Query *viewParse, bool replace)
ObjectAddress DefineView(ViewStmt *stmt, const char *queryString, int stmt_location, int stmt_len)
void StoreViewQuery(Oid viewOid, Query *viewParse, bool replace)
void CommandCounterIncrement(void)