Header And Logo

PostgreSQL
| The world's most advanced open source database.

Functions

view.c File Reference

#include "postgres.h"
#include "access/heapam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "commands/defrem.h"
#include "commands/tablecmds.h"
#include "commands/view.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/analyze.h"
#include "parser/parse_relation.h"
#include "rewrite/rewriteDefine.h"
#include "rewrite/rewriteManip.h"
#include "rewrite/rewriteSupport.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for view.c:

Go to the source code of this file.

Functions

static void checkViewTupleDesc (TupleDesc newdesc, TupleDesc olddesc)
static Oid DefineVirtualRelation (RangeVar *relation, List *tlist, bool replace, List *options)
static void DefineViewRules (Oid viewOid, Query *viewParse, bool replace)
static QueryUpdateRangeTableOfViewParse (Oid viewOid, Query *viewParse)
Oid DefineView (ViewStmt *stmt, const char *queryString)
void StoreViewQuery (Oid viewOid, Query *viewParse, bool replace)

Function Documentation

static void checkViewTupleDesc ( TupleDesc  newdesc,
TupleDesc  olddesc 
) [static]

Definition at line 233 of file view.c.

References tupleDesc::attrs, ereport, errcode(), errmsg(), ERROR, format_type_with_typemod(), i, NameStr, and tupleDesc::natts.

Referenced by DefineVirtualRelation().

{
    int         i;

    if (newdesc->natts < olddesc->natts)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
                 errmsg("cannot drop columns from view")));
    /* we can ignore tdhasoid */

    for (i = 0; i < olddesc->natts; i++)
    {
        Form_pg_attribute newattr = newdesc->attrs[i];
        Form_pg_attribute oldattr = olddesc->attrs[i];

        /* XXX msg not right, but we don't support DROP COL on view anyway */
        if (newattr->attisdropped != oldattr->attisdropped)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
                     errmsg("cannot drop columns from view")));

        if (strcmp(NameStr(newattr->attname), NameStr(oldattr->attname)) != 0)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
                 errmsg("cannot change name of view column \"%s\" to \"%s\"",
                        NameStr(oldattr->attname),
                        NameStr(newattr->attname))));
        /* XXX would it be safe to allow atttypmod to change?  Not sure */
        if (newattr->atttypid != oldattr->atttypid ||
            newattr->atttypmod != oldattr->atttypmod)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
                     errmsg("cannot change data type of view column \"%s\" from %s to %s",
                            NameStr(oldattr->attname),
                            format_type_with_typemod(oldattr->atttypid,
                                                     oldattr->atttypmod),
                            format_type_with_typemod(newattr->atttypid,
                                                     newattr->atttypmod))));
        /* We can ignore the remaining attributes of an attribute... */
    }

    /*
     * We ignore the constraint fields.  The new view desc can't have any
     * constraints, and the only ones that could be on the old view are
     * defaults, which we are happy to leave in place.
     */
}

Oid DefineView ( ViewStmt stmt,
const char *  queryString 
)

Definition at line 372 of file view.c.

References ViewStmt::aliases, Assert, CMD_SELECT, CommandCounterIncrement(), Query::commandType, copyObject(), DefineVirtualRelation(), elog, ereport, errcode(), errmsg(), ERROR, Query::hasModifyingCTE, IsA, isQueryUsingTempRelation(), lfirst, list_head(), lnext, NIL, NOTICE, NULL, ViewStmt::options, parse_analyze(), pstrdup(), ViewStmt::query, RangeVar::relname, RangeVar::relpersistence, RELPERSISTENCE_PERMANENT, RELPERSISTENCE_UNLOGGED, ViewStmt::replace, TargetEntry::resjunk, TargetEntry::resname, StoreViewQuery(), strVal, Query::targetList, Query::utilityStmt, and ViewStmt::view.

Referenced by ProcessUtilitySlow().

{
    Query      *viewParse;
    Oid         viewOid;
    RangeVar   *view;

    /*
     * Run parse analysis to convert the raw parse tree to a Query.  Note this
     * also acquires sufficient locks on the source table(s).
     *
     * Since parse analysis scribbles on its input, copy the raw parse tree;
     * this ensures we don't corrupt a prepared statement, for example.
     */
    viewParse = parse_analyze((Node *) copyObject(stmt->query),
                              queryString, NULL, 0);

    /*
     * The grammar should ensure that the result is a single SELECT Query.
     * However, it doesn't forbid SELECT INTO, so we have to check for that.
     */
    if (!IsA(viewParse, Query))
        elog(ERROR, "unexpected parse analysis result");
    if (viewParse->utilityStmt != NULL &&
        IsA(viewParse->utilityStmt, CreateTableAsStmt))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("views must not contain SELECT INTO")));
    if (viewParse->commandType != CMD_SELECT ||
        viewParse->utilityStmt != NULL)
        elog(ERROR, "unexpected parse analysis result");

    /*
     * Check for unsupported cases.  These tests are redundant with ones in
     * DefineQueryRewrite(), but that function will complain about a bogus ON
     * SELECT rule, and we'd rather the message complain about a view.
     */
    if (viewParse->hasModifyingCTE)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
        errmsg("views must not contain data-modifying statements in WITH")));

    /*
     * If a list of column names was given, run through and insert these into
     * the actual query tree. - thomas 2000-03-08
     */
    if (stmt->aliases != NIL)
    {
        ListCell   *alist_item = list_head(stmt->aliases);
        ListCell   *targetList;

        foreach(targetList, viewParse->targetList)
        {
            TargetEntry *te = (TargetEntry *) lfirst(targetList);

            Assert(IsA(te, TargetEntry));
            /* junk columns don't get aliases */
            if (te->resjunk)
                continue;
            te->resname = pstrdup(strVal(lfirst(alist_item)));
            alist_item = lnext(alist_item);
            if (alist_item == NULL)
                break;          /* done assigning aliases */
        }

        if (alist_item != NULL)
            ereport(ERROR,
                    (errcode(ERRCODE_SYNTAX_ERROR),
                     errmsg("CREATE VIEW specifies more column "
                            "names than columns")));
    }

    /* Unlogged views are not sensible. */
    if (stmt->view->relpersistence == RELPERSISTENCE_UNLOGGED)
        ereport(ERROR,
                (errcode(ERRCODE_SYNTAX_ERROR),
        errmsg("views cannot be unlogged because they do not have storage")));

    /*
     * If the user didn't explicitly ask for a temporary view, check whether
     * we need one implicitly.  We allow TEMP to be inserted automatically as
     * long as the CREATE command is consistent with that --- no explicit
     * schema name.
     */
    view = copyObject(stmt->view);      /* don't corrupt original command */
    if (view->relpersistence == RELPERSISTENCE_PERMANENT
        && isQueryUsingTempRelation(viewParse))
    {
        view->relpersistence = RELPERSISTENCE_TEMP;
        ereport(NOTICE,
                (errmsg("view \"%s\" will be a temporary view",
                        view->relname)));
    }

    /*
     * Create the view relation
     *
     * NOTE: if it already exists and replace is false, the xact will be
     * aborted.
     */
    viewOid = DefineVirtualRelation(view, viewParse->targetList,
                                    stmt->replace, stmt->options);

    /*
     * The relation we have just created is not visible to any other commands
     * running with the same transaction & command id. So, increment the
     * command id counter (but do NOT pfree any memory!!!!)
     */
    CommandCounterIncrement();

    StoreViewQuery(viewOid, viewParse, stmt->replace);

    return viewOid;
}

static void DefineViewRules ( Oid  viewOid,
Query viewParse,
bool  replace 
) [static]

Definition at line 282 of file view.c.

References CMD_SELECT, DefineQueryRewrite(), list_make1, NULL, pstrdup(), and ViewSelectRuleName.

Referenced by StoreViewQuery().

{
    /*
     * Set up the ON SELECT rule.  Since the query has already been through
     * parse analysis, we use DefineQueryRewrite() directly.
     */
    DefineQueryRewrite(pstrdup(ViewSelectRuleName),
                       viewOid,
                       NULL,
                       CMD_SELECT,
                       true,
                       replace,
                       list_make1(viewParse));

    /*
     * Someday: automatic ON INSERT, etc
     */
}

static Oid DefineVirtualRelation ( RangeVar relation,
List tlist,
bool  replace,
List options 
) [static]

Definition at line 50 of file view.c.

References AccessExclusiveLock, AlterTableInternal(), Assert, BuildDescForRelation(), CheckTableNotInUse(), checkViewTupleDesc(), ColumnDef::collClause, ColumnDef::collOid, ColumnDef::colname, CreateStmt::constraints, ColumnDef::constraints, ColumnDef::cooked_default, AlterTableCmd::def, DefineRelation(), ereport, errcode(), errhint(), errmsg(), ERROR, TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), CreateStmt::if_not_exists, ColumnDef::inhcount, CreateStmt::inhRelations, InvalidOid, ColumnDef::is_from_type, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), lfirst, list_length(), makeNode, makeTypeNameFromOid(), tupleDesc::natts, NIL, NoLock, OidIsValid, CreateStmt::oncommit, CreateStmt::options, pstrdup(), RangeVarGetAndCheckCreationNamespace(), ColumnDef::raw_default, RelationData::rd_att, RelationData::rd_rel, CreateStmt::relation, relation_close(), relation_open(), RelationGetRelationName, RELKIND_VIEW, RangeVar::relpersistence, TargetEntry::resjunk, TargetEntry::resname, skip(), ColumnDef::storage, AlterTableCmd::subtype, CreateStmt::tableElts, CreateStmt::tablespacename, type_is_collatable(), and ColumnDef::typeName.

Referenced by DefineView().

{
    Oid         viewOid;
    LOCKMODE    lockmode;
    CreateStmt *createStmt = makeNode(CreateStmt);
    List       *attrList;
    ListCell   *t;

    /*
     * create a list of ColumnDef nodes based on the names and types of the
     * (non-junk) targetlist items from the view's SELECT list.
     */
    attrList = NIL;
    foreach(t, tlist)
    {
        TargetEntry *tle = lfirst(t);

        if (!tle->resjunk)
        {
            ColumnDef  *def = makeNode(ColumnDef);

            def->colname = pstrdup(tle->resname);
            def->typeName = makeTypeNameFromOid(exprType((Node *) tle->expr),
                                             exprTypmod((Node *) tle->expr));
            def->inhcount = 0;
            def->is_local = true;
            def->is_not_null = false;
            def->is_from_type = false;
            def->storage = 0;
            def->raw_default = NULL;
            def->cooked_default = NULL;
            def->collClause = NULL;
            def->collOid = exprCollation((Node *) tle->expr);

            /*
             * It's possible that the column is of a collatable type but the
             * collation could not be resolved, so double-check.
             */
            if (type_is_collatable(exprType((Node *) tle->expr)))
            {
                if (!OidIsValid(def->collOid))
                    ereport(ERROR,
                            (errcode(ERRCODE_INDETERMINATE_COLLATION),
                             errmsg("could not determine which collation to use for view column \"%s\"",
                                    def->colname),
                             errhint("Use the COLLATE clause to set the collation explicitly.")));
            }
            else
                Assert(!OidIsValid(def->collOid));
            def->constraints = NIL;

            attrList = lappend(attrList, def);
        }
    }

    if (attrList == NIL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
                 errmsg("view must have at least one column")));

    /*
     * Look up, check permissions on, and lock the creation namespace; also
     * check for a preexisting view with the same name.  This will also set
     * relation->relpersistence to RELPERSISTENCE_TEMP if the selected
     * namespace is temporary.
     */
    lockmode = replace ? AccessExclusiveLock : NoLock;
    (void) RangeVarGetAndCheckCreationNamespace(relation, lockmode, &viewOid);

    if (OidIsValid(viewOid) && replace)
    {
        Relation    rel;
        TupleDesc   descriptor;
        List       *atcmds = NIL;
        AlterTableCmd *atcmd;

        /* Relation is already locked, but we must build a relcache entry. */
        rel = relation_open(viewOid, NoLock);

        /* Make sure it *is* a view. */
        if (rel->rd_rel->relkind != RELKIND_VIEW)
            ereport(ERROR,
                    (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                     errmsg("\"%s\" is not a view",
                            RelationGetRelationName(rel))));

        /* Also check it's not in use already */
        CheckTableNotInUse(rel, "CREATE OR REPLACE VIEW");

        /*
         * Due to the namespace visibility rules for temporary objects, we
         * should only end up replacing a temporary view with another
         * temporary view, and similarly for permanent views.
         */
        Assert(relation->relpersistence == rel->rd_rel->relpersistence);

        /*
         * Create a tuple descriptor to compare against the existing view, and
         * verify that the old column list is an initial prefix of the new
         * column list.
         */
        descriptor = BuildDescForRelation(attrList);
        checkViewTupleDesc(descriptor, rel->rd_att);

        /*
         * The new options list replaces the existing options list, even if
         * it's empty.
         */
        atcmd = makeNode(AlterTableCmd);
        atcmd->subtype = AT_ReplaceRelOptions;
        atcmd->def = (Node *) options;
        atcmds = lappend(atcmds, atcmd);

        /*
         * If new attributes have been added, we must add pg_attribute entries
         * for them.  It is convenient (although overkill) to use the ALTER
         * TABLE ADD COLUMN infrastructure for this.
         */
        if (list_length(attrList) > rel->rd_att->natts)
        {
            ListCell   *c;
            int         skip = rel->rd_att->natts;

            foreach(c, attrList)
            {
                if (skip > 0)
                {
                    skip--;
                    continue;
                }
                atcmd = makeNode(AlterTableCmd);
                atcmd->subtype = AT_AddColumnToView;
                atcmd->def = (Node *) lfirst(c);
                atcmds = lappend(atcmds, atcmd);
            }
        }

        /* OK, let's do it. */
        AlterTableInternal(viewOid, atcmds, true);

        /*
         * Seems okay, so return the OID of the pre-existing view.
         */
        relation_close(rel, NoLock);    /* keep the lock! */

        return viewOid;
    }
    else
    {
        Oid         relid;

        /*
         * now set the parameters for keys/inheritance etc. All of these are
         * uninteresting for views...
         */
        createStmt->relation = relation;
        createStmt->tableElts = attrList;
        createStmt->inhRelations = NIL;
        createStmt->constraints = NIL;
        createStmt->options = options;
        createStmt->oncommit = ONCOMMIT_NOOP;
        createStmt->tablespacename = NULL;
        createStmt->if_not_exists = false;

        /*
         * finally create the relation (this will error out if there's an
         * existing view, so we don't need more code to complain if "replace"
         * is false).
         */
        relid = DefineRelation(createStmt, RELKIND_VIEW, InvalidOid);
        Assert(relid != InvalidOid);
        return relid;
    }
}

void StoreViewQuery ( Oid  viewOid,
Query viewParse,
bool  replace 
)

Definition at line 490 of file view.c.

References DefineViewRules(), and UpdateRangeTableOfViewParse().

Referenced by DefineView(), and intorel_startup().

{
    /*
     * The range table of 'viewParse' does not contain entries for the "OLD"
     * and "NEW" relations. So... add them!
     */
    viewParse = UpdateRangeTableOfViewParse(viewOid, viewParse);

    /*
     * Now create the rules associated with the view.
     */
    DefineViewRules(viewOid, viewParse, replace);
}

static Query* UpdateRangeTableOfViewParse ( Oid  viewOid,
Query viewParse 
) [static]

Definition at line 319 of file view.c.

References AccessShareLock, addRangeTableEntryForRelation(), copyObject(), lcons(), makeAlias(), NIL, NULL, OffsetVarNodes(), relation_close(), relation_open(), RangeTblEntry::requiredPerms, and Query::rtable.

Referenced by StoreViewQuery().

{
    Relation    viewRel;
    List       *new_rt;
    RangeTblEntry *rt_entry1,
               *rt_entry2;

    /*
     * Make a copy of the given parsetree.  It's not so much that we don't
     * want to scribble on our input, it's that the parser has a bad habit of
     * outputting multiple links to the same subtree for constructs like
     * BETWEEN, and we mustn't have OffsetVarNodes increment the varno of a
     * Var node twice.  copyObject will expand any multiply-referenced subtree
     * into multiple copies.
     */
    viewParse = (Query *) copyObject(viewParse);

    /* need to open the rel for addRangeTableEntryForRelation */
    viewRel = relation_open(viewOid, AccessShareLock);

    /*
     * Create the 2 new range table entries and form the new range table...
     * OLD first, then NEW....
     */
    rt_entry1 = addRangeTableEntryForRelation(NULL, viewRel,
                                              makeAlias("old", NIL),
                                              false, false);
    rt_entry2 = addRangeTableEntryForRelation(NULL, viewRel,
                                              makeAlias("new", NIL),
                                              false, false);
    /* Must override addRangeTableEntry's default access-check flags */
    rt_entry1->requiredPerms = 0;
    rt_entry2->requiredPerms = 0;

    new_rt = lcons(rt_entry1, lcons(rt_entry2, viewParse->rtable));

    viewParse->rtable = new_rt;

    /*
     * Now offset all var nodes by 2, and jointree RT indexes too.
     */
    OffsetVarNodes((Node *) viewParse, 2, 0);

    relation_close(viewRel, AccessShareLock);

    return viewParse;
}