1 /*-------------------------------------------------------------------------
4 * Perform parse analysis work for various utility commands
6 * Formerly we did this work during parse_analyze() in analyze.c. However
7 * that is fairly unsafe in the presence of querytree caching, since any
8 * database state that we depend on in making the transformations might be
9 * obsolete by the time the utility command is executed; and utility commands
10 * have no infrastructure for holding locks or rechecking plan validity.
11 * Hence these functions are now called at the start of execution of their
12 * respective utility commands.
14 * NOTE: in general we must avoid scribbling on the passed-in raw parse
15 * tree, since it might be in a plan cache. The simplest solution is
16 * a quick copyObject() call before manipulating the query tree.
19 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * $PostgreSQL: pgsql/src/backend/parser/parse_utilcmd.c,v 2.1 2007/06/23 22:12:51 tgl Exp $
24 *-------------------------------------------------------------------------
29 #include "access/heapam.h"
30 #include "catalog/heap.h"
31 #include "catalog/index.h"
32 #include "catalog/namespace.h"
33 #include "catalog/pg_type.h"
34 #include "commands/defrem.h"
35 #include "commands/tablecmds.h"
36 #include "miscadmin.h"
37 #include "nodes/makefuncs.h"
38 #include "optimizer/clauses.h"
39 #include "parser/analyze.h"
40 #include "parser/gramparse.h"
41 #include "parser/parse_clause.h"
42 #include "parser/parse_expr.h"
43 #include "parser/parse_relation.h"
44 #include "parser/parse_type.h"
45 #include "parser/parse_utilcmd.h"
46 #include "rewrite/rewriteManip.h"
47 #include "utils/acl.h"
48 #include "utils/builtins.h"
49 #include "utils/lsyscache.h"
50 #include "utils/syscache.h"
53 /* State shared by transformCreateStmt and its subroutines */
56 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
57 RangeVar *relation; /* relation to create */
58 Relation rel; /* opened/locked rel, if ALTER */
59 List *inhRelations; /* relations to inherit from */
60 bool isalter; /* true if altering existing table */
61 bool hasoids; /* does relation have an OID column? */
62 List *columns; /* ColumnDef items */
63 List *ckconstraints; /* CHECK constraints */
64 List *fkconstraints; /* FOREIGN KEY constraints */
65 List *ixconstraints; /* index-creating constraints */
66 List *blist; /* "before list" of things to do before
67 * creating the table */
68 List *alist; /* "after list" of things to do after creating
70 IndexStmt *pkey; /* PRIMARY KEY index, if any */
73 /* State shared by transformCreateSchemaStmt and its subroutines */
76 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
77 char *schemaname; /* name of schema */
78 char *authid; /* owner of schema */
79 List *sequences; /* CREATE SEQUENCE items */
80 List *tables; /* CREATE TABLE items */
81 List *views; /* CREATE VIEW items */
82 List *indexes; /* CREATE INDEX items */
83 List *triggers; /* CREATE TRIGGER items */
84 List *grants; /* GRANT items */
85 } CreateSchemaStmtContext;
88 static void transformColumnDefinition(ParseState *pstate,
89 CreateStmtContext *cxt,
91 static void transformTableConstraint(ParseState *pstate,
92 CreateStmtContext *cxt,
93 Constraint *constraint);
94 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
95 InhRelation *inhrelation);
96 static void transformIndexConstraints(ParseState *pstate,
97 CreateStmtContext *cxt);
98 static void transformFKConstraints(ParseState *pstate,
99 CreateStmtContext *cxt,
101 bool isAddConstraint);
102 static void transformConstraintAttrs(List *constraintList);
103 static void transformColumnType(ParseState *pstate, ColumnDef *column);
104 static void setSchemaName(char *context_schema, char **stmt_schema_name);
108 * transformCreateStmt -
109 * parse analysis for CREATE TABLE
111 * Returns a List of utility commands to be done in sequence. One of these
112 * will be the transformed CreateStmt, but there may be additional actions
113 * to be done before and after the actual DefineRelation() call.
115 * SQL92 allows constraints to be scattered all over, so thumb through
116 * the columns and collect all constraints into one place.
117 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
118 * then expand those into multiple IndexStmt blocks.
119 * - thomas 1997-12-02
122 transformCreateStmt(CreateStmt *stmt, const char *queryString)
125 CreateStmtContext cxt;
131 * We must not scribble on the passed-in CreateStmt, so copy it. (This
132 * is overkill, but easy.)
134 stmt = (CreateStmt *) copyObject(stmt);
137 pstate = make_parsestate(NULL);
138 pstate->p_sourcetext = queryString;
140 cxt.stmtType = "CREATE TABLE";
141 cxt.relation = stmt->relation;
143 cxt.inhRelations = stmt->inhRelations;
146 cxt.ckconstraints = NIL;
147 cxt.fkconstraints = NIL;
148 cxt.ixconstraints = NIL;
152 cxt.hasoids = interpretOidsOption(stmt->options);
155 * Run through each primary element in the table creation clause. Separate
156 * column defs from constraints, and do preliminary analysis.
158 foreach(elements, stmt->tableElts)
160 Node *element = lfirst(elements);
162 switch (nodeTag(element))
165 transformColumnDefinition(pstate, &cxt,
166 (ColumnDef *) element);
170 transformTableConstraint(pstate, &cxt,
171 (Constraint *) element);
175 /* No pre-transformation needed */
176 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
180 transformInhRelation(pstate, &cxt,
181 (InhRelation *) element);
185 elog(ERROR, "unrecognized node type: %d",
186 (int) nodeTag(element));
192 * transformIndexConstraints wants cxt.alist to contain only index
193 * statements, so transfer anything we already have into save_alist.
195 save_alist = cxt.alist;
198 Assert(stmt->constraints == NIL);
201 * Postprocess constraints that give rise to index definitions.
203 transformIndexConstraints(pstate, &cxt);
206 * Postprocess foreign-key constraints.
208 transformFKConstraints(pstate, &cxt, true, false);
213 stmt->tableElts = cxt.columns;
214 stmt->constraints = cxt.ckconstraints;
216 result = lappend(cxt.blist, stmt);
217 result = list_concat(result, cxt.alist);
218 result = list_concat(result, save_alist);
224 * transformColumnDefinition -
225 * transform a single ColumnDef within CREATE TABLE
226 * Also used in ALTER TABLE ADD COLUMN
229 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
235 Constraint *constraint;
238 cxt->columns = lappend(cxt->columns, column);
240 /* Check for SERIAL pseudo-types */
242 if (list_length(column->typename->names) == 1)
244 char *typname = strVal(linitial(column->typename->names));
246 if (strcmp(typname, "serial") == 0 ||
247 strcmp(typname, "serial4") == 0)
250 column->typename->names = NIL;
251 column->typename->typeid = INT4OID;
253 else if (strcmp(typname, "bigserial") == 0 ||
254 strcmp(typname, "serial8") == 0)
257 column->typename->names = NIL;
258 column->typename->typeid = INT8OID;
262 /* Do necessary work on the column type declaration */
263 transformColumnType(pstate, column);
265 /* Special actions for SERIAL pseudo-types */
273 FuncCall *funccallnode;
274 CreateSeqStmt *seqstmt;
275 AlterSeqStmt *altseqstmt;
279 * Determine namespace and name to use for the sequence.
281 * Although we use ChooseRelationName, it's not guaranteed that the
282 * selected sequence name won't conflict; given sufficiently long
283 * field names, two different serial columns in the same table could
284 * be assigned the same sequence name, and we'd not notice since we
285 * aren't creating the sequence quite yet. In practice this seems
286 * quite unlikely to be a problem, especially since few people would
287 * need two serial columns in one table.
290 snamespaceid = RelationGetNamespace(cxt->rel);
292 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
293 snamespace = get_namespace_name(snamespaceid);
294 sname = ChooseRelationName(cxt->relation->relname,
300 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
301 cxt->stmtType, sname,
302 cxt->relation->relname, column->colname)));
305 * Build a CREATE SEQUENCE command to create the sequence object, and
306 * add it to the list of things to be done before this CREATE/ALTER
309 seqstmt = makeNode(CreateSeqStmt);
310 seqstmt->sequence = makeRangeVar(snamespace, sname);
311 seqstmt->options = NIL;
313 cxt->blist = lappend(cxt->blist, seqstmt);
316 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
317 * as owned by this column, and add it to the list of things to be
318 * done after this CREATE/ALTER TABLE.
320 altseqstmt = makeNode(AlterSeqStmt);
321 altseqstmt->sequence = makeRangeVar(snamespace, sname);
322 attnamelist = list_make3(makeString(snamespace),
323 makeString(cxt->relation->relname),
324 makeString(column->colname));
325 altseqstmt->options = list_make1(makeDefElem("owned_by",
326 (Node *) attnamelist));
328 cxt->alist = lappend(cxt->alist, altseqstmt);
331 * Create appropriate constraints for SERIAL. We do this in full,
332 * rather than shortcutting, so that we will detect any conflicting
333 * constraints the user wrote (like a different DEFAULT).
335 * Create an expression tree representing the function call
336 * nextval('sequencename'). We cannot reduce the raw tree to cooked
337 * form until after the sequence is created, but there's no need to do
340 qstring = quote_qualified_identifier(snamespace, sname);
341 snamenode = makeNode(A_Const);
342 snamenode->val.type = T_String;
343 snamenode->val.val.str = qstring;
344 snamenode->typename = SystemTypeName("regclass");
345 funccallnode = makeNode(FuncCall);
346 funccallnode->funcname = SystemFuncName("nextval");
347 funccallnode->args = list_make1(snamenode);
348 funccallnode->agg_star = false;
349 funccallnode->agg_distinct = false;
350 funccallnode->location = -1;
352 constraint = makeNode(Constraint);
353 constraint->contype = CONSTR_DEFAULT;
354 constraint->raw_expr = (Node *) funccallnode;
355 constraint->cooked_expr = NULL;
356 constraint->keys = NIL;
357 column->constraints = lappend(column->constraints, constraint);
359 constraint = makeNode(Constraint);
360 constraint->contype = CONSTR_NOTNULL;
361 column->constraints = lappend(column->constraints, constraint);
364 /* Process column constraints, if any... */
365 transformConstraintAttrs(column->constraints);
367 saw_nullable = false;
370 foreach(clist, column->constraints)
372 constraint = lfirst(clist);
375 * If this column constraint is a FOREIGN KEY constraint, then we fill
376 * in the current attribute's name and throw it into the list of FK
377 * constraints to be processed later.
379 if (IsA(constraint, FkConstraint))
381 FkConstraint *fkconstraint = (FkConstraint *) constraint;
383 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
384 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
388 Assert(IsA(constraint, Constraint));
390 switch (constraint->contype)
393 if (saw_nullable && column->is_not_null)
395 (errcode(ERRCODE_SYNTAX_ERROR),
396 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
397 column->colname, cxt->relation->relname)));
398 column->is_not_null = FALSE;
403 if (saw_nullable && !column->is_not_null)
405 (errcode(ERRCODE_SYNTAX_ERROR),
406 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
407 column->colname, cxt->relation->relname)));
408 column->is_not_null = TRUE;
415 (errcode(ERRCODE_SYNTAX_ERROR),
416 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
417 column->colname, cxt->relation->relname)));
418 /* Note: DEFAULT NULL maps to constraint->raw_expr == NULL */
419 column->raw_default = constraint->raw_expr;
420 Assert(constraint->cooked_expr == NULL);
426 if (constraint->keys == NIL)
427 constraint->keys = list_make1(makeString(column->colname));
428 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
432 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
435 case CONSTR_ATTR_DEFERRABLE:
436 case CONSTR_ATTR_NOT_DEFERRABLE:
437 case CONSTR_ATTR_DEFERRED:
438 case CONSTR_ATTR_IMMEDIATE:
439 /* transformConstraintAttrs took care of these */
443 elog(ERROR, "unrecognized constraint type: %d",
444 constraint->contype);
451 * transformTableConstraint
452 * transform a Constraint node within CREATE TABLE or ALTER TABLE
455 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
456 Constraint *constraint)
458 switch (constraint->contype)
462 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
466 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
472 case CONSTR_ATTR_DEFERRABLE:
473 case CONSTR_ATTR_NOT_DEFERRABLE:
474 case CONSTR_ATTR_DEFERRED:
475 case CONSTR_ATTR_IMMEDIATE:
476 elog(ERROR, "invalid context for constraint type %d",
477 constraint->contype);
481 elog(ERROR, "unrecognized constraint type: %d",
482 constraint->contype);
488 * transformInhRelation
490 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
491 * column definitions which recreate the user defined column portions of
495 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
496 InhRelation *inhRelation)
498 AttrNumber parent_attno;
503 bool including_defaults = false;
504 bool including_constraints = false;
505 bool including_indexes = false;
508 relation = heap_openrv(inhRelation->relation, AccessShareLock);
510 if (relation->rd_rel->relkind != RELKIND_RELATION)
512 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
513 errmsg("inherited relation \"%s\" is not a table",
514 inhRelation->relation->relname)));
517 * Check for SELECT privilages
519 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
521 if (aclresult != ACLCHECK_OK)
522 aclcheck_error(aclresult, ACL_KIND_CLASS,
523 RelationGetRelationName(relation));
525 tupleDesc = RelationGetDescr(relation);
526 constr = tupleDesc->constr;
528 foreach(elem, inhRelation->options)
530 int option = lfirst_int(elem);
534 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
535 including_defaults = true;
537 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
538 including_defaults = false;
540 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
541 including_constraints = true;
543 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
544 including_constraints = false;
546 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
547 including_indexes = true;
549 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
550 including_indexes = false;
553 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
558 if (including_indexes)
560 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
561 errmsg("LIKE INCLUDING INDEXES is not implemented")));
564 * Insert the copied attributes into the cxt for the new table
567 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
570 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
571 char *attributeName = NameStr(attribute->attname);
575 * Ignore dropped columns in the parent.
577 if (attribute->attisdropped)
581 * Create a new column, which is marked as NOT inherited.
583 * For constraints, ONLY the NOT NULL constraint is inherited by the
584 * new column definition per SQL99.
586 def = makeNode(ColumnDef);
587 def->colname = pstrdup(attributeName);
588 def->typename = makeTypeNameFromOid(attribute->atttypid,
589 attribute->atttypmod);
591 def->is_local = true;
592 def->is_not_null = attribute->attnotnull;
593 def->raw_default = NULL;
594 def->cooked_default = NULL;
595 def->constraints = NIL;
600 cxt->columns = lappend(cxt->columns, def);
603 * Copy default, if present and the default has been requested
605 if (attribute->atthasdef && including_defaults)
607 char *this_default = NULL;
608 AttrDefault *attrdef;
611 /* Find default in constraint structure */
612 Assert(constr != NULL);
613 attrdef = constr->defval;
614 for (i = 0; i < constr->num_defval; i++)
616 if (attrdef[i].adnum == parent_attno)
618 this_default = attrdef[i].adbin;
622 Assert(this_default != NULL);
625 * If default expr could contain any vars, we'd need to fix 'em,
626 * but it can't; so default is ready to apply to child.
629 def->cooked_default = pstrdup(this_default);
634 * Copy CHECK constraints if requested, being careful to adjust
637 if (including_constraints && tupleDesc->constr)
639 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
642 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
644 char *ccname = tupleDesc->constr->check[ccnum].ccname;
645 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
646 Node *ccbin_node = stringToNode(ccbin);
647 Constraint *n = makeNode(Constraint);
649 change_varattnos_of_a_node(ccbin_node, attmap);
651 n->contype = CONSTR_CHECK;
652 n->name = pstrdup(ccname);
654 n->cooked_expr = nodeToString(ccbin_node);
655 n->indexspace = NULL;
656 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
661 * Close the parent rel, but keep our AccessShareLock on it until xact
662 * commit. That will prevent someone else from deleting or ALTERing the
663 * parent before the child is committed.
665 heap_close(relation, NoLock);
669 * transformIndexConstraints
670 * Handle UNIQUE and PRIMARY KEY constraints, which create indexes
673 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
676 List *indexlist = NIL;
681 * Run through the constraints that need to generate an index. For PRIMARY
682 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
683 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
685 foreach(listptr, cxt->ixconstraints)
687 Constraint *constraint = lfirst(listptr);
691 Assert(IsA(constraint, Constraint));
692 Assert((constraint->contype == CONSTR_PRIMARY)
693 || (constraint->contype == CONSTR_UNIQUE));
695 index = makeNode(IndexStmt);
697 index->unique = true;
698 index->primary = (constraint->contype == CONSTR_PRIMARY);
701 if (cxt->pkey != NULL)
703 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
704 errmsg("multiple primary keys for table \"%s\" are not allowed",
705 cxt->relation->relname)));
709 * In ALTER TABLE case, a primary index might already exist, but
710 * DefineIndex will check for it.
713 index->isconstraint = true;
715 if (constraint->name != NULL)
716 index->idxname = pstrdup(constraint->name);
718 index->idxname = NULL; /* DefineIndex will choose name */
720 index->relation = cxt->relation;
721 index->accessMethod = DEFAULT_INDEX_TYPE;
722 index->options = constraint->options;
723 index->tableSpace = constraint->indexspace;
724 index->indexParams = NIL;
725 index->whereClause = NULL;
726 index->concurrent = false;
729 * Make sure referenced keys exist. If we are making a PRIMARY KEY
730 * index, also make sure they are NOT NULL, if possible. (Although we
731 * could leave it to DefineIndex to mark the columns NOT NULL, it's
732 * more efficient to get it right the first time.)
734 foreach(keys, constraint->keys)
736 char *key = strVal(lfirst(keys));
738 ColumnDef *column = NULL;
741 foreach(columns, cxt->columns)
743 column = (ColumnDef *) lfirst(columns);
744 Assert(IsA(column, ColumnDef));
745 if (strcmp(column->colname, key) == 0)
753 /* found column in the new table; force it to be NOT NULL */
754 if (constraint->contype == CONSTR_PRIMARY)
755 column->is_not_null = TRUE;
757 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
760 * column will be a system column in the new table, so accept
761 * it. System columns can't ever be null, so no need to worry
762 * about PRIMARY/NOT NULL constraint.
766 else if (cxt->inhRelations)
768 /* try inherited tables */
771 foreach(inher, cxt->inhRelations)
773 RangeVar *inh = (RangeVar *) lfirst(inher);
777 Assert(IsA(inh, RangeVar));
778 rel = heap_openrv(inh, AccessShareLock);
779 if (rel->rd_rel->relkind != RELKIND_RELATION)
781 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
782 errmsg("inherited relation \"%s\" is not a table",
784 for (count = 0; count < rel->rd_att->natts; count++)
786 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
787 char *inhname = NameStr(inhattr->attname);
789 if (inhattr->attisdropped)
791 if (strcmp(key, inhname) == 0)
796 * We currently have no easy way to force an
797 * inherited column to be NOT NULL at creation, if
798 * its parent wasn't so already. We leave it to
799 * DefineIndex to fix things up in this case.
804 heap_close(rel, NoLock);
811 * In the ALTER TABLE case, don't complain about index keys not
812 * created in the command; they may well exist already.
813 * DefineIndex will complain about them if not, and will also take
814 * care of marking them NOT NULL.
816 if (!found && !cxt->isalter)
818 (errcode(ERRCODE_UNDEFINED_COLUMN),
819 errmsg("column \"%s\" named in key does not exist",
822 /* Check for PRIMARY KEY(foo, foo) */
823 foreach(columns, index->indexParams)
825 iparam = (IndexElem *) lfirst(columns);
826 if (iparam->name && strcmp(key, iparam->name) == 0)
830 (errcode(ERRCODE_DUPLICATE_COLUMN),
831 errmsg("column \"%s\" appears twice in primary key constraint",
835 (errcode(ERRCODE_DUPLICATE_COLUMN),
836 errmsg("column \"%s\" appears twice in unique constraint",
841 /* OK, add it to the index definition */
842 iparam = makeNode(IndexElem);
843 iparam->name = pstrdup(key);
845 iparam->opclass = NIL;
846 iparam->ordering = SORTBY_DEFAULT;
847 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
848 index->indexParams = lappend(index->indexParams, iparam);
851 indexlist = lappend(indexlist, index);
855 * Scan the index list and remove any redundant index specifications. This
856 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
857 * strict reading of SQL92 would suggest raising an error instead, but
858 * that strikes me as too anal-retentive. - tgl 2001-02-14
860 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
861 * pre-existing indexes, too.
863 Assert(cxt->alist == NIL);
864 if (cxt->pkey != NULL)
866 /* Make sure we keep the PKEY index in preference to others... */
867 cxt->alist = list_make1(cxt->pkey);
870 foreach(l, indexlist)
877 /* if it's pkey, it's already in cxt->alist */
878 if (index == cxt->pkey)
881 foreach(k, cxt->alist)
883 IndexStmt *priorindex = lfirst(k);
885 if (equal(index->indexParams, priorindex->indexParams))
888 * If the prior index is as yet unnamed, and this one is
889 * named, then transfer the name to the prior index. This
890 * ensures that if we have named and unnamed constraints,
891 * we'll use (at least one of) the names for the index.
893 if (priorindex->idxname == NULL)
894 priorindex->idxname = index->idxname;
901 cxt->alist = lappend(cxt->alist, index);
906 * transformFKConstraints
907 * handle FOREIGN KEY constraints
910 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
911 bool skipValidation, bool isAddConstraint)
915 if (cxt->fkconstraints == NIL)
919 * If CREATE TABLE or adding a column with NULL default, we can safely
920 * skip validation of the constraint.
924 foreach(fkclist, cxt->fkconstraints)
926 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
928 fkconstraint->skip_validation = true;
933 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
934 * CONSTRAINT command to execute after the basic command is complete. (If
935 * called from ADD CONSTRAINT, that routine will add the FK constraints to
936 * its own subcommand list.)
938 * Note: the ADD CONSTRAINT command must also execute after any index
939 * creation commands. Thus, this should run after
940 * transformIndexConstraints, so that the CREATE INDEX commands are
941 * already in cxt->alist.
943 if (!isAddConstraint)
945 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
947 alterstmt->relation = cxt->relation;
948 alterstmt->cmds = NIL;
949 alterstmt->relkind = OBJECT_TABLE;
951 foreach(fkclist, cxt->fkconstraints)
953 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
954 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
956 altercmd->subtype = AT_ProcessedConstraint;
957 altercmd->name = NULL;
958 altercmd->def = (Node *) fkconstraint;
959 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
962 cxt->alist = lappend(cxt->alist, alterstmt);
967 * transformIndexStmt - parse analysis for CREATE INDEX
969 * Note: this is a no-op for an index not using either index expressions or
970 * a predicate expression. There are several code paths that create indexes
971 * without bothering to call this, because they know they don't have any
972 * such expressions to deal with.
975 transformIndexStmt(IndexStmt *stmt, const char *queryString)
983 * We must not scribble on the passed-in IndexStmt, so copy it. (This
984 * is overkill, but easy.)
986 stmt = (IndexStmt *) copyObject(stmt);
989 * Open the parent table with appropriate locking. We must do this
990 * because addRangeTableEntry() would acquire only AccessShareLock,
991 * leaving DefineIndex() needing to do a lock upgrade with consequent
992 * risk of deadlock. Make sure this stays in sync with the type of
993 * lock DefineIndex() wants.
995 rel = heap_openrv(stmt->relation,
996 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
999 pstate = make_parsestate(NULL);
1000 pstate->p_sourcetext = queryString;
1003 * Put the parent table into the rtable so that the expressions can
1004 * refer to its fields without qualification.
1006 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1008 /* no to join list, yes to namespaces */
1009 addRTEtoQuery(pstate, rte, false, true, true);
1011 /* take care of the where clause */
1012 if (stmt->whereClause)
1013 stmt->whereClause = transformWhereClause(pstate,
1017 /* take care of any index expressions */
1018 foreach(l, stmt->indexParams)
1020 IndexElem *ielem = (IndexElem *) lfirst(l);
1024 ielem->expr = transformExpr(pstate, ielem->expr);
1027 * We check only that the result type is legitimate; this is for
1028 * consistency with what transformWhereClause() checks for the
1029 * predicate. DefineIndex() will make more checks.
1031 if (expression_returns_set(ielem->expr))
1033 (errcode(ERRCODE_DATATYPE_MISMATCH),
1034 errmsg("index expression cannot return a set")));
1039 * Check that only the base rel is mentioned.
1041 if (list_length(pstate->p_rtable) != 1)
1043 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1044 errmsg("index expressions and predicates can refer only to the table being indexed")));
1046 free_parsestate(pstate);
1048 /* Close relation, but keep the lock */
1049 heap_close(rel, NoLock);
1056 * transformRuleStmt -
1057 * transform a CREATE RULE Statement. The action is a list of parse
1058 * trees which is transformed into a list of query trees, and we also
1059 * transform the WHERE clause if any.
1061 * actions and whereClause are output parameters that receive the
1062 * transformed results.
1064 * Note that we must not scribble on the passed-in RuleStmt, so we do
1065 * copyObject() on the actions and WHERE clause.
1068 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1069 List **actions, Node **whereClause)
1073 RangeTblEntry *oldrte;
1074 RangeTblEntry *newrte;
1077 * To avoid deadlock, make sure the first thing we do is grab
1078 * AccessExclusiveLock on the target relation. This will be needed by
1079 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1082 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1085 pstate = make_parsestate(NULL);
1086 pstate->p_sourcetext = queryString;
1089 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1090 * Set up their RTEs in the main pstate for use in parsing the rule
1093 oldrte = addRangeTableEntryForRelation(pstate, rel,
1094 makeAlias("*OLD*", NIL),
1096 newrte = addRangeTableEntryForRelation(pstate, rel,
1097 makeAlias("*NEW*", NIL),
1099 /* Must override addRangeTableEntry's default access-check flags */
1100 oldrte->requiredPerms = 0;
1101 newrte->requiredPerms = 0;
1104 * They must be in the namespace too for lookup purposes, but only add the
1105 * one(s) that are relevant for the current kind of rule. In an UPDATE
1106 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1107 * there's no need to be so picky for INSERT & DELETE. We do not add them
1110 switch (stmt->event)
1113 addRTEtoQuery(pstate, oldrte, false, true, true);
1116 addRTEtoQuery(pstate, oldrte, false, true, true);
1117 addRTEtoQuery(pstate, newrte, false, true, true);
1120 addRTEtoQuery(pstate, newrte, false, true, true);
1123 addRTEtoQuery(pstate, oldrte, false, true, true);
1126 elog(ERROR, "unrecognized event type: %d",
1131 /* take care of the where clause */
1132 *whereClause = transformWhereClause(pstate,
1133 (Node *) copyObject(stmt->whereClause),
1136 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1138 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1139 errmsg("rule WHERE condition cannot contain references to other relations")));
1141 /* aggregates not allowed (but subselects are okay) */
1142 if (pstate->p_hasAggs)
1144 (errcode(ERRCODE_GROUPING_ERROR),
1145 errmsg("cannot use aggregate function in rule WHERE condition")));
1148 * 'instead nothing' rules with a qualification need a query rangetable so
1149 * the rewrite handler can add the negated rule qualification to the
1150 * original query. We create a query with the new command type CMD_NOTHING
1151 * here that is treated specially by the rewrite system.
1153 if (stmt->actions == NIL)
1155 Query *nothing_qry = makeNode(Query);
1157 nothing_qry->commandType = CMD_NOTHING;
1158 nothing_qry->rtable = pstate->p_rtable;
1159 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1161 *actions = list_make1(nothing_qry);
1166 List *newactions = NIL;
1169 * transform each statement, like parse_sub_analyze()
1171 foreach(l, stmt->actions)
1173 Node *action = (Node *) lfirst(l);
1174 ParseState *sub_pstate = make_parsestate(NULL);
1181 * Since outer ParseState isn't parent of inner, have to pass
1182 * down the query text by hand.
1184 sub_pstate->p_sourcetext = queryString;
1187 * Set up OLD/NEW in the rtable for this statement. The entries
1188 * are added only to relnamespace, not varnamespace, because we
1189 * don't want them to be referred to by unqualified field names
1190 * nor "*" in the rule actions. We decide later whether to put
1191 * them in the joinlist.
1193 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1194 makeAlias("*OLD*", NIL),
1196 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1197 makeAlias("*NEW*", NIL),
1199 oldrte->requiredPerms = 0;
1200 newrte->requiredPerms = 0;
1201 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1202 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1204 /* Transform the rule action statement */
1205 top_subqry = transformStmt(sub_pstate,
1206 (Node *) copyObject(action));
1209 * We cannot support utility-statement actions (eg NOTIFY) with
1210 * nonempty rule WHERE conditions, because there's no way to make
1211 * the utility action execute conditionally.
1213 if (top_subqry->commandType == CMD_UTILITY &&
1214 *whereClause != NULL)
1216 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1217 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1220 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1221 * into the SELECT, and that's what we need to look at. (Ugly
1222 * kluge ... try to fix this when we redesign querytrees.)
1224 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1227 * If the sub_qry is a setop, we cannot attach any qualifications
1228 * to it, because the planner won't notice them. This could
1229 * perhaps be relaxed someday, but for now, we may as well reject
1230 * such a rule immediately.
1232 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1235 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1238 * Validate action's use of OLD/NEW, qual too
1241 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1242 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1244 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1245 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1247 switch (stmt->event)
1252 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1253 errmsg("ON SELECT rule cannot use OLD")));
1256 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1257 errmsg("ON SELECT rule cannot use NEW")));
1265 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1266 errmsg("ON INSERT rule cannot use OLD")));
1271 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1272 errmsg("ON DELETE rule cannot use NEW")));
1275 elog(ERROR, "unrecognized event type: %d",
1281 * For efficiency's sake, add OLD to the rule action's jointree
1282 * only if it was actually referenced in the statement or qual.
1284 * For INSERT, NEW is not really a relation (only a reference to
1285 * the to-be-inserted tuple) and should never be added to the
1288 * For UPDATE, we treat NEW as being another kind of reference to
1289 * OLD, because it represents references to *transformed* tuples
1290 * of the existing relation. It would be wrong to enter NEW
1291 * separately in the jointree, since that would cause a double
1292 * join of the updated relation. It's also wrong to fail to make
1293 * a jointree entry if only NEW and not OLD is mentioned.
1295 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1298 * If sub_qry is a setop, manipulating its jointree will do no
1299 * good at all, because the jointree is dummy. (This should be
1300 * a can't-happen case because of prior tests.)
1302 if (sub_qry->setOperations != NULL)
1304 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1305 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1306 /* hack so we can use addRTEtoQuery() */
1307 sub_pstate->p_rtable = sub_qry->rtable;
1308 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1309 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1310 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1313 newactions = lappend(newactions, top_subqry);
1315 free_parsestate(sub_pstate);
1318 *actions = newactions;
1321 free_parsestate(pstate);
1323 /* Close relation, but keep the exclusive lock */
1324 heap_close(rel, NoLock);
1329 * transformAlterTableStmt -
1330 * parse analysis for ALTER TABLE
1332 * Returns a List of utility commands to be done in sequence. One of these
1333 * will be the transformed AlterTableStmt, but there may be additional actions
1334 * to be done before and after the actual AlterTable() call.
1337 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1341 CreateStmtContext cxt;
1346 List *newcmds = NIL;
1347 bool skipValidation = true;
1348 AlterTableCmd *newcmd;
1351 * We must not scribble on the passed-in AlterTableStmt, so copy it.
1352 * (This is overkill, but easy.)
1354 stmt = (AlterTableStmt *) copyObject(stmt);
1357 * Acquire exclusive lock on the target relation, which will be held
1358 * until end of transaction. This ensures any decisions we make here
1359 * based on the state of the relation will still be good at execution.
1360 * We must get exclusive lock now because execution will; taking a lower
1361 * grade lock now and trying to upgrade later risks deadlock.
1363 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1366 pstate = make_parsestate(NULL);
1367 pstate->p_sourcetext = queryString;
1369 cxt.stmtType = "ALTER TABLE";
1370 cxt.relation = stmt->relation;
1372 cxt.inhRelations = NIL;
1374 cxt.hasoids = false; /* need not be right */
1376 cxt.ckconstraints = NIL;
1377 cxt.fkconstraints = NIL;
1378 cxt.ixconstraints = NIL;
1384 * The only subtypes that currently require parse transformation handling
1385 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1388 foreach(lcmd, stmt->cmds)
1390 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1392 switch (cmd->subtype)
1396 ColumnDef *def = (ColumnDef *) cmd->def;
1398 Assert(IsA(cmd->def, ColumnDef));
1399 transformColumnDefinition(pstate, &cxt,
1400 (ColumnDef *) cmd->def);
1403 * If the column has a non-null default, we can't skip
1404 * validation of foreign keys.
1406 if (((ColumnDef *) cmd->def)->raw_default != NULL)
1407 skipValidation = false;
1409 newcmds = lappend(newcmds, cmd);
1412 * Convert an ADD COLUMN ... NOT NULL constraint to a
1415 if (def->is_not_null)
1417 /* Remove NOT NULL from AddColumn */
1418 def->is_not_null = false;
1420 /* Add as a separate AlterTableCmd */
1421 newcmd = makeNode(AlterTableCmd);
1422 newcmd->subtype = AT_SetNotNull;
1423 newcmd->name = pstrdup(def->colname);
1424 newcmds = lappend(newcmds, newcmd);
1428 * All constraints are processed in other ways. Remove the
1431 def->constraints = NIL;
1435 case AT_AddConstraint:
1438 * The original AddConstraint cmd node doesn't go to newcmds
1441 if (IsA(cmd->def, Constraint))
1442 transformTableConstraint(pstate, &cxt,
1443 (Constraint *) cmd->def);
1444 else if (IsA(cmd->def, FkConstraint))
1446 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1447 skipValidation = false;
1450 elog(ERROR, "unrecognized node type: %d",
1451 (int) nodeTag(cmd->def));
1454 case AT_ProcessedConstraint:
1457 * Already-transformed ADD CONSTRAINT, so just make it look
1458 * like the standard case.
1460 cmd->subtype = AT_AddConstraint;
1461 newcmds = lappend(newcmds, cmd);
1465 newcmds = lappend(newcmds, cmd);
1471 * transformIndexConstraints wants cxt.alist to contain only index
1472 * statements, so transfer anything we already have into save_alist.
1475 save_alist = cxt.alist;
1478 /* Postprocess index and FK constraints */
1479 transformIndexConstraints(pstate, &cxt);
1481 transformFKConstraints(pstate, &cxt, skipValidation, true);
1484 * Push any index-creation commands into the ALTER, so that they can be
1485 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1486 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1487 * through transformIndexStmt.
1489 foreach(l, cxt.alist)
1491 Node *idxstmt = (Node *) lfirst(l);
1493 Assert(IsA(idxstmt, IndexStmt));
1494 newcmd = makeNode(AlterTableCmd);
1495 newcmd->subtype = AT_AddIndex;
1496 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1498 newcmds = lappend(newcmds, newcmd);
1502 /* Append any CHECK or FK constraints to the commands list */
1503 foreach(l, cxt.ckconstraints)
1505 newcmd = makeNode(AlterTableCmd);
1506 newcmd->subtype = AT_AddConstraint;
1507 newcmd->def = (Node *) lfirst(l);
1508 newcmds = lappend(newcmds, newcmd);
1510 foreach(l, cxt.fkconstraints)
1512 newcmd = makeNode(AlterTableCmd);
1513 newcmd->subtype = AT_AddConstraint;
1514 newcmd->def = (Node *) lfirst(l);
1515 newcmds = lappend(newcmds, newcmd);
1518 /* Close rel but keep lock */
1519 relation_close(rel, NoLock);
1524 stmt->cmds = newcmds;
1526 result = lappend(cxt.blist, stmt);
1527 result = list_concat(result, cxt.alist);
1528 result = list_concat(result, save_alist);
1535 * Preprocess a list of column constraint clauses
1536 * to attach constraint attributes to their primary constraint nodes
1537 * and detect inconsistent/misplaced constraint attributes.
1539 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
1540 * constraints, but someday they ought to be supported for other constraints.
1543 transformConstraintAttrs(List *constraintList)
1545 Node *lastprimarynode = NULL;
1546 bool saw_deferrability = false;
1547 bool saw_initially = false;
1550 foreach(clist, constraintList)
1552 Node *node = lfirst(clist);
1554 if (!IsA(node, Constraint))
1556 lastprimarynode = node;
1557 /* reset flags for new primary node */
1558 saw_deferrability = false;
1559 saw_initially = false;
1563 Constraint *con = (Constraint *) node;
1565 switch (con->contype)
1567 case CONSTR_ATTR_DEFERRABLE:
1568 if (lastprimarynode == NULL ||
1569 !IsA(lastprimarynode, FkConstraint))
1571 (errcode(ERRCODE_SYNTAX_ERROR),
1572 errmsg("misplaced DEFERRABLE clause")));
1573 if (saw_deferrability)
1575 (errcode(ERRCODE_SYNTAX_ERROR),
1576 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1577 saw_deferrability = true;
1578 ((FkConstraint *) lastprimarynode)->deferrable = true;
1580 case CONSTR_ATTR_NOT_DEFERRABLE:
1581 if (lastprimarynode == NULL ||
1582 !IsA(lastprimarynode, FkConstraint))
1584 (errcode(ERRCODE_SYNTAX_ERROR),
1585 errmsg("misplaced NOT DEFERRABLE clause")));
1586 if (saw_deferrability)
1588 (errcode(ERRCODE_SYNTAX_ERROR),
1589 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1590 saw_deferrability = true;
1591 ((FkConstraint *) lastprimarynode)->deferrable = false;
1592 if (saw_initially &&
1593 ((FkConstraint *) lastprimarynode)->initdeferred)
1595 (errcode(ERRCODE_SYNTAX_ERROR),
1596 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1598 case CONSTR_ATTR_DEFERRED:
1599 if (lastprimarynode == NULL ||
1600 !IsA(lastprimarynode, FkConstraint))
1602 (errcode(ERRCODE_SYNTAX_ERROR),
1603 errmsg("misplaced INITIALLY DEFERRED clause")));
1606 (errcode(ERRCODE_SYNTAX_ERROR),
1607 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1608 saw_initially = true;
1609 ((FkConstraint *) lastprimarynode)->initdeferred = true;
1612 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1614 if (!saw_deferrability)
1615 ((FkConstraint *) lastprimarynode)->deferrable = true;
1616 else if (!((FkConstraint *) lastprimarynode)->deferrable)
1618 (errcode(ERRCODE_SYNTAX_ERROR),
1619 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1621 case CONSTR_ATTR_IMMEDIATE:
1622 if (lastprimarynode == NULL ||
1623 !IsA(lastprimarynode, FkConstraint))
1625 (errcode(ERRCODE_SYNTAX_ERROR),
1626 errmsg("misplaced INITIALLY IMMEDIATE clause")));
1629 (errcode(ERRCODE_SYNTAX_ERROR),
1630 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1631 saw_initially = true;
1632 ((FkConstraint *) lastprimarynode)->initdeferred = false;
1635 /* Otherwise it's not an attribute */
1636 lastprimarynode = node;
1637 /* reset flags for new primary node */
1638 saw_deferrability = false;
1639 saw_initially = false;
1647 * Special handling of type definition for a column
1650 transformColumnType(ParseState *pstate, ColumnDef *column)
1653 * All we really need to do here is verify that the type is valid.
1655 Type ctype = typenameType(pstate, column->typename);
1657 ReleaseSysCache(ctype);
1662 * transformCreateSchemaStmt -
1663 * analyzes the CREATE SCHEMA statement
1665 * Split the schema element list into individual commands and place
1666 * them in the result list in an order such that there are no forward
1667 * references (e.g. GRANT to a table created later in the list). Note
1668 * that the logic we use for determining forward references is
1669 * presently quite incomplete.
1671 * SQL92 also allows constraints to make forward references, so thumb through
1672 * the table columns and move forward references to a posterior alter-table
1675 * The result is a list of parse nodes that still need to be analyzed ---
1676 * but we can't analyze the later commands until we've executed the earlier
1677 * ones, because of possible inter-object references.
1679 * Note: this breaks the rules a little bit by modifying schema-name fields
1680 * within passed-in structs. However, the transformation would be the same
1681 * if done over, so it should be all right to scribble on the input to this
1685 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
1687 CreateSchemaStmtContext cxt;
1691 cxt.stmtType = "CREATE SCHEMA";
1692 cxt.schemaname = stmt->schemaname;
1693 cxt.authid = stmt->authid;
1694 cxt.sequences = NIL;
1702 * Run through each schema element in the schema element list. Separate
1703 * statements by type, and do preliminary analysis.
1705 foreach(elements, stmt->schemaElts)
1707 Node *element = lfirst(elements);
1709 switch (nodeTag(element))
1711 case T_CreateSeqStmt:
1713 CreateSeqStmt *elp = (CreateSeqStmt *) element;
1715 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
1716 cxt.sequences = lappend(cxt.sequences, element);
1722 CreateStmt *elp = (CreateStmt *) element;
1724 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
1727 * XXX todo: deal with constraints
1729 cxt.tables = lappend(cxt.tables, element);
1735 ViewStmt *elp = (ViewStmt *) element;
1737 setSchemaName(cxt.schemaname, &elp->view->schemaname);
1740 * XXX todo: deal with references between views
1742 cxt.views = lappend(cxt.views, element);
1748 IndexStmt *elp = (IndexStmt *) element;
1750 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
1751 cxt.indexes = lappend(cxt.indexes, element);
1755 case T_CreateTrigStmt:
1757 CreateTrigStmt *elp = (CreateTrigStmt *) element;
1759 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
1760 cxt.triggers = lappend(cxt.triggers, element);
1765 cxt.grants = lappend(cxt.grants, element);
1769 elog(ERROR, "unrecognized node type: %d",
1770 (int) nodeTag(element));
1775 result = list_concat(result, cxt.sequences);
1776 result = list_concat(result, cxt.tables);
1777 result = list_concat(result, cxt.views);
1778 result = list_concat(result, cxt.indexes);
1779 result = list_concat(result, cxt.triggers);
1780 result = list_concat(result, cxt.grants);
1787 * Set or check schema name in an element of a CREATE SCHEMA command
1790 setSchemaName(char *context_schema, char **stmt_schema_name)
1792 if (*stmt_schema_name == NULL)
1793 *stmt_schema_name = context_schema;
1794 else if (strcmp(context_schema, *stmt_schema_name) != 0)
1796 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
1797 errmsg("CREATE specifies a schema (%s) "
1798 "different from the one being created (%s)",
1799 *stmt_schema_name, context_schema)));