PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_utilcmd.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parse_utilcmd.c
4  * Perform parse analysis work for various utility commands
5  *
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.
13  *
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.
17  *
18  *
19  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
20  * Portions Copyright (c) 1994, Regents of the University of California
21  *
22  * src/backend/parser/parse_utilcmd.c
23  *
24  *-------------------------------------------------------------------------
25  */
26 
27 #include "postgres.h"
28 
29 #include "access/amapi.h"
30 #include "access/htup_details.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_am.h"
37 #include "catalog/pg_collation.h"
38 #include "catalog/pg_constraint.h"
40 #include "catalog/pg_opclass.h"
41 #include "catalog/pg_operator.h"
42 #include "catalog/pg_type.h"
43 #include "commands/comment.h"
44 #include "commands/defrem.h"
45 #include "commands/tablecmds.h"
46 #include "commands/tablespace.h"
47 #include "miscadmin.h"
48 #include "nodes/makefuncs.h"
49 #include "nodes/nodeFuncs.h"
50 #include "parser/analyze.h"
51 #include "parser/parse_clause.h"
52 #include "parser/parse_collate.h"
53 #include "parser/parse_expr.h"
54 #include "parser/parse_relation.h"
55 #include "parser/parse_target.h"
56 #include "parser/parse_type.h"
57 #include "parser/parse_utilcmd.h"
58 #include "parser/parser.h"
59 #include "rewrite/rewriteManip.h"
60 #include "utils/acl.h"
61 #include "utils/builtins.h"
62 #include "utils/guc.h"
63 #include "utils/lsyscache.h"
64 #include "utils/rel.h"
65 #include "utils/syscache.h"
66 #include "utils/typcache.h"
67 
68 
69 /* State shared by transformCreateStmt and its subroutines */
70 typedef struct
71 {
72  ParseState *pstate; /* overall parser state */
73  const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
74  RangeVar *relation; /* relation to create */
75  Relation rel; /* opened/locked rel, if ALTER */
76  List *inhRelations; /* relations to inherit from */
77  bool isforeign; /* true if CREATE/ALTER FOREIGN TABLE */
78  bool isalter; /* true if altering existing table */
79  bool hasoids; /* does relation have an OID column? */
80  List *columns; /* ColumnDef items */
81  List *ckconstraints; /* CHECK constraints */
82  List *fkconstraints; /* FOREIGN KEY constraints */
83  List *ixconstraints; /* index-creating constraints */
84  List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
85  List *blist; /* "before list" of things to do before
86  * creating the table */
87  List *alist; /* "after list" of things to do after creating
88  * the table */
89  IndexStmt *pkey; /* PRIMARY KEY index, if any */
91 
92 /* State shared by transformCreateSchemaStmt and its subroutines */
93 typedef struct
94 {
95  const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
96  char *schemaname; /* name of schema */
97  RoleSpec *authrole; /* owner of schema */
98  List *sequences; /* CREATE SEQUENCE items */
99  List *tables; /* CREATE TABLE items */
100  List *views; /* CREATE VIEW items */
101  List *indexes; /* CREATE INDEX items */
102  List *triggers; /* CREATE TRIGGER items */
103  List *grants; /* GRANT items */
105 
106 
108  ColumnDef *column);
110  Constraint *constraint);
112  TableLikeClause *table_like_clause);
113 static void transformOfType(CreateStmtContext *cxt,
114  TypeName *ofTypename);
116  Relation source_idx,
117  const AttrNumber *attmap, int attmap_length);
118 static List *get_collation(Oid collation, Oid actual_datatype);
119 static List *get_opclass(Oid opclass, Oid actual_datatype);
121 static IndexStmt *transformIndexConstraint(Constraint *constraint,
122  CreateStmtContext *cxt);
124  bool skipValidation,
125  bool isAddConstraint);
127  bool skipValidation);
129  List *constraintList);
130 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
131 static void setSchemaName(char *context_schema, char **stmt_schema_name);
132 
133 
134 /*
135  * transformCreateStmt -
136  * parse analysis for CREATE TABLE
137  *
138  * Returns a List of utility commands to be done in sequence. One of these
139  * will be the transformed CreateStmt, but there may be additional actions
140  * to be done before and after the actual DefineRelation() call.
141  *
142  * SQL allows constraints to be scattered all over, so thumb through
143  * the columns and collect all constraints into one place.
144  * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
145  * then expand those into multiple IndexStmt blocks.
146  * - thomas 1997-12-02
147  */
148 List *
149 transformCreateStmt(CreateStmt *stmt, const char *queryString)
150 {
151  ParseState *pstate;
152  CreateStmtContext cxt;
153  List *result;
154  List *save_alist;
155  ListCell *elements;
156  Oid namespaceid;
157  Oid existing_relid;
158  ParseCallbackState pcbstate;
159  bool like_found = false;
160 
161  /*
162  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
163  * overkill, but easy.)
164  */
165  stmt = (CreateStmt *) copyObject(stmt);
166 
167  /* Set up pstate */
168  pstate = make_parsestate(NULL);
169  pstate->p_sourcetext = queryString;
170 
171  /*
172  * Look up the creation namespace. This also checks permissions on the
173  * target namespace, locks it against concurrent drops, checks for a
174  * preexisting relation in that namespace with the same name, and updates
175  * stmt->relation->relpersistence if the selected namespace is temporary.
176  */
177  setup_parser_errposition_callback(&pcbstate, pstate,
178  stmt->relation->location);
179  namespaceid =
181  &existing_relid);
183 
184  /*
185  * If the relation already exists and the user specified "IF NOT EXISTS",
186  * bail out with a NOTICE.
187  */
188  if (stmt->if_not_exists && OidIsValid(existing_relid))
189  {
190  ereport(NOTICE,
191  (errcode(ERRCODE_DUPLICATE_TABLE),
192  errmsg("relation \"%s\" already exists, skipping",
193  stmt->relation->relname)));
194  return NIL;
195  }
196 
197  /*
198  * If the target relation name isn't schema-qualified, make it so. This
199  * prevents some corner cases in which added-on rewritten commands might
200  * think they should apply to other relations that have the same name and
201  * are earlier in the search path. But a local temp table is effectively
202  * specified to be in pg_temp, so no need for anything extra in that case.
203  */
204  if (stmt->relation->schemaname == NULL
206  stmt->relation->schemaname = get_namespace_name(namespaceid);
207 
208  /* Set up CreateStmtContext */
209  cxt.pstate = pstate;
210  if (IsA(stmt, CreateForeignTableStmt))
211  {
212  cxt.stmtType = "CREATE FOREIGN TABLE";
213  cxt.isforeign = true;
214  }
215  else
216  {
217  cxt.stmtType = "CREATE TABLE";
218  cxt.isforeign = false;
219  }
220  cxt.relation = stmt->relation;
221  cxt.rel = NULL;
222  cxt.inhRelations = stmt->inhRelations;
223  cxt.isalter = false;
224  cxt.columns = NIL;
225  cxt.ckconstraints = NIL;
226  cxt.fkconstraints = NIL;
227  cxt.ixconstraints = NIL;
228  cxt.inh_indexes = NIL;
229  cxt.blist = NIL;
230  cxt.alist = NIL;
231  cxt.pkey = NULL;
232 
233  /*
234  * Notice that we allow OIDs here only for plain tables, even though
235  * foreign tables also support them. This is necessary because the
236  * default_with_oids GUC must apply only to plain tables and not any other
237  * relkind; doing otherwise would break existing pg_dump files. We could
238  * allow explicit "WITH OIDS" while not allowing default_with_oids to
239  * affect other relkinds, but it would complicate interpretOidsOption(),
240  * and right now there's no WITH OIDS option in CREATE FOREIGN TABLE
241  * anyway.
242  */
243  cxt.hasoids = interpretOidsOption(stmt->options, !cxt.isforeign);
244 
245  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
246 
247  if (stmt->ofTypename)
248  transformOfType(&cxt, stmt->ofTypename);
249 
250  /*
251  * Run through each primary element in the table creation clause. Separate
252  * column defs from constraints, and do preliminary analysis. We have to
253  * process column-defining clauses first because it can control the
254  * presence of columns which are referenced by columns referenced by
255  * constraints.
256  */
257  foreach(elements, stmt->tableElts)
258  {
259  Node *element = lfirst(elements);
260 
261  switch (nodeTag(element))
262  {
263  case T_ColumnDef:
264  transformColumnDefinition(&cxt, (ColumnDef *) element);
265  break;
266 
267  case T_TableLikeClause:
268  if (!like_found)
269  {
270  cxt.hasoids = false;
271  like_found = true;
272  }
273  transformTableLikeClause(&cxt, (TableLikeClause *) element);
274  break;
275 
276  case T_Constraint:
277  /* process later */
278  break;
279 
280  default:
281  elog(ERROR, "unrecognized node type: %d",
282  (int) nodeTag(element));
283  break;
284  }
285  }
286 
287  if (like_found)
288  {
289  /*
290  * To match INHERITS, the existence of any LIKE table with OIDs
291  * causes the new table to have oids. For the same reason,
292  * WITH/WITHOUT OIDs is also ignored with LIKE. We prepend
293  * because the first oid option list entry is honored. Our
294  * prepended WITHOUT OIDS clause will be overridden if an
295  * inherited table has oids.
296  */
297  stmt->options = lcons(makeDefElem("oids",
298  (Node *)makeInteger(cxt.hasoids)), stmt->options);
299  }
300 
301  foreach(elements, stmt->tableElts)
302  {
303  Node *element = lfirst(elements);
304 
305  if (nodeTag(element) == T_Constraint)
306  transformTableConstraint(&cxt, (Constraint *) element);
307  }
308  /*
309  * transformIndexConstraints wants cxt.alist to contain only index
310  * statements, so transfer anything we already have into save_alist.
311  */
312  save_alist = cxt.alist;
313  cxt.alist = NIL;
314 
315  Assert(stmt->constraints == NIL);
316 
317  /*
318  * Postprocess constraints that give rise to index definitions.
319  */
321 
322  /*
323  * Postprocess foreign-key constraints.
324  */
325  transformFKConstraints(&cxt, true, false);
326 
327  /*
328  * Postprocess check constraints.
329  */
330  transformCheckConstraints(&cxt, true);
331 
332  /*
333  * Output results.
334  */
335  stmt->tableElts = cxt.columns;
336  stmt->constraints = cxt.ckconstraints;
337 
338  result = lappend(cxt.blist, stmt);
339  result = list_concat(result, cxt.alist);
340  result = list_concat(result, save_alist);
341 
342  return result;
343 }
344 
345 /*
346  * transformColumnDefinition -
347  * transform a single ColumnDef within CREATE TABLE
348  * Also used in ALTER TABLE ADD COLUMN
349  */
350 static void
352 {
353  bool is_serial;
354  bool saw_nullable;
355  bool saw_default;
356  Constraint *constraint;
357  ListCell *clist;
358 
359  cxt->columns = lappend(cxt->columns, column);
360 
361  /* Check for SERIAL pseudo-types */
362  is_serial = false;
363  if (column->typeName
364  && list_length(column->typeName->names) == 1
365  && !column->typeName->pct_type)
366  {
367  char *typname = strVal(linitial(column->typeName->names));
368 
369  if (strcmp(typname, "smallserial") == 0 ||
370  strcmp(typname, "serial2") == 0)
371  {
372  is_serial = true;
373  column->typeName->names = NIL;
374  column->typeName->typeOid = INT2OID;
375  }
376  else if (strcmp(typname, "serial") == 0 ||
377  strcmp(typname, "serial4") == 0)
378  {
379  is_serial = true;
380  column->typeName->names = NIL;
381  column->typeName->typeOid = INT4OID;
382  }
383  else if (strcmp(typname, "bigserial") == 0 ||
384  strcmp(typname, "serial8") == 0)
385  {
386  is_serial = true;
387  column->typeName->names = NIL;
388  column->typeName->typeOid = INT8OID;
389  }
390 
391  /*
392  * We have to reject "serial[]" explicitly, because once we've set
393  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
394  * special coding for serial(typmod) though.
395  */
396  if (is_serial && column->typeName->arrayBounds != NIL)
397  ereport(ERROR,
398  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
399  errmsg("array of serial is not implemented"),
401  column->typeName->location)));
402  }
403 
404  /* Do necessary work on the column type declaration */
405  if (column->typeName)
406  transformColumnType(cxt, column);
407 
408  /* Special actions for SERIAL pseudo-types */
409  if (is_serial)
410  {
411  Oid snamespaceid;
412  char *snamespace;
413  char *sname;
414  char *qstring;
415  A_Const *snamenode;
416  TypeCast *castnode;
417  FuncCall *funccallnode;
418  CreateSeqStmt *seqstmt;
419  AlterSeqStmt *altseqstmt;
420  List *attnamelist;
421 
422  /*
423  * Determine namespace and name to use for the sequence.
424  *
425  * Although we use ChooseRelationName, it's not guaranteed that the
426  * selected sequence name won't conflict; given sufficiently long
427  * field names, two different serial columns in the same table could
428  * be assigned the same sequence name, and we'd not notice since we
429  * aren't creating the sequence quite yet. In practice this seems
430  * quite unlikely to be a problem, especially since few people would
431  * need two serial columns in one table.
432  */
433  if (cxt->rel)
434  snamespaceid = RelationGetNamespace(cxt->rel);
435  else
436  {
437  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
438  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
439  }
440  snamespace = get_namespace_name(snamespaceid);
441  sname = ChooseRelationName(cxt->relation->relname,
442  column->colname,
443  "seq",
444  snamespaceid);
445 
446  ereport(DEBUG1,
447  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
448  cxt->stmtType, sname,
449  cxt->relation->relname, column->colname)));
450 
451  /*
452  * Build a CREATE SEQUENCE command to create the sequence object, and
453  * add it to the list of things to be done before this CREATE/ALTER
454  * TABLE.
455  */
456  seqstmt = makeNode(CreateSeqStmt);
457  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
458  seqstmt->options = NIL;
459 
460  /*
461  * If this is ALTER ADD COLUMN, make sure the sequence will be owned
462  * by the table's owner. The current user might be someone else
463  * (perhaps a superuser, or someone who's only a member of the owning
464  * role), but the SEQUENCE OWNED BY mechanisms will bleat unless table
465  * and sequence have exactly the same owning role.
466  */
467  if (cxt->rel)
468  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
469  else
470  seqstmt->ownerId = InvalidOid;
471 
472  cxt->blist = lappend(cxt->blist, seqstmt);
473 
474  /*
475  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
476  * as owned by this column, and add it to the list of things to be
477  * done after this CREATE/ALTER TABLE.
478  */
479  altseqstmt = makeNode(AlterSeqStmt);
480  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
481  attnamelist = list_make3(makeString(snamespace),
482  makeString(cxt->relation->relname),
483  makeString(column->colname));
484  altseqstmt->options = list_make1(makeDefElem("owned_by",
485  (Node *) attnamelist));
486 
487  cxt->alist = lappend(cxt->alist, altseqstmt);
488 
489  /*
490  * Create appropriate constraints for SERIAL. We do this in full,
491  * rather than shortcutting, so that we will detect any conflicting
492  * constraints the user wrote (like a different DEFAULT).
493  *
494  * Create an expression tree representing the function call
495  * nextval('sequencename'). We cannot reduce the raw tree to cooked
496  * form until after the sequence is created, but there's no need to do
497  * so.
498  */
499  qstring = quote_qualified_identifier(snamespace, sname);
500  snamenode = makeNode(A_Const);
501  snamenode->val.type = T_String;
502  snamenode->val.val.str = qstring;
503  snamenode->location = -1;
504  castnode = makeNode(TypeCast);
505  castnode->typeName = SystemTypeName("regclass");
506  castnode->arg = (Node *) snamenode;
507  castnode->location = -1;
508  funccallnode = makeFuncCall(SystemFuncName("nextval"),
509  list_make1(castnode),
510  -1);
511  constraint = makeNode(Constraint);
512  constraint->contype = CONSTR_DEFAULT;
513  constraint->location = -1;
514  constraint->raw_expr = (Node *) funccallnode;
515  constraint->cooked_expr = NULL;
516  column->constraints = lappend(column->constraints, constraint);
517 
518  constraint = makeNode(Constraint);
519  constraint->contype = CONSTR_NOTNULL;
520  constraint->location = -1;
521  column->constraints = lappend(column->constraints, constraint);
522  }
523 
524  /* Process column constraints, if any... */
526 
527  saw_nullable = false;
528  saw_default = false;
529 
530  foreach(clist, column->constraints)
531  {
532  constraint = lfirst(clist);
533  Assert(IsA(constraint, Constraint));
534 
535  switch (constraint->contype)
536  {
537  case CONSTR_NULL:
538  if (saw_nullable && column->is_not_null)
539  ereport(ERROR,
540  (errcode(ERRCODE_SYNTAX_ERROR),
541  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
542  column->colname, cxt->relation->relname),
544  constraint->location)));
545  column->is_not_null = FALSE;
546  saw_nullable = true;
547  break;
548 
549  case CONSTR_NOTNULL:
550  if (saw_nullable && !column->is_not_null)
551  ereport(ERROR,
552  (errcode(ERRCODE_SYNTAX_ERROR),
553  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
554  column->colname, cxt->relation->relname),
556  constraint->location)));
557  column->is_not_null = TRUE;
558  saw_nullable = true;
559  break;
560 
561  case CONSTR_DEFAULT:
562  if (saw_default)
563  ereport(ERROR,
564  (errcode(ERRCODE_SYNTAX_ERROR),
565  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
566  column->colname, cxt->relation->relname),
568  constraint->location)));
569  column->raw_default = constraint->raw_expr;
570  Assert(constraint->cooked_expr == NULL);
571  saw_default = true;
572  break;
573 
574  case CONSTR_CHECK:
575  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
576  break;
577 
578  case CONSTR_PRIMARY:
579  if (cxt->isforeign)
580  ereport(ERROR,
581  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
582  errmsg("primary key constraints are not supported on foreign tables"),
584  constraint->location)));
585  /* FALL THRU */
586 
587  case CONSTR_UNIQUE:
588  if (cxt->isforeign)
589  ereport(ERROR,
590  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
591  errmsg("unique constraints are not supported on foreign tables"),
593  constraint->location)));
594  if (constraint->keys == NIL)
595  constraint->keys = list_make1(makeString(column->colname));
596  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
597  break;
598 
599  case CONSTR_EXCLUSION:
600  /* grammar does not allow EXCLUDE as a column constraint */
601  elog(ERROR, "column exclusion constraints are not supported");
602  break;
603 
604  case CONSTR_FOREIGN:
605  if (cxt->isforeign)
606  ereport(ERROR,
607  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
608  errmsg("foreign key constraints are not supported on foreign tables"),
610  constraint->location)));
611 
612  /*
613  * Fill in the current attribute's name and throw it into the
614  * list of FK constraints to be processed later.
615  */
616  constraint->fk_attrs = list_make1(makeString(column->colname));
617  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
618  break;
619 
624  /* transformConstraintAttrs took care of these */
625  break;
626 
627  default:
628  elog(ERROR, "unrecognized constraint type: %d",
629  constraint->contype);
630  break;
631  }
632  }
633 
634  /*
635  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
636  * per-column foreign data wrapper options to this column after creation.
637  */
638  if (column->fdwoptions != NIL)
639  {
640  AlterTableStmt *stmt;
641  AlterTableCmd *cmd;
642 
643  cmd = makeNode(AlterTableCmd);
645  cmd->name = column->colname;
646  cmd->def = (Node *) column->fdwoptions;
647  cmd->behavior = DROP_RESTRICT;
648  cmd->missing_ok = false;
649 
650  stmt = makeNode(AlterTableStmt);
651  stmt->relation = cxt->relation;
652  stmt->cmds = NIL;
654  stmt->cmds = lappend(stmt->cmds, cmd);
655 
656  cxt->alist = lappend(cxt->alist, stmt);
657  }
658 }
659 
660 /*
661  * transformTableConstraint
662  * transform a Constraint node within CREATE TABLE or ALTER TABLE
663  */
664 static void
666 {
667  switch (constraint->contype)
668  {
669  case CONSTR_PRIMARY:
670  if (cxt->isforeign)
671  ereport(ERROR,
672  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
673  errmsg("primary key constraints are not supported on foreign tables"),
675  constraint->location)));
676  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
677  break;
678 
679  case CONSTR_UNIQUE:
680  if (cxt->isforeign)
681  ereport(ERROR,
682  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
683  errmsg("unique constraints are not supported on foreign tables"),
685  constraint->location)));
686  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
687  break;
688 
689  case CONSTR_EXCLUSION:
690  if (cxt->isforeign)
691  ereport(ERROR,
692  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
693  errmsg("exclusion constraints are not supported on foreign tables"),
695  constraint->location)));
696  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
697  break;
698 
699  case CONSTR_CHECK:
700  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
701  break;
702 
703  case CONSTR_FOREIGN:
704  if (cxt->isforeign)
705  ereport(ERROR,
706  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
707  errmsg("foreign key constraints are not supported on foreign tables"),
709  constraint->location)));
710  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
711  break;
712 
713  case CONSTR_NULL:
714  case CONSTR_NOTNULL:
715  case CONSTR_DEFAULT:
720  elog(ERROR, "invalid context for constraint type %d",
721  constraint->contype);
722  break;
723 
724  default:
725  elog(ERROR, "unrecognized constraint type: %d",
726  constraint->contype);
727  break;
728  }
729 }
730 
731 /*
732  * transformTableLikeClause
733  *
734  * Change the LIKE <srctable> portion of a CREATE TABLE statement into
735  * column definitions which recreate the user defined column portions of
736  * <srctable>.
737  */
738 static void
740 {
741  AttrNumber parent_attno;
742  Relation relation;
744  TupleConstr *constr;
745  AttrNumber *attmap;
746  AclResult aclresult;
747  char *comment;
748  ParseCallbackState pcbstate;
749 
751  table_like_clause->relation->location);
752 
753  /* we could support LIKE in many cases, but worry about it another day */
754  if (cxt->isforeign)
755  ereport(ERROR,
756  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
757  errmsg("LIKE is not supported for creating foreign tables")));
758 
759  relation = relation_openrv(table_like_clause->relation, AccessShareLock);
760 
761  if (relation->rd_rel->relkind != RELKIND_RELATION &&
762  relation->rd_rel->relkind != RELKIND_VIEW &&
763  relation->rd_rel->relkind != RELKIND_MATVIEW &&
764  relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
765  relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
766  ereport(ERROR,
767  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
768  errmsg("\"%s\" is not a table, view, materialized view, composite type, or foreign table",
769  RelationGetRelationName(relation))));
770 
772 
773  /*
774  * Check for privileges
775  */
776  if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
777  {
778  aclresult = pg_type_aclcheck(relation->rd_rel->reltype, GetUserId(),
779  ACL_USAGE);
780  if (aclresult != ACLCHECK_OK)
781  aclcheck_error(aclresult, ACL_KIND_TYPE,
782  RelationGetRelationName(relation));
783  }
784  else
785  {
786  aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
787  ACL_SELECT);
788  if (aclresult != ACLCHECK_OK)
789  aclcheck_error(aclresult, ACL_KIND_CLASS,
790  RelationGetRelationName(relation));
791  }
792 
793  tupleDesc = RelationGetDescr(relation);
794  constr = tupleDesc->constr;
795 
796  /*
797  * Initialize column number map for map_variable_attnos(). We need this
798  * since dropped columns in the source table aren't copied, so the new
799  * table can have different column numbers.
800  */
801  attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * tupleDesc->natts);
802 
803  /*
804  * Insert the copied attributes into the cxt for the new table definition.
805  */
806  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
807  parent_attno++)
808  {
809  Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
810  char *attributeName = NameStr(attribute->attname);
811  ColumnDef *def;
812 
813  /*
814  * Ignore dropped columns in the parent. attmap entry is left zero.
815  */
816  if (attribute->attisdropped)
817  continue;
818 
819  /*
820  * Create a new column, which is marked as NOT inherited.
821  *
822  * For constraints, ONLY the NOT NULL constraint is inherited by the
823  * new column definition per SQL99.
824  */
825  def = makeNode(ColumnDef);
826  def->colname = pstrdup(attributeName);
827  def->typeName = makeTypeNameFromOid(attribute->atttypid,
828  attribute->atttypmod);
829  def->inhcount = 0;
830  def->is_local = true;
831  def->is_not_null = attribute->attnotnull;
832  def->is_from_type = false;
833  def->storage = 0;
834  def->raw_default = NULL;
835  def->cooked_default = NULL;
836  def->collClause = NULL;
837  def->collOid = attribute->attcollation;
838  def->constraints = NIL;
839  def->location = -1;
840 
841  /*
842  * Add to column list
843  */
844  cxt->columns = lappend(cxt->columns, def);
845 
846  attmap[parent_attno - 1] = list_length(cxt->columns);
847 
848  /*
849  * Copy default, if present and the default has been requested
850  */
851  if (attribute->atthasdef &&
852  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS))
853  {
854  Node *this_default = NULL;
855  AttrDefault *attrdef;
856  int i;
857 
858  /* Find default in constraint structure */
859  Assert(constr != NULL);
860  attrdef = constr->defval;
861  for (i = 0; i < constr->num_defval; i++)
862  {
863  if (attrdef[i].adnum == parent_attno)
864  {
865  this_default = stringToNode(attrdef[i].adbin);
866  break;
867  }
868  }
869  Assert(this_default != NULL);
870 
871  /*
872  * If default expr could contain any vars, we'd need to fix 'em,
873  * but it can't; so default is ready to apply to child.
874  */
875 
876  def->cooked_default = this_default;
877  }
878 
879  /* Likewise, copy storage if requested */
880  if (table_like_clause->options & CREATE_TABLE_LIKE_STORAGE)
881  def->storage = attribute->attstorage;
882  else
883  def->storage = 0;
884 
885  /* Likewise, copy comment if requested */
886  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
887  (comment = GetComment(attribute->attrelid,
889  attribute->attnum)) != NULL)
890  {
892 
893  stmt->objtype = OBJECT_COLUMN;
895  makeString(cxt->relation->relname),
896  makeString(def->colname));
897  stmt->objargs = NIL;
898  stmt->comment = comment;
899 
900  cxt->alist = lappend(cxt->alist, stmt);
901  }
902  }
903 
904  /* We use oids if at least one LIKE'ed table has oids. */
905  cxt->hasoids = cxt->hasoids || relation->rd_rel->relhasoids;
906 
907  /*
908  * Copy CHECK constraints if requested, being careful to adjust attribute
909  * numbers so they match the child.
910  */
911  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
912  tupleDesc->constr)
913  {
914  int ccnum;
915 
916  for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
917  {
918  char *ccname = tupleDesc->constr->check[ccnum].ccname;
919  char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
921  Node *ccbin_node;
922  bool found_whole_row;
923 
924  ccbin_node = map_variable_attnos(stringToNode(ccbin),
925  1, 0,
926  attmap, tupleDesc->natts,
927  &found_whole_row);
928 
929  /*
930  * We reject whole-row variables because the whole point of LIKE
931  * is that the new table's rowtype might later diverge from the
932  * parent's. So, while translation might be possible right now,
933  * it wouldn't be possible to guarantee it would work in future.
934  */
935  if (found_whole_row)
936  ereport(ERROR,
937  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
938  errmsg("cannot convert whole-row table reference"),
939  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
940  ccname,
941  RelationGetRelationName(relation))));
942 
943  n->contype = CONSTR_CHECK;
944  n->location = -1;
945  n->conname = pstrdup(ccname);
946  n->raw_expr = NULL;
947  n->cooked_expr = nodeToString(ccbin_node);
948  cxt->ckconstraints = lappend(cxt->ckconstraints, n);
949 
950  /* Copy comment on constraint */
951  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
953  n->conname, false),
955  0)) != NULL)
956  {
958 
961  makeString(cxt->relation->relname),
962  makeString(n->conname));
963  stmt->objargs = NIL;
964  stmt->comment = comment;
965 
966  cxt->alist = lappend(cxt->alist, stmt);
967  }
968  }
969  }
970 
971  /*
972  * Likewise, copy indexes if requested
973  */
974  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
975  relation->rd_rel->relhasindex)
976  {
977  List *parent_indexes;
978  ListCell *l;
979 
980  parent_indexes = RelationGetIndexList(relation);
981 
982  foreach(l, parent_indexes)
983  {
984  Oid parent_index_oid = lfirst_oid(l);
985  Relation parent_index;
986  IndexStmt *index_stmt;
987 
988  parent_index = index_open(parent_index_oid, AccessShareLock);
989 
990  /* Build CREATE INDEX statement to recreate the parent_index */
991  index_stmt = generateClonedIndexStmt(cxt, parent_index,
992  attmap, tupleDesc->natts);
993 
994  /* Copy comment on index, if requested */
995  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
996  {
997  comment = GetComment(parent_index_oid, RelationRelationId, 0);
998 
999  /*
1000  * We make use of IndexStmt's idxcomment option, so as not to
1001  * need to know now what name the index will have.
1002  */
1003  index_stmt->idxcomment = comment;
1004  }
1005 
1006  /* Save it in the inh_indexes list for the time being */
1007  cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
1008 
1009  index_close(parent_index, AccessShareLock);
1010  }
1011  }
1012 
1013  /*
1014  * Close the parent rel, but keep our AccessShareLock on it until xact
1015  * commit. That will prevent someone else from deleting or ALTERing the
1016  * parent before the child is committed.
1017  */
1018  heap_close(relation, NoLock);
1019 }
1020 
1021 static void
1023 {
1024  HeapTuple tuple;
1025  TupleDesc tupdesc;
1026  int i;
1027  Oid ofTypeId;
1028 
1029  AssertArg(ofTypename);
1030 
1031  tuple = typenameType(NULL, ofTypename, NULL);
1032  check_of_type(tuple);
1033  ofTypeId = HeapTupleGetOid(tuple);
1034  ofTypename->typeOid = ofTypeId; /* cached for later */
1035 
1036  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1037  for (i = 0; i < tupdesc->natts; i++)
1038  {
1039  Form_pg_attribute attr = tupdesc->attrs[i];
1040  ColumnDef *n;
1041 
1042  if (attr->attisdropped)
1043  continue;
1044 
1045  n = makeNode(ColumnDef);
1046  n->colname = pstrdup(NameStr(attr->attname));
1047  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1048  n->inhcount = 0;
1049  n->is_local = true;
1050  n->is_not_null = false;
1051  n->is_from_type = true;
1052  n->storage = 0;
1053  n->raw_default = NULL;
1054  n->cooked_default = NULL;
1055  n->collClause = NULL;
1056  n->collOid = attr->attcollation;
1057  n->constraints = NIL;
1058  n->location = -1;
1059  cxt->columns = lappend(cxt->columns, n);
1060  }
1061  DecrTupleDescRefCount(tupdesc);
1062 
1063  ReleaseSysCache(tuple);
1064 }
1065 
1066 /*
1067  * Generate an IndexStmt node using information from an already existing index
1068  * "source_idx". Attribute numbers should be adjusted according to attmap.
1069  */
1070 static IndexStmt *
1072  const AttrNumber *attmap, int attmap_length)
1073 {
1074  Oid source_relid = RelationGetRelid(source_idx);
1075  Form_pg_attribute *attrs = RelationGetDescr(source_idx)->attrs;
1076  HeapTuple ht_idxrel;
1077  HeapTuple ht_idx;
1078  HeapTuple ht_am;
1079  Form_pg_class idxrelrec;
1080  Form_pg_index idxrec;
1081  Form_pg_am amrec;
1082  oidvector *indcollation;
1083  oidvector *indclass;
1084  IndexStmt *index;
1085  List *indexprs;
1086  ListCell *indexpr_item;
1087  Oid indrelid;
1088  int keyno;
1089  Oid keycoltype;
1090  Datum datum;
1091  bool isnull;
1092 
1093  /*
1094  * Fetch pg_class tuple of source index. We can't use the copy in the
1095  * relcache entry because it doesn't include optional fields.
1096  */
1097  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1098  if (!HeapTupleIsValid(ht_idxrel))
1099  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1100  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1101 
1102  /* Fetch pg_index tuple for source index from relcache entry */
1103  ht_idx = source_idx->rd_indextuple;
1104  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1105  indrelid = idxrec->indrelid;
1106 
1107  /* Fetch the pg_am tuple of the index' access method */
1108  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1109  if (!HeapTupleIsValid(ht_am))
1110  elog(ERROR, "cache lookup failed for access method %u",
1111  idxrelrec->relam);
1112  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1113 
1114  /* Extract indcollation from the pg_index tuple */
1115  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1116  Anum_pg_index_indcollation, &isnull);
1117  Assert(!isnull);
1118  indcollation = (oidvector *) DatumGetPointer(datum);
1119 
1120  /* Extract indclass from the pg_index tuple */
1121  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1122  Anum_pg_index_indclass, &isnull);
1123  Assert(!isnull);
1124  indclass = (oidvector *) DatumGetPointer(datum);
1125 
1126  /* Begin building the IndexStmt */
1127  index = makeNode(IndexStmt);
1128  index->relation = cxt->relation;
1129  index->accessMethod = pstrdup(NameStr(amrec->amname));
1130  if (OidIsValid(idxrelrec->reltablespace))
1131  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1132  else
1133  index->tableSpace = NULL;
1134  index->excludeOpNames = NIL;
1135  index->idxcomment = NULL;
1136  index->indexOid = InvalidOid;
1137  index->oldNode = InvalidOid;
1138  index->unique = idxrec->indisunique;
1139  index->primary = idxrec->indisprimary;
1140  index->transformed = true; /* don't need transformIndexStmt */
1141  index->concurrent = false;
1142  index->if_not_exists = false;
1143 
1144  /*
1145  * We don't try to preserve the name of the source index; instead, just
1146  * let DefineIndex() choose a reasonable name.
1147  */
1148  index->idxname = NULL;
1149 
1150  /*
1151  * If the index is marked PRIMARY or has an exclusion condition, it's
1152  * certainly from a constraint; else, if it's not marked UNIQUE, it
1153  * certainly isn't. If it is or might be from a constraint, we have to
1154  * fetch the pg_constraint record.
1155  */
1156  if (index->primary || index->unique || idxrec->indisexclusion)
1157  {
1158  Oid constraintId = get_index_constraint(source_relid);
1159 
1160  if (OidIsValid(constraintId))
1161  {
1162  HeapTuple ht_constr;
1163  Form_pg_constraint conrec;
1164 
1165  ht_constr = SearchSysCache1(CONSTROID,
1166  ObjectIdGetDatum(constraintId));
1167  if (!HeapTupleIsValid(ht_constr))
1168  elog(ERROR, "cache lookup failed for constraint %u",
1169  constraintId);
1170  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1171 
1172  index->isconstraint = true;
1173  index->deferrable = conrec->condeferrable;
1174  index->initdeferred = conrec->condeferred;
1175 
1176  /* If it's an exclusion constraint, we need the operator names */
1177  if (idxrec->indisexclusion)
1178  {
1179  Datum *elems;
1180  int nElems;
1181  int i;
1182 
1183  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1184  /* Extract operator OIDs from the pg_constraint tuple */
1185  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1187  &isnull);
1188  if (isnull)
1189  elog(ERROR, "null conexclop for constraint %u",
1190  constraintId);
1191 
1193  OIDOID, sizeof(Oid), true, 'i',
1194  &elems, NULL, &nElems);
1195 
1196  for (i = 0; i < nElems; i++)
1197  {
1198  Oid operid = DatumGetObjectId(elems[i]);
1199  HeapTuple opertup;
1200  Form_pg_operator operform;
1201  char *oprname;
1202  char *nspname;
1203  List *namelist;
1204 
1205  opertup = SearchSysCache1(OPEROID,
1206  ObjectIdGetDatum(operid));
1207  if (!HeapTupleIsValid(opertup))
1208  elog(ERROR, "cache lookup failed for operator %u",
1209  operid);
1210  operform = (Form_pg_operator) GETSTRUCT(opertup);
1211  oprname = pstrdup(NameStr(operform->oprname));
1212  /* For simplicity we always schema-qualify the op name */
1213  nspname = get_namespace_name(operform->oprnamespace);
1214  namelist = list_make2(makeString(nspname),
1215  makeString(oprname));
1216  index->excludeOpNames = lappend(index->excludeOpNames,
1217  namelist);
1218  ReleaseSysCache(opertup);
1219  }
1220  }
1221 
1222  ReleaseSysCache(ht_constr);
1223  }
1224  else
1225  index->isconstraint = false;
1226  }
1227  else
1228  index->isconstraint = false;
1229 
1230  /* Get the index expressions, if any */
1231  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1232  Anum_pg_index_indexprs, &isnull);
1233  if (!isnull)
1234  {
1235  char *exprsString;
1236 
1237  exprsString = TextDatumGetCString(datum);
1238  indexprs = (List *) stringToNode(exprsString);
1239  }
1240  else
1241  indexprs = NIL;
1242 
1243  /* Build the list of IndexElem */
1244  index->indexParams = NIL;
1245 
1246  indexpr_item = list_head(indexprs);
1247  for (keyno = 0; keyno < idxrec->indnatts; keyno++)
1248  {
1249  IndexElem *iparam;
1250  AttrNumber attnum = idxrec->indkey.values[keyno];
1251  int16 opt = source_idx->rd_indoption[keyno];
1252 
1253  iparam = makeNode(IndexElem);
1254 
1255  if (AttributeNumberIsValid(attnum))
1256  {
1257  /* Simple index column */
1258  char *attname;
1259 
1260  attname = get_relid_attribute_name(indrelid, attnum);
1261  keycoltype = get_atttype(indrelid, attnum);
1262 
1263  iparam->name = attname;
1264  iparam->expr = NULL;
1265  }
1266  else
1267  {
1268  /* Expressional index */
1269  Node *indexkey;
1270  bool found_whole_row;
1271 
1272  if (indexpr_item == NULL)
1273  elog(ERROR, "too few entries in indexprs list");
1274  indexkey = (Node *) lfirst(indexpr_item);
1275  indexpr_item = lnext(indexpr_item);
1276 
1277  /* Adjust Vars to match new table's column numbering */
1278  indexkey = map_variable_attnos(indexkey,
1279  1, 0,
1280  attmap, attmap_length,
1281  &found_whole_row);
1282 
1283  /* As in transformTableLikeClause, reject whole-row variables */
1284  if (found_whole_row)
1285  ereport(ERROR,
1286  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1287  errmsg("cannot convert whole-row table reference"),
1288  errdetail("Index \"%s\" contains a whole-row table reference.",
1289  RelationGetRelationName(source_idx))));
1290 
1291  iparam->name = NULL;
1292  iparam->expr = indexkey;
1293 
1294  keycoltype = exprType(indexkey);
1295  }
1296 
1297  /* Copy the original index column name */
1298  iparam->indexcolname = pstrdup(NameStr(attrs[keyno]->attname));
1299 
1300  /* Add the collation name, if non-default */
1301  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1302 
1303  /* Add the operator class name, if non-default */
1304  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1305 
1306  iparam->ordering = SORTBY_DEFAULT;
1308 
1309  /* Adjust options if necessary */
1310  if (source_idx->rd_amroutine->amcanorder)
1311  {
1312  /*
1313  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1314  * set non-default settings unnecessarily, though, so as to
1315  * improve the chance of recognizing equivalence to constraint
1316  * indexes.
1317  */
1318  if (opt & INDOPTION_DESC)
1319  {
1320  iparam->ordering = SORTBY_DESC;
1321  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1323  }
1324  else
1325  {
1326  if (opt & INDOPTION_NULLS_FIRST)
1328  }
1329  }
1330 
1331  index->indexParams = lappend(index->indexParams, iparam);
1332  }
1333 
1334  /* Copy reloptions if any */
1335  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1336  Anum_pg_class_reloptions, &isnull);
1337  if (!isnull)
1338  index->options = untransformRelOptions(datum);
1339 
1340  /* If it's a partial index, decompile and append the predicate */
1341  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1342  Anum_pg_index_indpred, &isnull);
1343  if (!isnull)
1344  {
1345  char *pred_str;
1346  Node *pred_tree;
1347  bool found_whole_row;
1348 
1349  /* Convert text string to node tree */
1350  pred_str = TextDatumGetCString(datum);
1351  pred_tree = (Node *) stringToNode(pred_str);
1352 
1353  /* Adjust Vars to match new table's column numbering */
1354  pred_tree = map_variable_attnos(pred_tree,
1355  1, 0,
1356  attmap, attmap_length,
1357  &found_whole_row);
1358 
1359  /* As in transformTableLikeClause, reject whole-row variables */
1360  if (found_whole_row)
1361  ereport(ERROR,
1362  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1363  errmsg("cannot convert whole-row table reference"),
1364  errdetail("Index \"%s\" contains a whole-row table reference.",
1365  RelationGetRelationName(source_idx))));
1366 
1367  index->whereClause = pred_tree;
1368  }
1369 
1370  /* Clean up */
1371  ReleaseSysCache(ht_idxrel);
1372  ReleaseSysCache(ht_am);
1373 
1374  return index;
1375 }
1376 
1377 /*
1378  * get_collation - fetch qualified name of a collation
1379  *
1380  * If collation is InvalidOid or is the default for the given actual_datatype,
1381  * then the return value is NIL.
1382  */
1383 static List *
1384 get_collation(Oid collation, Oid actual_datatype)
1385 {
1386  List *result;
1387  HeapTuple ht_coll;
1388  Form_pg_collation coll_rec;
1389  char *nsp_name;
1390  char *coll_name;
1391 
1392  if (!OidIsValid(collation))
1393  return NIL; /* easy case */
1394  if (collation == get_typcollation(actual_datatype))
1395  return NIL; /* just let it default */
1396 
1397  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1398  if (!HeapTupleIsValid(ht_coll))
1399  elog(ERROR, "cache lookup failed for collation %u", collation);
1400  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1401 
1402  /* For simplicity, we always schema-qualify the name */
1403  nsp_name = get_namespace_name(coll_rec->collnamespace);
1404  coll_name = pstrdup(NameStr(coll_rec->collname));
1405  result = list_make2(makeString(nsp_name), makeString(coll_name));
1406 
1407  ReleaseSysCache(ht_coll);
1408  return result;
1409 }
1410 
1411 /*
1412  * get_opclass - fetch qualified name of an index operator class
1413  *
1414  * If the opclass is the default for the given actual_datatype, then
1415  * the return value is NIL.
1416  */
1417 static List *
1418 get_opclass(Oid opclass, Oid actual_datatype)
1419 {
1420  List *result = NIL;
1421  HeapTuple ht_opc;
1422  Form_pg_opclass opc_rec;
1423 
1424  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1425  if (!HeapTupleIsValid(ht_opc))
1426  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1427  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1428 
1429  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1430  {
1431  /* For simplicity, we always schema-qualify the name */
1432  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1433  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1434 
1435  result = list_make2(makeString(nsp_name), makeString(opc_name));
1436  }
1437 
1438  ReleaseSysCache(ht_opc);
1439  return result;
1440 }
1441 
1442 
1443 /*
1444  * transformIndexConstraints
1445  * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1446  * We also merge in any index definitions arising from
1447  * LIKE ... INCLUDING INDEXES.
1448  */
1449 static void
1451 {
1452  IndexStmt *index;
1453  List *indexlist = NIL;
1454  ListCell *lc;
1455 
1456  /*
1457  * Run through the constraints that need to generate an index. For PRIMARY
1458  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1459  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1460  * NULL.
1461  */
1462  foreach(lc, cxt->ixconstraints)
1463  {
1464  Constraint *constraint = (Constraint *) lfirst(lc);
1465 
1466  Assert(IsA(constraint, Constraint));
1467  Assert(constraint->contype == CONSTR_PRIMARY ||
1468  constraint->contype == CONSTR_UNIQUE ||
1469  constraint->contype == CONSTR_EXCLUSION);
1470 
1471  index = transformIndexConstraint(constraint, cxt);
1472 
1473  indexlist = lappend(indexlist, index);
1474  }
1475 
1476  /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1477  foreach(lc, cxt->inh_indexes)
1478  {
1479  index = (IndexStmt *) lfirst(lc);
1480 
1481  if (index->primary)
1482  {
1483  if (cxt->pkey != NULL)
1484  ereport(ERROR,
1485  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1486  errmsg("multiple primary keys for table \"%s\" are not allowed",
1487  cxt->relation->relname)));
1488  cxt->pkey = index;
1489  }
1490 
1491  indexlist = lappend(indexlist, index);
1492  }
1493 
1494  /*
1495  * Scan the index list and remove any redundant index specifications. This
1496  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1497  * strict reading of SQL would suggest raising an error instead, but that
1498  * strikes me as too anal-retentive. - tgl 2001-02-14
1499  *
1500  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1501  * pre-existing indexes, too.
1502  */
1503  Assert(cxt->alist == NIL);
1504  if (cxt->pkey != NULL)
1505  {
1506  /* Make sure we keep the PKEY index in preference to others... */
1507  cxt->alist = list_make1(cxt->pkey);
1508  }
1509 
1510  foreach(lc, indexlist)
1511  {
1512  bool keep = true;
1513  ListCell *k;
1514 
1515  index = lfirst(lc);
1516 
1517  /* if it's pkey, it's already in cxt->alist */
1518  if (index == cxt->pkey)
1519  continue;
1520 
1521  foreach(k, cxt->alist)
1522  {
1523  IndexStmt *priorindex = lfirst(k);
1524 
1525  if (equal(index->indexParams, priorindex->indexParams) &&
1526  equal(index->whereClause, priorindex->whereClause) &&
1527  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1528  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1529  index->deferrable == priorindex->deferrable &&
1530  index->initdeferred == priorindex->initdeferred)
1531  {
1532  priorindex->unique |= index->unique;
1533 
1534  /*
1535  * If the prior index is as yet unnamed, and this one is
1536  * named, then transfer the name to the prior index. This
1537  * ensures that if we have named and unnamed constraints,
1538  * we'll use (at least one of) the names for the index.
1539  */
1540  if (priorindex->idxname == NULL)
1541  priorindex->idxname = index->idxname;
1542  keep = false;
1543  break;
1544  }
1545  }
1546 
1547  if (keep)
1548  cxt->alist = lappend(cxt->alist, index);
1549  }
1550 }
1551 
1552 /*
1553  * transformIndexConstraint
1554  * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1555  * transformIndexConstraints.
1556  */
1557 static IndexStmt *
1559 {
1560  IndexStmt *index;
1561  ListCell *lc;
1562 
1563  index = makeNode(IndexStmt);
1564 
1565  index->unique = (constraint->contype != CONSTR_EXCLUSION);
1566  index->primary = (constraint->contype == CONSTR_PRIMARY);
1567  if (index->primary)
1568  {
1569  if (cxt->pkey != NULL)
1570  ereport(ERROR,
1571  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1572  errmsg("multiple primary keys for table \"%s\" are not allowed",
1573  cxt->relation->relname),
1574  parser_errposition(cxt->pstate, constraint->location)));
1575  cxt->pkey = index;
1576 
1577  /*
1578  * In ALTER TABLE case, a primary index might already exist, but
1579  * DefineIndex will check for it.
1580  */
1581  }
1582  index->isconstraint = true;
1583  index->deferrable = constraint->deferrable;
1584  index->initdeferred = constraint->initdeferred;
1585 
1586  if (constraint->conname != NULL)
1587  index->idxname = pstrdup(constraint->conname);
1588  else
1589  index->idxname = NULL; /* DefineIndex will choose name */
1590 
1591  index->relation = cxt->relation;
1592  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1593  index->options = constraint->options;
1594  index->tableSpace = constraint->indexspace;
1595  index->whereClause = constraint->where_clause;
1596  index->indexParams = NIL;
1597  index->excludeOpNames = NIL;
1598  index->idxcomment = NULL;
1599  index->indexOid = InvalidOid;
1600  index->oldNode = InvalidOid;
1601  index->transformed = false;
1602  index->concurrent = false;
1603  index->if_not_exists = false;
1604 
1605  /*
1606  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1607  * verify it's usable, then extract the implied column name list. (We
1608  * will not actually need the column name list at runtime, but we need it
1609  * now to check for duplicate column entries below.)
1610  */
1611  if (constraint->indexname != NULL)
1612  {
1613  char *index_name = constraint->indexname;
1614  Relation heap_rel = cxt->rel;
1615  Oid index_oid;
1616  Relation index_rel;
1617  Form_pg_index index_form;
1618  oidvector *indclass;
1619  Datum indclassDatum;
1620  bool isnull;
1621  int i;
1622 
1623  /* Grammar should not allow this with explicit column list */
1624  Assert(constraint->keys == NIL);
1625 
1626  /* Grammar should only allow PRIMARY and UNIQUE constraints */
1627  Assert(constraint->contype == CONSTR_PRIMARY ||
1628  constraint->contype == CONSTR_UNIQUE);
1629 
1630  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1631  if (!cxt->isalter)
1632  ereport(ERROR,
1633  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1634  errmsg("cannot use an existing index in CREATE TABLE"),
1635  parser_errposition(cxt->pstate, constraint->location)));
1636 
1637  /* Look for the index in the same schema as the table */
1638  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1639 
1640  if (!OidIsValid(index_oid))
1641  ereport(ERROR,
1642  (errcode(ERRCODE_UNDEFINED_OBJECT),
1643  errmsg("index \"%s\" does not exist", index_name),
1644  parser_errposition(cxt->pstate, constraint->location)));
1645 
1646  /* Open the index (this will throw an error if it is not an index) */
1647  index_rel = index_open(index_oid, AccessShareLock);
1648  index_form = index_rel->rd_index;
1649 
1650  /* Check that it does not have an associated constraint already */
1651  if (OidIsValid(get_index_constraint(index_oid)))
1652  ereport(ERROR,
1653  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1654  errmsg("index \"%s\" is already associated with a constraint",
1655  index_name),
1656  parser_errposition(cxt->pstate, constraint->location)));
1657 
1658  /* Perform validity checks on the index */
1659  if (index_form->indrelid != RelationGetRelid(heap_rel))
1660  ereport(ERROR,
1661  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1662  errmsg("index \"%s\" does not belong to table \"%s\"",
1663  index_name, RelationGetRelationName(heap_rel)),
1664  parser_errposition(cxt->pstate, constraint->location)));
1665 
1666  if (!IndexIsValid(index_form))
1667  ereport(ERROR,
1668  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1669  errmsg("index \"%s\" is not valid", index_name),
1670  parser_errposition(cxt->pstate, constraint->location)));
1671 
1672  if (!index_form->indisunique)
1673  ereport(ERROR,
1674  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1675  errmsg("\"%s\" is not a unique index", index_name),
1676  errdetail("Cannot create a primary key or unique constraint using such an index."),
1677  parser_errposition(cxt->pstate, constraint->location)));
1678 
1679  if (RelationGetIndexExpressions(index_rel) != NIL)
1680  ereport(ERROR,
1681  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1682  errmsg("index \"%s\" contains expressions", index_name),
1683  errdetail("Cannot create a primary key or unique constraint using such an index."),
1684  parser_errposition(cxt->pstate, constraint->location)));
1685 
1686  if (RelationGetIndexPredicate(index_rel) != NIL)
1687  ereport(ERROR,
1688  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1689  errmsg("\"%s\" is a partial index", index_name),
1690  errdetail("Cannot create a primary key or unique constraint using such an index."),
1691  parser_errposition(cxt->pstate, constraint->location)));
1692 
1693  /*
1694  * It's probably unsafe to change a deferred index to non-deferred. (A
1695  * non-constraint index couldn't be deferred anyway, so this case
1696  * should never occur; no need to sweat, but let's check it.)
1697  */
1698  if (!index_form->indimmediate && !constraint->deferrable)
1699  ereport(ERROR,
1700  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1701  errmsg("\"%s\" is a deferrable index", index_name),
1702  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
1703  parser_errposition(cxt->pstate, constraint->location)));
1704 
1705  /*
1706  * Insist on it being a btree. That's the only kind that supports
1707  * uniqueness at the moment anyway; but we must have an index that
1708  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
1709  * else dump and reload will produce a different index (breaking
1710  * pg_upgrade in particular).
1711  */
1712  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
1713  ereport(ERROR,
1714  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1715  errmsg("index \"%s\" is not a btree", index_name),
1716  parser_errposition(cxt->pstate, constraint->location)));
1717 
1718  /* Must get indclass the hard way */
1719  indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
1720  Anum_pg_index_indclass, &isnull);
1721  Assert(!isnull);
1722  indclass = (oidvector *) DatumGetPointer(indclassDatum);
1723 
1724  for (i = 0; i < index_form->indnatts; i++)
1725  {
1726  int16 attnum = index_form->indkey.values[i];
1727  Form_pg_attribute attform;
1728  char *attname;
1729  Oid defopclass;
1730 
1731  /*
1732  * We shouldn't see attnum == 0 here, since we already rejected
1733  * expression indexes. If we do, SystemAttributeDefinition will
1734  * throw an error.
1735  */
1736  if (attnum > 0)
1737  {
1738  Assert(attnum <= heap_rel->rd_att->natts);
1739  attform = heap_rel->rd_att->attrs[attnum - 1];
1740  }
1741  else
1742  attform = SystemAttributeDefinition(attnum,
1743  heap_rel->rd_rel->relhasoids);
1744  attname = pstrdup(NameStr(attform->attname));
1745 
1746  /*
1747  * Insist on default opclass and sort options. While the index
1748  * would still work as a constraint with non-default settings, it
1749  * might not provide exactly the same uniqueness semantics as
1750  * you'd get from a normally-created constraint; and there's also
1751  * the dump/reload problem mentioned above.
1752  */
1753  defopclass = GetDefaultOpClass(attform->atttypid,
1754  index_rel->rd_rel->relam);
1755  if (indclass->values[i] != defopclass ||
1756  index_rel->rd_indoption[i] != 0)
1757  ereport(ERROR,
1758  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1759  errmsg("index \"%s\" does not have default sorting behavior", index_name),
1760  errdetail("Cannot create a primary key or unique constraint using such an index."),
1761  parser_errposition(cxt->pstate, constraint->location)));
1762 
1763  constraint->keys = lappend(constraint->keys, makeString(attname));
1764  }
1765 
1766  /* Close the index relation but keep the lock */
1767  relation_close(index_rel, NoLock);
1768 
1769  index->indexOid = index_oid;
1770  }
1771 
1772  /*
1773  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
1774  * IndexElems and operator names. We have to break that apart into
1775  * separate lists.
1776  */
1777  if (constraint->contype == CONSTR_EXCLUSION)
1778  {
1779  foreach(lc, constraint->exclusions)
1780  {
1781  List *pair = (List *) lfirst(lc);
1782  IndexElem *elem;
1783  List *opname;
1784 
1785  Assert(list_length(pair) == 2);
1786  elem = (IndexElem *) linitial(pair);
1787  Assert(IsA(elem, IndexElem));
1788  opname = (List *) lsecond(pair);
1789  Assert(IsA(opname, List));
1790 
1791  index->indexParams = lappend(index->indexParams, elem);
1792  index->excludeOpNames = lappend(index->excludeOpNames, opname);
1793  }
1794 
1795  return index;
1796  }
1797 
1798  /*
1799  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
1800  *
1801  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
1802  * also make sure they are NOT NULL, if possible. (Although we could leave
1803  * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
1804  * get it right the first time.)
1805  */
1806  foreach(lc, constraint->keys)
1807  {
1808  char *key = strVal(lfirst(lc));
1809  bool found = false;
1810  ColumnDef *column = NULL;
1811  ListCell *columns;
1812  IndexElem *iparam;
1813 
1814  foreach(columns, cxt->columns)
1815  {
1816  column = (ColumnDef *) lfirst(columns);
1817  Assert(IsA(column, ColumnDef));
1818  if (strcmp(column->colname, key) == 0)
1819  {
1820  found = true;
1821  break;
1822  }
1823  }
1824  if (found)
1825  {
1826  /* found column in the new table; force it to be NOT NULL */
1827  if (constraint->contype == CONSTR_PRIMARY)
1828  column->is_not_null = TRUE;
1829  }
1830  else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1831  {
1832  /*
1833  * column will be a system column in the new table, so accept it.
1834  * System columns can't ever be null, so no need to worry about
1835  * PRIMARY/NOT NULL constraint.
1836  */
1837  found = true;
1838  }
1839  else if (cxt->inhRelations)
1840  {
1841  /* try inherited tables */
1842  ListCell *inher;
1843 
1844  foreach(inher, cxt->inhRelations)
1845  {
1846  RangeVar *inh = (RangeVar *) lfirst(inher);
1847  Relation rel;
1848  int count;
1849 
1850  Assert(IsA(inh, RangeVar));
1851  rel = heap_openrv(inh, AccessShareLock);
1852  /* check user requested inheritance from valid relkind */
1853  if (rel->rd_rel->relkind != RELKIND_RELATION &&
1854  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1855  ereport(ERROR,
1856  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1857  errmsg("inherited relation \"%s\" is not a table or foreign table",
1858  inh->relname)));
1859  for (count = 0; count < rel->rd_att->natts; count++)
1860  {
1861  Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1862  char *inhname = NameStr(inhattr->attname);
1863 
1864  if (inhattr->attisdropped)
1865  continue;
1866  if (strcmp(key, inhname) == 0)
1867  {
1868  found = true;
1869 
1870  /*
1871  * We currently have no easy way to force an inherited
1872  * column to be NOT NULL at creation, if its parent
1873  * wasn't so already. We leave it to DefineIndex to
1874  * fix things up in this case.
1875  */
1876  break;
1877  }
1878  }
1879  heap_close(rel, NoLock);
1880  if (found)
1881  break;
1882  }
1883  }
1884 
1885  /*
1886  * In the ALTER TABLE case, don't complain about index keys not
1887  * created in the command; they may well exist already. DefineIndex
1888  * will complain about them if not, and will also take care of marking
1889  * them NOT NULL.
1890  */
1891  if (!found && !cxt->isalter)
1892  ereport(ERROR,
1893  (errcode(ERRCODE_UNDEFINED_COLUMN),
1894  errmsg("column \"%s\" named in key does not exist", key),
1895  parser_errposition(cxt->pstate, constraint->location)));
1896 
1897  /* Check for PRIMARY KEY(foo, foo) */
1898  foreach(columns, index->indexParams)
1899  {
1900  iparam = (IndexElem *) lfirst(columns);
1901  if (iparam->name && strcmp(key, iparam->name) == 0)
1902  {
1903  if (index->primary)
1904  ereport(ERROR,
1905  (errcode(ERRCODE_DUPLICATE_COLUMN),
1906  errmsg("column \"%s\" appears twice in primary key constraint",
1907  key),
1908  parser_errposition(cxt->pstate, constraint->location)));
1909  else
1910  ereport(ERROR,
1911  (errcode(ERRCODE_DUPLICATE_COLUMN),
1912  errmsg("column \"%s\" appears twice in unique constraint",
1913  key),
1914  parser_errposition(cxt->pstate, constraint->location)));
1915  }
1916  }
1917 
1918  /* OK, add it to the index definition */
1919  iparam = makeNode(IndexElem);
1920  iparam->name = pstrdup(key);
1921  iparam->expr = NULL;
1922  iparam->indexcolname = NULL;
1923  iparam->collation = NIL;
1924  iparam->opclass = NIL;
1925  iparam->ordering = SORTBY_DEFAULT;
1927  index->indexParams = lappend(index->indexParams, iparam);
1928  }
1929 
1930  return index;
1931 }
1932 
1933 /*
1934  * transformCheckConstraints
1935  * handle CHECK constraints
1936  *
1937  * Right now, there's nothing to do here when called from ALTER TABLE,
1938  * but the other constraint-transformation functions are called in both
1939  * the CREATE TABLE and ALTER TABLE paths, so do the same here, and just
1940  * don't do anything if we're not authorized to skip validation.
1941  */
1942 static void
1944 {
1945  ListCell *ckclist;
1946 
1947  if (cxt->ckconstraints == NIL)
1948  return;
1949 
1950  /*
1951  * If creating a new table, we can safely skip validation of check
1952  * constraints, and nonetheless mark them valid. (This will override
1953  * any user-supplied NOT VALID flag.)
1954  */
1955  if (skipValidation)
1956  {
1957  foreach(ckclist, cxt->ckconstraints)
1958  {
1959  Constraint *constraint = (Constraint *) lfirst(ckclist);
1960 
1961  constraint->skip_validation = true;
1962  constraint->initially_valid = true;
1963  }
1964  }
1965 }
1966 
1967 /*
1968  * transformFKConstraints
1969  * handle FOREIGN KEY constraints
1970  */
1971 static void
1973  bool skipValidation, bool isAddConstraint)
1974 {
1975  ListCell *fkclist;
1976 
1977  if (cxt->fkconstraints == NIL)
1978  return;
1979 
1980  /*
1981  * If CREATE TABLE or adding a column with NULL default, we can safely
1982  * skip validation of FK constraints, and nonetheless mark them valid.
1983  * (This will override any user-supplied NOT VALID flag.)
1984  */
1985  if (skipValidation)
1986  {
1987  foreach(fkclist, cxt->fkconstraints)
1988  {
1989  Constraint *constraint = (Constraint *) lfirst(fkclist);
1990 
1991  constraint->skip_validation = true;
1992  constraint->initially_valid = true;
1993  }
1994  }
1995 
1996  /*
1997  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1998  * CONSTRAINT command to execute after the basic command is complete. (If
1999  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2000  * its own subcommand list.)
2001  *
2002  * Note: the ADD CONSTRAINT command must also execute after any index
2003  * creation commands. Thus, this should run after
2004  * transformIndexConstraints, so that the CREATE INDEX commands are
2005  * already in cxt->alist.
2006  */
2007  if (!isAddConstraint)
2008  {
2009  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2010 
2011  alterstmt->relation = cxt->relation;
2012  alterstmt->cmds = NIL;
2013  alterstmt->relkind = OBJECT_TABLE;
2014 
2015  foreach(fkclist, cxt->fkconstraints)
2016  {
2017  Constraint *constraint = (Constraint *) lfirst(fkclist);
2018  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2019 
2020  altercmd->subtype = AT_ProcessedConstraint;
2021  altercmd->name = NULL;
2022  altercmd->def = (Node *) constraint;
2023  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2024  }
2025 
2026  cxt->alist = lappend(cxt->alist, alterstmt);
2027  }
2028 }
2029 
2030 /*
2031  * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
2032  *
2033  * Note: this is a no-op for an index not using either index expressions or
2034  * a predicate expression. There are several code paths that create indexes
2035  * without bothering to call this, because they know they don't have any
2036  * such expressions to deal with.
2037  *
2038  * To avoid race conditions, it's important that this function rely only on
2039  * the passed-in relid (and not on stmt->relation) to determine the target
2040  * relation.
2041  */
2042 IndexStmt *
2043 transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
2044 {
2045  ParseState *pstate;
2046  RangeTblEntry *rte;
2047  ListCell *l;
2048  Relation rel;
2049 
2050  /* Nothing to do if statement already transformed. */
2051  if (stmt->transformed)
2052  return stmt;
2053 
2054  /*
2055  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2056  * overkill, but easy.)
2057  */
2058  stmt = (IndexStmt *) copyObject(stmt);
2059 
2060  /* Set up pstate */
2061  pstate = make_parsestate(NULL);
2062  pstate->p_sourcetext = queryString;
2063 
2064  /*
2065  * Put the parent table into the rtable so that the expressions can refer
2066  * to its fields without qualification. Caller is responsible for locking
2067  * relation, but we still need to open it.
2068  */
2069  rel = relation_open(relid, NoLock);
2070  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2071 
2072  /* no to join list, yes to namespaces */
2073  addRTEtoQuery(pstate, rte, false, true, true);
2074 
2075  /* take care of the where clause */
2076  if (stmt->whereClause)
2077  {
2078  stmt->whereClause = transformWhereClause(pstate,
2079  stmt->whereClause,
2081  "WHERE");
2082  /* we have to fix its collations too */
2083  assign_expr_collations(pstate, stmt->whereClause);
2084  }
2085 
2086  /* take care of any index expressions */
2087  foreach(l, stmt->indexParams)
2088  {
2089  IndexElem *ielem = (IndexElem *) lfirst(l);
2090 
2091  if (ielem->expr)
2092  {
2093  /* Extract preliminary index col name before transforming expr */
2094  if (ielem->indexcolname == NULL)
2095  ielem->indexcolname = FigureIndexColname(ielem->expr);
2096 
2097  /* Now do parse transformation of the expression */
2098  ielem->expr = transformExpr(pstate, ielem->expr,
2100 
2101  /* We have to fix its collations too */
2102  assign_expr_collations(pstate, ielem->expr);
2103 
2104  /*
2105  * transformExpr() should have already rejected subqueries,
2106  * aggregates, and window functions, based on the EXPR_KIND_ for
2107  * an index expression.
2108  *
2109  * Also reject expressions returning sets; this is for consistency
2110  * with what transformWhereClause() checks for the predicate.
2111  * DefineIndex() will make more checks.
2112  */
2113  if (expression_returns_set(ielem->expr))
2114  ereport(ERROR,
2115  (errcode(ERRCODE_DATATYPE_MISMATCH),
2116  errmsg("index expression cannot return a set")));
2117  }
2118  }
2119 
2120  /*
2121  * Check that only the base rel is mentioned. (This should be dead code
2122  * now that add_missing_from is history.)
2123  */
2124  if (list_length(pstate->p_rtable) != 1)
2125  ereport(ERROR,
2126  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2127  errmsg("index expressions and predicates can refer only to the table being indexed")));
2128 
2129  free_parsestate(pstate);
2130 
2131  /* Close relation */
2132  heap_close(rel, NoLock);
2133 
2134  /* Mark statement as successfully transformed */
2135  stmt->transformed = true;
2136 
2137  return stmt;
2138 }
2139 
2140 
2141 /*
2142  * transformRuleStmt -
2143  * transform a CREATE RULE Statement. The action is a list of parse
2144  * trees which is transformed into a list of query trees, and we also
2145  * transform the WHERE clause if any.
2146  *
2147  * actions and whereClause are output parameters that receive the
2148  * transformed results.
2149  *
2150  * Note that we must not scribble on the passed-in RuleStmt, so we do
2151  * copyObject() on the actions and WHERE clause.
2152  */
2153 void
2154 transformRuleStmt(RuleStmt *stmt, const char *queryString,
2155  List **actions, Node **whereClause)
2156 {
2157  Relation rel;
2158  ParseState *pstate;
2159  RangeTblEntry *oldrte;
2160  RangeTblEntry *newrte;
2161 
2162  /*
2163  * To avoid deadlock, make sure the first thing we do is grab
2164  * AccessExclusiveLock on the target relation. This will be needed by
2165  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2166  * beforehand.
2167  */
2169 
2170  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2171  ereport(ERROR,
2172  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2173  errmsg("rules on materialized views are not supported")));
2174 
2175  /* Set up pstate */
2176  pstate = make_parsestate(NULL);
2177  pstate->p_sourcetext = queryString;
2178 
2179  /*
2180  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2181  * Set up their RTEs in the main pstate for use in parsing the rule
2182  * qualification.
2183  */
2184  oldrte = addRangeTableEntryForRelation(pstate, rel,
2185  makeAlias("old", NIL),
2186  false, false);
2187  newrte = addRangeTableEntryForRelation(pstate, rel,
2188  makeAlias("new", NIL),
2189  false, false);
2190  /* Must override addRangeTableEntry's default access-check flags */
2191  oldrte->requiredPerms = 0;
2192  newrte->requiredPerms = 0;
2193 
2194  /*
2195  * They must be in the namespace too for lookup purposes, but only add the
2196  * one(s) that are relevant for the current kind of rule. In an UPDATE
2197  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2198  * there's no need to be so picky for INSERT & DELETE. We do not add them
2199  * to the joinlist.
2200  */
2201  switch (stmt->event)
2202  {
2203  case CMD_SELECT:
2204  addRTEtoQuery(pstate, oldrte, false, true, true);
2205  break;
2206  case CMD_UPDATE:
2207  addRTEtoQuery(pstate, oldrte, false, true, true);
2208  addRTEtoQuery(pstate, newrte, false, true, true);
2209  break;
2210  case CMD_INSERT:
2211  addRTEtoQuery(pstate, newrte, false, true, true);
2212  break;
2213  case CMD_DELETE:
2214  addRTEtoQuery(pstate, oldrte, false, true, true);
2215  break;
2216  default:
2217  elog(ERROR, "unrecognized event type: %d",
2218  (int) stmt->event);
2219  break;
2220  }
2221 
2222  /* take care of the where clause */
2223  *whereClause = transformWhereClause(pstate,
2224  (Node *) copyObject(stmt->whereClause),
2226  "WHERE");
2227  /* we have to fix its collations too */
2228  assign_expr_collations(pstate, *whereClause);
2229 
2230  /* this is probably dead code without add_missing_from: */
2231  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2232  ereport(ERROR,
2233  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2234  errmsg("rule WHERE condition cannot contain references to other relations")));
2235 
2236  /*
2237  * 'instead nothing' rules with a qualification need a query rangetable so
2238  * the rewrite handler can add the negated rule qualification to the
2239  * original query. We create a query with the new command type CMD_NOTHING
2240  * here that is treated specially by the rewrite system.
2241  */
2242  if (stmt->actions == NIL)
2243  {
2244  Query *nothing_qry = makeNode(Query);
2245 
2246  nothing_qry->commandType = CMD_NOTHING;
2247  nothing_qry->rtable = pstate->p_rtable;
2248  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2249 
2250  *actions = list_make1(nothing_qry);
2251  }
2252  else
2253  {
2254  ListCell *l;
2255  List *newactions = NIL;
2256 
2257  /*
2258  * transform each statement, like parse_sub_analyze()
2259  */
2260  foreach(l, stmt->actions)
2261  {
2262  Node *action = (Node *) lfirst(l);
2263  ParseState *sub_pstate = make_parsestate(NULL);
2264  Query *sub_qry,
2265  *top_subqry;
2266  bool has_old,
2267  has_new;
2268 
2269  /*
2270  * Since outer ParseState isn't parent of inner, have to pass down
2271  * the query text by hand.
2272  */
2273  sub_pstate->p_sourcetext = queryString;
2274 
2275  /*
2276  * Set up OLD/NEW in the rtable for this statement. The entries
2277  * are added only to relnamespace, not varnamespace, because we
2278  * don't want them to be referred to by unqualified field names
2279  * nor "*" in the rule actions. We decide later whether to put
2280  * them in the joinlist.
2281  */
2282  oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2283  makeAlias("old", NIL),
2284  false, false);
2285  newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2286  makeAlias("new", NIL),
2287  false, false);
2288  oldrte->requiredPerms = 0;
2289  newrte->requiredPerms = 0;
2290  addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2291  addRTEtoQuery(sub_pstate, newrte, false, true, false);
2292 
2293  /* Transform the rule action statement */
2294  top_subqry = transformStmt(sub_pstate,
2295  (Node *) copyObject(action));
2296 
2297  /*
2298  * We cannot support utility-statement actions (eg NOTIFY) with
2299  * nonempty rule WHERE conditions, because there's no way to make
2300  * the utility action execute conditionally.
2301  */
2302  if (top_subqry->commandType == CMD_UTILITY &&
2303  *whereClause != NULL)
2304  ereport(ERROR,
2305  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2306  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2307 
2308  /*
2309  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2310  * into the SELECT, and that's what we need to look at. (Ugly
2311  * kluge ... try to fix this when we redesign querytrees.)
2312  */
2313  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2314 
2315  /*
2316  * If the sub_qry is a setop, we cannot attach any qualifications
2317  * to it, because the planner won't notice them. This could
2318  * perhaps be relaxed someday, but for now, we may as well reject
2319  * such a rule immediately.
2320  */
2321  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2322  ereport(ERROR,
2323  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2324  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2325 
2326  /*
2327  * Validate action's use of OLD/NEW, qual too
2328  */
2329  has_old =
2330  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2331  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2332  has_new =
2333  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2334  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2335 
2336  switch (stmt->event)
2337  {
2338  case CMD_SELECT:
2339  if (has_old)
2340  ereport(ERROR,
2341  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2342  errmsg("ON SELECT rule cannot use OLD")));
2343  if (has_new)
2344  ereport(ERROR,
2345  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2346  errmsg("ON SELECT rule cannot use NEW")));
2347  break;
2348  case CMD_UPDATE:
2349  /* both are OK */
2350  break;
2351  case CMD_INSERT:
2352  if (has_old)
2353  ereport(ERROR,
2354  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2355  errmsg("ON INSERT rule cannot use OLD")));
2356  break;
2357  case CMD_DELETE:
2358  if (has_new)
2359  ereport(ERROR,
2360  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2361  errmsg("ON DELETE rule cannot use NEW")));
2362  break;
2363  default:
2364  elog(ERROR, "unrecognized event type: %d",
2365  (int) stmt->event);
2366  break;
2367  }
2368 
2369  /*
2370  * OLD/NEW are not allowed in WITH queries, because they would
2371  * amount to outer references for the WITH, which we disallow.
2372  * However, they were already in the outer rangetable when we
2373  * analyzed the query, so we have to check.
2374  *
2375  * Note that in the INSERT...SELECT case, we need to examine the
2376  * CTE lists of both top_subqry and sub_qry.
2377  *
2378  * Note that we aren't digging into the body of the query looking
2379  * for WITHs in nested sub-SELECTs. A WITH down there can
2380  * legitimately refer to OLD/NEW, because it'd be an
2381  * indirect-correlated outer reference.
2382  */
2383  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2384  PRS2_OLD_VARNO, 0) ||
2385  rangeTableEntry_used((Node *) sub_qry->cteList,
2386  PRS2_OLD_VARNO, 0))
2387  ereport(ERROR,
2388  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2389  errmsg("cannot refer to OLD within WITH query")));
2390  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2391  PRS2_NEW_VARNO, 0) ||
2392  rangeTableEntry_used((Node *) sub_qry->cteList,
2393  PRS2_NEW_VARNO, 0))
2394  ereport(ERROR,
2395  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2396  errmsg("cannot refer to NEW within WITH query")));
2397 
2398  /*
2399  * For efficiency's sake, add OLD to the rule action's jointree
2400  * only if it was actually referenced in the statement or qual.
2401  *
2402  * For INSERT, NEW is not really a relation (only a reference to
2403  * the to-be-inserted tuple) and should never be added to the
2404  * jointree.
2405  *
2406  * For UPDATE, we treat NEW as being another kind of reference to
2407  * OLD, because it represents references to *transformed* tuples
2408  * of the existing relation. It would be wrong to enter NEW
2409  * separately in the jointree, since that would cause a double
2410  * join of the updated relation. It's also wrong to fail to make
2411  * a jointree entry if only NEW and not OLD is mentioned.
2412  */
2413  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2414  {
2415  /*
2416  * If sub_qry is a setop, manipulating its jointree will do no
2417  * good at all, because the jointree is dummy. (This should be
2418  * a can't-happen case because of prior tests.)
2419  */
2420  if (sub_qry->setOperations != NULL)
2421  ereport(ERROR,
2422  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2423  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2424  /* hack so we can use addRTEtoQuery() */
2425  sub_pstate->p_rtable = sub_qry->rtable;
2426  sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2427  addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2428  sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2429  }
2430 
2431  newactions = lappend(newactions, top_subqry);
2432 
2433  free_parsestate(sub_pstate);
2434  }
2435 
2436  *actions = newactions;
2437  }
2438 
2439  free_parsestate(pstate);
2440 
2441  /* Close relation, but keep the exclusive lock */
2442  heap_close(rel, NoLock);
2443 }
2444 
2445 
2446 /*
2447  * transformAlterTableStmt -
2448  * parse analysis for ALTER TABLE
2449  *
2450  * Returns a List of utility commands to be done in sequence. One of these
2451  * will be the transformed AlterTableStmt, but there may be additional actions
2452  * to be done before and after the actual AlterTable() call.
2453  *
2454  * To avoid race conditions, it's important that this function rely only on
2455  * the passed-in relid (and not on stmt->relation) to determine the target
2456  * relation.
2457  */
2458 List *
2460  const char *queryString)
2461 {
2462  Relation rel;
2463  ParseState *pstate;
2464  CreateStmtContext cxt;
2465  List *result;
2466  List *save_alist;
2467  ListCell *lcmd,
2468  *l;
2469  List *newcmds = NIL;
2470  bool skipValidation = true;
2471  AlterTableCmd *newcmd;
2472  RangeTblEntry *rte;
2473 
2474  /*
2475  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2476  * is overkill, but easy.)
2477  */
2478  stmt = (AlterTableStmt *) copyObject(stmt);
2479 
2480  /* Caller is responsible for locking the relation */
2481  rel = relation_open(relid, NoLock);
2482 
2483  /* Set up pstate */
2484  pstate = make_parsestate(NULL);
2485  pstate->p_sourcetext = queryString;
2486  rte = addRangeTableEntryForRelation(pstate,
2487  rel,
2488  NULL,
2489  false,
2490  true);
2491  addRTEtoQuery(pstate, rte, false, true, true);
2492 
2493  /* Set up CreateStmtContext */
2494  cxt.pstate = pstate;
2495  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2496  {
2497  cxt.stmtType = "ALTER FOREIGN TABLE";
2498  cxt.isforeign = true;
2499  }
2500  else
2501  {
2502  cxt.stmtType = "ALTER TABLE";
2503  cxt.isforeign = false;
2504  }
2505  cxt.relation = stmt->relation;
2506  cxt.rel = rel;
2507  cxt.inhRelations = NIL;
2508  cxt.isalter = true;
2509  cxt.hasoids = false; /* need not be right */
2510  cxt.columns = NIL;
2511  cxt.ckconstraints = NIL;
2512  cxt.fkconstraints = NIL;
2513  cxt.ixconstraints = NIL;
2514  cxt.inh_indexes = NIL;
2515  cxt.blist = NIL;
2516  cxt.alist = NIL;
2517  cxt.pkey = NULL;
2518 
2519  /*
2520  * The only subtypes that currently require parse transformation handling
2521  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
2522  * code from CREATE TABLE.
2523  */
2524  foreach(lcmd, stmt->cmds)
2525  {
2526  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2527 
2528  switch (cmd->subtype)
2529  {
2530  case AT_AddColumn:
2531  case AT_AddColumnToView:
2532  {
2533  ColumnDef *def = (ColumnDef *) cmd->def;
2534 
2535  Assert(IsA(def, ColumnDef));
2536  transformColumnDefinition(&cxt, def);
2537 
2538  /*
2539  * If the column has a non-null default, we can't skip
2540  * validation of foreign keys.
2541  */
2542  if (def->raw_default != NULL)
2543  skipValidation = false;
2544 
2545  /*
2546  * All constraints are processed in other ways. Remove the
2547  * original list
2548  */
2549  def->constraints = NIL;
2550 
2551  newcmds = lappend(newcmds, cmd);
2552  break;
2553  }
2554 
2555  case AT_AddConstraint:
2556 
2557  /*
2558  * The original AddConstraint cmd node doesn't go to newcmds
2559  */
2560  if (IsA(cmd->def, Constraint))
2561  {
2562  transformTableConstraint(&cxt, (Constraint *) cmd->def);
2563  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
2564  skipValidation = false;
2565  }
2566  else
2567  elog(ERROR, "unrecognized node type: %d",
2568  (int) nodeTag(cmd->def));
2569  break;
2570 
2572 
2573  /*
2574  * Already-transformed ADD CONSTRAINT, so just make it look
2575  * like the standard case.
2576  */
2577  cmd->subtype = AT_AddConstraint;
2578  newcmds = lappend(newcmds, cmd);
2579  break;
2580 
2581  case AT_AlterColumnType:
2582  {
2583  ColumnDef *def = (ColumnDef *) cmd->def;
2584 
2585  /*
2586  * For ALTER COLUMN TYPE, transform the USING clause if
2587  * one was specified.
2588  */
2589  if (def->raw_default)
2590  {
2591  def->cooked_default =
2592  transformExpr(pstate, def->raw_default,
2594 
2595  /* it can't return a set */
2597  ereport(ERROR,
2598  (errcode(ERRCODE_DATATYPE_MISMATCH),
2599  errmsg("transform expression must not return a set")));
2600  }
2601 
2602  newcmds = lappend(newcmds, cmd);
2603  break;
2604  }
2605 
2606  default:
2607  newcmds = lappend(newcmds, cmd);
2608  break;
2609  }
2610  }
2611 
2612  /*
2613  * transformIndexConstraints wants cxt.alist to contain only index
2614  * statements, so transfer anything we already have into save_alist
2615  * immediately.
2616  */
2617  save_alist = cxt.alist;
2618  cxt.alist = NIL;
2619 
2620  /* Postprocess constraints */
2622  transformFKConstraints(&cxt, skipValidation, true);
2623  transformCheckConstraints(&cxt, false);
2624 
2625  /*
2626  * Push any index-creation commands into the ALTER, so that they can be
2627  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
2628  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
2629  * subcommand has already been through transformIndexStmt.
2630  */
2631  foreach(l, cxt.alist)
2632  {
2633  IndexStmt *idxstmt = (IndexStmt *) lfirst(l);
2634 
2635  Assert(IsA(idxstmt, IndexStmt));
2636  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
2637  newcmd = makeNode(AlterTableCmd);
2639  newcmd->def = (Node *) idxstmt;
2640  newcmds = lappend(newcmds, newcmd);
2641  }
2642  cxt.alist = NIL;
2643 
2644  /* Append any CHECK or FK constraints to the commands list */
2645  foreach(l, cxt.ckconstraints)
2646  {
2647  newcmd = makeNode(AlterTableCmd);
2648  newcmd->subtype = AT_AddConstraint;
2649  newcmd->def = (Node *) lfirst(l);
2650  newcmds = lappend(newcmds, newcmd);
2651  }
2652  foreach(l, cxt.fkconstraints)
2653  {
2654  newcmd = makeNode(AlterTableCmd);
2655  newcmd->subtype = AT_AddConstraint;
2656  newcmd->def = (Node *) lfirst(l);
2657  newcmds = lappend(newcmds, newcmd);
2658  }
2659 
2660  /* Close rel */
2661  relation_close(rel, NoLock);
2662 
2663  /*
2664  * Output results.
2665  */
2666  stmt->cmds = newcmds;
2667 
2668  result = lappend(cxt.blist, stmt);
2669  result = list_concat(result, cxt.alist);
2670  result = list_concat(result, save_alist);
2671 
2672  return result;
2673 }
2674 
2675 
2676 /*
2677  * Preprocess a list of column constraint clauses
2678  * to attach constraint attributes to their primary constraint nodes
2679  * and detect inconsistent/misplaced constraint attributes.
2680  *
2681  * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
2682  * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
2683  * supported for other constraint types.
2684  */
2685 static void
2687 {
2688  Constraint *lastprimarycon = NULL;
2689  bool saw_deferrability = false;
2690  bool saw_initially = false;
2691  ListCell *clist;
2692 
2693 #define SUPPORTS_ATTRS(node) \
2694  ((node) != NULL && \
2695  ((node)->contype == CONSTR_PRIMARY || \
2696  (node)->contype == CONSTR_UNIQUE || \
2697  (node)->contype == CONSTR_EXCLUSION || \
2698  (node)->contype == CONSTR_FOREIGN))
2699 
2700  foreach(clist, constraintList)
2701  {
2702  Constraint *con = (Constraint *) lfirst(clist);
2703 
2704  if (!IsA(con, Constraint))
2705  elog(ERROR, "unrecognized node type: %d",
2706  (int) nodeTag(con));
2707  switch (con->contype)
2708  {
2710  if (!SUPPORTS_ATTRS(lastprimarycon))
2711  ereport(ERROR,
2712  (errcode(ERRCODE_SYNTAX_ERROR),
2713  errmsg("misplaced DEFERRABLE clause"),
2714  parser_errposition(cxt->pstate, con->location)));
2715  if (saw_deferrability)
2716  ereport(ERROR,
2717  (errcode(ERRCODE_SYNTAX_ERROR),
2718  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2719  parser_errposition(cxt->pstate, con->location)));
2720  saw_deferrability = true;
2721  lastprimarycon->deferrable = true;
2722  break;
2723 
2725  if (!SUPPORTS_ATTRS(lastprimarycon))
2726  ereport(ERROR,
2727  (errcode(ERRCODE_SYNTAX_ERROR),
2728  errmsg("misplaced NOT DEFERRABLE clause"),
2729  parser_errposition(cxt->pstate, con->location)));
2730  if (saw_deferrability)
2731  ereport(ERROR,
2732  (errcode(ERRCODE_SYNTAX_ERROR),
2733  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
2734  parser_errposition(cxt->pstate, con->location)));
2735  saw_deferrability = true;
2736  lastprimarycon->deferrable = false;
2737  if (saw_initially &&
2738  lastprimarycon->initdeferred)
2739  ereport(ERROR,
2740  (errcode(ERRCODE_SYNTAX_ERROR),
2741  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2742  parser_errposition(cxt->pstate, con->location)));
2743  break;
2744 
2745  case CONSTR_ATTR_DEFERRED:
2746  if (!SUPPORTS_ATTRS(lastprimarycon))
2747  ereport(ERROR,
2748  (errcode(ERRCODE_SYNTAX_ERROR),
2749  errmsg("misplaced INITIALLY DEFERRED clause"),
2750  parser_errposition(cxt->pstate, con->location)));
2751  if (saw_initially)
2752  ereport(ERROR,
2753  (errcode(ERRCODE_SYNTAX_ERROR),
2754  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2755  parser_errposition(cxt->pstate, con->location)));
2756  saw_initially = true;
2757  lastprimarycon->initdeferred = true;
2758 
2759  /*
2760  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
2761  */
2762  if (!saw_deferrability)
2763  lastprimarycon->deferrable = true;
2764  else if (!lastprimarycon->deferrable)
2765  ereport(ERROR,
2766  (errcode(ERRCODE_SYNTAX_ERROR),
2767  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2768  parser_errposition(cxt->pstate, con->location)));
2769  break;
2770 
2771  case CONSTR_ATTR_IMMEDIATE:
2772  if (!SUPPORTS_ATTRS(lastprimarycon))
2773  ereport(ERROR,
2774  (errcode(ERRCODE_SYNTAX_ERROR),
2775  errmsg("misplaced INITIALLY IMMEDIATE clause"),
2776  parser_errposition(cxt->pstate, con->location)));
2777  if (saw_initially)
2778  ereport(ERROR,
2779  (errcode(ERRCODE_SYNTAX_ERROR),
2780  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
2781  parser_errposition(cxt->pstate, con->location)));
2782  saw_initially = true;
2783  lastprimarycon->initdeferred = false;
2784  break;
2785 
2786  default:
2787  /* Otherwise it's not an attribute */
2788  lastprimarycon = con;
2789  /* reset flags for new primary node */
2790  saw_deferrability = false;
2791  saw_initially = false;
2792  break;
2793  }
2794  }
2795 }
2796 
2797 /*
2798  * Special handling of type definition for a column
2799  */
2800 static void
2802 {
2803  /*
2804  * All we really need to do here is verify that the type is valid,
2805  * including any collation spec that might be present.
2806  */
2807  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
2808 
2809  if (column->collClause)
2810  {
2811  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
2812 
2813  LookupCollation(cxt->pstate,
2814  column->collClause->collname,
2815  column->collClause->location);
2816  /* Complain if COLLATE is applied to an uncollatable type */
2817  if (!OidIsValid(typtup->typcollation))
2818  ereport(ERROR,
2819  (errcode(ERRCODE_DATATYPE_MISMATCH),
2820  errmsg("collations are not supported by type %s",
2823  column->collClause->location)));
2824  }
2825 
2826  ReleaseSysCache(ctype);
2827 }
2828 
2829 
2830 /*
2831  * transformCreateSchemaStmt -
2832  * analyzes the CREATE SCHEMA statement
2833  *
2834  * Split the schema element list into individual commands and place
2835  * them in the result list in an order such that there are no forward
2836  * references (e.g. GRANT to a table created later in the list). Note
2837  * that the logic we use for determining forward references is
2838  * presently quite incomplete.
2839  *
2840  * SQL also allows constraints to make forward references, so thumb through
2841  * the table columns and move forward references to a posterior alter-table
2842  * command.
2843  *
2844  * The result is a list of parse nodes that still need to be analyzed ---
2845  * but we can't analyze the later commands until we've executed the earlier
2846  * ones, because of possible inter-object references.
2847  *
2848  * Note: this breaks the rules a little bit by modifying schema-name fields
2849  * within passed-in structs. However, the transformation would be the same
2850  * if done over, so it should be all right to scribble on the input to this
2851  * extent.
2852  */
2853 List *
2855 {
2857  List *result;
2858  ListCell *elements;
2859 
2860  cxt.stmtType = "CREATE SCHEMA";
2861  cxt.schemaname = stmt->schemaname;
2862  cxt.authrole = (RoleSpec *) stmt->authrole;
2863  cxt.sequences = NIL;
2864  cxt.tables = NIL;
2865  cxt.views = NIL;
2866  cxt.indexes = NIL;
2867  cxt.triggers = NIL;
2868  cxt.grants = NIL;
2869 
2870  /*
2871  * Run through each schema element in the schema element list. Separate
2872  * statements by type, and do preliminary analysis.
2873  */
2874  foreach(elements, stmt->schemaElts)
2875  {
2876  Node *element = lfirst(elements);
2877 
2878  switch (nodeTag(element))
2879  {
2880  case T_CreateSeqStmt:
2881  {
2882  CreateSeqStmt *elp = (CreateSeqStmt *) element;
2883 
2885  cxt.sequences = lappend(cxt.sequences, element);
2886  }
2887  break;
2888 
2889  case T_CreateStmt:
2890  {
2891  CreateStmt *elp = (CreateStmt *) element;
2892 
2894 
2895  /*
2896  * XXX todo: deal with constraints
2897  */
2898  cxt.tables = lappend(cxt.tables, element);
2899  }
2900  break;
2901 
2902  case T_ViewStmt:
2903  {
2904  ViewStmt *elp = (ViewStmt *) element;
2905 
2906  setSchemaName(cxt.schemaname, &elp->view->schemaname);
2907 
2908  /*
2909  * XXX todo: deal with references between views
2910  */
2911  cxt.views = lappend(cxt.views, element);
2912  }
2913  break;
2914 
2915  case T_IndexStmt:
2916  {
2917  IndexStmt *elp = (IndexStmt *) element;
2918 
2920  cxt.indexes = lappend(cxt.indexes, element);
2921  }
2922  break;
2923 
2924  case T_CreateTrigStmt:
2925  {
2926  CreateTrigStmt *elp = (CreateTrigStmt *) element;
2927 
2929  cxt.triggers = lappend(cxt.triggers, element);
2930  }
2931  break;
2932 
2933  case T_GrantStmt:
2934  cxt.grants = lappend(cxt.grants, element);
2935  break;
2936 
2937  default:
2938  elog(ERROR, "unrecognized node type: %d",
2939  (int) nodeTag(element));
2940  }
2941  }
2942 
2943  result = NIL;
2944  result = list_concat(result, cxt.sequences);
2945  result = list_concat(result, cxt.tables);
2946  result = list_concat(result, cxt.views);
2947  result = list_concat(result, cxt.indexes);
2948  result = list_concat(result, cxt.triggers);
2949  result = list_concat(result, cxt.grants);
2950 
2951  return result;
2952 }
2953 
2954 /*
2955  * setSchemaName
2956  * Set or check schema name in an element of a CREATE SCHEMA command
2957  */
2958 static void
2959 setSchemaName(char *context_schema, char **stmt_schema_name)
2960 {
2961  if (*stmt_schema_name == NULL)
2962  *stmt_schema_name = context_schema;
2963  else if (strcmp(context_schema, *stmt_schema_name) != 0)
2964  ereport(ERROR,
2965  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
2966  errmsg("CREATE specifies a schema (%s) "
2967  "different from the one being created (%s)",
2968  *stmt_schema_name, context_schema)));
2969 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
bool deferrable
Definition: parsenodes.h:2451
RangeVar * relation
Definition: parsenodes.h:1749
ObjectType objtype
Definition: parsenodes.h:2340
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrNumber *attno_map, int map_length, bool *found_whole_row)
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:135
signed short int16
Definition: c.h:252
#define NIL
Definition: pg_list.h:69
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:473
bool primary
Definition: parsenodes.h:2449
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1206
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
List * inhRelations
Definition: parsenodes.h:1751
List * SystemFuncName(char *name)
void * stringToNode(char *str)
Definition: read.c:38
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:282
Oid typeOid
Definition: parsenodes.h:192
#define IsA(nodeptr, _type_)
Definition: nodes.h:542
List * keys
Definition: parsenodes.h:1838
List * exclusions
Definition: parsenodes.h:1841
int16 * rd_indoption
Definition: rel.h:141
#define DEBUG1
Definition: elog.h:25
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1371
SortByDir ordering
Definition: parsenodes.h:639
List * objname
Definition: parsenodes.h:2341
#define GETSTRUCT(TUP)
Definition: htup_details.h:631
char * ccname
Definition: tupdesc.h:30
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
List * names
Definition: parsenodes.h:191
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2442
char storage
Definition: parsenodes.h:594
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1243
bool is_local
Definition: parsenodes.h:591
FromExpr * jointree
Definition: parsenodes.h:129
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2716
#define RelationGetDescr(relation)
Definition: rel.h:353
Oid GetUserId(void)
Definition: miscinit.c:282
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define OIDOID
Definition: pg_type.h:328
ConstrCheck * check
Definition: tupdesc.h:40
char * tableSpace
Definition: parsenodes.h:2440
#define Anum_pg_class_reloptions
Definition: pg_class.h:130
List * constraints
Definition: parsenodes.h:599
#define DatumGetObjectId(X)
Definition: postgres.h:508
char * pstrdup(const char *in)
Definition: mcxt.c:1168
char * ccbin
Definition: tupdesc.h:31
Node * raw_expr
Definition: parsenodes.h:1834
#define RelationRelationId
Definition: pg_class.h:29
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:664
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:141
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define RELKIND_MATVIEW
Definition: pg_class.h:162
Node * whereClause
Definition: parsenodes.h:2443
#define Anum_pg_index_indclass
Definition: pg_index.h:89
Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids)
Definition: heap.c:208
#define AccessShareLock
Definition: lockdefs.h:36
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:491
#define CONSTRAINT_EXCLUSION
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
char * FigureIndexColname(Node *node)
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1274
bool initdeferred
Definition: parsenodes.h:1829
AlterTableType subtype
Definition: parsenodes.h:1540
List * actions
Definition: parsenodes.h:2607
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
List * list_concat(List *list1, List *list2)
Definition: list.c:321
char * comment
Definition: parsenodes.h:2343
AclMode requiredPerms
Definition: parsenodes.h:867
List * fromlist
Definition: primnodes.h:1383
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:1827
bool is_not_null
Definition: parsenodes.h:592
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
Form_pg_class rd_rel
Definition: rel.h:83
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:530
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:629
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:136
int natts
Definition: tupdesc.h:73
#define lsecond(l)
Definition: pg_list.h:114
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:160
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
List * options
Definition: parsenodes.h:2217
RangeVar * view
Definition: parsenodes.h:2729
List * options
Definition: parsenodes.h:1844
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4228
int location
Definition: parsenodes.h:281
struct HeapTupleData * rd_indextuple
Definition: rel.h:116
char * schemaname
Definition: primnodes.h:73
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void * copyObject(const void *from)
Definition: copyfuncs.c:4262
Definition: type.h:90
List * constraints
Definition: parsenodes.h:1754
#define list_make1(x1)
Definition: pg_list.h:133
bool if_not_exists
Definition: parsenodes.h:1758
int location
Definition: primnodes.h:79
void assign_expr_collations(ParseState *pstate, Node *expr)
ParseState * pstate
Definition: parse_utilcmd.c:72
Node * cooked_default
Definition: parsenodes.h:596
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:384
char * relname
Definition: primnodes.h:74
Value * makeInteger(long i)
Definition: value.c:23
Oid indexOid
Definition: parsenodes.h:2446
Node * expr
Definition: parsenodes.h:635
RangeVar * relation
Definition: parse_utilcmd.c:74
RangeVar * relation
Definition: parsenodes.h:2438
IndexStmt * pkey
Definition: parse_utilcmd.c:89
Form_pg_index rd_index
Definition: rel.h:114
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:158
#define linitial(l)
Definition: pg_list.h:110
AttrDefault * defval
Definition: tupdesc.h:39
List * rtable
Definition: parsenodes.h:128
SortByNulls nulls_ordering
Definition: parsenodes.h:640
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
List * objargs
Definition: parsenodes.h:2342
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
#define FALSE
Definition: c.h:218
bool deferrable
Definition: parsenodes.h:1828
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:4641
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1651
#define INT2OID
Definition: pg_type.h:308
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:184
#define NoLock
Definition: lockdefs.h:34
List * transformAlterTableStmt(Oid relid, AlterTableStmt *stmt, const char *queryString)
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4167
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:481
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3391
bool transformed
Definition: parsenodes.h:2453
Oid collOid
Definition: parsenodes.h:598
union Value::ValUnion val
List * fdwoptions
Definition: parsenodes.h:600
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:636
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:361
List * options
Definition: parsenodes.h:1755
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
#define ACL_USAGE
Definition: parsenodes.h:71
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:679
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:161
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:417
int location
Definition: parsenodes.h:601
const char * p_sourcetext
Definition: parse_node.h:134
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:846
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
ObjectType relkind
Definition: parsenodes.h:1460
#define AssertArg(condition)
Definition: c.h:669
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:142
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:222
Node * raw_default
Definition: parsenodes.h:595
List * lappend(List *list, void *datum)
Definition: list.c:128
#define PRS2_OLD_VARNO
Definition: primnodes.h:145
char * idxname
Definition: parsenodes.h:2437
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:9604
DefElem * makeDefElem(char *name, Node *arg)
Definition: makefuncs.c:513
char * get_relid_attribute_name(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:801
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:522
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:550
TypeName * SystemTypeName(char *name)
#define TextDatumGetCString(d)
Definition: builtins.h:807
bool if_not_exists
Definition: parsenodes.h:2455
void * palloc0(Size size)
Definition: mcxt.c:923
AclResult
Definition: acl.h:169
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
#define ACL_SELECT
Definition: parsenodes.h:64
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1152
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2448
TypeName * typeName
Definition: parsenodes.h:280
List * untransformRelOptions(Datum options)
Definition: reloptions.c:856
TupleDesc rd_att
Definition: rel.h:84
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:497
char * accessMethod
Definition: parsenodes.h:2439
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:469
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1326
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:194
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2216
bool initially_valid
Definition: parsenodes.h:1863
uint16 num_defval
Definition: tupdesc.h:41
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2749
RangeVar * sequence
Definition: parsenodes.h:2207
List * opclass
Definition: parsenodes.h:638
bool is_from_type
Definition: parsenodes.h:593
#define NOTICE
Definition: elog.h:37
#define INT8OID
Definition: pg_type.h:304
CmdType commandType
Definition: parsenodes.h:103
List * tableElts
Definition: parsenodes.h:1750
#define Anum_pg_index_indpred
Definition: pg_index.h:92
List * lcons(void *datum, List *list)
Definition: list.c:259
Node * where_clause
Definition: parsenodes.h:1849
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define makeNode(_type_)
Definition: nodes.h:539
CmdType event
Definition: parsenodes.h:2605
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
#define lfirst(lc)
Definition: pg_list.h:106
static void setSchemaName(char *context_schema, char **stmt_schema_name)
int location
Definition: parsenodes.h:270
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
#define INDOPTION_DESC
Definition: pg_index.h:99
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:333
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2441
int location
Definition: parsenodes.h:198
TupleConstr * constr
Definition: tupdesc.h:76
Node * whereClause
Definition: parsenodes.h:2604
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
List * excludeOpNames
Definition: parsenodes.h:2444
static int list_length(const List *l)
Definition: pg_list.h:89
List * transformCreateStmt(CreateStmt *stmt, const char *queryString)
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:108
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
TypeName * typeName
Definition: parsenodes.h:589
CollateClause * collClause
Definition: parsenodes.h:597
bool initdeferred
Definition: parsenodes.h:2452
bool amcanorder
Definition: amapi.h:124
char * name
Definition: parsenodes.h:634
char * idxcomment
Definition: parsenodes.h:2445
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:3843
FormData_pg_operator* Form_pg_operator
Definition: pg_operator.h:57
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:47
#define nodeTag(nodeptr)
Definition: nodes.h:496
const char * stmtType
Definition: parse_utilcmd.c:73
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:171
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4405
char relpersistence
Definition: primnodes.h:77
#define DatumGetPointer(X)
Definition: postgres.h:557
RangeVar * relation
Definition: parsenodes.h:610
#define Anum_pg_index_indcollation
Definition: pg_index.h:88
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:266
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
FormData_pg_class * Form_pg_class
Definition: pg_class.h:92
List * transformCreateSchemaStmt(CreateSchemaStmt *stmt)
bool concurrent
Definition: parsenodes.h:2454
#define AccessExclusiveLock
Definition: lockdefs.h:46
List * collname
Definition: parsenodes.h:291
List * cteList
Definition: parsenodes.h:126
List * arrayBounds
Definition: parsenodes.h:197
Node * setOperations
Definition: parsenodes.h:154
bool isconstraint
Definition: parsenodes.h:2450
char * indexname
Definition: parsenodes.h:1845
FormData_pg_am * Form_pg_am
Definition: pg_am.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
RangeVar * relation
Definition: parsenodes.h:1458
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1430
#define RELKIND_VIEW
Definition: pg_class.h:159
#define SUPPORTS_ATTRS(node)
static IndexStmt * generateClonedIndexStmt(CreateStmtContext *cxt, Relation source_idx, const AttrNumber *attmap, int attmap_length)
char * str
Definition: value.h:48
int i
static celt element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:367
int inhcount
Definition: parsenodes.h:590
RangeVar * relation
Definition: parsenodes.h:2094
#define NameStr(name)
Definition: c.h:494
char * nodeToString(const void *obj)
Definition: outfuncs.c:3819
List * p_joinlist
Definition: parse_node.h:137
ConstrType contype
Definition: parsenodes.h:1824
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1116
List * collation
Definition: parsenodes.h:637
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:889
DropBehavior behavior
Definition: parsenodes.h:1546
uint16 num_check
Definition: tupdesc.h:42
char * colname
Definition: parsenodes.h:588
#define TRUE
Definition: c.h:214
#define ConstraintRelationId
Definition: pg_constraint.h:29
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: indexcmds.c:1559
#define elog
Definition: elog.h:218
char * cooked_expr
Definition: parsenodes.h:1835
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:670
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:166
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4517
RangeVar * relation
Definition: parsenodes.h:2602
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:74
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
#define RELKIND_RELATION
Definition: pg_class.h:155
static List * get_collation(Oid collation, Oid actual_datatype)
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
Value val
Definition: parsenodes.h:269
Definition: pg_list.h:45
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:1862
#define RelationGetRelid(relation)
Definition: rel.h:341
void transformRuleStmt(RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
char * access_method
Definition: parsenodes.h:1848
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:146
List * fk_attrs
Definition: parsenodes.h:1853
#define Anum_pg_constraint_conexclop
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:419
#define PRS2_NEW_VARNO
Definition: primnodes.h:146
TypeName * ofTypename
Definition: parsenodes.h:1753
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:435
char * indexspace
Definition: parsenodes.h:1846
#define lfirst_oid(lc)
Definition: pg_list.h:108
List * options
Definition: parsenodes.h:2208
#define Anum_pg_index_indexprs
Definition: pg_index.h:91
NodeTag type
Definition: value.h:44
bool pct_type
Definition: parsenodes.h:194
Node * arg
Definition: parsenodes.h:279
#define RelationGetNamespace(relation)
Definition: rel.h:368
List * p_rtable
Definition: parse_node.h:135
#define DatumGetArrayTypeP(X)
Definition: array.h:242