Fix oversight in previous error-reporting patch; mustn't pfree path string
[PostgreSQL.git] / src / backend / parser / parse_utilcmd.c
blobecc40f72c4d216767e548fc00f73140a1f5a4f62
1 /*-------------------------------------------------------------------------
3 * parse_utilcmd.c
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-2008, PostgreSQL Global Development Group
20 * Portions Copyright (c) 1994, Regents of the University of California
22 * $PostgreSQL$
24 *-------------------------------------------------------------------------
27 #include "postgres.h"
29 #include "access/genam.h"
30 #include "access/heapam.h"
31 #include "access/reloptions.h"
32 #include "catalog/dependency.h"
33 #include "catalog/heap.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_opclass.h"
37 #include "catalog/pg_type.h"
38 #include "commands/defrem.h"
39 #include "commands/tablecmds.h"
40 #include "commands/tablespace.h"
41 #include "miscadmin.h"
42 #include "nodes/makefuncs.h"
43 #include "nodes/nodeFuncs.h"
44 #include "parser/analyze.h"
45 #include "parser/gramparse.h"
46 #include "parser/parse_clause.h"
47 #include "parser/parse_expr.h"
48 #include "parser/parse_relation.h"
49 #include "parser/parse_type.h"
50 #include "parser/parse_utilcmd.h"
51 #include "rewrite/rewriteManip.h"
52 #include "utils/acl.h"
53 #include "utils/builtins.h"
54 #include "utils/lsyscache.h"
55 #include "utils/relcache.h"
56 #include "utils/syscache.h"
59 /* State shared by transformCreateStmt and its subroutines */
60 typedef struct
62 const char *stmtType; /* "CREATE TABLE" or "ALTER TABLE" */
63 RangeVar *relation; /* relation to create */
64 Relation rel; /* opened/locked rel, if ALTER */
65 List *inhRelations; /* relations to inherit from */
66 bool isalter; /* true if altering existing table */
67 bool hasoids; /* does relation have an OID column? */
68 List *columns; /* ColumnDef items */
69 List *ckconstraints; /* CHECK constraints */
70 List *fkconstraints; /* FOREIGN KEY constraints */
71 List *ixconstraints; /* index-creating constraints */
72 List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
73 List *blist; /* "before list" of things to do before
74 * creating the table */
75 List *alist; /* "after list" of things to do after creating
76 * the table */
77 IndexStmt *pkey; /* PRIMARY KEY index, if any */
78 } CreateStmtContext;
80 /* State shared by transformCreateSchemaStmt and its subroutines */
81 typedef struct
83 const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
84 char *schemaname; /* name of schema */
85 char *authid; /* owner of schema */
86 List *sequences; /* CREATE SEQUENCE items */
87 List *tables; /* CREATE TABLE items */
88 List *views; /* CREATE VIEW items */
89 List *indexes; /* CREATE INDEX items */
90 List *triggers; /* CREATE TRIGGER items */
91 List *grants; /* GRANT items */
92 } CreateSchemaStmtContext;
95 static void transformColumnDefinition(ParseState *pstate,
96 CreateStmtContext *cxt,
97 ColumnDef *column);
98 static void transformTableConstraint(ParseState *pstate,
99 CreateStmtContext *cxt,
100 Constraint *constraint);
101 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
102 InhRelation *inhrelation);
103 static IndexStmt *generateClonedIndexStmt(CreateStmtContext *cxt,
104 Relation parent_index, AttrNumber *attmap);
105 static List *get_opclass(Oid opclass, Oid actual_datatype);
106 static void transformIndexConstraints(ParseState *pstate,
107 CreateStmtContext *cxt);
108 static IndexStmt *transformIndexConstraint(Constraint *constraint,
109 CreateStmtContext *cxt);
110 static void transformFKConstraints(ParseState *pstate,
111 CreateStmtContext *cxt,
112 bool skipValidation,
113 bool isAddConstraint);
114 static void transformConstraintAttrs(List *constraintList);
115 static void transformColumnType(ParseState *pstate, ColumnDef *column);
116 static void setSchemaName(char *context_schema, char **stmt_schema_name);
120 * transformCreateStmt -
121 * parse analysis for CREATE TABLE
123 * Returns a List of utility commands to be done in sequence. One of these
124 * will be the transformed CreateStmt, but there may be additional actions
125 * to be done before and after the actual DefineRelation() call.
127 * SQL92 allows constraints to be scattered all over, so thumb through
128 * the columns and collect all constraints into one place.
129 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
130 * then expand those into multiple IndexStmt blocks.
131 * - thomas 1997-12-02
133 List *
134 transformCreateStmt(CreateStmt *stmt, const char *queryString)
136 ParseState *pstate;
137 CreateStmtContext cxt;
138 List *result;
139 List *save_alist;
140 ListCell *elements;
143 * We must not scribble on the passed-in CreateStmt, so copy it. (This is
144 * overkill, but easy.)
146 stmt = (CreateStmt *) copyObject(stmt);
149 * If the target relation name isn't schema-qualified, make it so. This
150 * prevents some corner cases in which added-on rewritten commands might
151 * think they should apply to other relations that have the same name and
152 * are earlier in the search path. "istemp" is equivalent to a
153 * specification of pg_temp, so no need for anything extra in that case.
155 if (stmt->relation->schemaname == NULL && !stmt->relation->istemp)
157 Oid namespaceid = RangeVarGetCreationNamespace(stmt->relation);
159 stmt->relation->schemaname = get_namespace_name(namespaceid);
162 /* Set up pstate */
163 pstate = make_parsestate(NULL);
164 pstate->p_sourcetext = queryString;
166 cxt.stmtType = "CREATE TABLE";
167 cxt.relation = stmt->relation;
168 cxt.rel = NULL;
169 cxt.inhRelations = stmt->inhRelations;
170 cxt.isalter = false;
171 cxt.columns = NIL;
172 cxt.ckconstraints = NIL;
173 cxt.fkconstraints = NIL;
174 cxt.ixconstraints = NIL;
175 cxt.inh_indexes = NIL;
176 cxt.blist = NIL;
177 cxt.alist = NIL;
178 cxt.pkey = NULL;
179 cxt.hasoids = interpretOidsOption(stmt->options);
182 * Run through each primary element in the table creation clause. Separate
183 * column defs from constraints, and do preliminary analysis.
185 foreach(elements, stmt->tableElts)
187 Node *element = lfirst(elements);
189 switch (nodeTag(element))
191 case T_ColumnDef:
192 transformColumnDefinition(pstate, &cxt,
193 (ColumnDef *) element);
194 break;
196 case T_Constraint:
197 transformTableConstraint(pstate, &cxt,
198 (Constraint *) element);
199 break;
201 case T_FkConstraint:
202 /* No pre-transformation needed */
203 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
204 break;
206 case T_InhRelation:
207 transformInhRelation(pstate, &cxt,
208 (InhRelation *) element);
209 break;
211 default:
212 elog(ERROR, "unrecognized node type: %d",
213 (int) nodeTag(element));
214 break;
219 * transformIndexConstraints wants cxt.alist to contain only index
220 * statements, so transfer anything we already have into save_alist.
222 save_alist = cxt.alist;
223 cxt.alist = NIL;
225 Assert(stmt->constraints == NIL);
228 * Postprocess constraints that give rise to index definitions.
230 transformIndexConstraints(pstate, &cxt);
233 * Postprocess foreign-key constraints.
235 transformFKConstraints(pstate, &cxt, true, false);
238 * Output results.
240 stmt->tableElts = cxt.columns;
241 stmt->constraints = cxt.ckconstraints;
243 result = lappend(cxt.blist, stmt);
244 result = list_concat(result, cxt.alist);
245 result = list_concat(result, save_alist);
247 return result;
251 * transformColumnDefinition -
252 * transform a single ColumnDef within CREATE TABLE
253 * Also used in ALTER TABLE ADD COLUMN
255 static void
256 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
257 ColumnDef *column)
259 bool is_serial;
260 bool saw_nullable;
261 bool saw_default;
262 Constraint *constraint;
263 ListCell *clist;
265 cxt->columns = lappend(cxt->columns, column);
267 /* Check for SERIAL pseudo-types */
268 is_serial = false;
269 if (list_length(column->typename->names) == 1 &&
270 !column->typename->pct_type)
272 char *typname = strVal(linitial(column->typename->names));
274 if (strcmp(typname, "serial") == 0 ||
275 strcmp(typname, "serial4") == 0)
277 is_serial = true;
278 column->typename->names = NIL;
279 column->typename->typeid = INT4OID;
281 else if (strcmp(typname, "bigserial") == 0 ||
282 strcmp(typname, "serial8") == 0)
284 is_serial = true;
285 column->typename->names = NIL;
286 column->typename->typeid = INT8OID;
290 * We have to reject "serial[]" explicitly, because once we've
291 * set typeid, LookupTypeName won't notice arrayBounds. We don't
292 * need any special coding for serial(typmod) though.
294 if (is_serial && column->typename->arrayBounds != NIL)
295 ereport(ERROR,
296 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
297 errmsg("array of serial is not implemented")));
300 /* Do necessary work on the column type declaration */
301 transformColumnType(pstate, column);
303 /* Special actions for SERIAL pseudo-types */
304 if (is_serial)
306 Oid snamespaceid;
307 char *snamespace;
308 char *sname;
309 char *qstring;
310 A_Const *snamenode;
311 TypeCast *castnode;
312 FuncCall *funccallnode;
313 CreateSeqStmt *seqstmt;
314 AlterSeqStmt *altseqstmt;
315 List *attnamelist;
318 * Determine namespace and name to use for the sequence.
320 * Although we use ChooseRelationName, it's not guaranteed that the
321 * selected sequence name won't conflict; given sufficiently long
322 * field names, two different serial columns in the same table could
323 * be assigned the same sequence name, and we'd not notice since we
324 * aren't creating the sequence quite yet. In practice this seems
325 * quite unlikely to be a problem, especially since few people would
326 * need two serial columns in one table.
328 if (cxt->rel)
329 snamespaceid = RelationGetNamespace(cxt->rel);
330 else
331 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
332 snamespace = get_namespace_name(snamespaceid);
333 sname = ChooseRelationName(cxt->relation->relname,
334 column->colname,
335 "seq",
336 snamespaceid);
338 ereport(NOTICE,
339 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
340 cxt->stmtType, sname,
341 cxt->relation->relname, column->colname)));
344 * Build a CREATE SEQUENCE command to create the sequence object, and
345 * add it to the list of things to be done before this CREATE/ALTER
346 * TABLE.
348 seqstmt = makeNode(CreateSeqStmt);
349 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
350 seqstmt->options = NIL;
352 cxt->blist = lappend(cxt->blist, seqstmt);
355 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
356 * as owned by this column, and add it to the list of things to be
357 * done after this CREATE/ALTER TABLE.
359 altseqstmt = makeNode(AlterSeqStmt);
360 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
361 attnamelist = list_make3(makeString(snamespace),
362 makeString(cxt->relation->relname),
363 makeString(column->colname));
364 altseqstmt->options = list_make1(makeDefElem("owned_by",
365 (Node *) attnamelist));
367 cxt->alist = lappend(cxt->alist, altseqstmt);
370 * Create appropriate constraints for SERIAL. We do this in full,
371 * rather than shortcutting, so that we will detect any conflicting
372 * constraints the user wrote (like a different DEFAULT).
374 * Create an expression tree representing the function call
375 * nextval('sequencename'). We cannot reduce the raw tree to cooked
376 * form until after the sequence is created, but there's no need to do
377 * so.
379 qstring = quote_qualified_identifier(snamespace, sname);
380 snamenode = makeNode(A_Const);
381 snamenode->val.type = T_String;
382 snamenode->val.val.str = qstring;
383 snamenode->location = -1;
384 castnode = makeNode(TypeCast);
385 castnode->typename = SystemTypeName("regclass");
386 castnode->arg = (Node *) snamenode;
387 castnode->location = -1;
388 funccallnode = makeNode(FuncCall);
389 funccallnode->funcname = SystemFuncName("nextval");
390 funccallnode->args = list_make1(castnode);
391 funccallnode->agg_star = false;
392 funccallnode->agg_distinct = false;
393 funccallnode->func_variadic = false;
394 funccallnode->location = -1;
396 constraint = makeNode(Constraint);
397 constraint->contype = CONSTR_DEFAULT;
398 constraint->raw_expr = (Node *) funccallnode;
399 constraint->cooked_expr = NULL;
400 constraint->keys = NIL;
401 column->constraints = lappend(column->constraints, constraint);
403 constraint = makeNode(Constraint);
404 constraint->contype = CONSTR_NOTNULL;
405 column->constraints = lappend(column->constraints, constraint);
408 /* Process column constraints, if any... */
409 transformConstraintAttrs(column->constraints);
411 saw_nullable = false;
412 saw_default = false;
414 foreach(clist, column->constraints)
416 constraint = lfirst(clist);
419 * If this column constraint is a FOREIGN KEY constraint, then we fill
420 * in the current attribute's name and throw it into the list of FK
421 * constraints to be processed later.
423 if (IsA(constraint, FkConstraint))
425 FkConstraint *fkconstraint = (FkConstraint *) constraint;
427 fkconstraint->fk_attrs = list_make1(makeString(column->colname));
428 cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
429 continue;
432 Assert(IsA(constraint, Constraint));
434 switch (constraint->contype)
436 case CONSTR_NULL:
437 if (saw_nullable && column->is_not_null)
438 ereport(ERROR,
439 (errcode(ERRCODE_SYNTAX_ERROR),
440 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
441 column->colname, cxt->relation->relname)));
442 column->is_not_null = FALSE;
443 saw_nullable = true;
444 break;
446 case CONSTR_NOTNULL:
447 if (saw_nullable && !column->is_not_null)
448 ereport(ERROR,
449 (errcode(ERRCODE_SYNTAX_ERROR),
450 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
451 column->colname, cxt->relation->relname)));
452 column->is_not_null = TRUE;
453 saw_nullable = true;
454 break;
456 case CONSTR_DEFAULT:
457 if (saw_default)
458 ereport(ERROR,
459 (errcode(ERRCODE_SYNTAX_ERROR),
460 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
461 column->colname, cxt->relation->relname)));
462 column->raw_default = constraint->raw_expr;
463 Assert(constraint->cooked_expr == NULL);
464 saw_default = true;
465 break;
467 case CONSTR_PRIMARY:
468 case CONSTR_UNIQUE:
469 if (constraint->keys == NIL)
470 constraint->keys = list_make1(makeString(column->colname));
471 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
472 break;
474 case CONSTR_CHECK:
475 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
476 break;
478 case CONSTR_ATTR_DEFERRABLE:
479 case CONSTR_ATTR_NOT_DEFERRABLE:
480 case CONSTR_ATTR_DEFERRED:
481 case CONSTR_ATTR_IMMEDIATE:
482 /* transformConstraintAttrs took care of these */
483 break;
485 default:
486 elog(ERROR, "unrecognized constraint type: %d",
487 constraint->contype);
488 break;
494 * transformTableConstraint
495 * transform a Constraint node within CREATE TABLE or ALTER TABLE
497 static void
498 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
499 Constraint *constraint)
501 switch (constraint->contype)
503 case CONSTR_PRIMARY:
504 case CONSTR_UNIQUE:
505 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
506 break;
508 case CONSTR_CHECK:
509 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
510 break;
512 case CONSTR_NULL:
513 case CONSTR_NOTNULL:
514 case CONSTR_DEFAULT:
515 case CONSTR_ATTR_DEFERRABLE:
516 case CONSTR_ATTR_NOT_DEFERRABLE:
517 case CONSTR_ATTR_DEFERRED:
518 case CONSTR_ATTR_IMMEDIATE:
519 elog(ERROR, "invalid context for constraint type %d",
520 constraint->contype);
521 break;
523 default:
524 elog(ERROR, "unrecognized constraint type: %d",
525 constraint->contype);
526 break;
531 * transformInhRelation
533 * Change the LIKE <subtable> portion of a CREATE TABLE statement into
534 * column definitions which recreate the user defined column portions of
535 * <subtable>.
537 static void
538 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
539 InhRelation *inhRelation)
541 AttrNumber parent_attno;
542 Relation relation;
543 TupleDesc tupleDesc;
544 TupleConstr *constr;
545 AclResult aclresult;
546 bool including_defaults = false;
547 bool including_constraints = false;
548 bool including_indexes = false;
549 ListCell *elem;
551 relation = parserOpenTable(pstate, inhRelation->relation, AccessShareLock);
553 if (relation->rd_rel->relkind != RELKIND_RELATION)
554 ereport(ERROR,
555 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
556 errmsg("inherited relation \"%s\" is not a table",
557 inhRelation->relation->relname)));
560 * Check for SELECT privilages
562 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
563 ACL_SELECT);
564 if (aclresult != ACLCHECK_OK)
565 aclcheck_error(aclresult, ACL_KIND_CLASS,
566 RelationGetRelationName(relation));
568 tupleDesc = RelationGetDescr(relation);
569 constr = tupleDesc->constr;
571 foreach(elem, inhRelation->options)
573 int option = lfirst_int(elem);
575 switch (option)
577 case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
578 including_defaults = true;
579 break;
580 case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
581 including_defaults = false;
582 break;
583 case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
584 including_constraints = true;
585 break;
586 case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
587 including_constraints = false;
588 break;
589 case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
590 including_indexes = true;
591 break;
592 case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
593 including_indexes = false;
594 break;
595 default:
596 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
597 option);
602 * Insert the copied attributes into the cxt for the new table definition.
604 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
605 parent_attno++)
607 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
608 char *attributeName = NameStr(attribute->attname);
609 ColumnDef *def;
612 * Ignore dropped columns in the parent.
614 if (attribute->attisdropped)
615 continue;
618 * Create a new column, which is marked as NOT inherited.
620 * For constraints, ONLY the NOT NULL constraint is inherited by the
621 * new column definition per SQL99.
623 def = makeNode(ColumnDef);
624 def->colname = pstrdup(attributeName);
625 def->typename = makeTypeNameFromOid(attribute->atttypid,
626 attribute->atttypmod);
627 def->inhcount = 0;
628 def->is_local = true;
629 def->is_not_null = attribute->attnotnull;
630 def->raw_default = NULL;
631 def->cooked_default = NULL;
632 def->constraints = NIL;
635 * Add to column list
637 cxt->columns = lappend(cxt->columns, def);
640 * Copy default, if present and the default has been requested
642 if (attribute->atthasdef && including_defaults)
644 char *this_default = NULL;
645 AttrDefault *attrdef;
646 int i;
648 /* Find default in constraint structure */
649 Assert(constr != NULL);
650 attrdef = constr->defval;
651 for (i = 0; i < constr->num_defval; i++)
653 if (attrdef[i].adnum == parent_attno)
655 this_default = attrdef[i].adbin;
656 break;
659 Assert(this_default != NULL);
662 * If default expr could contain any vars, we'd need to fix 'em,
663 * but it can't; so default is ready to apply to child.
666 def->cooked_default = pstrdup(this_default);
671 * Copy CHECK constraints if requested, being careful to adjust attribute
672 * numbers
674 if (including_constraints && tupleDesc->constr)
676 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
677 int ccnum;
679 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
681 char *ccname = tupleDesc->constr->check[ccnum].ccname;
682 char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
683 Node *ccbin_node = stringToNode(ccbin);
684 Constraint *n = makeNode(Constraint);
686 change_varattnos_of_a_node(ccbin_node, attmap);
688 n->contype = CONSTR_CHECK;
689 n->name = pstrdup(ccname);
690 n->raw_expr = NULL;
691 n->cooked_expr = nodeToString(ccbin_node);
692 n->indexspace = NULL;
693 cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
698 * Likewise, copy indexes if requested
700 if (including_indexes && relation->rd_rel->relhasindex)
702 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
703 List *parent_indexes;
704 ListCell *l;
706 parent_indexes = RelationGetIndexList(relation);
708 foreach(l, parent_indexes)
710 Oid parent_index_oid = lfirst_oid(l);
711 Relation parent_index;
712 IndexStmt *index_stmt;
714 parent_index = index_open(parent_index_oid, AccessShareLock);
716 /* Build CREATE INDEX statement to recreate the parent_index */
717 index_stmt = generateClonedIndexStmt(cxt, parent_index, attmap);
719 /* Save it in the inh_indexes list for the time being */
720 cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
722 index_close(parent_index, AccessShareLock);
727 * Close the parent rel, but keep our AccessShareLock on it until xact
728 * commit. That will prevent someone else from deleting or ALTERing the
729 * parent before the child is committed.
731 heap_close(relation, NoLock);
735 * Generate an IndexStmt node using information from an already existing index
736 * "source_idx". Attribute numbers should be adjusted according to attmap.
738 static IndexStmt *
739 generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx,
740 AttrNumber *attmap)
742 Oid source_relid = RelationGetRelid(source_idx);
743 HeapTuple ht_idxrel;
744 HeapTuple ht_idx;
745 Form_pg_class idxrelrec;
746 Form_pg_index idxrec;
747 Form_pg_am amrec;
748 oidvector *indclass;
749 IndexStmt *index;
750 List *indexprs;
751 ListCell *indexpr_item;
752 Oid indrelid;
753 int keyno;
754 Oid keycoltype;
755 Datum datum;
756 bool isnull;
759 * Fetch pg_class tuple of source index. We can't use the copy in the
760 * relcache entry because it doesn't include optional fields.
762 ht_idxrel = SearchSysCache(RELOID,
763 ObjectIdGetDatum(source_relid),
764 0, 0, 0);
765 if (!HeapTupleIsValid(ht_idxrel))
766 elog(ERROR, "cache lookup failed for relation %u", source_relid);
767 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
769 /* Fetch pg_index tuple for source index from relcache entry */
770 ht_idx = source_idx->rd_indextuple;
771 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
772 indrelid = idxrec->indrelid;
774 /* Fetch pg_am tuple for source index from relcache entry */
775 amrec = source_idx->rd_am;
777 /* Must get indclass the hard way, since it's not stored in relcache */
778 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
779 Anum_pg_index_indclass, &isnull);
780 Assert(!isnull);
781 indclass = (oidvector *) DatumGetPointer(datum);
783 /* Begin building the IndexStmt */
784 index = makeNode(IndexStmt);
785 index->relation = cxt->relation;
786 index->accessMethod = pstrdup(NameStr(amrec->amname));
787 if (OidIsValid(idxrelrec->reltablespace))
788 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
789 else
790 index->tableSpace = NULL;
791 index->unique = idxrec->indisunique;
792 index->primary = idxrec->indisprimary;
793 index->concurrent = false;
796 * We don't try to preserve the name of the source index; instead, just
797 * let DefineIndex() choose a reasonable name.
799 index->idxname = NULL;
802 * If the index is marked PRIMARY, it's certainly from a constraint;
803 * else, if it's not marked UNIQUE, it certainly isn't; else, we have
804 * to search pg_depend to see if there's an associated unique constraint.
806 if (index->primary)
807 index->isconstraint = true;
808 else if (!index->unique)
809 index->isconstraint = false;
810 else
811 index->isconstraint = OidIsValid(get_index_constraint(source_relid));
813 /* Get the index expressions, if any */
814 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
815 Anum_pg_index_indexprs, &isnull);
816 if (!isnull)
818 char *exprsString;
820 exprsString = TextDatumGetCString(datum);
821 indexprs = (List *) stringToNode(exprsString);
823 else
824 indexprs = NIL;
826 /* Build the list of IndexElem */
827 index->indexParams = NIL;
829 indexpr_item = list_head(indexprs);
830 for (keyno = 0; keyno < idxrec->indnatts; keyno++)
832 IndexElem *iparam;
833 AttrNumber attnum = idxrec->indkey.values[keyno];
834 int16 opt = source_idx->rd_indoption[keyno];
836 iparam = makeNode(IndexElem);
838 if (AttributeNumberIsValid(attnum))
840 /* Simple index column */
841 char *attname;
843 attname = get_relid_attribute_name(indrelid, attnum);
844 keycoltype = get_atttype(indrelid, attnum);
846 iparam->name = attname;
847 iparam->expr = NULL;
849 else
851 /* Expressional index */
852 Node *indexkey;
854 if (indexpr_item == NULL)
855 elog(ERROR, "too few entries in indexprs list");
856 indexkey = (Node *) lfirst(indexpr_item);
857 indexpr_item = lnext(indexpr_item);
859 /* OK to modify indexkey since we are working on a private copy */
860 change_varattnos_of_a_node(indexkey, attmap);
862 iparam->name = NULL;
863 iparam->expr = indexkey;
865 keycoltype = exprType(indexkey);
868 /* Add the operator class name, if non-default */
869 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
871 iparam->ordering = SORTBY_DEFAULT;
872 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
874 /* Adjust options if necessary */
875 if (amrec->amcanorder)
878 * If it supports sort ordering, copy DESC and NULLS opts.
879 * Don't set non-default settings unnecessarily, though,
880 * so as to improve the chance of recognizing equivalence
881 * to constraint indexes.
883 if (opt & INDOPTION_DESC)
885 iparam->ordering = SORTBY_DESC;
886 if ((opt & INDOPTION_NULLS_FIRST) == 0)
887 iparam->nulls_ordering = SORTBY_NULLS_LAST;
889 else
891 if (opt & INDOPTION_NULLS_FIRST)
892 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
896 index->indexParams = lappend(index->indexParams, iparam);
899 /* Copy reloptions if any */
900 datum = SysCacheGetAttr(RELOID, ht_idxrel,
901 Anum_pg_class_reloptions, &isnull);
902 if (!isnull)
903 index->options = untransformRelOptions(datum);
905 /* If it's a partial index, decompile and append the predicate */
906 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
907 Anum_pg_index_indpred, &isnull);
908 if (!isnull)
910 char *pred_str;
912 /* Convert text string to node tree */
913 pred_str = TextDatumGetCString(datum);
914 index->whereClause = (Node *) stringToNode(pred_str);
915 /* Adjust attribute numbers */
916 change_varattnos_of_a_node(index->whereClause, attmap);
919 /* Clean up */
920 ReleaseSysCache(ht_idxrel);
922 return index;
926 * get_opclass - fetch name of an index operator class
928 * If the opclass is the default for the given actual_datatype, then
929 * the return value is NIL.
931 static List *
932 get_opclass(Oid opclass, Oid actual_datatype)
934 HeapTuple ht_opc;
935 Form_pg_opclass opc_rec;
936 List *result = NIL;
938 ht_opc = SearchSysCache(CLAOID,
939 ObjectIdGetDatum(opclass),
940 0, 0, 0);
941 if (!HeapTupleIsValid(ht_opc))
942 elog(ERROR, "cache lookup failed for opclass %u", opclass);
943 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
945 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
947 /* For simplicity, we always schema-qualify the name */
948 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
949 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
951 result = list_make2(makeString(nsp_name), makeString(opc_name));
954 ReleaseSysCache(ht_opc);
955 return result;
960 * transformIndexConstraints
961 * Handle UNIQUE and PRIMARY KEY constraints, which create indexes.
962 * We also merge in any index definitions arising from
963 * LIKE ... INCLUDING INDEXES.
965 static void
966 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
968 IndexStmt *index;
969 List *indexlist = NIL;
970 ListCell *lc;
973 * Run through the constraints that need to generate an index. For PRIMARY
974 * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
975 * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
977 foreach(lc, cxt->ixconstraints)
979 Constraint *constraint = (Constraint *) lfirst(lc);
981 Assert(IsA(constraint, Constraint));
982 Assert(constraint->contype == CONSTR_PRIMARY ||
983 constraint->contype == CONSTR_UNIQUE);
985 index = transformIndexConstraint(constraint, cxt);
987 indexlist = lappend(indexlist, index);
990 /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
991 foreach(lc, cxt->inh_indexes)
993 index = (IndexStmt *) lfirst(lc);
995 if (index->primary)
997 if (cxt->pkey != NULL)
998 ereport(ERROR,
999 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1000 errmsg("multiple primary keys for table \"%s\" are not allowed",
1001 cxt->relation->relname)));
1002 cxt->pkey = index;
1005 indexlist = lappend(indexlist, index);
1009 * Scan the index list and remove any redundant index specifications. This
1010 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1011 * strict reading of SQL92 would suggest raising an error instead, but
1012 * that strikes me as too anal-retentive. - tgl 2001-02-14
1014 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1015 * pre-existing indexes, too.
1017 Assert(cxt->alist == NIL);
1018 if (cxt->pkey != NULL)
1020 /* Make sure we keep the PKEY index in preference to others... */
1021 cxt->alist = list_make1(cxt->pkey);
1024 foreach(lc, indexlist)
1026 bool keep = true;
1027 ListCell *k;
1029 index = lfirst(lc);
1031 /* if it's pkey, it's already in cxt->alist */
1032 if (index == cxt->pkey)
1033 continue;
1035 foreach(k, cxt->alist)
1037 IndexStmt *priorindex = lfirst(k);
1039 if (equal(index->indexParams, priorindex->indexParams) &&
1040 equal(index->whereClause, priorindex->whereClause) &&
1041 strcmp(index->accessMethod, priorindex->accessMethod) == 0)
1043 priorindex->unique |= index->unique;
1045 * If the prior index is as yet unnamed, and this one is
1046 * named, then transfer the name to the prior index. This
1047 * ensures that if we have named and unnamed constraints,
1048 * we'll use (at least one of) the names for the index.
1050 if (priorindex->idxname == NULL)
1051 priorindex->idxname = index->idxname;
1052 keep = false;
1053 break;
1057 if (keep)
1058 cxt->alist = lappend(cxt->alist, index);
1063 * transformIndexConstraint
1064 * Transform one UNIQUE or PRIMARY KEY constraint for
1065 * transformIndexConstraints.
1067 static IndexStmt *
1068 transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
1070 IndexStmt *index;
1071 ListCell *keys;
1072 IndexElem *iparam;
1074 index = makeNode(IndexStmt);
1076 index->unique = true;
1077 index->primary = (constraint->contype == CONSTR_PRIMARY);
1078 if (index->primary)
1080 if (cxt->pkey != NULL)
1081 ereport(ERROR,
1082 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1083 errmsg("multiple primary keys for table \"%s\" are not allowed",
1084 cxt->relation->relname)));
1085 cxt->pkey = index;
1088 * In ALTER TABLE case, a primary index might already exist, but
1089 * DefineIndex will check for it.
1092 index->isconstraint = true;
1094 if (constraint->name != NULL)
1095 index->idxname = pstrdup(constraint->name);
1096 else
1097 index->idxname = NULL; /* DefineIndex will choose name */
1099 index->relation = cxt->relation;
1100 index->accessMethod = DEFAULT_INDEX_TYPE;
1101 index->options = constraint->options;
1102 index->tableSpace = constraint->indexspace;
1103 index->indexParams = NIL;
1104 index->whereClause = NULL;
1105 index->concurrent = false;
1108 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1109 * also make sure they are NOT NULL, if possible. (Although we could leave
1110 * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1111 * get it right the first time.)
1113 foreach(keys, constraint->keys)
1115 char *key = strVal(lfirst(keys));
1116 bool found = false;
1117 ColumnDef *column = NULL;
1118 ListCell *columns;
1120 foreach(columns, cxt->columns)
1122 column = (ColumnDef *) lfirst(columns);
1123 Assert(IsA(column, ColumnDef));
1124 if (strcmp(column->colname, key) == 0)
1126 found = true;
1127 break;
1130 if (found)
1132 /* found column in the new table; force it to be NOT NULL */
1133 if (constraint->contype == CONSTR_PRIMARY)
1134 column->is_not_null = TRUE;
1136 else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1139 * column will be a system column in the new table, so accept it.
1140 * System columns can't ever be null, so no need to worry about
1141 * PRIMARY/NOT NULL constraint.
1143 found = true;
1145 else if (cxt->inhRelations)
1147 /* try inherited tables */
1148 ListCell *inher;
1150 foreach(inher, cxt->inhRelations)
1152 RangeVar *inh = (RangeVar *) lfirst(inher);
1153 Relation rel;
1154 int count;
1156 Assert(IsA(inh, RangeVar));
1157 rel = heap_openrv(inh, AccessShareLock);
1158 if (rel->rd_rel->relkind != RELKIND_RELATION)
1159 ereport(ERROR,
1160 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1161 errmsg("inherited relation \"%s\" is not a table",
1162 inh->relname)));
1163 for (count = 0; count < rel->rd_att->natts; count++)
1165 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1166 char *inhname = NameStr(inhattr->attname);
1168 if (inhattr->attisdropped)
1169 continue;
1170 if (strcmp(key, inhname) == 0)
1172 found = true;
1175 * We currently have no easy way to force an inherited
1176 * column to be NOT NULL at creation, if its parent
1177 * wasn't so already. We leave it to DefineIndex to
1178 * fix things up in this case.
1180 break;
1183 heap_close(rel, NoLock);
1184 if (found)
1185 break;
1190 * In the ALTER TABLE case, don't complain about index keys not
1191 * created in the command; they may well exist already. DefineIndex
1192 * will complain about them if not, and will also take care of marking
1193 * them NOT NULL.
1195 if (!found && !cxt->isalter)
1196 ereport(ERROR,
1197 (errcode(ERRCODE_UNDEFINED_COLUMN),
1198 errmsg("column \"%s\" named in key does not exist",
1199 key)));
1201 /* Check for PRIMARY KEY(foo, foo) */
1202 foreach(columns, index->indexParams)
1204 iparam = (IndexElem *) lfirst(columns);
1205 if (iparam->name && strcmp(key, iparam->name) == 0)
1207 if (index->primary)
1208 ereport(ERROR,
1209 (errcode(ERRCODE_DUPLICATE_COLUMN),
1210 errmsg("column \"%s\" appears twice in primary key constraint",
1211 key)));
1212 else
1213 ereport(ERROR,
1214 (errcode(ERRCODE_DUPLICATE_COLUMN),
1215 errmsg("column \"%s\" appears twice in unique constraint",
1216 key)));
1220 /* OK, add it to the index definition */
1221 iparam = makeNode(IndexElem);
1222 iparam->name = pstrdup(key);
1223 iparam->expr = NULL;
1224 iparam->opclass = NIL;
1225 iparam->ordering = SORTBY_DEFAULT;
1226 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1227 index->indexParams = lappend(index->indexParams, iparam);
1230 return index;
1234 * transformFKConstraints
1235 * handle FOREIGN KEY constraints
1237 static void
1238 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1239 bool skipValidation, bool isAddConstraint)
1241 ListCell *fkclist;
1243 if (cxt->fkconstraints == NIL)
1244 return;
1247 * If CREATE TABLE or adding a column with NULL default, we can safely
1248 * skip validation of the constraint.
1250 if (skipValidation)
1252 foreach(fkclist, cxt->fkconstraints)
1254 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1256 fkconstraint->skip_validation = true;
1261 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1262 * CONSTRAINT command to execute after the basic command is complete. (If
1263 * called from ADD CONSTRAINT, that routine will add the FK constraints to
1264 * its own subcommand list.)
1266 * Note: the ADD CONSTRAINT command must also execute after any index
1267 * creation commands. Thus, this should run after
1268 * transformIndexConstraints, so that the CREATE INDEX commands are
1269 * already in cxt->alist.
1271 if (!isAddConstraint)
1273 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1275 alterstmt->relation = cxt->relation;
1276 alterstmt->cmds = NIL;
1277 alterstmt->relkind = OBJECT_TABLE;
1279 foreach(fkclist, cxt->fkconstraints)
1281 FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1282 AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1284 altercmd->subtype = AT_ProcessedConstraint;
1285 altercmd->name = NULL;
1286 altercmd->def = (Node *) fkconstraint;
1287 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1290 cxt->alist = lappend(cxt->alist, alterstmt);
1295 * transformIndexStmt - parse analysis for CREATE INDEX
1297 * Note: this is a no-op for an index not using either index expressions or
1298 * a predicate expression. There are several code paths that create indexes
1299 * without bothering to call this, because they know they don't have any
1300 * such expressions to deal with.
1302 IndexStmt *
1303 transformIndexStmt(IndexStmt *stmt, const char *queryString)
1305 Relation rel;
1306 ParseState *pstate;
1307 RangeTblEntry *rte;
1308 ListCell *l;
1311 * We must not scribble on the passed-in IndexStmt, so copy it. (This is
1312 * overkill, but easy.)
1314 stmt = (IndexStmt *) copyObject(stmt);
1317 * Open the parent table with appropriate locking. We must do this
1318 * because addRangeTableEntry() would acquire only AccessShareLock,
1319 * leaving DefineIndex() needing to do a lock upgrade with consequent risk
1320 * of deadlock. Make sure this stays in sync with the type of lock
1321 * DefineIndex() wants.
1323 rel = heap_openrv(stmt->relation,
1324 (stmt->concurrent ? ShareUpdateExclusiveLock : ShareLock));
1326 /* Set up pstate */
1327 pstate = make_parsestate(NULL);
1328 pstate->p_sourcetext = queryString;
1331 * Put the parent table into the rtable so that the expressions can refer
1332 * to its fields without qualification.
1334 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1336 /* no to join list, yes to namespaces */
1337 addRTEtoQuery(pstate, rte, false, true, true);
1339 /* take care of the where clause */
1340 if (stmt->whereClause)
1341 stmt->whereClause = transformWhereClause(pstate,
1342 stmt->whereClause,
1343 "WHERE");
1345 /* take care of any index expressions */
1346 foreach(l, stmt->indexParams)
1348 IndexElem *ielem = (IndexElem *) lfirst(l);
1350 if (ielem->expr)
1352 ielem->expr = transformExpr(pstate, ielem->expr);
1355 * We check only that the result type is legitimate; this is for
1356 * consistency with what transformWhereClause() checks for the
1357 * predicate. DefineIndex() will make more checks.
1359 if (expression_returns_set(ielem->expr))
1360 ereport(ERROR,
1361 (errcode(ERRCODE_DATATYPE_MISMATCH),
1362 errmsg("index expression cannot return a set")));
1367 * Check that only the base rel is mentioned.
1369 if (list_length(pstate->p_rtable) != 1)
1370 ereport(ERROR,
1371 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1372 errmsg("index expressions and predicates can refer only to the table being indexed")));
1374 free_parsestate(pstate);
1376 /* Close relation, but keep the lock */
1377 heap_close(rel, NoLock);
1379 return stmt;
1384 * transformRuleStmt -
1385 * transform a CREATE RULE Statement. The action is a list of parse
1386 * trees which is transformed into a list of query trees, and we also
1387 * transform the WHERE clause if any.
1389 * actions and whereClause are output parameters that receive the
1390 * transformed results.
1392 * Note that we must not scribble on the passed-in RuleStmt, so we do
1393 * copyObject() on the actions and WHERE clause.
1395 void
1396 transformRuleStmt(RuleStmt *stmt, const char *queryString,
1397 List **actions, Node **whereClause)
1399 Relation rel;
1400 ParseState *pstate;
1401 RangeTblEntry *oldrte;
1402 RangeTblEntry *newrte;
1405 * To avoid deadlock, make sure the first thing we do is grab
1406 * AccessExclusiveLock on the target relation. This will be needed by
1407 * DefineQueryRewrite(), and we don't want to grab a lesser lock
1408 * beforehand.
1410 rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1412 /* Set up pstate */
1413 pstate = make_parsestate(NULL);
1414 pstate->p_sourcetext = queryString;
1417 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1418 * Set up their RTEs in the main pstate for use in parsing the rule
1419 * qualification.
1421 oldrte = addRangeTableEntryForRelation(pstate, rel,
1422 makeAlias("*OLD*", NIL),
1423 false, false);
1424 newrte = addRangeTableEntryForRelation(pstate, rel,
1425 makeAlias("*NEW*", NIL),
1426 false, false);
1427 /* Must override addRangeTableEntry's default access-check flags */
1428 oldrte->requiredPerms = 0;
1429 newrte->requiredPerms = 0;
1432 * They must be in the namespace too for lookup purposes, but only add the
1433 * one(s) that are relevant for the current kind of rule. In an UPDATE
1434 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1435 * there's no need to be so picky for INSERT & DELETE. We do not add them
1436 * to the joinlist.
1438 switch (stmt->event)
1440 case CMD_SELECT:
1441 addRTEtoQuery(pstate, oldrte, false, true, true);
1442 break;
1443 case CMD_UPDATE:
1444 addRTEtoQuery(pstate, oldrte, false, true, true);
1445 addRTEtoQuery(pstate, newrte, false, true, true);
1446 break;
1447 case CMD_INSERT:
1448 addRTEtoQuery(pstate, newrte, false, true, true);
1449 break;
1450 case CMD_DELETE:
1451 addRTEtoQuery(pstate, oldrte, false, true, true);
1452 break;
1453 default:
1454 elog(ERROR, "unrecognized event type: %d",
1455 (int) stmt->event);
1456 break;
1459 /* take care of the where clause */
1460 *whereClause = transformWhereClause(pstate,
1461 (Node *) copyObject(stmt->whereClause),
1462 "WHERE");
1464 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
1465 ereport(ERROR,
1466 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1467 errmsg("rule WHERE condition cannot contain references to other relations")));
1469 /* aggregates not allowed (but subselects are okay) */
1470 if (pstate->p_hasAggs)
1471 ereport(ERROR,
1472 (errcode(ERRCODE_GROUPING_ERROR),
1473 errmsg("cannot use aggregate function in rule WHERE condition")));
1476 * 'instead nothing' rules with a qualification need a query rangetable so
1477 * the rewrite handler can add the negated rule qualification to the
1478 * original query. We create a query with the new command type CMD_NOTHING
1479 * here that is treated specially by the rewrite system.
1481 if (stmt->actions == NIL)
1483 Query *nothing_qry = makeNode(Query);
1485 nothing_qry->commandType = CMD_NOTHING;
1486 nothing_qry->rtable = pstate->p_rtable;
1487 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
1489 *actions = list_make1(nothing_qry);
1491 else
1493 ListCell *l;
1494 List *newactions = NIL;
1497 * transform each statement, like parse_sub_analyze()
1499 foreach(l, stmt->actions)
1501 Node *action = (Node *) lfirst(l);
1502 ParseState *sub_pstate = make_parsestate(NULL);
1503 Query *sub_qry,
1504 *top_subqry;
1505 bool has_old,
1506 has_new;
1509 * Since outer ParseState isn't parent of inner, have to pass down
1510 * the query text by hand.
1512 sub_pstate->p_sourcetext = queryString;
1515 * Set up OLD/NEW in the rtable for this statement. The entries
1516 * are added only to relnamespace, not varnamespace, because we
1517 * don't want them to be referred to by unqualified field names
1518 * nor "*" in the rule actions. We decide later whether to put
1519 * them in the joinlist.
1521 oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1522 makeAlias("*OLD*", NIL),
1523 false, false);
1524 newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1525 makeAlias("*NEW*", NIL),
1526 false, false);
1527 oldrte->requiredPerms = 0;
1528 newrte->requiredPerms = 0;
1529 addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1530 addRTEtoQuery(sub_pstate, newrte, false, true, false);
1532 /* Transform the rule action statement */
1533 top_subqry = transformStmt(sub_pstate,
1534 (Node *) copyObject(action));
1537 * We cannot support utility-statement actions (eg NOTIFY) with
1538 * nonempty rule WHERE conditions, because there's no way to make
1539 * the utility action execute conditionally.
1541 if (top_subqry->commandType == CMD_UTILITY &&
1542 *whereClause != NULL)
1543 ereport(ERROR,
1544 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1545 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1548 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1549 * into the SELECT, and that's what we need to look at. (Ugly
1550 * kluge ... try to fix this when we redesign querytrees.)
1552 sub_qry = getInsertSelectQuery(top_subqry, NULL);
1555 * If the sub_qry is a setop, we cannot attach any qualifications
1556 * to it, because the planner won't notice them. This could
1557 * perhaps be relaxed someday, but for now, we may as well reject
1558 * such a rule immediately.
1560 if (sub_qry->setOperations != NULL && *whereClause != NULL)
1561 ereport(ERROR,
1562 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1563 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1566 * Validate action's use of OLD/NEW, qual too
1568 has_old =
1569 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1570 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
1571 has_new =
1572 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1573 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
1575 switch (stmt->event)
1577 case CMD_SELECT:
1578 if (has_old)
1579 ereport(ERROR,
1580 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1581 errmsg("ON SELECT rule cannot use OLD")));
1582 if (has_new)
1583 ereport(ERROR,
1584 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1585 errmsg("ON SELECT rule cannot use NEW")));
1586 break;
1587 case CMD_UPDATE:
1588 /* both are OK */
1589 break;
1590 case CMD_INSERT:
1591 if (has_old)
1592 ereport(ERROR,
1593 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1594 errmsg("ON INSERT rule cannot use OLD")));
1595 break;
1596 case CMD_DELETE:
1597 if (has_new)
1598 ereport(ERROR,
1599 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1600 errmsg("ON DELETE rule cannot use NEW")));
1601 break;
1602 default:
1603 elog(ERROR, "unrecognized event type: %d",
1604 (int) stmt->event);
1605 break;
1609 * For efficiency's sake, add OLD to the rule action's jointree
1610 * only if it was actually referenced in the statement or qual.
1612 * For INSERT, NEW is not really a relation (only a reference to
1613 * the to-be-inserted tuple) and should never be added to the
1614 * jointree.
1616 * For UPDATE, we treat NEW as being another kind of reference to
1617 * OLD, because it represents references to *transformed* tuples
1618 * of the existing relation. It would be wrong to enter NEW
1619 * separately in the jointree, since that would cause a double
1620 * join of the updated relation. It's also wrong to fail to make
1621 * a jointree entry if only NEW and not OLD is mentioned.
1623 if (has_old || (has_new && stmt->event == CMD_UPDATE))
1626 * If sub_qry is a setop, manipulating its jointree will do no
1627 * good at all, because the jointree is dummy. (This should be
1628 * a can't-happen case because of prior tests.)
1630 if (sub_qry->setOperations != NULL)
1631 ereport(ERROR,
1632 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1633 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1634 /* hack so we can use addRTEtoQuery() */
1635 sub_pstate->p_rtable = sub_qry->rtable;
1636 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1637 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
1638 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1641 newactions = lappend(newactions, top_subqry);
1643 free_parsestate(sub_pstate);
1646 *actions = newactions;
1649 free_parsestate(pstate);
1651 /* Close relation, but keep the exclusive lock */
1652 heap_close(rel, NoLock);
1657 * transformAlterTableStmt -
1658 * parse analysis for ALTER TABLE
1660 * Returns a List of utility commands to be done in sequence. One of these
1661 * will be the transformed AlterTableStmt, but there may be additional actions
1662 * to be done before and after the actual AlterTable() call.
1664 List *
1665 transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString)
1667 Relation rel;
1668 ParseState *pstate;
1669 CreateStmtContext cxt;
1670 List *result;
1671 List *save_alist;
1672 ListCell *lcmd,
1674 List *newcmds = NIL;
1675 bool skipValidation = true;
1676 AlterTableCmd *newcmd;
1679 * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
1680 * is overkill, but easy.)
1682 stmt = (AlterTableStmt *) copyObject(stmt);
1685 * Acquire exclusive lock on the target relation, which will be held until
1686 * end of transaction. This ensures any decisions we make here based on
1687 * the state of the relation will still be good at execution. We must get
1688 * exclusive lock now because execution will; taking a lower grade lock
1689 * now and trying to upgrade later risks deadlock.
1691 rel = relation_openrv(stmt->relation, AccessExclusiveLock);
1693 /* Set up pstate */
1694 pstate = make_parsestate(NULL);
1695 pstate->p_sourcetext = queryString;
1697 cxt.stmtType = "ALTER TABLE";
1698 cxt.relation = stmt->relation;
1699 cxt.rel = rel;
1700 cxt.inhRelations = NIL;
1701 cxt.isalter = true;
1702 cxt.hasoids = false; /* need not be right */
1703 cxt.columns = NIL;
1704 cxt.ckconstraints = NIL;
1705 cxt.fkconstraints = NIL;
1706 cxt.ixconstraints = NIL;
1707 cxt.inh_indexes = NIL;
1708 cxt.blist = NIL;
1709 cxt.alist = NIL;
1710 cxt.pkey = NULL;
1713 * The only subtypes that currently require parse transformation handling
1714 * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from
1715 * CREATE TABLE.
1717 foreach(lcmd, stmt->cmds)
1719 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
1721 switch (cmd->subtype)
1723 case AT_AddColumn:
1725 ColumnDef *def = (ColumnDef *) cmd->def;
1727 Assert(IsA(def, ColumnDef));
1728 transformColumnDefinition(pstate, &cxt, def);
1731 * If the column has a non-null default, we can't skip
1732 * validation of foreign keys.
1734 if (def->raw_default != NULL)
1735 skipValidation = false;
1738 * All constraints are processed in other ways. Remove the
1739 * original list
1741 def->constraints = NIL;
1743 newcmds = lappend(newcmds, cmd);
1744 break;
1746 case AT_AddConstraint:
1749 * The original AddConstraint cmd node doesn't go to newcmds
1751 if (IsA(cmd->def, Constraint))
1752 transformTableConstraint(pstate, &cxt,
1753 (Constraint *) cmd->def);
1754 else if (IsA(cmd->def, FkConstraint))
1756 cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
1757 skipValidation = false;
1759 else
1760 elog(ERROR, "unrecognized node type: %d",
1761 (int) nodeTag(cmd->def));
1762 break;
1764 case AT_ProcessedConstraint:
1767 * Already-transformed ADD CONSTRAINT, so just make it look
1768 * like the standard case.
1770 cmd->subtype = AT_AddConstraint;
1771 newcmds = lappend(newcmds, cmd);
1772 break;
1774 default:
1775 newcmds = lappend(newcmds, cmd);
1776 break;
1781 * transformIndexConstraints wants cxt.alist to contain only index
1782 * statements, so transfer anything we already have into save_alist
1783 * immediately.
1785 save_alist = cxt.alist;
1786 cxt.alist = NIL;
1788 /* Postprocess index and FK constraints */
1789 transformIndexConstraints(pstate, &cxt);
1791 transformFKConstraints(pstate, &cxt, skipValidation, true);
1794 * Push any index-creation commands into the ALTER, so that they can be
1795 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
1796 * the IndexStmt attached to an AT_AddIndex subcommand has already been
1797 * through transformIndexStmt.
1799 foreach(l, cxt.alist)
1801 Node *idxstmt = (Node *) lfirst(l);
1803 Assert(IsA(idxstmt, IndexStmt));
1804 newcmd = makeNode(AlterTableCmd);
1805 newcmd->subtype = AT_AddIndex;
1806 newcmd->def = (Node *) transformIndexStmt((IndexStmt *) idxstmt,
1807 queryString);
1808 newcmds = lappend(newcmds, newcmd);
1810 cxt.alist = NIL;
1812 /* Append any CHECK or FK constraints to the commands list */
1813 foreach(l, cxt.ckconstraints)
1815 newcmd = makeNode(AlterTableCmd);
1816 newcmd->subtype = AT_AddConstraint;
1817 newcmd->def = (Node *) lfirst(l);
1818 newcmds = lappend(newcmds, newcmd);
1820 foreach(l, cxt.fkconstraints)
1822 newcmd = makeNode(AlterTableCmd);
1823 newcmd->subtype = AT_AddConstraint;
1824 newcmd->def = (Node *) lfirst(l);
1825 newcmds = lappend(newcmds, newcmd);
1828 /* Close rel but keep lock */
1829 relation_close(rel, NoLock);
1832 * Output results.
1834 stmt->cmds = newcmds;
1836 result = lappend(cxt.blist, stmt);
1837 result = list_concat(result, cxt.alist);
1838 result = list_concat(result, save_alist);
1840 return result;
1845 * Preprocess a list of column constraint clauses
1846 * to attach constraint attributes to their primary constraint nodes
1847 * and detect inconsistent/misplaced constraint attributes.
1849 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
1850 * constraints, but someday they ought to be supported for other constraints.
1852 static void
1853 transformConstraintAttrs(List *constraintList)
1855 Node *lastprimarynode = NULL;
1856 bool saw_deferrability = false;
1857 bool saw_initially = false;
1858 ListCell *clist;
1860 foreach(clist, constraintList)
1862 Node *node = lfirst(clist);
1864 if (!IsA(node, Constraint))
1866 lastprimarynode = node;
1867 /* reset flags for new primary node */
1868 saw_deferrability = false;
1869 saw_initially = false;
1871 else
1873 Constraint *con = (Constraint *) node;
1875 switch (con->contype)
1877 case CONSTR_ATTR_DEFERRABLE:
1878 if (lastprimarynode == NULL ||
1879 !IsA(lastprimarynode, FkConstraint))
1880 ereport(ERROR,
1881 (errcode(ERRCODE_SYNTAX_ERROR),
1882 errmsg("misplaced DEFERRABLE clause")));
1883 if (saw_deferrability)
1884 ereport(ERROR,
1885 (errcode(ERRCODE_SYNTAX_ERROR),
1886 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1887 saw_deferrability = true;
1888 ((FkConstraint *) lastprimarynode)->deferrable = true;
1889 break;
1890 case CONSTR_ATTR_NOT_DEFERRABLE:
1891 if (lastprimarynode == NULL ||
1892 !IsA(lastprimarynode, FkConstraint))
1893 ereport(ERROR,
1894 (errcode(ERRCODE_SYNTAX_ERROR),
1895 errmsg("misplaced NOT DEFERRABLE clause")));
1896 if (saw_deferrability)
1897 ereport(ERROR,
1898 (errcode(ERRCODE_SYNTAX_ERROR),
1899 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
1900 saw_deferrability = true;
1901 ((FkConstraint *) lastprimarynode)->deferrable = false;
1902 if (saw_initially &&
1903 ((FkConstraint *) lastprimarynode)->initdeferred)
1904 ereport(ERROR,
1905 (errcode(ERRCODE_SYNTAX_ERROR),
1906 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1907 break;
1908 case CONSTR_ATTR_DEFERRED:
1909 if (lastprimarynode == NULL ||
1910 !IsA(lastprimarynode, FkConstraint))
1911 ereport(ERROR,
1912 (errcode(ERRCODE_SYNTAX_ERROR),
1913 errmsg("misplaced INITIALLY DEFERRED clause")));
1914 if (saw_initially)
1915 ereport(ERROR,
1916 (errcode(ERRCODE_SYNTAX_ERROR),
1917 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1918 saw_initially = true;
1919 ((FkConstraint *) lastprimarynode)->initdeferred = true;
1922 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
1924 if (!saw_deferrability)
1925 ((FkConstraint *) lastprimarynode)->deferrable = true;
1926 else if (!((FkConstraint *) lastprimarynode)->deferrable)
1927 ereport(ERROR,
1928 (errcode(ERRCODE_SYNTAX_ERROR),
1929 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
1930 break;
1931 case CONSTR_ATTR_IMMEDIATE:
1932 if (lastprimarynode == NULL ||
1933 !IsA(lastprimarynode, FkConstraint))
1934 ereport(ERROR,
1935 (errcode(ERRCODE_SYNTAX_ERROR),
1936 errmsg("misplaced INITIALLY IMMEDIATE clause")));
1937 if (saw_initially)
1938 ereport(ERROR,
1939 (errcode(ERRCODE_SYNTAX_ERROR),
1940 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
1941 saw_initially = true;
1942 ((FkConstraint *) lastprimarynode)->initdeferred = false;
1943 break;
1944 default:
1945 /* Otherwise it's not an attribute */
1946 lastprimarynode = node;
1947 /* reset flags for new primary node */
1948 saw_deferrability = false;
1949 saw_initially = false;
1950 break;
1957 * Special handling of type definition for a column
1959 static void
1960 transformColumnType(ParseState *pstate, ColumnDef *column)
1963 * All we really need to do here is verify that the type is valid.
1965 Type ctype = typenameType(pstate, column->typename, NULL);
1967 ReleaseSysCache(ctype);
1972 * transformCreateSchemaStmt -
1973 * analyzes the CREATE SCHEMA statement
1975 * Split the schema element list into individual commands and place
1976 * them in the result list in an order such that there are no forward
1977 * references (e.g. GRANT to a table created later in the list). Note
1978 * that the logic we use for determining forward references is
1979 * presently quite incomplete.
1981 * SQL92 also allows constraints to make forward references, so thumb through
1982 * the table columns and move forward references to a posterior alter-table
1983 * command.
1985 * The result is a list of parse nodes that still need to be analyzed ---
1986 * but we can't analyze the later commands until we've executed the earlier
1987 * ones, because of possible inter-object references.
1989 * Note: this breaks the rules a little bit by modifying schema-name fields
1990 * within passed-in structs. However, the transformation would be the same
1991 * if done over, so it should be all right to scribble on the input to this
1992 * extent.
1994 List *
1995 transformCreateSchemaStmt(CreateSchemaStmt *stmt)
1997 CreateSchemaStmtContext cxt;
1998 List *result;
1999 ListCell *elements;
2001 cxt.stmtType = "CREATE SCHEMA";
2002 cxt.schemaname = stmt->schemaname;
2003 cxt.authid = stmt->authid;
2004 cxt.sequences = NIL;
2005 cxt.tables = NIL;
2006 cxt.views = NIL;
2007 cxt.indexes = NIL;
2008 cxt.triggers = NIL;
2009 cxt.grants = NIL;
2012 * Run through each schema element in the schema element list. Separate
2013 * statements by type, and do preliminary analysis.
2015 foreach(elements, stmt->schemaElts)
2017 Node *element = lfirst(elements);
2019 switch (nodeTag(element))
2021 case T_CreateSeqStmt:
2023 CreateSeqStmt *elp = (CreateSeqStmt *) element;
2025 setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
2026 cxt.sequences = lappend(cxt.sequences, element);
2028 break;
2030 case T_CreateStmt:
2032 CreateStmt *elp = (CreateStmt *) element;
2034 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2037 * XXX todo: deal with constraints
2039 cxt.tables = lappend(cxt.tables, element);
2041 break;
2043 case T_ViewStmt:
2045 ViewStmt *elp = (ViewStmt *) element;
2047 setSchemaName(cxt.schemaname, &elp->view->schemaname);
2050 * XXX todo: deal with references between views
2052 cxt.views = lappend(cxt.views, element);
2054 break;
2056 case T_IndexStmt:
2058 IndexStmt *elp = (IndexStmt *) element;
2060 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2061 cxt.indexes = lappend(cxt.indexes, element);
2063 break;
2065 case T_CreateTrigStmt:
2067 CreateTrigStmt *elp = (CreateTrigStmt *) element;
2069 setSchemaName(cxt.schemaname, &elp->relation->schemaname);
2070 cxt.triggers = lappend(cxt.triggers, element);
2072 break;
2074 case T_GrantStmt:
2075 cxt.grants = lappend(cxt.grants, element);
2076 break;
2078 default:
2079 elog(ERROR, "unrecognized node type: %d",
2080 (int) nodeTag(element));
2084 result = NIL;
2085 result = list_concat(result, cxt.sequences);
2086 result = list_concat(result, cxt.tables);
2087 result = list_concat(result, cxt.views);
2088 result = list_concat(result, cxt.indexes);
2089 result = list_concat(result, cxt.triggers);
2090 result = list_concat(result, cxt.grants);
2092 return result;
2096 * setSchemaName
2097 * Set or check schema name in an element of a CREATE SCHEMA command
2099 static void
2100 setSchemaName(char *context_schema, char **stmt_schema_name)
2102 if (*stmt_schema_name == NULL)
2103 *stmt_schema_name = context_schema;
2104 else if (strcmp(context_schema, *stmt_schema_name) != 0)
2105 ereport(ERROR,
2106 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2107 errmsg("CREATE specifies a schema (%s) "
2108 "different from the one being created (%s)",
2109 *stmt_schema_name, context_schema)));