PostgreSQL Source Code  git master
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-2018, 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"
39 #include "catalog/pg_opclass.h"
40 #include "catalog/pg_operator.h"
42 #include "catalog/pg_type.h"
43 #include "commands/comment.h"
44 #include "commands/defrem.h"
45 #include "commands/sequence.h"
46 #include "commands/tablecmds.h"
47 #include "commands/tablespace.h"
48 #include "miscadmin.h"
49 #include "nodes/makefuncs.h"
50 #include "nodes/nodeFuncs.h"
51 #include "optimizer/planner.h"
52 #include "parser/analyze.h"
53 #include "parser/parse_clause.h"
54 #include "parser/parse_coerce.h"
55 #include "parser/parse_collate.h"
56 #include "parser/parse_expr.h"
57 #include "parser/parse_relation.h"
58 #include "parser/parse_target.h"
59 #include "parser/parse_type.h"
60 #include "parser/parse_utilcmd.h"
61 #include "parser/parser.h"
62 #include "rewrite/rewriteManip.h"
63 #include "utils/acl.h"
64 #include "utils/builtins.h"
65 #include "utils/lsyscache.h"
66 #include "utils/partcache.h"
67 #include "utils/rel.h"
68 #include "utils/ruleutils.h"
69 #include "utils/syscache.h"
70 #include "utils/typcache.h"
71 
72 
73 /* State shared by transformCreateStmt and its subroutines */
74 typedef struct
75 {
76  ParseState *pstate; /* overall parser state */
77  const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
78  RangeVar *relation; /* relation to create */
79  Relation rel; /* opened/locked rel, if ALTER */
80  List *inhRelations; /* relations to inherit from */
81  bool isforeign; /* true if CREATE/ALTER FOREIGN TABLE */
82  bool isalter; /* true if altering existing table */
83  bool hasoids; /* does relation have an OID column? */
84  List *columns; /* ColumnDef items */
85  List *ckconstraints; /* CHECK constraints */
86  List *fkconstraints; /* FOREIGN KEY constraints */
87  List *ixconstraints; /* index-creating constraints */
88  List *inh_indexes; /* cloned indexes from INCLUDING INDEXES */
89  List *extstats; /* cloned extended statistics */
90  List *blist; /* "before list" of things to do before
91  * creating the table */
92  List *alist; /* "after list" of things to do after creating
93  * the table */
94  IndexStmt *pkey; /* PRIMARY KEY index, if any */
95  bool ispartitioned; /* true if table is partitioned */
96  PartitionBoundSpec *partbound; /* transformed FOR VALUES */
97  bool ofType; /* true if statement contains OF typename */
99 
100 /* State shared by transformCreateSchemaStmt and its subroutines */
101 typedef struct
102 {
103  const char *stmtType; /* "CREATE SCHEMA" or "ALTER SCHEMA" */
104  char *schemaname; /* name of schema */
105  RoleSpec *authrole; /* owner of schema */
106  List *sequences; /* CREATE SEQUENCE items */
107  List *tables; /* CREATE TABLE items */
108  List *views; /* CREATE VIEW items */
109  List *indexes; /* CREATE INDEX items */
110  List *triggers; /* CREATE TRIGGER items */
111  List *grants; /* GRANT items */
113 
114 
116  ColumnDef *column);
118  Constraint *constraint);
120  TableLikeClause *table_like_clause);
121 static void transformOfType(CreateStmtContext *cxt,
122  TypeName *ofTypename);
124  Oid heapRelid, Oid source_statsid);
125 static List *get_collation(Oid collation, Oid actual_datatype);
126 static List *get_opclass(Oid opclass, Oid actual_datatype);
128 static IndexStmt *transformIndexConstraint(Constraint *constraint,
129  CreateStmtContext *cxt);
132  bool skipValidation,
133  bool isAddConstraint);
135  bool skipValidation);
137  List *constraintList);
138 static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column);
139 static void setSchemaName(char *context_schema, char **stmt_schema_name);
141 static void validateInfiniteBounds(ParseState *pstate, List *blist);
143  const char *colName, Oid colType, int32 colTypmod);
144 
145 
146 /*
147  * transformCreateStmt -
148  * parse analysis for CREATE TABLE
149  *
150  * Returns a List of utility commands to be done in sequence. One of these
151  * will be the transformed CreateStmt, but there may be additional actions
152  * to be done before and after the actual DefineRelation() call.
153  *
154  * SQL allows constraints to be scattered all over, so thumb through
155  * the columns and collect all constraints into one place.
156  * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
157  * then expand those into multiple IndexStmt blocks.
158  * - thomas 1997-12-02
159  */
160 List *
161 transformCreateStmt(CreateStmt *stmt, const char *queryString)
162 {
163  ParseState *pstate;
164  CreateStmtContext cxt;
165  List *result;
166  List *save_alist;
167  ListCell *elements;
168  Oid namespaceid;
169  Oid existing_relid;
170  ParseCallbackState pcbstate;
171  bool like_found = false;
172  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
173 
174  /*
175  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
176  * overkill, but easy.)
177  */
178  stmt = copyObject(stmt);
179 
180  /* Set up pstate */
181  pstate = make_parsestate(NULL);
182  pstate->p_sourcetext = queryString;
183 
184  /*
185  * Look up the creation namespace. This also checks permissions on the
186  * target namespace, locks it against concurrent drops, checks for a
187  * preexisting relation in that namespace with the same name, and updates
188  * stmt->relation->relpersistence if the selected namespace is temporary.
189  */
190  setup_parser_errposition_callback(&pcbstate, pstate,
191  stmt->relation->location);
192  namespaceid =
194  &existing_relid);
196 
197  /*
198  * If the relation already exists and the user specified "IF NOT EXISTS",
199  * bail out with a NOTICE.
200  */
201  if (stmt->if_not_exists && OidIsValid(existing_relid))
202  {
203  ereport(NOTICE,
204  (errcode(ERRCODE_DUPLICATE_TABLE),
205  errmsg("relation \"%s\" already exists, skipping",
206  stmt->relation->relname)));
207  return NIL;
208  }
209 
210  /*
211  * If the target relation name isn't schema-qualified, make it so. This
212  * prevents some corner cases in which added-on rewritten commands might
213  * think they should apply to other relations that have the same name and
214  * are earlier in the search path. But a local temp table is effectively
215  * specified to be in pg_temp, so no need for anything extra in that case.
216  */
217  if (stmt->relation->schemaname == NULL
218  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
219  stmt->relation->schemaname = get_namespace_name(namespaceid);
220 
221  /* Set up CreateStmtContext */
222  cxt.pstate = pstate;
223  if (IsA(stmt, CreateForeignTableStmt))
224  {
225  cxt.stmtType = "CREATE FOREIGN TABLE";
226  cxt.isforeign = true;
227  }
228  else
229  {
230  cxt.stmtType = "CREATE TABLE";
231  cxt.isforeign = false;
232  }
233  cxt.relation = stmt->relation;
234  cxt.rel = NULL;
235  cxt.inhRelations = stmt->inhRelations;
236  cxt.isalter = false;
237  cxt.columns = NIL;
238  cxt.ckconstraints = NIL;
239  cxt.fkconstraints = NIL;
240  cxt.ixconstraints = NIL;
241  cxt.inh_indexes = NIL;
242  cxt.extstats = NIL;
243  cxt.blist = NIL;
244  cxt.alist = NIL;
245  cxt.pkey = NULL;
246  cxt.ispartitioned = stmt->partspec != NULL;
247  cxt.partbound = stmt->partbound;
248  cxt.ofType = (stmt->ofTypename != NULL);
249 
250  /*
251  * Notice that we allow OIDs here only for plain tables, even though
252  * foreign tables also support them. This is necessary because the
253  * default_with_oids GUC must apply only to plain tables and not any other
254  * relkind; doing otherwise would break existing pg_dump files. We could
255  * allow explicit "WITH OIDS" while not allowing default_with_oids to
256  * affect other relkinds, but it would complicate interpretOidsOption(),
257  * and right now there's no WITH OIDS option in CREATE FOREIGN TABLE
258  * anyway.
259  */
260  cxt.hasoids = interpretOidsOption(stmt->options, !cxt.isforeign);
261 
262  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
263 
264  if (stmt->ofTypename)
265  transformOfType(&cxt, stmt->ofTypename);
266 
267  if (stmt->partspec)
268  {
269  if (stmt->inhRelations && !stmt->partbound)
270  ereport(ERROR,
271  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
272  errmsg("cannot create partitioned table as inheritance child")));
273  }
274 
275  /*
276  * Run through each primary element in the table creation clause. Separate
277  * column defs from constraints, and do preliminary analysis.
278  */
279  foreach(elements, stmt->tableElts)
280  {
281  Node *element = lfirst(elements);
282 
283  switch (nodeTag(element))
284  {
285  case T_ColumnDef:
286  transformColumnDefinition(&cxt, (ColumnDef *) element);
287  break;
288 
289  case T_Constraint:
290  transformTableConstraint(&cxt, (Constraint *) element);
291  break;
292 
293  case T_TableLikeClause:
294  like_found = true;
295  transformTableLikeClause(&cxt, (TableLikeClause *) element);
296  break;
297 
298  default:
299  elog(ERROR, "unrecognized node type: %d",
300  (int) nodeTag(element));
301  break;
302  }
303  }
304 
305  /*
306  * If we had any LIKE tables, they may require creation of an OID column
307  * even though the command's own WITH clause didn't ask for one (or,
308  * perhaps, even specifically rejected having one). Insert a WITH option
309  * to ensure that happens. We prepend to the list because the first oid
310  * option will be honored, and we want to override anything already there.
311  * (But note that DefineRelation will override this again to add an OID
312  * column if one appears in an inheritance parent table.)
313  */
314  if (like_found && cxt.hasoids)
315  stmt->options = lcons(makeDefElem("oids",
316  (Node *) makeInteger(true), -1),
317  stmt->options);
318 
319  /*
320  * transformIndexConstraints wants cxt.alist to contain only index
321  * statements, so transfer anything we already have into save_alist.
322  */
323  save_alist = cxt.alist;
324  cxt.alist = NIL;
325 
326  Assert(stmt->constraints == NIL);
327 
328  /*
329  * Postprocess constraints that give rise to index definitions.
330  */
332 
333  /*
334  * Postprocess foreign-key constraints.
335  */
336  transformFKConstraints(&cxt, true, false);
337 
338  /*
339  * Postprocess check constraints.
340  */
341  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
342 
343  /*
344  * Postprocess extended statistics.
345  */
347 
348  /*
349  * Output results.
350  */
351  stmt->tableElts = cxt.columns;
352  stmt->constraints = cxt.ckconstraints;
353 
354  result = lappend(cxt.blist, stmt);
355  result = list_concat(result, cxt.alist);
356  result = list_concat(result, save_alist);
357 
358  return result;
359 }
360 
361 /*
362  * generateSerialExtraStmts
363  * Generate CREATE SEQUENCE and ALTER SEQUENCE ... OWNED BY statements
364  * to create the sequence for a serial or identity column.
365  *
366  * This includes determining the name the sequence will have. The caller
367  * can ask to get back the name components by passing non-null pointers
368  * for snamespace_p and sname_p.
369  */
370 static void
372  Oid seqtypid, List *seqoptions, bool for_identity,
373  char **snamespace_p, char **sname_p)
374 {
375  ListCell *option;
376  DefElem *nameEl = NULL;
377  Oid snamespaceid;
378  char *snamespace;
379  char *sname;
380  CreateSeqStmt *seqstmt;
381  AlterSeqStmt *altseqstmt;
382  List *attnamelist;
383 
384  /*
385  * Determine namespace and name to use for the sequence.
386  *
387  * First, check if a sequence name was passed in as an option. This is
388  * used by pg_dump. Else, generate a name.
389  *
390  * Although we use ChooseRelationName, it's not guaranteed that the
391  * selected sequence name won't conflict; given sufficiently long field
392  * names, two different serial columns in the same table could be assigned
393  * the same sequence name, and we'd not notice since we aren't creating
394  * the sequence quite yet. In practice this seems quite unlikely to be a
395  * problem, especially since few people would need two serial columns in
396  * one table.
397  */
398  foreach(option, seqoptions)
399  {
400  DefElem *defel = lfirst_node(DefElem, option);
401 
402  if (strcmp(defel->defname, "sequence_name") == 0)
403  {
404  if (nameEl)
405  ereport(ERROR,
406  (errcode(ERRCODE_SYNTAX_ERROR),
407  errmsg("conflicting or redundant options")));
408  nameEl = defel;
409  }
410  }
411 
412  if (nameEl)
413  {
415 
416  snamespace = rv->schemaname;
417  if (!snamespace)
418  {
419  /* Given unqualified SEQUENCE NAME, select namespace */
420  if (cxt->rel)
421  snamespaceid = RelationGetNamespace(cxt->rel);
422  else
423  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
424  snamespace = get_namespace_name(snamespaceid);
425  }
426  sname = rv->relname;
427  /* Remove the SEQUENCE NAME item from seqoptions */
428  seqoptions = list_delete_ptr(seqoptions, nameEl);
429  }
430  else
431  {
432  if (cxt->rel)
433  snamespaceid = RelationGetNamespace(cxt->rel);
434  else
435  {
436  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
437  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
438  }
439  snamespace = get_namespace_name(snamespaceid);
440  sname = ChooseRelationName(cxt->relation->relname,
441  column->colname,
442  "seq",
443  snamespaceid);
444  }
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 add
453  * it to the list of things to be done before this CREATE/ALTER TABLE.
454  */
455  seqstmt = makeNode(CreateSeqStmt);
456  seqstmt->for_identity = for_identity;
457  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
458  seqstmt->options = seqoptions;
459 
460  /*
461  * If a sequence data type was specified, add it to the options. Prepend
462  * to the list rather than append; in case a user supplied their own AS
463  * clause, the "redundant options" error will point to their occurrence,
464  * not our synthetic one.
465  */
466  if (seqtypid)
467  seqstmt->options = lcons(makeDefElem("as",
468  (Node *) makeTypeNameFromOid(seqtypid, -1),
469  -1),
470  seqstmt->options);
471 
472  /*
473  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
474  * the table's owner. The current user might be someone else (perhaps a
475  * superuser, or someone who's only a member of the owning role), but the
476  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
477  * exactly the same owning role.
478  */
479  if (cxt->rel)
480  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
481  else
482  seqstmt->ownerId = InvalidOid;
483 
484  cxt->blist = lappend(cxt->blist, seqstmt);
485 
486  /*
487  * Store the identity sequence name that we decided on. ALTER TABLE ...
488  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
489  * with values from the sequence, while the association of the sequence
490  * with the table is not set until after the ALTER TABLE.
491  */
492  column->identitySequence = seqstmt->sequence;
493 
494  /*
495  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
496  * owned by this column, and add it to the list of things to be done after
497  * this CREATE/ALTER TABLE.
498  */
499  altseqstmt = makeNode(AlterSeqStmt);
500  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
501  attnamelist = list_make3(makeString(snamespace),
502  makeString(cxt->relation->relname),
503  makeString(column->colname));
504  altseqstmt->options = list_make1(makeDefElem("owned_by",
505  (Node *) attnamelist, -1));
506  altseqstmt->for_identity = for_identity;
507 
508  cxt->alist = lappend(cxt->alist, altseqstmt);
509 
510  if (snamespace_p)
511  *snamespace_p = snamespace;
512  if (sname_p)
513  *sname_p = sname;
514 }
515 
516 /*
517  * transformColumnDefinition -
518  * transform a single ColumnDef within CREATE TABLE
519  * Also used in ALTER TABLE ADD COLUMN
520  */
521 static void
523 {
524  bool is_serial;
525  bool saw_nullable;
526  bool saw_default;
527  bool saw_identity;
528  ListCell *clist;
529 
530  cxt->columns = lappend(cxt->columns, column);
531 
532  /* Check for SERIAL pseudo-types */
533  is_serial = false;
534  if (column->typeName
535  && list_length(column->typeName->names) == 1
536  && !column->typeName->pct_type)
537  {
538  char *typname = strVal(linitial(column->typeName->names));
539 
540  if (strcmp(typname, "smallserial") == 0 ||
541  strcmp(typname, "serial2") == 0)
542  {
543  is_serial = true;
544  column->typeName->names = NIL;
545  column->typeName->typeOid = INT2OID;
546  }
547  else if (strcmp(typname, "serial") == 0 ||
548  strcmp(typname, "serial4") == 0)
549  {
550  is_serial = true;
551  column->typeName->names = NIL;
552  column->typeName->typeOid = INT4OID;
553  }
554  else if (strcmp(typname, "bigserial") == 0 ||
555  strcmp(typname, "serial8") == 0)
556  {
557  is_serial = true;
558  column->typeName->names = NIL;
559  column->typeName->typeOid = INT8OID;
560  }
561 
562  /*
563  * We have to reject "serial[]" explicitly, because once we've set
564  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
565  * special coding for serial(typmod) though.
566  */
567  if (is_serial && column->typeName->arrayBounds != NIL)
568  ereport(ERROR,
569  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
570  errmsg("array of serial is not implemented"),
572  column->typeName->location)));
573  }
574 
575  /* Do necessary work on the column type declaration */
576  if (column->typeName)
577  transformColumnType(cxt, column);
578 
579  /* Special actions for SERIAL pseudo-types */
580  if (is_serial)
581  {
582  char *snamespace;
583  char *sname;
584  char *qstring;
585  A_Const *snamenode;
586  TypeCast *castnode;
587  FuncCall *funccallnode;
588  Constraint *constraint;
589 
590  generateSerialExtraStmts(cxt, column,
591  column->typeName->typeOid, NIL, false,
592  &snamespace, &sname);
593 
594  /*
595  * Create appropriate constraints for SERIAL. We do this in full,
596  * rather than shortcutting, so that we will detect any conflicting
597  * constraints the user wrote (like a different DEFAULT).
598  *
599  * Create an expression tree representing the function call
600  * nextval('sequencename'). We cannot reduce the raw tree to cooked
601  * form until after the sequence is created, but there's no need to do
602  * so.
603  */
604  qstring = quote_qualified_identifier(snamespace, sname);
605  snamenode = makeNode(A_Const);
606  snamenode->val.type = T_String;
607  snamenode->val.val.str = qstring;
608  snamenode->location = -1;
609  castnode = makeNode(TypeCast);
610  castnode->typeName = SystemTypeName("regclass");
611  castnode->arg = (Node *) snamenode;
612  castnode->location = -1;
613  funccallnode = makeFuncCall(SystemFuncName("nextval"),
614  list_make1(castnode),
615  -1);
616  constraint = makeNode(Constraint);
617  constraint->contype = CONSTR_DEFAULT;
618  constraint->location = -1;
619  constraint->raw_expr = (Node *) funccallnode;
620  constraint->cooked_expr = NULL;
621  column->constraints = lappend(column->constraints, constraint);
622 
623  constraint = makeNode(Constraint);
624  constraint->contype = CONSTR_NOTNULL;
625  constraint->location = -1;
626  column->constraints = lappend(column->constraints, constraint);
627  }
628 
629  /* Process column constraints, if any... */
631 
632  saw_nullable = false;
633  saw_default = false;
634  saw_identity = false;
635 
636  foreach(clist, column->constraints)
637  {
638  Constraint *constraint = lfirst_node(Constraint, clist);
639 
640  switch (constraint->contype)
641  {
642  case CONSTR_NULL:
643  if (saw_nullable && column->is_not_null)
644  ereport(ERROR,
645  (errcode(ERRCODE_SYNTAX_ERROR),
646  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
647  column->colname, cxt->relation->relname),
649  constraint->location)));
650  column->is_not_null = false;
651  saw_nullable = true;
652  break;
653 
654  case CONSTR_NOTNULL:
655  if (saw_nullable && !column->is_not_null)
656  ereport(ERROR,
657  (errcode(ERRCODE_SYNTAX_ERROR),
658  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
659  column->colname, cxt->relation->relname),
661  constraint->location)));
662  column->is_not_null = true;
663  saw_nullable = true;
664  break;
665 
666  case CONSTR_DEFAULT:
667  if (saw_default)
668  ereport(ERROR,
669  (errcode(ERRCODE_SYNTAX_ERROR),
670  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
671  column->colname, cxt->relation->relname),
673  constraint->location)));
674  column->raw_default = constraint->raw_expr;
675  Assert(constraint->cooked_expr == NULL);
676  saw_default = true;
677  break;
678 
679  case CONSTR_IDENTITY:
680  {
681  Type ctype;
682  Oid typeOid;
683 
684  if (cxt->ofType)
685  ereport(ERROR,
686  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
687  errmsg("identity columns are not supported on typed tables")));
688  if (cxt->partbound)
689  ereport(ERROR,
690  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
691  errmsg("identity columns are not supported on partitions")));
692 
693  ctype = typenameType(cxt->pstate, column->typeName, NULL);
694  typeOid = HeapTupleGetOid(ctype);
695  ReleaseSysCache(ctype);
696 
697  if (saw_identity)
698  ereport(ERROR,
699  (errcode(ERRCODE_SYNTAX_ERROR),
700  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
701  column->colname, cxt->relation->relname),
703  constraint->location)));
704 
705  generateSerialExtraStmts(cxt, column,
706  typeOid, constraint->options, true,
707  NULL, NULL);
708 
709  column->identity = constraint->generated_when;
710  saw_identity = true;
711  column->is_not_null = true;
712  break;
713  }
714 
715  case CONSTR_CHECK:
716  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
717  break;
718 
719  case CONSTR_PRIMARY:
720  if (cxt->isforeign)
721  ereport(ERROR,
722  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
723  errmsg("primary key constraints are not supported on foreign tables"),
725  constraint->location)));
726  /* FALL THRU */
727 
728  case CONSTR_UNIQUE:
729  if (cxt->isforeign)
730  ereport(ERROR,
731  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
732  errmsg("unique constraints are not supported on foreign tables"),
734  constraint->location)));
735  if (constraint->keys == NIL)
736  constraint->keys = list_make1(makeString(column->colname));
737  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
738  break;
739 
740  case CONSTR_EXCLUSION:
741  /* grammar does not allow EXCLUDE as a column constraint */
742  elog(ERROR, "column exclusion constraints are not supported");
743  break;
744 
745  case CONSTR_FOREIGN:
746  if (cxt->isforeign)
747  ereport(ERROR,
748  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
749  errmsg("foreign key constraints are not supported on foreign tables"),
751  constraint->location)));
752 
753  /*
754  * Fill in the current attribute's name and throw it into the
755  * list of FK constraints to be processed later.
756  */
757  constraint->fk_attrs = list_make1(makeString(column->colname));
758  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
759  break;
760 
765  /* transformConstraintAttrs took care of these */
766  break;
767 
768  default:
769  elog(ERROR, "unrecognized constraint type: %d",
770  constraint->contype);
771  break;
772  }
773 
774  if (saw_default && saw_identity)
775  ereport(ERROR,
776  (errcode(ERRCODE_SYNTAX_ERROR),
777  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
778  column->colname, cxt->relation->relname),
780  constraint->location)));
781  }
782 
783  /*
784  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
785  * per-column foreign data wrapper options to this column after creation.
786  */
787  if (column->fdwoptions != NIL)
788  {
789  AlterTableStmt *stmt;
790  AlterTableCmd *cmd;
791 
792  cmd = makeNode(AlterTableCmd);
794  cmd->name = column->colname;
795  cmd->def = (Node *) column->fdwoptions;
796  cmd->behavior = DROP_RESTRICT;
797  cmd->missing_ok = false;
798 
799  stmt = makeNode(AlterTableStmt);
800  stmt->relation = cxt->relation;
801  stmt->cmds = NIL;
803  stmt->cmds = lappend(stmt->cmds, cmd);
804 
805  cxt->alist = lappend(cxt->alist, stmt);
806  }
807 }
808 
809 /*
810  * transformTableConstraint
811  * transform a Constraint node within CREATE TABLE or ALTER TABLE
812  */
813 static void
815 {
816  switch (constraint->contype)
817  {
818  case CONSTR_PRIMARY:
819  if (cxt->isforeign)
820  ereport(ERROR,
821  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
822  errmsg("primary key constraints are not supported on foreign tables"),
824  constraint->location)));
825  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
826  break;
827 
828  case CONSTR_UNIQUE:
829  if (cxt->isforeign)
830  ereport(ERROR,
831  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
832  errmsg("unique constraints are not supported on foreign tables"),
834  constraint->location)));
835  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
836  break;
837 
838  case CONSTR_EXCLUSION:
839  if (cxt->isforeign)
840  ereport(ERROR,
841  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
842  errmsg("exclusion constraints are not supported on foreign tables"),
844  constraint->location)));
845  if (cxt->ispartitioned)
846  ereport(ERROR,
847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
848  errmsg("exclusion constraints are not supported on partitioned tables"),
850  constraint->location)));
851  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
852  break;
853 
854  case CONSTR_CHECK:
855  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
856  break;
857 
858  case CONSTR_FOREIGN:
859  if (cxt->isforeign)
860  ereport(ERROR,
861  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
862  errmsg("foreign key constraints are not supported on foreign tables"),
864  constraint->location)));
865  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
866  break;
867 
868  case CONSTR_NULL:
869  case CONSTR_NOTNULL:
870  case CONSTR_DEFAULT:
875  elog(ERROR, "invalid context for constraint type %d",
876  constraint->contype);
877  break;
878 
879  default:
880  elog(ERROR, "unrecognized constraint type: %d",
881  constraint->contype);
882  break;
883  }
884 }
885 
886 /*
887  * transformTableLikeClause
888  *
889  * Change the LIKE <srctable> portion of a CREATE TABLE statement into
890  * column definitions which recreate the user defined column portions of
891  * <srctable>.
892  */
893 static void
895 {
896  AttrNumber parent_attno;
897  Relation relation;
899  TupleConstr *constr;
900  AttrNumber *attmap;
901  AclResult aclresult;
902  char *comment;
903  ParseCallbackState pcbstate;
904 
906  table_like_clause->relation->location);
907 
908  /* we could support LIKE in many cases, but worry about it another day */
909  if (cxt->isforeign)
910  ereport(ERROR,
911  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
912  errmsg("LIKE is not supported for creating foreign tables")));
913 
914  relation = relation_openrv(table_like_clause->relation, AccessShareLock);
915 
916  if (relation->rd_rel->relkind != RELKIND_RELATION &&
917  relation->rd_rel->relkind != RELKIND_VIEW &&
918  relation->rd_rel->relkind != RELKIND_MATVIEW &&
919  relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
920  relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
921  relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
922  ereport(ERROR,
923  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
924  errmsg("\"%s\" is not a table, view, materialized view, composite type, or foreign table",
925  RelationGetRelationName(relation))));
926 
928 
929  /*
930  * Check for privileges
931  */
932  if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
933  {
934  aclresult = pg_type_aclcheck(relation->rd_rel->reltype, GetUserId(),
935  ACL_USAGE);
936  if (aclresult != ACLCHECK_OK)
937  aclcheck_error(aclresult, OBJECT_TYPE,
938  RelationGetRelationName(relation));
939  }
940  else
941  {
942  aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
943  ACL_SELECT);
944  if (aclresult != ACLCHECK_OK)
945  aclcheck_error(aclresult, get_relkind_objtype(relation->rd_rel->relkind),
946  RelationGetRelationName(relation));
947  }
948 
949  tupleDesc = RelationGetDescr(relation);
950  constr = tupleDesc->constr;
951 
952  /*
953  * Initialize column number map for map_variable_attnos(). We need this
954  * since dropped columns in the source table aren't copied, so the new
955  * table can have different column numbers.
956  */
957  attmap = (AttrNumber *) palloc0(sizeof(AttrNumber) * tupleDesc->natts);
958 
959  /*
960  * Insert the copied attributes into the cxt for the new table definition.
961  */
962  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
963  parent_attno++)
964  {
965  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
966  parent_attno - 1);
967  char *attributeName = NameStr(attribute->attname);
968  ColumnDef *def;
969 
970  /*
971  * Ignore dropped columns in the parent. attmap entry is left zero.
972  */
973  if (attribute->attisdropped)
974  continue;
975 
976  /*
977  * Create a new column, which is marked as NOT inherited.
978  *
979  * For constraints, ONLY the NOT NULL constraint is inherited by the
980  * new column definition per SQL99.
981  */
982  def = makeNode(ColumnDef);
983  def->colname = pstrdup(attributeName);
984  def->typeName = makeTypeNameFromOid(attribute->atttypid,
985  attribute->atttypmod);
986  def->inhcount = 0;
987  def->is_local = true;
988  def->is_not_null = attribute->attnotnull;
989  def->is_from_type = false;
990  def->is_from_parent = false;
991  def->storage = 0;
992  def->raw_default = NULL;
993  def->cooked_default = NULL;
994  def->collClause = NULL;
995  def->collOid = attribute->attcollation;
996  def->constraints = NIL;
997  def->location = -1;
998 
999  /*
1000  * Add to column list
1001  */
1002  cxt->columns = lappend(cxt->columns, def);
1003 
1004  attmap[parent_attno - 1] = list_length(cxt->columns);
1005 
1006  /*
1007  * Copy default, if present and the default has been requested
1008  */
1009  if (attribute->atthasdef &&
1010  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS))
1011  {
1012  Node *this_default = NULL;
1013  AttrDefault *attrdef;
1014  int i;
1015 
1016  /* Find default in constraint structure */
1017  Assert(constr != NULL);
1018  attrdef = constr->defval;
1019  for (i = 0; i < constr->num_defval; i++)
1020  {
1021  if (attrdef[i].adnum == parent_attno)
1022  {
1023  this_default = stringToNode(attrdef[i].adbin);
1024  break;
1025  }
1026  }
1027  Assert(this_default != NULL);
1028 
1029  /*
1030  * If default expr could contain any vars, we'd need to fix 'em,
1031  * but it can't; so default is ready to apply to child.
1032  */
1033 
1034  def->cooked_default = this_default;
1035  }
1036 
1037  /*
1038  * Copy identity if requested
1039  */
1040  if (attribute->attidentity &&
1041  (table_like_clause->options & CREATE_TABLE_LIKE_IDENTITY))
1042  {
1043  Oid seq_relid;
1044  List *seq_options;
1045 
1046  /*
1047  * find sequence owned by old column; extract sequence parameters;
1048  * build new create sequence command
1049  */
1050  seq_relid = getOwnedSequence(RelationGetRelid(relation), attribute->attnum);
1051  seq_options = sequence_options(seq_relid);
1052  generateSerialExtraStmts(cxt, def,
1053  InvalidOid, seq_options, true,
1054  NULL, NULL);
1055  def->identity = attribute->attidentity;
1056  }
1057 
1058  /* Likewise, copy storage if requested */
1059  if (table_like_clause->options & CREATE_TABLE_LIKE_STORAGE)
1060  def->storage = attribute->attstorage;
1061  else
1062  def->storage = 0;
1063 
1064  /* Likewise, copy comment if requested */
1065  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1066  (comment = GetComment(attribute->attrelid,
1067  RelationRelationId,
1068  attribute->attnum)) != NULL)
1069  {
1070  CommentStmt *stmt = makeNode(CommentStmt);
1071 
1072  stmt->objtype = OBJECT_COLUMN;
1073  stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1074  makeString(cxt->relation->relname),
1075  makeString(def->colname));
1076  stmt->comment = comment;
1077 
1078  cxt->alist = lappend(cxt->alist, stmt);
1079  }
1080  }
1081 
1082  /* We use oids if at least one LIKE'ed table has oids. */
1083  cxt->hasoids |= relation->rd_rel->relhasoids;
1084 
1085  /*
1086  * Copy CHECK constraints if requested, being careful to adjust attribute
1087  * numbers so they match the child.
1088  */
1089  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1090  tupleDesc->constr)
1091  {
1092  int ccnum;
1093 
1094  for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
1095  {
1096  char *ccname = tupleDesc->constr->check[ccnum].ccname;
1097  char *ccbin = tupleDesc->constr->check[ccnum].ccbin;
1099  Node *ccbin_node;
1100  bool found_whole_row;
1101 
1102  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1103  1, 0,
1104  attmap, tupleDesc->natts,
1105  InvalidOid, &found_whole_row);
1106 
1107  /*
1108  * We reject whole-row variables because the whole point of LIKE
1109  * is that the new table's rowtype might later diverge from the
1110  * parent's. So, while translation might be possible right now,
1111  * it wouldn't be possible to guarantee it would work in future.
1112  */
1113  if (found_whole_row)
1114  ereport(ERROR,
1115  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1116  errmsg("cannot convert whole-row table reference"),
1117  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1118  ccname,
1119  RelationGetRelationName(relation))));
1120 
1121  n->contype = CONSTR_CHECK;
1122  n->location = -1;
1123  n->conname = pstrdup(ccname);
1124  n->raw_expr = NULL;
1125  n->cooked_expr = nodeToString(ccbin_node);
1126  cxt->ckconstraints = lappend(cxt->ckconstraints, n);
1127 
1128  /* Copy comment on constraint */
1129  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1131  n->conname, false),
1132  ConstraintRelationId,
1133  0)) != NULL)
1134  {
1135  CommentStmt *stmt = makeNode(CommentStmt);
1136 
1137  stmt->objtype = OBJECT_TABCONSTRAINT;
1138  stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1139  makeString(cxt->relation->relname),
1140  makeString(n->conname));
1141  stmt->comment = comment;
1142 
1143  cxt->alist = lappend(cxt->alist, stmt);
1144  }
1145  }
1146  }
1147 
1148  /*
1149  * Likewise, copy indexes if requested
1150  */
1151  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1152  relation->rd_rel->relhasindex)
1153  {
1154  List *parent_indexes;
1155  ListCell *l;
1156 
1157  parent_indexes = RelationGetIndexList(relation);
1158 
1159  foreach(l, parent_indexes)
1160  {
1161  Oid parent_index_oid = lfirst_oid(l);
1162  Relation parent_index;
1163  IndexStmt *index_stmt;
1164 
1165  parent_index = index_open(parent_index_oid, AccessShareLock);
1166 
1167  /* Build CREATE INDEX statement to recreate the parent_index */
1168  index_stmt = generateClonedIndexStmt(cxt->relation, InvalidOid,
1169  parent_index,
1170  attmap, tupleDesc->natts, NULL);
1171 
1172  /* Copy comment on index, if requested */
1173  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1174  {
1175  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1176 
1177  /*
1178  * We make use of IndexStmt's idxcomment option, so as not to
1179  * need to know now what name the index will have.
1180  */
1181  index_stmt->idxcomment = comment;
1182  }
1183 
1184  /* Save it in the inh_indexes list for the time being */
1185  cxt->inh_indexes = lappend(cxt->inh_indexes, index_stmt);
1186 
1187  index_close(parent_index, AccessShareLock);
1188  }
1189  }
1190 
1191  /*
1192  * Likewise, copy extended statistics if requested
1193  */
1194  if (table_like_clause->options & CREATE_TABLE_LIKE_STATISTICS)
1195  {
1196  List *parent_extstats;
1197  ListCell *l;
1198 
1199  parent_extstats = RelationGetStatExtList(relation);
1200 
1201  foreach(l, parent_extstats)
1202  {
1203  Oid parent_stat_oid = lfirst_oid(l);
1204  CreateStatsStmt *stats_stmt;
1205 
1206  stats_stmt = generateClonedExtStatsStmt(cxt->relation,
1207  RelationGetRelid(relation),
1208  parent_stat_oid);
1209 
1210  /* Copy comment on statistics object, if requested */
1211  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1212  {
1213  comment = GetComment(parent_stat_oid, StatisticExtRelationId, 0);
1214 
1215  /*
1216  * We make use of CreateStatsStmt's stxcomment option, so as
1217  * not to need to know now what name the statistics will have.
1218  */
1219  stats_stmt->stxcomment = comment;
1220  }
1221 
1222  cxt->extstats = lappend(cxt->extstats, stats_stmt);
1223  }
1224 
1225  list_free(parent_extstats);
1226  }
1227 
1228  /*
1229  * Close the parent rel, but keep our AccessShareLock on it until xact
1230  * commit. That will prevent someone else from deleting or ALTERing the
1231  * parent before the child is committed.
1232  */
1233  heap_close(relation, NoLock);
1234 }
1235 
1236 static void
1238 {
1239  HeapTuple tuple;
1240  TupleDesc tupdesc;
1241  int i;
1242  Oid ofTypeId;
1243 
1244  AssertArg(ofTypename);
1245 
1246  tuple = typenameType(NULL, ofTypename, NULL);
1247  check_of_type(tuple);
1248  ofTypeId = HeapTupleGetOid(tuple);
1249  ofTypename->typeOid = ofTypeId; /* cached for later */
1250 
1251  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1252  for (i = 0; i < tupdesc->natts; i++)
1253  {
1254  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1255  ColumnDef *n;
1256 
1257  if (attr->attisdropped)
1258  continue;
1259 
1260  n = makeNode(ColumnDef);
1261  n->colname = pstrdup(NameStr(attr->attname));
1262  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1263  n->inhcount = 0;
1264  n->is_local = true;
1265  n->is_not_null = false;
1266  n->is_from_type = true;
1267  n->is_from_parent = false;
1268  n->storage = 0;
1269  n->raw_default = NULL;
1270  n->cooked_default = NULL;
1271  n->collClause = NULL;
1272  n->collOid = attr->attcollation;
1273  n->constraints = NIL;
1274  n->location = -1;
1275  cxt->columns = lappend(cxt->columns, n);
1276  }
1277  DecrTupleDescRefCount(tupdesc);
1278 
1279  ReleaseSysCache(tuple);
1280 }
1281 
1282 /*
1283  * Generate an IndexStmt node using information from an already existing index
1284  * "source_idx", for the rel identified either by heapRel or heapRelid.
1285  *
1286  * Attribute numbers should be adjusted according to attmap.
1287  */
1288 IndexStmt *
1289 generateClonedIndexStmt(RangeVar *heapRel, Oid heapRelid, Relation source_idx,
1290  const AttrNumber *attmap, int attmap_length, Oid *constraintOid)
1291 {
1292  Oid source_relid = RelationGetRelid(source_idx);
1293  HeapTuple ht_idxrel;
1294  HeapTuple ht_idx;
1295  HeapTuple ht_am;
1296  Form_pg_class idxrelrec;
1297  Form_pg_index idxrec;
1298  Form_pg_am amrec;
1299  oidvector *indcollation;
1300  oidvector *indclass;
1301  IndexStmt *index;
1302  List *indexprs;
1303  ListCell *indexpr_item;
1304  Oid indrelid;
1305  int keyno;
1306  Oid keycoltype;
1307  Datum datum;
1308  bool isnull;
1309 
1310  Assert((heapRel == NULL && OidIsValid(heapRelid)) ||
1311  (heapRel != NULL && !OidIsValid(heapRelid)));
1312 
1313  /*
1314  * Fetch pg_class tuple of source index. We can't use the copy in the
1315  * relcache entry because it doesn't include optional fields.
1316  */
1317  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1318  if (!HeapTupleIsValid(ht_idxrel))
1319  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1320  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1321 
1322  /* Fetch pg_index tuple for source index from relcache entry */
1323  ht_idx = source_idx->rd_indextuple;
1324  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1325  indrelid = idxrec->indrelid;
1326 
1327  /* Fetch the pg_am tuple of the index' access method */
1328  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1329  if (!HeapTupleIsValid(ht_am))
1330  elog(ERROR, "cache lookup failed for access method %u",
1331  idxrelrec->relam);
1332  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1333 
1334  /* Extract indcollation from the pg_index tuple */
1335  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1336  Anum_pg_index_indcollation, &isnull);
1337  Assert(!isnull);
1338  indcollation = (oidvector *) DatumGetPointer(datum);
1339 
1340  /* Extract indclass from the pg_index tuple */
1341  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1342  Anum_pg_index_indclass, &isnull);
1343  Assert(!isnull);
1344  indclass = (oidvector *) DatumGetPointer(datum);
1345 
1346  /* Begin building the IndexStmt */
1347  index = makeNode(IndexStmt);
1348  index->relation = heapRel;
1349  index->relationId = heapRelid;
1350  index->accessMethod = pstrdup(NameStr(amrec->amname));
1351  if (OidIsValid(idxrelrec->reltablespace))
1352  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1353  else
1354  index->tableSpace = NULL;
1355  index->excludeOpNames = NIL;
1356  index->idxcomment = NULL;
1357  index->indexOid = InvalidOid;
1358  index->oldNode = InvalidOid;
1359  index->unique = idxrec->indisunique;
1360  index->primary = idxrec->indisprimary;
1361  index->transformed = true; /* don't need transformIndexStmt */
1362  index->concurrent = false;
1363  index->if_not_exists = false;
1364 
1365  /*
1366  * We don't try to preserve the name of the source index; instead, just
1367  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1368  * the name, we'd get duplicate-relation-name failures unless the source
1369  * table was in a different schema.)
1370  */
1371  index->idxname = NULL;
1372 
1373  /*
1374  * If the index is marked PRIMARY or has an exclusion condition, it's
1375  * certainly from a constraint; else, if it's not marked UNIQUE, it
1376  * certainly isn't. If it is or might be from a constraint, we have to
1377  * fetch the pg_constraint record.
1378  */
1379  if (index->primary || index->unique || idxrec->indisexclusion)
1380  {
1381  Oid constraintId = get_index_constraint(source_relid);
1382 
1383  if (OidIsValid(constraintId))
1384  {
1385  HeapTuple ht_constr;
1386  Form_pg_constraint conrec;
1387 
1388  if (constraintOid)
1389  *constraintOid = constraintId;
1390 
1391  ht_constr = SearchSysCache1(CONSTROID,
1392  ObjectIdGetDatum(constraintId));
1393  if (!HeapTupleIsValid(ht_constr))
1394  elog(ERROR, "cache lookup failed for constraint %u",
1395  constraintId);
1396  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1397 
1398  index->isconstraint = true;
1399  index->deferrable = conrec->condeferrable;
1400  index->initdeferred = conrec->condeferred;
1401 
1402  /* If it's an exclusion constraint, we need the operator names */
1403  if (idxrec->indisexclusion)
1404  {
1405  Datum *elems;
1406  int nElems;
1407  int i;
1408 
1409  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1410  /* Extract operator OIDs from the pg_constraint tuple */
1411  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1412  Anum_pg_constraint_conexclop,
1413  &isnull);
1414  if (isnull)
1415  elog(ERROR, "null conexclop for constraint %u",
1416  constraintId);
1417 
1419  OIDOID, sizeof(Oid), true, 'i',
1420  &elems, NULL, &nElems);
1421 
1422  for (i = 0; i < nElems; i++)
1423  {
1424  Oid operid = DatumGetObjectId(elems[i]);
1425  HeapTuple opertup;
1426  Form_pg_operator operform;
1427  char *oprname;
1428  char *nspname;
1429  List *namelist;
1430 
1431  opertup = SearchSysCache1(OPEROID,
1432  ObjectIdGetDatum(operid));
1433  if (!HeapTupleIsValid(opertup))
1434  elog(ERROR, "cache lookup failed for operator %u",
1435  operid);
1436  operform = (Form_pg_operator) GETSTRUCT(opertup);
1437  oprname = pstrdup(NameStr(operform->oprname));
1438  /* For simplicity we always schema-qualify the op name */
1439  nspname = get_namespace_name(operform->oprnamespace);
1440  namelist = list_make2(makeString(nspname),
1441  makeString(oprname));
1442  index->excludeOpNames = lappend(index->excludeOpNames,
1443  namelist);
1444  ReleaseSysCache(opertup);
1445  }
1446  }
1447 
1448  ReleaseSysCache(ht_constr);
1449  }
1450  else
1451  index->isconstraint = false;
1452  }
1453  else
1454  index->isconstraint = false;
1455 
1456  /* Get the index expressions, if any */
1457  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1458  Anum_pg_index_indexprs, &isnull);
1459  if (!isnull)
1460  {
1461  char *exprsString;
1462 
1463  exprsString = TextDatumGetCString(datum);
1464  indexprs = (List *) stringToNode(exprsString);
1465  }
1466  else
1467  indexprs = NIL;
1468 
1469  /* Build the list of IndexElem */
1470  index->indexParams = NIL;
1471  index->indexIncludingParams = NIL;
1472 
1473  indexpr_item = list_head(indexprs);
1474  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1475  {
1476  IndexElem *iparam;
1477  AttrNumber attnum = idxrec->indkey.values[keyno];
1479  keyno);
1480  int16 opt = source_idx->rd_indoption[keyno];
1481 
1482  iparam = makeNode(IndexElem);
1483 
1484  if (AttributeNumberIsValid(attnum))
1485  {
1486  /* Simple index column */
1487  char *attname;
1488 
1489  attname = get_attname(indrelid, attnum, false);
1490  keycoltype = get_atttype(indrelid, attnum);
1491 
1492  iparam->name = attname;
1493  iparam->expr = NULL;
1494  }
1495  else
1496  {
1497  /* Expressional index */
1498  Node *indexkey;
1499  bool found_whole_row;
1500 
1501  if (indexpr_item == NULL)
1502  elog(ERROR, "too few entries in indexprs list");
1503  indexkey = (Node *) lfirst(indexpr_item);
1504  indexpr_item = lnext(indexpr_item);
1505 
1506  /* Adjust Vars to match new table's column numbering */
1507  indexkey = map_variable_attnos(indexkey,
1508  1, 0,
1509  attmap, attmap_length,
1510  InvalidOid, &found_whole_row);
1511 
1512  /* As in transformTableLikeClause, reject whole-row variables */
1513  if (found_whole_row)
1514  ereport(ERROR,
1515  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1516  errmsg("cannot convert whole-row table reference"),
1517  errdetail("Index \"%s\" contains a whole-row table reference.",
1518  RelationGetRelationName(source_idx))));
1519 
1520  iparam->name = NULL;
1521  iparam->expr = indexkey;
1522 
1523  keycoltype = exprType(indexkey);
1524  }
1525 
1526  /* Copy the original index column name */
1527  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1528 
1529  /* Add the collation name, if non-default */
1530  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1531 
1532  /* Add the operator class name, if non-default */
1533  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1534 
1535  iparam->ordering = SORTBY_DEFAULT;
1537 
1538  /* Adjust options if necessary */
1539  if (source_idx->rd_amroutine->amcanorder)
1540  {
1541  /*
1542  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1543  * set non-default settings unnecessarily, though, so as to
1544  * improve the chance of recognizing equivalence to constraint
1545  * indexes.
1546  */
1547  if (opt & INDOPTION_DESC)
1548  {
1549  iparam->ordering = SORTBY_DESC;
1550  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1552  }
1553  else
1554  {
1555  if (opt & INDOPTION_NULLS_FIRST)
1557  }
1558  }
1559 
1560  index->indexParams = lappend(index->indexParams, iparam);
1561  }
1562 
1563  /* Handle included columns separately */
1564  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1565  {
1566  IndexElem *iparam;
1567  AttrNumber attnum = idxrec->indkey.values[keyno];
1569  keyno);
1570 
1571  iparam = makeNode(IndexElem);
1572 
1573  if (AttributeNumberIsValid(attnum))
1574  {
1575  /* Simple index column */
1576  char *attname;
1577 
1578  attname = get_attname(indrelid, attnum, false);
1579  keycoltype = get_atttype(indrelid, attnum);
1580 
1581  iparam->name = attname;
1582  iparam->expr = NULL;
1583  }
1584  else
1585  ereport(ERROR,
1586  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1587  errmsg("expressions are not supported in included columns")));
1588 
1589  /* Copy the original index column name */
1590  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1591 
1592  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1593  }
1594  /* Copy reloptions if any */
1595  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1596  Anum_pg_class_reloptions, &isnull);
1597  if (!isnull)
1598  index->options = untransformRelOptions(datum);
1599 
1600  /* If it's a partial index, decompile and append the predicate */
1601  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1602  Anum_pg_index_indpred, &isnull);
1603  if (!isnull)
1604  {
1605  char *pred_str;
1606  Node *pred_tree;
1607  bool found_whole_row;
1608 
1609  /* Convert text string to node tree */
1610  pred_str = TextDatumGetCString(datum);
1611  pred_tree = (Node *) stringToNode(pred_str);
1612 
1613  /* Adjust Vars to match new table's column numbering */
1614  pred_tree = map_variable_attnos(pred_tree,
1615  1, 0,
1616  attmap, attmap_length,
1617  InvalidOid, &found_whole_row);
1618 
1619  /* As in transformTableLikeClause, reject whole-row variables */
1620  if (found_whole_row)
1621  ereport(ERROR,
1622  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1623  errmsg("cannot convert whole-row table reference"),
1624  errdetail("Index \"%s\" contains a whole-row table reference.",
1625  RelationGetRelationName(source_idx))));
1626 
1627  index->whereClause = pred_tree;
1628  }
1629 
1630  /* Clean up */
1631  ReleaseSysCache(ht_idxrel);
1632  ReleaseSysCache(ht_am);
1633 
1634  return index;
1635 }
1636 
1637 /*
1638  * Generate a CreateStatsStmt node using information from an already existing
1639  * extended statistic "source_statsid", for the rel identified by heapRel and
1640  * heapRelid.
1641  */
1642 static CreateStatsStmt *
1644  Oid source_statsid)
1645 {
1646  HeapTuple ht_stats;
1647  Form_pg_statistic_ext statsrec;
1648  CreateStatsStmt *stats;
1649  List *stat_types = NIL;
1650  List *def_names = NIL;
1651  bool isnull;
1652  Datum datum;
1653  ArrayType *arr;
1654  char *enabled;
1655  int i;
1656 
1657  Assert(OidIsValid(heapRelid));
1658  Assert(heapRel != NULL);
1659 
1660  /*
1661  * Fetch pg_statistic_ext tuple of source statistics object.
1662  */
1663  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1664  if (!HeapTupleIsValid(ht_stats))
1665  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1666  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1667 
1668  /* Determine which statistics types exist */
1669  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1670  Anum_pg_statistic_ext_stxkind, &isnull);
1671  Assert(!isnull);
1672  arr = DatumGetArrayTypeP(datum);
1673  if (ARR_NDIM(arr) != 1 ||
1674  ARR_HASNULL(arr) ||
1675  ARR_ELEMTYPE(arr) != CHAROID)
1676  elog(ERROR, "stxkind is not a 1-D char array");
1677  enabled = (char *) ARR_DATA_PTR(arr);
1678  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1679  {
1680  if (enabled[i] == STATS_EXT_NDISTINCT)
1681  stat_types = lappend(stat_types, makeString("ndistinct"));
1682  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1683  stat_types = lappend(stat_types, makeString("dependencies"));
1684  else
1685  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1686  }
1687 
1688  /* Determine which columns the statistics are on */
1689  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1690  {
1691  ColumnRef *cref = makeNode(ColumnRef);
1692  AttrNumber attnum = statsrec->stxkeys.values[i];
1693 
1694  cref->fields = list_make1(makeString(get_attname(heapRelid,
1695  attnum, false)));
1696  cref->location = -1;
1697 
1698  def_names = lappend(def_names, cref);
1699  }
1700 
1701  /* finally, build the output node */
1702  stats = makeNode(CreateStatsStmt);
1703  stats->defnames = NULL;
1704  stats->stat_types = stat_types;
1705  stats->exprs = def_names;
1706  stats->relations = list_make1(heapRel);
1707  stats->stxcomment = NULL;
1708  stats->if_not_exists = false;
1709 
1710  /* Clean up */
1711  ReleaseSysCache(ht_stats);
1712 
1713  return stats;
1714 }
1715 
1716 /*
1717  * get_collation - fetch qualified name of a collation
1718  *
1719  * If collation is InvalidOid or is the default for the given actual_datatype,
1720  * then the return value is NIL.
1721  */
1722 static List *
1723 get_collation(Oid collation, Oid actual_datatype)
1724 {
1725  List *result;
1726  HeapTuple ht_coll;
1727  Form_pg_collation coll_rec;
1728  char *nsp_name;
1729  char *coll_name;
1730 
1731  if (!OidIsValid(collation))
1732  return NIL; /* easy case */
1733  if (collation == get_typcollation(actual_datatype))
1734  return NIL; /* just let it default */
1735 
1736  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1737  if (!HeapTupleIsValid(ht_coll))
1738  elog(ERROR, "cache lookup failed for collation %u", collation);
1739  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1740 
1741  /* For simplicity, we always schema-qualify the name */
1742  nsp_name = get_namespace_name(coll_rec->collnamespace);
1743  coll_name = pstrdup(NameStr(coll_rec->collname));
1744  result = list_make2(makeString(nsp_name), makeString(coll_name));
1745 
1746  ReleaseSysCache(ht_coll);
1747  return result;
1748 }
1749 
1750 /*
1751  * get_opclass - fetch qualified name of an index operator class
1752  *
1753  * If the opclass is the default for the given actual_datatype, then
1754  * the return value is NIL.
1755  */
1756 static List *
1757 get_opclass(Oid opclass, Oid actual_datatype)
1758 {
1759  List *result = NIL;
1760  HeapTuple ht_opc;
1761  Form_pg_opclass opc_rec;
1762 
1763  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1764  if (!HeapTupleIsValid(ht_opc))
1765  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1766  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1767 
1768  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1769  {
1770  /* For simplicity, we always schema-qualify the name */
1771  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1772  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1773 
1774  result = list_make2(makeString(nsp_name), makeString(opc_name));
1775  }
1776 
1777  ReleaseSysCache(ht_opc);
1778  return result;
1779 }
1780 
1781 
1782 /*
1783  * transformIndexConstraints
1784  * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
1785  * We also merge in any index definitions arising from
1786  * LIKE ... INCLUDING INDEXES.
1787  */
1788 static void
1790 {
1791  IndexStmt *index;
1792  List *indexlist = NIL;
1793  ListCell *lc;
1794 
1795  /*
1796  * Run through the constraints that need to generate an index. For PRIMARY
1797  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1798  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1799  * NULL.
1800  */
1801  foreach(lc, cxt->ixconstraints)
1802  {
1803  Constraint *constraint = lfirst_node(Constraint, lc);
1804 
1805  Assert(constraint->contype == CONSTR_PRIMARY ||
1806  constraint->contype == CONSTR_UNIQUE ||
1807  constraint->contype == CONSTR_EXCLUSION);
1808 
1809  index = transformIndexConstraint(constraint, cxt);
1810 
1811  indexlist = lappend(indexlist, index);
1812  }
1813 
1814  /* Add in any indexes defined by LIKE ... INCLUDING INDEXES */
1815  foreach(lc, cxt->inh_indexes)
1816  {
1817  index = (IndexStmt *) lfirst(lc);
1818 
1819  if (index->primary)
1820  {
1821  if (cxt->pkey != NULL)
1822  ereport(ERROR,
1823  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1824  errmsg("multiple primary keys for table \"%s\" are not allowed",
1825  cxt->relation->relname)));
1826  cxt->pkey = index;
1827  }
1828 
1829  indexlist = lappend(indexlist, index);
1830  }
1831 
1832  /*
1833  * Scan the index list and remove any redundant index specifications. This
1834  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1835  * strict reading of SQL would suggest raising an error instead, but that
1836  * strikes me as too anal-retentive. - tgl 2001-02-14
1837  *
1838  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1839  * pre-existing indexes, too.
1840  */
1841  Assert(cxt->alist == NIL);
1842  if (cxt->pkey != NULL)
1843  {
1844  /* Make sure we keep the PKEY index in preference to others... */
1845  cxt->alist = list_make1(cxt->pkey);
1846  }
1847 
1848  foreach(lc, indexlist)
1849  {
1850  bool keep = true;
1851  ListCell *k;
1852 
1853  index = lfirst(lc);
1854 
1855  /* if it's pkey, it's already in cxt->alist */
1856  if (index == cxt->pkey)
1857  continue;
1858 
1859  foreach(k, cxt->alist)
1860  {
1861  IndexStmt *priorindex = lfirst(k);
1862 
1863  if (equal(index->indexParams, priorindex->indexParams) &&
1864  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
1865  equal(index->whereClause, priorindex->whereClause) &&
1866  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
1867  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
1868  index->deferrable == priorindex->deferrable &&
1869  index->initdeferred == priorindex->initdeferred)
1870  {
1871  priorindex->unique |= index->unique;
1872 
1873  /*
1874  * If the prior index is as yet unnamed, and this one is
1875  * named, then transfer the name to the prior index. This
1876  * ensures that if we have named and unnamed constraints,
1877  * we'll use (at least one of) the names for the index.
1878  */
1879  if (priorindex->idxname == NULL)
1880  priorindex->idxname = index->idxname;
1881  keep = false;
1882  break;
1883  }
1884  }
1885 
1886  if (keep)
1887  cxt->alist = lappend(cxt->alist, index);
1888  }
1889 }
1890 
1891 /*
1892  * transformIndexConstraint
1893  * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
1894  * transformIndexConstraints.
1895  */
1896 static IndexStmt *
1898 {
1899  IndexStmt *index;
1900  ListCell *lc;
1901 
1902  index = makeNode(IndexStmt);
1903 
1904  index->unique = (constraint->contype != CONSTR_EXCLUSION);
1905  index->primary = (constraint->contype == CONSTR_PRIMARY);
1906  if (index->primary)
1907  {
1908  if (cxt->pkey != NULL)
1909  ereport(ERROR,
1910  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1911  errmsg("multiple primary keys for table \"%s\" are not allowed",
1912  cxt->relation->relname),
1913  parser_errposition(cxt->pstate, constraint->location)));
1914  cxt->pkey = index;
1915 
1916  /*
1917  * In ALTER TABLE case, a primary index might already exist, but
1918  * DefineIndex will check for it.
1919  */
1920  }
1921  index->isconstraint = true;
1922  index->deferrable = constraint->deferrable;
1923  index->initdeferred = constraint->initdeferred;
1924 
1925  if (constraint->conname != NULL)
1926  index->idxname = pstrdup(constraint->conname);
1927  else
1928  index->idxname = NULL; /* DefineIndex will choose name */
1929 
1930  index->relation = cxt->relation;
1931  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
1932  index->options = constraint->options;
1933  index->tableSpace = constraint->indexspace;
1934  index->whereClause = constraint->where_clause;
1935  index->indexParams = NIL;
1936  index->indexIncludingParams = NIL;
1937  index->excludeOpNames = NIL;
1938  index->idxcomment = NULL;
1939  index->indexOid = InvalidOid;
1940  index->oldNode = InvalidOid;
1941  index->transformed = false;
1942  index->concurrent = false;
1943  index->if_not_exists = false;
1944 
1945  /*
1946  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
1947  * verify it's usable, then extract the implied column name list. (We
1948  * will not actually need the column name list at runtime, but we need it
1949  * now to check for duplicate column entries below.)
1950  */
1951  if (constraint->indexname != NULL)
1952  {
1953  char *index_name = constraint->indexname;
1954  Relation heap_rel = cxt->rel;
1955  Oid index_oid;
1956  Relation index_rel;
1957  Form_pg_index index_form;
1958  oidvector *indclass;
1959  Datum indclassDatum;
1960  bool isnull;
1961  int i;
1962 
1963  /* Grammar should not allow this with explicit column list */
1964  Assert(constraint->keys == NIL);
1965 
1966  /* Grammar should only allow PRIMARY and UNIQUE constraints */
1967  Assert(constraint->contype == CONSTR_PRIMARY ||
1968  constraint->contype == CONSTR_UNIQUE);
1969 
1970  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
1971  if (!cxt->isalter)
1972  ereport(ERROR,
1973  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1974  errmsg("cannot use an existing index in CREATE TABLE"),
1975  parser_errposition(cxt->pstate, constraint->location)));
1976 
1977  /* Look for the index in the same schema as the table */
1978  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
1979 
1980  if (!OidIsValid(index_oid))
1981  ereport(ERROR,
1982  (errcode(ERRCODE_UNDEFINED_OBJECT),
1983  errmsg("index \"%s\" does not exist", index_name),
1984  parser_errposition(cxt->pstate, constraint->location)));
1985 
1986  /* Open the index (this will throw an error if it is not an index) */
1987  index_rel = index_open(index_oid, AccessShareLock);
1988  index_form = index_rel->rd_index;
1989 
1990  /* Check that it does not have an associated constraint already */
1991  if (OidIsValid(get_index_constraint(index_oid)))
1992  ereport(ERROR,
1993  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1994  errmsg("index \"%s\" is already associated with a constraint",
1995  index_name),
1996  parser_errposition(cxt->pstate, constraint->location)));
1997 
1998  /* Perform validity checks on the index */
1999  if (index_form->indrelid != RelationGetRelid(heap_rel))
2000  ereport(ERROR,
2001  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2002  errmsg("index \"%s\" does not belong to table \"%s\"",
2003  index_name, RelationGetRelationName(heap_rel)),
2004  parser_errposition(cxt->pstate, constraint->location)));
2005 
2006  if (!IndexIsValid(index_form))
2007  ereport(ERROR,
2008  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2009  errmsg("index \"%s\" is not valid", index_name),
2010  parser_errposition(cxt->pstate, constraint->location)));
2011 
2012  if (!index_form->indisunique)
2013  ereport(ERROR,
2014  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2015  errmsg("\"%s\" is not a unique index", index_name),
2016  errdetail("Cannot create a primary key or unique constraint using such an index."),
2017  parser_errposition(cxt->pstate, constraint->location)));
2018 
2019  if (RelationGetIndexExpressions(index_rel) != NIL)
2020  ereport(ERROR,
2021  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2022  errmsg("index \"%s\" contains expressions", index_name),
2023  errdetail("Cannot create a primary key or unique constraint using such an index."),
2024  parser_errposition(cxt->pstate, constraint->location)));
2025 
2026  if (RelationGetIndexPredicate(index_rel) != NIL)
2027  ereport(ERROR,
2028  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2029  errmsg("\"%s\" is a partial index", index_name),
2030  errdetail("Cannot create a primary key or unique constraint using such an index."),
2031  parser_errposition(cxt->pstate, constraint->location)));
2032 
2033  /*
2034  * It's probably unsafe to change a deferred index to non-deferred. (A
2035  * non-constraint index couldn't be deferred anyway, so this case
2036  * should never occur; no need to sweat, but let's check it.)
2037  */
2038  if (!index_form->indimmediate && !constraint->deferrable)
2039  ereport(ERROR,
2040  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2041  errmsg("\"%s\" is a deferrable index", index_name),
2042  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2043  parser_errposition(cxt->pstate, constraint->location)));
2044 
2045  /*
2046  * Insist on it being a btree. That's the only kind that supports
2047  * uniqueness at the moment anyway; but we must have an index that
2048  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2049  * else dump and reload will produce a different index (breaking
2050  * pg_upgrade in particular).
2051  */
2052  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2053  ereport(ERROR,
2054  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2055  errmsg("index \"%s\" is not a btree", index_name),
2056  parser_errposition(cxt->pstate, constraint->location)));
2057 
2058  /* Must get indclass the hard way */
2059  indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
2060  Anum_pg_index_indclass, &isnull);
2061  Assert(!isnull);
2062  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2063 
2064  for (i = 0; i < index_form->indnatts; i++)
2065  {
2066  int16 attnum = index_form->indkey.values[i];
2067  Form_pg_attribute attform;
2068  char *attname;
2069  Oid defopclass;
2070 
2071  /*
2072  * We shouldn't see attnum == 0 here, since we already rejected
2073  * expression indexes. If we do, SystemAttributeDefinition will
2074  * throw an error.
2075  */
2076  if (attnum > 0)
2077  {
2078  Assert(attnum <= heap_rel->rd_att->natts);
2079  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2080  }
2081  else
2082  attform = SystemAttributeDefinition(attnum,
2083  heap_rel->rd_rel->relhasoids);
2084  attname = pstrdup(NameStr(attform->attname));
2085 
2086  if (i < index_form->indnkeyatts)
2087  {
2088  /*
2089  * Insist on default opclass and sort options. While the
2090  * index would still work as a constraint with non-default
2091  * settings, it might not provide exactly the same uniqueness
2092  * semantics as you'd get from a normally-created constraint;
2093  * and there's also the dump/reload problem mentioned above.
2094  */
2095  defopclass = GetDefaultOpClass(attform->atttypid,
2096  index_rel->rd_rel->relam);
2097  if (indclass->values[i] != defopclass ||
2098  index_rel->rd_indoption[i] != 0)
2099  ereport(ERROR,
2100  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2101  errmsg("index \"%s\" does not have default sorting behavior", index_name),
2102  errdetail("Cannot create a primary key or unique constraint using such an index."),
2103  parser_errposition(cxt->pstate, constraint->location)));
2104 
2105  constraint->keys = lappend(constraint->keys, makeString(attname));
2106  }
2107  else
2108  constraint->including = lappend(constraint->including, makeString(attname));
2109  }
2110 
2111  /* Close the index relation but keep the lock */
2112  relation_close(index_rel, NoLock);
2113 
2114  index->indexOid = index_oid;
2115  }
2116 
2117  /*
2118  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2119  * IndexElems and operator names. We have to break that apart into
2120  * separate lists.
2121  */
2122  if (constraint->contype == CONSTR_EXCLUSION)
2123  {
2124  foreach(lc, constraint->exclusions)
2125  {
2126  List *pair = (List *) lfirst(lc);
2127  IndexElem *elem;
2128  List *opname;
2129 
2130  Assert(list_length(pair) == 2);
2131  elem = linitial_node(IndexElem, pair);
2132  opname = lsecond_node(List, pair);
2133 
2134  index->indexParams = lappend(index->indexParams, elem);
2135  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2136  }
2137  }
2138 
2139  /*
2140  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2141  *
2142  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2143  * also make sure they are NOT NULL, if possible. (Although we could leave
2144  * it to DefineIndex to mark the columns NOT NULL, it's more efficient to
2145  * get it right the first time.)
2146  */
2147  else
2148  {
2149  foreach(lc, constraint->keys)
2150  {
2151  char *key = strVal(lfirst(lc));
2152  bool found = false;
2153  ColumnDef *column = NULL;
2154  ListCell *columns;
2155  IndexElem *iparam;
2156 
2157  /* Make sure referenced column exist. */
2158  foreach(columns, cxt->columns)
2159  {
2160  column = castNode(ColumnDef, lfirst(columns));
2161  if (strcmp(column->colname, key) == 0)
2162  {
2163  found = true;
2164  break;
2165  }
2166  }
2167  if (found)
2168  {
2169  /* found column in the new table; force it to be NOT NULL */
2170  if (constraint->contype == CONSTR_PRIMARY)
2171  column->is_not_null = true;
2172  }
2173  else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
2174  {
2175  /*
2176  * column will be a system column in the new table, so accept
2177  * it. System columns can't ever be null, so no need to worry
2178  * about PRIMARY/NOT NULL constraint.
2179  */
2180  found = true;
2181  }
2182  else if (cxt->inhRelations)
2183  {
2184  /* try inherited tables */
2185  ListCell *inher;
2186 
2187  foreach(inher, cxt->inhRelations)
2188  {
2189  RangeVar *inh = castNode(RangeVar, lfirst(inher));
2190  Relation rel;
2191  int count;
2192 
2193  rel = heap_openrv(inh, AccessShareLock);
2194  /* check user requested inheritance from valid relkind */
2195  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2196  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2197  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2198  ereport(ERROR,
2199  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2200  errmsg("inherited relation \"%s\" is not a table or foreign table",
2201  inh->relname)));
2202  for (count = 0; count < rel->rd_att->natts; count++)
2203  {
2204  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2205  count);
2206  char *inhname = NameStr(inhattr->attname);
2207 
2208  if (inhattr->attisdropped)
2209  continue;
2210  if (strcmp(key, inhname) == 0)
2211  {
2212  found = true;
2213 
2214  /*
2215  * We currently have no easy way to force an
2216  * inherited column to be NOT NULL at creation, if
2217  * its parent wasn't so already. We leave it to
2218  * DefineIndex to fix things up in this case.
2219  */
2220  break;
2221  }
2222  }
2223  heap_close(rel, NoLock);
2224  if (found)
2225  break;
2226  }
2227  }
2228 
2229  /*
2230  * In the ALTER TABLE case, don't complain about index keys not
2231  * created in the command; they may well exist already.
2232  * DefineIndex will complain about them if not, and will also take
2233  * care of marking them NOT NULL.
2234  */
2235  if (!found && !cxt->isalter)
2236  ereport(ERROR,
2237  (errcode(ERRCODE_UNDEFINED_COLUMN),
2238  errmsg("column \"%s\" named in key does not exist", key),
2239  parser_errposition(cxt->pstate, constraint->location)));
2240 
2241  /* Check for PRIMARY KEY(foo, foo) */
2242  foreach(columns, index->indexParams)
2243  {
2244  iparam = (IndexElem *) lfirst(columns);
2245  if (iparam->name && strcmp(key, iparam->name) == 0)
2246  {
2247  if (index->primary)
2248  ereport(ERROR,
2249  (errcode(ERRCODE_DUPLICATE_COLUMN),
2250  errmsg("column \"%s\" appears twice in primary key constraint",
2251  key),
2252  parser_errposition(cxt->pstate, constraint->location)));
2253  else
2254  ereport(ERROR,
2255  (errcode(ERRCODE_DUPLICATE_COLUMN),
2256  errmsg("column \"%s\" appears twice in unique constraint",
2257  key),
2258  parser_errposition(cxt->pstate, constraint->location)));
2259  }
2260  }
2261 
2262  /* OK, add it to the index definition */
2263  iparam = makeNode(IndexElem);
2264  iparam->name = pstrdup(key);
2265  iparam->expr = NULL;
2266  iparam->indexcolname = NULL;
2267  iparam->collation = NIL;
2268  iparam->opclass = NIL;
2269  iparam->ordering = SORTBY_DEFAULT;
2271  index->indexParams = lappend(index->indexParams, iparam);
2272  }
2273  }
2274 
2275  /* Add included columns to index definition */
2276  foreach(lc, constraint->including)
2277  {
2278  char *key = strVal(lfirst(lc));
2279  bool found = false;
2280  ColumnDef *column = NULL;
2281  ListCell *columns;
2282  IndexElem *iparam;
2283 
2284  foreach(columns, cxt->columns)
2285  {
2286  column = lfirst_node(ColumnDef, columns);
2287  if (strcmp(column->colname, key) == 0)
2288  {
2289  found = true;
2290  break;
2291  }
2292  }
2293 
2294  if (!found)
2295  {
2296  if (SystemAttributeByName(key, cxt->hasoids) != NULL)
2297  {
2298  /*
2299  * column will be a system column in the new table, so accept
2300  * it. System columns can't ever be null, so no need to worry
2301  * about PRIMARY/NOT NULL constraint.
2302  */
2303  found = true;
2304  }
2305  else if (cxt->inhRelations)
2306  {
2307  /* try inherited tables */
2308  ListCell *inher;
2309 
2310  foreach(inher, cxt->inhRelations)
2311  {
2312  RangeVar *inh = lfirst_node(RangeVar, inher);
2313  Relation rel;
2314  int count;
2315 
2316  rel = heap_openrv(inh, AccessShareLock);
2317  /* check user requested inheritance from valid relkind */
2318  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2319  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2320  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2321  ereport(ERROR,
2322  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2323  errmsg("inherited relation \"%s\" is not a table or foreign table",
2324  inh->relname)));
2325  for (count = 0; count < rel->rd_att->natts; count++)
2326  {
2327  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2328  count);
2329  char *inhname = NameStr(inhattr->attname);
2330 
2331  if (inhattr->attisdropped)
2332  continue;
2333  if (strcmp(key, inhname) == 0)
2334  {
2335  found = true;
2336 
2337  /*
2338  * We currently have no easy way to force an
2339  * inherited column to be NOT NULL at creation, if
2340  * its parent wasn't so already. We leave it to
2341  * DefineIndex to fix things up in this case.
2342  */
2343  break;
2344  }
2345  }
2346  heap_close(rel, NoLock);
2347  if (found)
2348  break;
2349  }
2350  }
2351  }
2352 
2353  /*
2354  * In the ALTER TABLE case, don't complain about index keys not
2355  * created in the command; they may well exist already. DefineIndex
2356  * will complain about them if not, and will also take care of marking
2357  * them NOT NULL.
2358  */
2359  if (!found && !cxt->isalter)
2360  ereport(ERROR,
2361  (errcode(ERRCODE_UNDEFINED_COLUMN),
2362  errmsg("column \"%s\" named in key does not exist", key),
2363  parser_errposition(cxt->pstate, constraint->location)));
2364 
2365  /* OK, add it to the index definition */
2366  iparam = makeNode(IndexElem);
2367  iparam->name = pstrdup(key);
2368  iparam->expr = NULL;
2369  iparam->indexcolname = NULL;
2370  iparam->collation = NIL;
2371  iparam->opclass = NIL;
2372  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2373  }
2374 
2375  return index;
2376 }
2377 
2378 /*
2379  * transformExtendedStatistics
2380  * Handle extended statistic objects
2381  *
2382  * Right now, there's nothing to do here, so we just append the list to
2383  * the existing "after" list.
2384  */
2385 static void
2387 {
2388  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2389 }
2390 
2391 /*
2392  * transformCheckConstraints
2393  * handle CHECK constraints
2394  *
2395  * Right now, there's nothing to do here when called from ALTER TABLE,
2396  * but the other constraint-transformation functions are called in both
2397  * the CREATE TABLE and ALTER TABLE paths, so do the same here, and just
2398  * don't do anything if we're not authorized to skip validation.
2399  */
2400 static void
2402 {
2403  ListCell *ckclist;
2404 
2405  if (cxt->ckconstraints == NIL)
2406  return;
2407 
2408  /*
2409  * If creating a new table (but not a foreign table), we can safely skip
2410  * validation of check constraints, and nonetheless mark them valid. (This
2411  * will override any user-supplied NOT VALID flag.)
2412  */
2413  if (skipValidation)
2414  {
2415  foreach(ckclist, cxt->ckconstraints)
2416  {
2417  Constraint *constraint = (Constraint *) lfirst(ckclist);
2418 
2419  constraint->skip_validation = true;
2420  constraint->initially_valid = true;
2421  }
2422  }
2423 }
2424 
2425 /*
2426  * transformFKConstraints
2427  * handle FOREIGN KEY constraints
2428  */
2429 static void
2431  bool skipValidation, bool isAddConstraint)
2432 {
2433  ListCell *fkclist;
2434 
2435  if (cxt->fkconstraints == NIL)
2436  return;
2437 
2438  /*
2439  * If CREATE TABLE or adding a column with NULL default, we can safely
2440  * skip validation of FK constraints, and nonetheless mark them valid.
2441  * (This will override any user-supplied NOT VALID flag.)
2442  */
2443  if (skipValidation)
2444  {
2445  foreach(fkclist, cxt->fkconstraints)
2446  {
2447  Constraint *constraint = (Constraint *) lfirst(fkclist);
2448 
2449  constraint->skip_validation = true;
2450  constraint->initially_valid = true;
2451  }
2452  }
2453 
2454  /*
2455  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2456  * CONSTRAINT command to execute after the basic command is complete. (If
2457  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2458  * its own subcommand list.)
2459  *
2460  * Note: the ADD CONSTRAINT command must also execute after any index
2461  * creation commands. Thus, this should run after
2462  * transformIndexConstraints, so that the CREATE INDEX commands are
2463  * already in cxt->alist.
2464  */
2465  if (!isAddConstraint)
2466  {
2467  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2468 
2469  alterstmt->relation = cxt->relation;
2470  alterstmt->cmds = NIL;
2471  alterstmt->relkind = OBJECT_TABLE;
2472 
2473  foreach(fkclist, cxt->fkconstraints)
2474  {
2475  Constraint *constraint = (Constraint *) lfirst(fkclist);
2476  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2477 
2478  altercmd->subtype = AT_ProcessedConstraint;
2479  altercmd->name = NULL;
2480  altercmd->def = (Node *) constraint;
2481  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2482  }
2483 
2484  cxt->alist = lappend(cxt->alist, alterstmt);
2485  }
2486 }
2487 
2488 /*
2489  * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
2490  *
2491  * Note: this is a no-op for an index not using either index expressions or
2492  * a predicate expression. There are several code paths that create indexes
2493  * without bothering to call this, because they know they don't have any
2494  * such expressions to deal with.
2495  *
2496  * To avoid race conditions, it's important that this function rely only on
2497  * the passed-in relid (and not on stmt->relation) to determine the target
2498  * relation.
2499  */
2500 IndexStmt *
2501 transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
2502 {
2503  ParseState *pstate;
2504  RangeTblEntry *rte;
2505  ListCell *l;
2506  Relation rel;
2507 
2508  /* Nothing to do if statement already transformed. */
2509  if (stmt->transformed)
2510  return stmt;
2511 
2512  /*
2513  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2514  * overkill, but easy.)
2515  */
2516  stmt = copyObject(stmt);
2517 
2518  /* Set up pstate */
2519  pstate = make_parsestate(NULL);
2520  pstate->p_sourcetext = queryString;
2521 
2522  /*
2523  * Put the parent table into the rtable so that the expressions can refer
2524  * to its fields without qualification. Caller is responsible for locking
2525  * relation, but we still need to open it.
2526  */
2527  rel = relation_open(relid, NoLock);
2528  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, true);
2529 
2530  /* no to join list, yes to namespaces */
2531  addRTEtoQuery(pstate, rte, false, true, true);
2532 
2533  /* take care of the where clause */
2534  if (stmt->whereClause)
2535  {
2536  stmt->whereClause = transformWhereClause(pstate,
2537  stmt->whereClause,
2539  "WHERE");
2540  /* we have to fix its collations too */
2541  assign_expr_collations(pstate, stmt->whereClause);
2542  }
2543 
2544  /* take care of any index expressions */
2545  foreach(l, stmt->indexParams)
2546  {
2547  IndexElem *ielem = (IndexElem *) lfirst(l);
2548 
2549  if (ielem->expr)
2550  {
2551  /* Extract preliminary index col name before transforming expr */
2552  if (ielem->indexcolname == NULL)
2553  ielem->indexcolname = FigureIndexColname(ielem->expr);
2554 
2555  /* Now do parse transformation of the expression */
2556  ielem->expr = transformExpr(pstate, ielem->expr,
2558 
2559  /* We have to fix its collations too */
2560  assign_expr_collations(pstate, ielem->expr);
2561 
2562  /*
2563  * transformExpr() should have already rejected subqueries,
2564  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2565  * for an index expression.
2566  *
2567  * DefineIndex() will make more checks.
2568  */
2569  }
2570  }
2571 
2572  /*
2573  * Check that only the base rel is mentioned. (This should be dead code
2574  * now that add_missing_from is history.)
2575  */
2576  if (list_length(pstate->p_rtable) != 1)
2577  ereport(ERROR,
2578  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2579  errmsg("index expressions and predicates can refer only to the table being indexed")));
2580 
2581  free_parsestate(pstate);
2582 
2583  /* Close relation */
2584  heap_close(rel, NoLock);
2585 
2586  /* Mark statement as successfully transformed */
2587  stmt->transformed = true;
2588 
2589  return stmt;
2590 }
2591 
2592 
2593 /*
2594  * transformRuleStmt -
2595  * transform a CREATE RULE Statement. The action is a list of parse
2596  * trees which is transformed into a list of query trees, and we also
2597  * transform the WHERE clause if any.
2598  *
2599  * actions and whereClause are output parameters that receive the
2600  * transformed results.
2601  *
2602  * Note that we must not scribble on the passed-in RuleStmt, so we do
2603  * copyObject() on the actions and WHERE clause.
2604  */
2605 void
2606 transformRuleStmt(RuleStmt *stmt, const char *queryString,
2607  List **actions, Node **whereClause)
2608 {
2609  Relation rel;
2610  ParseState *pstate;
2611  RangeTblEntry *oldrte;
2612  RangeTblEntry *newrte;
2613 
2614  /*
2615  * To avoid deadlock, make sure the first thing we do is grab
2616  * AccessExclusiveLock on the target relation. This will be needed by
2617  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2618  * beforehand.
2619  */
2621 
2622  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2623  ereport(ERROR,
2624  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2625  errmsg("rules on materialized views are not supported")));
2626 
2627  /* Set up pstate */
2628  pstate = make_parsestate(NULL);
2629  pstate->p_sourcetext = queryString;
2630 
2631  /*
2632  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2633  * Set up their RTEs in the main pstate for use in parsing the rule
2634  * qualification.
2635  */
2636  oldrte = addRangeTableEntryForRelation(pstate, rel,
2637  makeAlias("old", NIL),
2638  false, false);
2639  newrte = addRangeTableEntryForRelation(pstate, rel,
2640  makeAlias("new", NIL),
2641  false, false);
2642  /* Must override addRangeTableEntry's default access-check flags */
2643  oldrte->requiredPerms = 0;
2644  newrte->requiredPerms = 0;
2645 
2646  /*
2647  * They must be in the namespace too for lookup purposes, but only add the
2648  * one(s) that are relevant for the current kind of rule. In an UPDATE
2649  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2650  * there's no need to be so picky for INSERT & DELETE. We do not add them
2651  * to the joinlist.
2652  */
2653  switch (stmt->event)
2654  {
2655  case CMD_SELECT:
2656  addRTEtoQuery(pstate, oldrte, false, true, true);
2657  break;
2658  case CMD_UPDATE:
2659  addRTEtoQuery(pstate, oldrte, false, true, true);
2660  addRTEtoQuery(pstate, newrte, false, true, true);
2661  break;
2662  case CMD_INSERT:
2663  addRTEtoQuery(pstate, newrte, false, true, true);
2664  break;
2665  case CMD_DELETE:
2666  addRTEtoQuery(pstate, oldrte, false, true, true);
2667  break;
2668  default:
2669  elog(ERROR, "unrecognized event type: %d",
2670  (int) stmt->event);
2671  break;
2672  }
2673 
2674  /* take care of the where clause */
2675  *whereClause = transformWhereClause(pstate,
2676  (Node *) copyObject(stmt->whereClause),
2678  "WHERE");
2679  /* we have to fix its collations too */
2680  assign_expr_collations(pstate, *whereClause);
2681 
2682  /* this is probably dead code without add_missing_from: */
2683  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
2684  ereport(ERROR,
2685  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2686  errmsg("rule WHERE condition cannot contain references to other relations")));
2687 
2688  /*
2689  * 'instead nothing' rules with a qualification need a query rangetable so
2690  * the rewrite handler can add the negated rule qualification to the
2691  * original query. We create a query with the new command type CMD_NOTHING
2692  * here that is treated specially by the rewrite system.
2693  */
2694  if (stmt->actions == NIL)
2695  {
2696  Query *nothing_qry = makeNode(Query);
2697 
2698  nothing_qry->commandType = CMD_NOTHING;
2699  nothing_qry->rtable = pstate->p_rtable;
2700  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
2701 
2702  *actions = list_make1(nothing_qry);
2703  }
2704  else
2705  {
2706  ListCell *l;
2707  List *newactions = NIL;
2708 
2709  /*
2710  * transform each statement, like parse_sub_analyze()
2711  */
2712  foreach(l, stmt->actions)
2713  {
2714  Node *action = (Node *) lfirst(l);
2715  ParseState *sub_pstate = make_parsestate(NULL);
2716  Query *sub_qry,
2717  *top_subqry;
2718  bool has_old,
2719  has_new;
2720 
2721  /*
2722  * Since outer ParseState isn't parent of inner, have to pass down
2723  * the query text by hand.
2724  */
2725  sub_pstate->p_sourcetext = queryString;
2726 
2727  /*
2728  * Set up OLD/NEW in the rtable for this statement. The entries
2729  * are added only to relnamespace, not varnamespace, because we
2730  * don't want them to be referred to by unqualified field names
2731  * nor "*" in the rule actions. We decide later whether to put
2732  * them in the joinlist.
2733  */
2734  oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
2735  makeAlias("old", NIL),
2736  false, false);
2737  newrte = addRangeTableEntryForRelation(sub_pstate, rel,
2738  makeAlias("new", NIL),
2739  false, false);
2740  oldrte->requiredPerms = 0;
2741  newrte->requiredPerms = 0;
2742  addRTEtoQuery(sub_pstate, oldrte, false, true, false);
2743  addRTEtoQuery(sub_pstate, newrte, false, true, false);
2744 
2745  /* Transform the rule action statement */
2746  top_subqry = transformStmt(sub_pstate,
2747  (Node *) copyObject(action));
2748 
2749  /*
2750  * We cannot support utility-statement actions (eg NOTIFY) with
2751  * nonempty rule WHERE conditions, because there's no way to make
2752  * the utility action execute conditionally.
2753  */
2754  if (top_subqry->commandType == CMD_UTILITY &&
2755  *whereClause != NULL)
2756  ereport(ERROR,
2757  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2758  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
2759 
2760  /*
2761  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
2762  * into the SELECT, and that's what we need to look at. (Ugly
2763  * kluge ... try to fix this when we redesign querytrees.)
2764  */
2765  sub_qry = getInsertSelectQuery(top_subqry, NULL);
2766 
2767  /*
2768  * If the sub_qry is a setop, we cannot attach any qualifications
2769  * to it, because the planner won't notice them. This could
2770  * perhaps be relaxed someday, but for now, we may as well reject
2771  * such a rule immediately.
2772  */
2773  if (sub_qry->setOperations != NULL && *whereClause != NULL)
2774  ereport(ERROR,
2775  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2776  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2777 
2778  /*
2779  * Validate action's use of OLD/NEW, qual too
2780  */
2781  has_old =
2782  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
2783  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
2784  has_new =
2785  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
2786  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
2787 
2788  switch (stmt->event)
2789  {
2790  case CMD_SELECT:
2791  if (has_old)
2792  ereport(ERROR,
2793  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2794  errmsg("ON SELECT rule cannot use OLD")));
2795  if (has_new)
2796  ereport(ERROR,
2797  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2798  errmsg("ON SELECT rule cannot use NEW")));
2799  break;
2800  case CMD_UPDATE:
2801  /* both are OK */
2802  break;
2803  case CMD_INSERT:
2804  if (has_old)
2805  ereport(ERROR,
2806  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2807  errmsg("ON INSERT rule cannot use OLD")));
2808  break;
2809  case CMD_DELETE:
2810  if (has_new)
2811  ereport(ERROR,
2812  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2813  errmsg("ON DELETE rule cannot use NEW")));
2814  break;
2815  default:
2816  elog(ERROR, "unrecognized event type: %d",
2817  (int) stmt->event);
2818  break;
2819  }
2820 
2821  /*
2822  * OLD/NEW are not allowed in WITH queries, because they would
2823  * amount to outer references for the WITH, which we disallow.
2824  * However, they were already in the outer rangetable when we
2825  * analyzed the query, so we have to check.
2826  *
2827  * Note that in the INSERT...SELECT case, we need to examine the
2828  * CTE lists of both top_subqry and sub_qry.
2829  *
2830  * Note that we aren't digging into the body of the query looking
2831  * for WITHs in nested sub-SELECTs. A WITH down there can
2832  * legitimately refer to OLD/NEW, because it'd be an
2833  * indirect-correlated outer reference.
2834  */
2835  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2836  PRS2_OLD_VARNO, 0) ||
2837  rangeTableEntry_used((Node *) sub_qry->cteList,
2838  PRS2_OLD_VARNO, 0))
2839  ereport(ERROR,
2840  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2841  errmsg("cannot refer to OLD within WITH query")));
2842  if (rangeTableEntry_used((Node *) top_subqry->cteList,
2843  PRS2_NEW_VARNO, 0) ||
2844  rangeTableEntry_used((Node *) sub_qry->cteList,
2845  PRS2_NEW_VARNO, 0))
2846  ereport(ERROR,
2847  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2848  errmsg("cannot refer to NEW within WITH query")));
2849 
2850  /*
2851  * For efficiency's sake, add OLD to the rule action's jointree
2852  * only if it was actually referenced in the statement or qual.
2853  *
2854  * For INSERT, NEW is not really a relation (only a reference to
2855  * the to-be-inserted tuple) and should never be added to the
2856  * jointree.
2857  *
2858  * For UPDATE, we treat NEW as being another kind of reference to
2859  * OLD, because it represents references to *transformed* tuples
2860  * of the existing relation. It would be wrong to enter NEW
2861  * separately in the jointree, since that would cause a double
2862  * join of the updated relation. It's also wrong to fail to make
2863  * a jointree entry if only NEW and not OLD is mentioned.
2864  */
2865  if (has_old || (has_new && stmt->event == CMD_UPDATE))
2866  {
2867  /*
2868  * If sub_qry is a setop, manipulating its jointree will do no
2869  * good at all, because the jointree is dummy. (This should be
2870  * a can't-happen case because of prior tests.)
2871  */
2872  if (sub_qry->setOperations != NULL)
2873  ereport(ERROR,
2874  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2875  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2876  /* hack so we can use addRTEtoQuery() */
2877  sub_pstate->p_rtable = sub_qry->rtable;
2878  sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2879  addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2880  sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2881  }
2882 
2883  newactions = lappend(newactions, top_subqry);
2884 
2885  free_parsestate(sub_pstate);
2886  }
2887 
2888  *actions = newactions;
2889  }
2890 
2891  free_parsestate(pstate);
2892 
2893  /* Close relation, but keep the exclusive lock */
2894  heap_close(rel, NoLock);
2895 }
2896 
2897 
2898 /*
2899  * transformAlterTableStmt -
2900  * parse analysis for ALTER TABLE
2901  *
2902  * Returns a List of utility commands to be done in sequence. One of these
2903  * will be the transformed AlterTableStmt, but there may be additional actions
2904  * to be done before and after the actual AlterTable() call.
2905  *
2906  * To avoid race conditions, it's important that this function rely only on
2907  * the passed-in relid (and not on stmt->relation) to determine the target
2908  * relation.
2909  */
2910 List *
2912  const char *queryString)
2913 {
2914  Relation rel;
2915  ParseState *pstate;
2916  CreateStmtContext cxt;
2917  List *result;
2918  List *save_alist;
2919  ListCell *lcmd,
2920  *l;
2921  List *newcmds = NIL;
2922  bool skipValidation = true;
2923  AlterTableCmd *newcmd;
2924  RangeTblEntry *rte;
2925 
2926  /*
2927  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
2928  * is overkill, but easy.)
2929  */
2930  stmt = copyObject(stmt);
2931 
2932  /* Caller is responsible for locking the relation */
2933  rel = relation_open(relid, NoLock);
2934 
2935  /* Set up pstate */
2936  pstate = make_parsestate(NULL);
2937  pstate->p_sourcetext = queryString;
2938  rte = addRangeTableEntryForRelation(pstate,
2939  rel,
2940  NULL,
2941  false,
2942  true);
2943  addRTEtoQuery(pstate, rte, false, true, true);
2944 
2945  /* Set up CreateStmtContext */
2946  cxt.pstate = pstate;
2947  if (stmt->relkind == OBJECT_FOREIGN_TABLE)
2948  {
2949  cxt.stmtType = "ALTER FOREIGN TABLE";
2950  cxt.isforeign = true;
2951  }
2952  else
2953  {
2954  cxt.stmtType = "ALTER TABLE";
2955  cxt.isforeign = false;
2956  }
2957  cxt.relation = stmt->relation;
2958  cxt.rel = rel;
2959  cxt.inhRelations = NIL;
2960  cxt.isalter = true;
2961  cxt.hasoids = false; /* need not be right */
2962  cxt.columns = NIL;
2963  cxt.ckconstraints = NIL;
2964  cxt.fkconstraints = NIL;
2965  cxt.ixconstraints = NIL;
2966  cxt.inh_indexes = NIL;
2967  cxt.extstats = NIL;
2968  cxt.blist = NIL;
2969  cxt.alist = NIL;
2970  cxt.pkey = NULL;
2971  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
2972  cxt.partbound = NULL;
2973  cxt.ofType = false;
2974 
2975  /*
2976  * The only subtypes that currently require parse transformation handling
2977  * are ADD COLUMN, ADD CONSTRAINT and SET DATA TYPE. These largely re-use
2978  * code from CREATE TABLE.
2979  */
2980  foreach(lcmd, stmt->cmds)
2981  {
2982  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2983 
2984  switch (cmd->subtype)
2985  {
2986  case AT_AddColumn:
2987  case AT_AddColumnToView:
2988  {
2989  ColumnDef *def = castNode(ColumnDef, cmd->def);
2990 
2991  transformColumnDefinition(&cxt, def);
2992 
2993  /*
2994  * If the column has a non-null default, we can't skip
2995  * validation of foreign keys.
2996  */
2997  if (def->raw_default != NULL)
2998  skipValidation = false;
2999 
3000  /*
3001  * All constraints are processed in other ways. Remove the
3002  * original list
3003  */
3004  def->constraints = NIL;
3005 
3006  newcmds = lappend(newcmds, cmd);
3007  break;
3008  }
3009 
3010  case AT_AddConstraint:
3011 
3012  /*
3013  * The original AddConstraint cmd node doesn't go to newcmds
3014  */
3015  if (IsA(cmd->def, Constraint))
3016  {
3017  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3018  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3019  skipValidation = false;
3020  }
3021  else
3022  elog(ERROR, "unrecognized node type: %d",
3023  (int) nodeTag(cmd->def));
3024  break;
3025 
3027 
3028  /*
3029  * Already-transformed ADD CONSTRAINT, so just make it look
3030  * like the standard case.
3031  */
3032  cmd->subtype = AT_AddConstraint;
3033  newcmds = lappend(newcmds, cmd);
3034  break;
3035 
3036  case AT_AlterColumnType:
3037  {
3038  ColumnDef *def = (ColumnDef *) cmd->def;
3040 
3041  /*
3042  * For ALTER COLUMN TYPE, transform the USING clause if
3043  * one was specified.
3044  */
3045  if (def->raw_default)
3046  {
3047  def->cooked_default =
3048  transformExpr(pstate, def->raw_default,
3050  }
3051 
3052  /*
3053  * For identity column, create ALTER SEQUENCE command to
3054  * change the data type of the sequence.
3055  */
3056  attnum = get_attnum(relid, cmd->name);
3057 
3058  /*
3059  * if attribute not found, something will error about it
3060  * later
3061  */
3062  if (attnum != InvalidAttrNumber && get_attidentity(relid, attnum))
3063  {
3064  Oid seq_relid = getOwnedSequence(relid, attnum);
3065  Oid typeOid = typenameTypeId(pstate, def->typeName);
3066  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3067 
3068  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3069  get_rel_name(seq_relid),
3070  -1);
3071  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3072  altseqstmt->for_identity = true;
3073  cxt.blist = lappend(cxt.blist, altseqstmt);
3074  }
3075 
3076  newcmds = lappend(newcmds, cmd);
3077  break;
3078  }
3079 
3080  case AT_AddIdentity:
3081  {
3082  Constraint *def = castNode(Constraint, cmd->def);
3083  ColumnDef *newdef = makeNode(ColumnDef);
3085 
3086  newdef->colname = cmd->name;
3087  newdef->identity = def->generated_when;
3088  cmd->def = (Node *) newdef;
3089 
3090  attnum = get_attnum(relid, cmd->name);
3091 
3092  /*
3093  * if attribute not found, something will error about it
3094  * later
3095  */
3096  if (attnum != InvalidAttrNumber)
3097  generateSerialExtraStmts(&cxt, newdef,
3098  get_atttype(relid, attnum),
3099  def->options, true,
3100  NULL, NULL);
3101 
3102  newcmds = lappend(newcmds, cmd);
3103  break;
3104  }
3105 
3106  case AT_SetIdentity:
3107  {
3108  /*
3109  * Create an ALTER SEQUENCE statement for the internal
3110  * sequence of the identity column.
3111  */
3112  ListCell *lc;
3113  List *newseqopts = NIL;
3114  List *newdef = NIL;
3115  List *seqlist;
3117 
3118  /*
3119  * Split options into those handled by ALTER SEQUENCE and
3120  * those for ALTER TABLE proper.
3121  */
3122  foreach(lc, castNode(List, cmd->def))
3123  {
3124  DefElem *def = lfirst_node(DefElem, lc);
3125 
3126  if (strcmp(def->defname, "generated") == 0)
3127  newdef = lappend(newdef, def);
3128  else
3129  newseqopts = lappend(newseqopts, def);
3130  }
3131 
3132  attnum = get_attnum(relid, cmd->name);
3133 
3134  if (attnum)
3135  {
3136  seqlist = getOwnedSequences(relid, attnum);
3137  if (seqlist)
3138  {
3139  AlterSeqStmt *seqstmt;
3140  Oid seq_relid;
3141 
3142  seqstmt = makeNode(AlterSeqStmt);
3143  seq_relid = linitial_oid(seqlist);
3145  get_rel_name(seq_relid), -1);
3146  seqstmt->options = newseqopts;
3147  seqstmt->for_identity = true;
3148  seqstmt->missing_ok = false;
3149 
3150  cxt.alist = lappend(cxt.alist, seqstmt);
3151  }
3152  }
3153 
3154  /*
3155  * If column was not found or was not an identity column,
3156  * we just let the ALTER TABLE command error out later.
3157  */
3158 
3159  cmd->def = (Node *) newdef;
3160  newcmds = lappend(newcmds, cmd);
3161  break;
3162  }
3163 
3164  case AT_AttachPartition:
3165  case AT_DetachPartition:
3166  {
3167  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3168 
3169  transformPartitionCmd(&cxt, partcmd);
3170  /* assign transformed value of the partition bound */
3171  partcmd->bound = cxt.partbound;
3172  }
3173 
3174  newcmds = lappend(newcmds, cmd);
3175  break;
3176 
3177  default:
3178  newcmds = lappend(newcmds, cmd);
3179  break;
3180  }
3181  }
3182 
3183  /*
3184  * transformIndexConstraints wants cxt.alist to contain only index
3185  * statements, so transfer anything we already have into save_alist
3186  * immediately.
3187  */
3188  save_alist = cxt.alist;
3189  cxt.alist = NIL;
3190 
3191  /* Postprocess constraints */
3193  transformFKConstraints(&cxt, skipValidation, true);
3194  transformCheckConstraints(&cxt, false);
3195 
3196  /*
3197  * Push any index-creation commands into the ALTER, so that they can be
3198  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3199  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3200  * subcommand has already been through transformIndexStmt.
3201  */
3202  foreach(l, cxt.alist)
3203  {
3204  IndexStmt *idxstmt = lfirst_node(IndexStmt, l);
3205 
3206  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3207  newcmd = makeNode(AlterTableCmd);
3209  newcmd->def = (Node *) idxstmt;
3210  newcmds = lappend(newcmds, newcmd);
3211  }
3212  cxt.alist = NIL;
3213 
3214  /* Append any CHECK or FK constraints to the commands list */
3215  foreach(l, cxt.ckconstraints)
3216  {
3217  newcmd = makeNode(AlterTableCmd);
3218  newcmd->subtype = AT_AddConstraint;
3219  newcmd->def = (Node *) lfirst(l);
3220  newcmds = lappend(newcmds, newcmd);
3221  }
3222  foreach(l, cxt.fkconstraints)
3223  {
3224  newcmd = makeNode(AlterTableCmd);
3225  newcmd->subtype = AT_AddConstraint;
3226  newcmd->def = (Node *) lfirst(l);
3227  newcmds = lappend(newcmds, newcmd);
3228  }
3229 
3230  /* Append extended statistic objects */
3232 
3233  /* Close rel */
3234  relation_close(rel, NoLock);
3235 
3236  /*
3237  * Output results.
3238  */
3239  stmt->cmds = newcmds;
3240 
3241  result = lappend(cxt.blist, stmt);
3242  result = list_concat(result, cxt.alist);
3243  result = list_concat(result, save_alist);
3244 
3245  return result;
3246 }
3247 
3248 
3249 /*
3250  * Preprocess a list of column constraint clauses
3251  * to attach constraint attributes to their primary constraint nodes
3252  * and detect inconsistent/misplaced constraint attributes.
3253  *
3254  * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
3255  * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
3256  * supported for other constraint types.
3257  */
3258 static void
3260 {
3261  Constraint *lastprimarycon = NULL;
3262  bool saw_deferrability = false;
3263  bool saw_initially = false;
3264  ListCell *clist;
3265 
3266 #define SUPPORTS_ATTRS(node) \
3267  ((node) != NULL && \
3268  ((node)->contype == CONSTR_PRIMARY || \
3269  (node)->contype == CONSTR_UNIQUE || \
3270  (node)->contype == CONSTR_EXCLUSION || \
3271  (node)->contype == CONSTR_FOREIGN))
3272 
3273  foreach(clist, constraintList)
3274  {
3275  Constraint *con = (Constraint *) lfirst(clist);
3276 
3277  if (!IsA(con, Constraint))
3278  elog(ERROR, "unrecognized node type: %d",
3279  (int) nodeTag(con));
3280  switch (con->contype)
3281  {
3283  if (!SUPPORTS_ATTRS(lastprimarycon))
3284  ereport(ERROR,
3285  (errcode(ERRCODE_SYNTAX_ERROR),
3286  errmsg("misplaced DEFERRABLE clause"),
3287  parser_errposition(cxt->pstate, con->location)));
3288  if (saw_deferrability)
3289  ereport(ERROR,
3290  (errcode(ERRCODE_SYNTAX_ERROR),
3291  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3292  parser_errposition(cxt->pstate, con->location)));
3293  saw_deferrability = true;
3294  lastprimarycon->deferrable = true;
3295  break;
3296 
3298  if (!SUPPORTS_ATTRS(lastprimarycon))
3299  ereport(ERROR,
3300  (errcode(ERRCODE_SYNTAX_ERROR),
3301  errmsg("misplaced NOT DEFERRABLE clause"),
3302  parser_errposition(cxt->pstate, con->location)));
3303  if (saw_deferrability)
3304  ereport(ERROR,
3305  (errcode(ERRCODE_SYNTAX_ERROR),
3306  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3307  parser_errposition(cxt->pstate, con->location)));
3308  saw_deferrability = true;
3309  lastprimarycon->deferrable = false;
3310  if (saw_initially &&
3311  lastprimarycon->initdeferred)
3312  ereport(ERROR,
3313  (errcode(ERRCODE_SYNTAX_ERROR),
3314  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3315  parser_errposition(cxt->pstate, con->location)));
3316  break;
3317 
3318  case CONSTR_ATTR_DEFERRED:
3319  if (!SUPPORTS_ATTRS(lastprimarycon))
3320  ereport(ERROR,
3321  (errcode(ERRCODE_SYNTAX_ERROR),
3322  errmsg("misplaced INITIALLY DEFERRED clause"),
3323  parser_errposition(cxt->pstate, con->location)));
3324  if (saw_initially)
3325  ereport(ERROR,
3326  (errcode(ERRCODE_SYNTAX_ERROR),
3327  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3328  parser_errposition(cxt->pstate, con->location)));
3329  saw_initially = true;
3330  lastprimarycon->initdeferred = true;
3331 
3332  /*
3333  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3334  */
3335  if (!saw_deferrability)
3336  lastprimarycon->deferrable = true;
3337  else if (!lastprimarycon->deferrable)
3338  ereport(ERROR,
3339  (errcode(ERRCODE_SYNTAX_ERROR),
3340  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3341  parser_errposition(cxt->pstate, con->location)));
3342  break;
3343 
3344  case CONSTR_ATTR_IMMEDIATE:
3345  if (!SUPPORTS_ATTRS(lastprimarycon))
3346  ereport(ERROR,
3347  (errcode(ERRCODE_SYNTAX_ERROR),
3348  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3349  parser_errposition(cxt->pstate, con->location)));
3350  if (saw_initially)
3351  ereport(ERROR,
3352  (errcode(ERRCODE_SYNTAX_ERROR),
3353  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3354  parser_errposition(cxt->pstate, con->location)));
3355  saw_initially = true;
3356  lastprimarycon->initdeferred = false;
3357  break;
3358 
3359  default:
3360  /* Otherwise it's not an attribute */
3361  lastprimarycon = con;
3362  /* reset flags for new primary node */
3363  saw_deferrability = false;
3364  saw_initially = false;
3365  break;
3366  }
3367  }
3368 }
3369 
3370 /*
3371  * Special handling of type definition for a column
3372  */
3373 static void
3375 {
3376  /*
3377  * All we really need to do here is verify that the type is valid,
3378  * including any collation spec that might be present.
3379  */
3380  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3381 
3382  if (column->collClause)
3383  {
3384  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3385 
3386  LookupCollation(cxt->pstate,
3387  column->collClause->collname,
3388  column->collClause->location);
3389  /* Complain if COLLATE is applied to an uncollatable type */
3390  if (!OidIsValid(typtup->typcollation))
3391  ereport(ERROR,
3392  (errcode(ERRCODE_DATATYPE_MISMATCH),
3393  errmsg("collations are not supported by type %s",
3396  column->collClause->location)));
3397  }
3398 
3399  ReleaseSysCache(ctype);
3400 }
3401 
3402 
3403 /*
3404  * transformCreateSchemaStmt -
3405  * analyzes the CREATE SCHEMA statement
3406  *
3407  * Split the schema element list into individual commands and place
3408  * them in the result list in an order such that there are no forward
3409  * references (e.g. GRANT to a table created later in the list). Note
3410  * that the logic we use for determining forward references is
3411  * presently quite incomplete.
3412  *
3413  * SQL also allows constraints to make forward references, so thumb through
3414  * the table columns and move forward references to a posterior alter-table
3415  * command.
3416  *
3417  * The result is a list of parse nodes that still need to be analyzed ---
3418  * but we can't analyze the later commands until we've executed the earlier
3419  * ones, because of possible inter-object references.
3420  *
3421  * Note: this breaks the rules a little bit by modifying schema-name fields
3422  * within passed-in structs. However, the transformation would be the same
3423  * if done over, so it should be all right to scribble on the input to this
3424  * extent.
3425  */
3426 List *
3428 {
3430  List *result;
3431  ListCell *elements;
3432 
3433  cxt.stmtType = "CREATE SCHEMA";
3434  cxt.schemaname = stmt->schemaname;
3435  cxt.authrole = (RoleSpec *) stmt->authrole;
3436  cxt.sequences = NIL;
3437  cxt.tables = NIL;
3438  cxt.views = NIL;
3439  cxt.indexes = NIL;
3440  cxt.triggers = NIL;
3441  cxt.grants = NIL;
3442 
3443  /*
3444  * Run through each schema element in the schema element list. Separate
3445  * statements by type, and do preliminary analysis.
3446  */
3447  foreach(elements, stmt->schemaElts)
3448  {
3449  Node *element = lfirst(elements);
3450 
3451  switch (nodeTag(element))
3452  {
3453  case T_CreateSeqStmt:
3454  {
3455  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3456 
3458  cxt.sequences = lappend(cxt.sequences, element);
3459  }
3460  break;
3461 
3462  case T_CreateStmt:
3463  {
3464  CreateStmt *elp = (CreateStmt *) element;
3465 
3467 
3468  /*
3469  * XXX todo: deal with constraints
3470  */
3471  cxt.tables = lappend(cxt.tables, element);
3472  }
3473  break;
3474 
3475  case T_ViewStmt:
3476  {
3477  ViewStmt *elp = (ViewStmt *) element;
3478 
3479  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3480 
3481  /*
3482  * XXX todo: deal with references between views
3483  */
3484  cxt.views = lappend(cxt.views, element);
3485  }
3486  break;
3487 
3488  case T_IndexStmt:
3489  {
3490  IndexStmt *elp = (IndexStmt *) element;
3491 
3493  cxt.indexes = lappend(cxt.indexes, element);
3494  }
3495  break;
3496 
3497  case T_CreateTrigStmt:
3498  {
3499  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3500 
3502  cxt.triggers = lappend(cxt.triggers, element);
3503  }
3504  break;
3505 
3506  case T_GrantStmt:
3507  cxt.grants = lappend(cxt.grants, element);
3508  break;
3509 
3510  default:
3511  elog(ERROR, "unrecognized node type: %d",
3512  (int) nodeTag(element));
3513  }
3514  }
3515 
3516  result = NIL;
3517  result = list_concat(result, cxt.sequences);
3518  result = list_concat(result, cxt.tables);
3519  result = list_concat(result, cxt.views);
3520  result = list_concat(result, cxt.indexes);
3521  result = list_concat(result, cxt.triggers);
3522  result = list_concat(result, cxt.grants);
3523 
3524  return result;
3525 }
3526 
3527 /*
3528  * setSchemaName
3529  * Set or check schema name in an element of a CREATE SCHEMA command
3530  */
3531 static void
3532 setSchemaName(char *context_schema, char **stmt_schema_name)
3533 {
3534  if (*stmt_schema_name == NULL)
3535  *stmt_schema_name = context_schema;
3536  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3537  ereport(ERROR,
3538  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3539  errmsg("CREATE specifies a schema (%s) "
3540  "different from the one being created (%s)",
3541  *stmt_schema_name, context_schema)));
3542 }
3543 
3544 /*
3545  * transformPartitionCmd
3546  * Analyze the ATTACH/DETACH PARTITION command
3547  *
3548  * In case of the ATTACH PARTITION command, cxt->partbound is set to the
3549  * transformed value of cmd->bound.
3550  */
3551 static void
3553 {
3554  Relation parentRel = cxt->rel;
3555 
3556  switch (parentRel->rd_rel->relkind)
3557  {
3558  case RELKIND_PARTITIONED_TABLE:
3559  /* transform the partition bound, if any */
3560  Assert(RelationGetPartitionKey(parentRel) != NULL);
3561  if (cmd->bound != NULL)
3562  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
3563  cmd->bound);
3564  break;
3565  case RELKIND_PARTITIONED_INDEX:
3566  /* nothing to check */
3567  Assert(cmd->bound == NULL);
3568  break;
3569  case RELKIND_RELATION:
3570  /* the table must be partitioned */
3571  ereport(ERROR,
3572  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3573  errmsg("table \"%s\" is not partitioned",
3574  RelationGetRelationName(parentRel))));
3575  break;
3576  case RELKIND_INDEX:
3577  /* the index must be partitioned */
3578  ereport(ERROR,
3579  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3580  errmsg("index \"%s\" is not partitioned",
3581  RelationGetRelationName(parentRel))));
3582  break;
3583  default:
3584  /* parser shouldn't let this case through */
3585  elog(ERROR, "\"%s\" is not a partitioned table or index",
3586  RelationGetRelationName(parentRel));
3587  break;
3588  }
3589 }
3590 
3591 /*
3592  * transformPartitionBound
3593  *
3594  * Transform a partition bound specification
3595  */
3598  PartitionBoundSpec *spec)
3599 {
3600  PartitionBoundSpec *result_spec;
3601  PartitionKey key = RelationGetPartitionKey(parent);
3602  char strategy = get_partition_strategy(key);
3603  int partnatts = get_partition_natts(key);
3604  List *partexprs = get_partition_exprs(key);
3605 
3606  /* Avoid scribbling on input */
3607  result_spec = copyObject(spec);
3608 
3609  if (spec->is_default)
3610  {
3611  if (strategy == PARTITION_STRATEGY_HASH)
3612  ereport(ERROR,
3613  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3614  errmsg("a hash-partitioned table may not have a default partition")));
3615 
3616  /*
3617  * In case of the default partition, parser had no way to identify the
3618  * partition strategy. Assign the parent's strategy to the default
3619  * partition bound spec.
3620  */
3621  result_spec->strategy = strategy;
3622 
3623  return result_spec;
3624  }
3625 
3626  if (strategy == PARTITION_STRATEGY_HASH)
3627  {
3628  if (spec->strategy != PARTITION_STRATEGY_HASH)
3629  ereport(ERROR,
3630  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3631  errmsg("invalid bound specification for a hash partition"),
3632  parser_errposition(pstate, exprLocation((Node *) spec))));
3633 
3634  if (spec->modulus <= 0)
3635  ereport(ERROR,
3636  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3637  errmsg("modulus for hash partition must be a positive integer")));
3638 
3639  Assert(spec->remainder >= 0);
3640 
3641  if (spec->remainder >= spec->modulus)
3642  ereport(ERROR,
3643  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3644  errmsg("remainder for hash partition must be less than modulus")));
3645  }
3646  else if (strategy == PARTITION_STRATEGY_LIST)
3647  {
3648  ListCell *cell;
3649  char *colname;
3650  Oid coltype;
3651  int32 coltypmod;
3652 
3653  if (spec->strategy != PARTITION_STRATEGY_LIST)
3654  ereport(ERROR,
3655  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3656  errmsg("invalid bound specification for a list partition"),
3657  parser_errposition(pstate, exprLocation((Node *) spec))));
3658 
3659  /* Get the only column's name in case we need to output an error */
3660  if (key->partattrs[0] != 0)
3661  colname = get_attname(RelationGetRelid(parent),
3662  key->partattrs[0], false);
3663  else
3664  colname = deparse_expression((Node *) linitial(partexprs),
3666  RelationGetRelid(parent)),
3667  false, false);
3668  /* Need its type data too */
3669  coltype = get_partition_col_typid(key, 0);
3670  coltypmod = get_partition_col_typmod(key, 0);
3671 
3672  result_spec->listdatums = NIL;
3673  foreach(cell, spec->listdatums)
3674  {
3675  A_Const *con = castNode(A_Const, lfirst(cell));
3676  Const *value;
3677  ListCell *cell2;
3678  bool duplicate;
3679 
3680  value = transformPartitionBoundValue(pstate, con,
3681  colname, coltype, coltypmod);
3682 
3683  /* Don't add to the result if the value is a duplicate */
3684  duplicate = false;
3685  foreach(cell2, result_spec->listdatums)
3686  {
3687  Const *value2 = castNode(Const, lfirst(cell2));
3688 
3689  if (equal(value, value2))
3690  {
3691  duplicate = true;
3692  break;
3693  }
3694  }
3695  if (duplicate)
3696  continue;
3697 
3698  result_spec->listdatums = lappend(result_spec->listdatums,
3699  value);
3700  }
3701  }
3702  else if (strategy == PARTITION_STRATEGY_RANGE)
3703  {
3704  ListCell *cell1,
3705  *cell2;
3706  int i,
3707  j;
3708 
3709  if (spec->strategy != PARTITION_STRATEGY_RANGE)
3710  ereport(ERROR,
3711  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3712  errmsg("invalid bound specification for a range partition"),
3713  parser_errposition(pstate, exprLocation((Node *) spec))));
3714 
3715  if (list_length(spec->lowerdatums) != partnatts)
3716  ereport(ERROR,
3717  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3718  errmsg("FROM must specify exactly one value per partitioning column")));
3719  if (list_length(spec->upperdatums) != partnatts)
3720  ereport(ERROR,
3721  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3722  errmsg("TO must specify exactly one value per partitioning column")));
3723 
3724  /*
3725  * Once we see MINVALUE or MAXVALUE for one column, the remaining
3726  * columns must be the same.
3727  */
3728  validateInfiniteBounds(pstate, spec->lowerdatums);
3729  validateInfiniteBounds(pstate, spec->upperdatums);
3730 
3731  /* Transform all the constants */
3732  i = j = 0;
3733  result_spec->lowerdatums = result_spec->upperdatums = NIL;
3734  forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
3735  {
3736  PartitionRangeDatum *ldatum = (PartitionRangeDatum *) lfirst(cell1);
3737  PartitionRangeDatum *rdatum = (PartitionRangeDatum *) lfirst(cell2);
3738  char *colname;
3739  Oid coltype;
3740  int32 coltypmod;
3741  A_Const *con;
3742  Const *value;
3743 
3744  /* Get the column's name in case we need to output an error */
3745  if (key->partattrs[i] != 0)
3746  colname = get_attname(RelationGetRelid(parent),
3747  key->partattrs[i], false);
3748  else
3749  {
3750  colname = deparse_expression((Node *) list_nth(partexprs, j),
3752  RelationGetRelid(parent)),
3753  false, false);
3754  ++j;
3755  }
3756  /* Need its type data too */
3757  coltype = get_partition_col_typid(key, i);
3758  coltypmod = get_partition_col_typmod(key, i);
3759 
3760  if (ldatum->value)
3761  {
3762  con = castNode(A_Const, ldatum->value);
3763  value = transformPartitionBoundValue(pstate, con,
3764  colname,
3765  coltype, coltypmod);
3766  if (value->constisnull)
3767  ereport(ERROR,
3768  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3769  errmsg("cannot specify NULL in range bound")));
3770  ldatum = copyObject(ldatum); /* don't scribble on input */
3771  ldatum->value = (Node *) value;
3772  }
3773 
3774  if (rdatum->value)
3775  {
3776  con = castNode(A_Const, rdatum->value);
3777  value = transformPartitionBoundValue(pstate, con,
3778  colname,
3779  coltype, coltypmod);
3780  if (value->constisnull)
3781  ereport(ERROR,
3782  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3783  errmsg("cannot specify NULL in range bound")));
3784  rdatum = copyObject(rdatum); /* don't scribble on input */
3785  rdatum->value = (Node *) value;
3786  }
3787 
3788  result_spec->lowerdatums = lappend(result_spec->lowerdatums,
3789  ldatum);
3790  result_spec->upperdatums = lappend(result_spec->upperdatums,
3791  rdatum);
3792 
3793  ++i;
3794  }
3795  }
3796  else
3797  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
3798 
3799  return result_spec;
3800 }
3801 
3802 /*
3803  * validateInfiniteBounds
3804  *
3805  * Check that a MAXVALUE or MINVALUE specification in a partition bound is
3806  * followed only by more of the same.
3807  */
3808 static void
3810 {
3811  ListCell *lc;
3813 
3814  foreach(lc, blist)
3815  {
3817 
3818  if (kind == prd->kind)
3819  continue;
3820 
3821  switch (kind)
3822  {
3824  kind = prd->kind;
3825  break;
3826 
3828  ereport(ERROR,
3829  (errcode(ERRCODE_DATATYPE_MISMATCH),
3830  errmsg("every bound following MAXVALUE must also be MAXVALUE"),
3831  parser_errposition(pstate, exprLocation((Node *) prd))));
3832  break;
3833 
3835  ereport(ERROR,
3836  (errcode(ERRCODE_DATATYPE_MISMATCH),
3837  errmsg("every bound following MINVALUE must also be MINVALUE"),
3838  parser_errposition(pstate, exprLocation((Node *) prd))));
3839  break;
3840  }
3841  }
3842 }
3843 
3844 /*
3845  * Transform one constant in a partition bound spec
3846  */
3847 static Const *
3849  const char *colName, Oid colType, int32 colTypmod)
3850 {
3851  Node *value;
3852 
3853  /* Make it into a Const */
3854  value = (Node *) make_const(pstate, &con->val, con->location);
3855 
3856  /* Coerce to correct type */
3857  value = coerce_to_target_type(pstate,
3858  value, exprType(value),
3859  colType,
3860  colTypmod,
3863  -1);
3864 
3865  if (value == NULL)
3866  ereport(ERROR,
3867  (errcode(ERRCODE_DATATYPE_MISMATCH),
3868  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3869  format_type_be(colType), colName),
3870  parser_errposition(pstate, con->location)));
3871 
3872  /* Simplify the expression, in case we had a coercion */
3873  if (!IsA(value, Const))
3874  value = (Node *) expression_planner((Expr *) value);
3875 
3876  /* Fail if we don't have a constant (i.e., non-immutable coercion) */
3877  if (!IsA(value, Const))
3878  ereport(ERROR,
3879  (errcode(ERRCODE_DATATYPE_MISMATCH),
3880  errmsg("specified value cannot be cast to type %s for column \"%s\"",
3881  format_type_be(colType), colName),
3882  errdetail("The cast requires a non-immutable conversion."),
3883  errhint("Try putting the literal value in single quotes."),
3884  parser_errposition(pstate, con->location)));
3885 
3886  return (Const *) value;
3887 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
bool deferrable
Definition: parsenodes.h:2734
RangeVar * relation
Definition: parsenodes.h:2014
ObjectType objtype
Definition: parsenodes.h:2618
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:141
signed short int16
Definition: c.h:312
#define NIL
Definition: pg_list.h:69
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:555
bool primary
Definition: parsenodes.h:2732
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1202
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:921
List * inhRelations
Definition: parsenodes.h:2016
List * SystemFuncName(char *name)
void * stringToNode(char *str)
Definition: read.c:39
Oid getOwnedSequence(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:605
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:284
Oid typeOid
Definition: parsenodes.h:211
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
List * keys
Definition: parsenodes.h:2107
char get_attidentity(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:836
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, char **snamespace_p, char **sname_p)
List * exclusions
Definition: parsenodes.h:2113
int16 * rd_indoption
Definition: rel.h:158
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:1824
SortByDir ordering
Definition: parsenodes.h:704
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
char generated_when
Definition: parsenodes.h:2104
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
char * ccname
Definition: tupdesc.h:32
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:247
List * names
Definition: parsenodes.h:210
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2725
char storage
Definition: parsenodes.h:654
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
#define IndexIsValid(indexForm)
Definition: pg_index.h:85
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1641
bool is_local
Definition: parsenodes.h:650
FromExpr * jointree
Definition: parsenodes.h:138
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
#define RelationGetDescr(relation)
Definition: rel.h:433
Oid GetUserId(void)
Definition: miscinit.c:379
#define castNode(_type_, nodeptr)
Definition: nodes.h:585
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
ConstrCheck * check
Definition: tupdesc.h:42
char identity
Definition: parsenodes.h:657
PartitionRangeDatumKind
Definition: parsenodes.h:834
char * tableSpace
Definition: parsenodes.h:2721
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:91
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
List * constraints
Definition: parsenodes.h:662
#define DatumGetObjectId(X)
Definition: postgres.h:485
char * pstrdup(const char *in)
Definition: mcxt.c:1161
char * ccbin
Definition: tupdesc.h:33
Node * raw_expr
Definition: parsenodes.h:2102
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:85
bool is_from_parent
Definition: parsenodes.h:653
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1754
Expr * expression_planner(Expr *expr)
Definition: planner.c:5888
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
PartitionRangeDatumKind kind
Definition: parsenodes.h:845
Node * whereClause
Definition: parsenodes.h:2726
Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids)
Definition: heap.c:217
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:516
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:64
#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:1270
bool initdeferred
Definition: parsenodes.h:2097
AlterTableType subtype
Definition: parsenodes.h:1806
List * actions
Definition: parsenodes.h:2919
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
List * list_concat(List *list1, List *list2)
Definition: list.c:321
char * comment
Definition: parsenodes.h:2620
static Const * transformPartitionBoundValue(ParseState *pstate, A_Const *con, const char *colName, Oid colType, int32 colTypmod)
static CreateStatsStmt * generateClonedExtStatsStmt(RangeVar *heapRel, Oid heapRelid, Oid source_statsid)
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3042
AclMode requiredPerms
Definition: parsenodes.h:1070
#define heap_close(r, l)
Definition: heapam.h:97
char * conname
Definition: parsenodes.h:2095
bool is_not_null
Definition: parsenodes.h:651
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
Node * object
Definition: parsenodes.h:2619
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
Const * make_const(ParseState *pstate, Value *value, int location)
Definition: parse_node.c:470
#define linitial_node(type, l)
Definition: pg_list.h:114
#define OidIsValid(objectId)
Definition: c.h:605
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:634
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:153
int natts
Definition: tupdesc.h:82
List * options
Definition: parsenodes.h:2495
RangeVar * view
Definition: parsenodes.h:3043
signed int int32
Definition: c.h:313
List * options
Definition: parsenodes.h:2116
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4678
int location
Definition: parsenodes.h:301
struct HeapTupleData * rd_indextuple
Definition: rel.h:133
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * indexIncludingParams
Definition: parsenodes.h:2723
int location
Definition: parsenodes.h:237
Definition: type.h:89
List * constraints
Definition: parsenodes.h:2021
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
#define list_make1(x1)
Definition: pg_list.h:139
bool if_not_exists
Definition: parsenodes.h:2025
int location
Definition: primnodes.h:73
RangeVar * identitySequence
Definition: parsenodes.h:658
void assign_expr_collations(ParseState *pstate, Node *expr)
ParseState * pstate
Definition: parse_utilcmd.c:76
PartitionBoundSpec * partbound
Definition: parsenodes.h:2018
Node * cooked_default
Definition: parsenodes.h:656
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:386
char * relname
Definition: primnodes.h:68
Oid indexOid
Definition: parsenodes.h:2729
Node * expr
Definition: parsenodes.h:700
RangeVar * relation
Definition: parse_utilcmd.c:78
RangeVar * relation
Definition: parsenodes.h:2718
IndexStmt * pkey
Definition: parse_utilcmd.c:94
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:70
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3349
Form_pg_index rd_index
Definition: rel.h:131
RoleSpec * authrole
Definition: parsenodes.h:1700
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
#define linitial(l)
Definition: pg_list.h:111
AttrDefault * defval
Definition: tupdesc.h:41
List * rtable
Definition: parsenodes.h:137
SortByNulls nulls_ordering
Definition: parsenodes.h:705
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
bool deferrable
Definition: parsenodes.h:2096
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
#define ARR_DIMS(a)
Definition: array.h:279
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5287
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1687
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define ARR_DATA_PTR(a)
Definition: array.h:307
static void validateInfiniteBounds(ParseState *pstate, List *blist)
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:183
void * list_nth(const List *list, int n)
Definition: list.c:410
#define NoLock
Definition: lockdefs.h:34
List * transformAlterTableStmt(Oid relid, AlterTableStmt *stmt, const char *queryString)
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:806
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4616
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:563
bool transformed
Definition: parsenodes.h:2736
Oid collOid
Definition: parsenodes.h:661
union Value::ValUnion val
List * fdwoptions
Definition: parsenodes.h:663
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3130
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Oid heapRelid, Relation source_idx, const AttrNumber *attmap, int attmap_length, Oid *constraintOid)
int errdetail(const char *fmt,...)
Definition: elog.c:873
char * indexcolname
Definition: parsenodes.h:701
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:441
List * options
Definition: parsenodes.h:2022
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
#define ARR_HASNULL(a)
Definition: array.h:276
#define ACL_USAGE
Definition: parsenodes.h:82
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:689
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:409
int location
Definition: parsenodes.h:664
const char * p_sourcetext
Definition: parse_node.h:173
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:863
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrNumber *attno_map, int map_length, Oid to_rowtype, bool *found_whole_row)
ObjectType relkind
Definition: parsenodes.h:1720
#define AssertArg(condition)
Definition: c.h:701
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:145
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:254
Node * arg
Definition: parsenodes.h:731
Node * raw_default
Definition: parsenodes.h:655
List * lappend(List *list, void *datum)
Definition: list.c:128
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
#define PRS2_OLD_VARNO
Definition: primnodes.h:160
char * idxname
Definition: parsenodes.h:2717
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10574
Value * makeInteger(int i)
Definition: value.c:23
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:527
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:585
TypeName * SystemTypeName(char *name)
#define TextDatumGetCString(d)
Definition: builtins.h:96
bool if_not_exists
Definition: parsenodes.h:2738
#define lsecond_node(type, l)
Definition: pg_list.h:119
void * palloc0(Size size)
Definition: mcxt.c:955
AclResult
Definition: acl.h:178
List * getOwnedSequences(Oid relid, AttrNumber attnum)
Definition: pg_depend.c:548
AttrNumber * partattrs
Definition: partcache.h:28
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:75
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1368
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2731
TypeName * typeName
Definition: parsenodes.h:300
List * untransformRelOptions(Datum options)
Definition: reloptions.c:934
static struct @131 value
TupleDesc rd_att
Definition: rel.h:85
#define PARTITION_STRATEGY_HASH
Definition: parsenodes.h:798
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:496
char * accessMethod
Definition: parsenodes.h:2720
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:471
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1323
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:203
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2494
int16 attnum
Definition: pg_attribute.h:79
bool initially_valid
Definition: parsenodes.h:2136
uint16 num_defval
Definition: tupdesc.h:44
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2799
RangeVar * sequence
Definition: parsenodes.h:2484
List * opclass
Definition: parsenodes.h:703
bool is_from_type
Definition: parsenodes.h:652
#define NOTICE
Definition: elog.h:37
CmdType commandType
Definition: parsenodes.h:112
List * tableElts
Definition: parsenodes.h:2015
List * lcons(void *datum, List *list)
Definition: list.c:259
Node * where_clause
Definition: parsenodes.h:2121
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define makeNode(_type_)
Definition: nodes.h:564
CmdType event
Definition: parsenodes.h:2917
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
static void setSchemaName(char *context_schema, char **stmt_schema_name)
int location
Definition: parsenodes.h:290
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:391
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
PartitionBoundSpec * bound
Definition: parsenodes.h:859
List * indexParams
Definition: parsenodes.h:2722
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3071
int location
Definition: parsenodes.h:217
TupleConstr * constr
Definition: tupdesc.h:87
#define linitial_oid(l)
Definition: pg_list.h:113
Node * whereClause
Definition: parsenodes.h:2916
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
FormData_pg_type * Form_pg_type
Definition: pg_type.h:248
List * excludeOpNames
Definition: parsenodes.h:2727
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:111
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
TypeName * typeName
Definition: parsenodes.h:648
CollateClause * collClause
Definition: parsenodes.h:660
bool initdeferred
Definition: parsenodes.h:2735
bool amcanorder
Definition: amapi.h:172
char * name
Definition: parsenodes.h:699
char * idxcomment
Definition: parsenodes.h:2728
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
#define ARR_NDIM(a)
Definition: array.h:275
#define PARTITION_STRATEGY_LIST
Definition: parsenodes.h:799
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4260
#define RelationGetPartitionKey(relation)
Definition: rel.h:589
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:82
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:49
#define nodeTag(nodeptr)
Definition: nodes.h:521
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4400
const char * stmtType
Definition: parse_utilcmd.c:77
static void transformExtendedStatistics(CreateStmtContext *cxt)
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4627
char relpersistence
Definition: primnodes.h:71
#define DatumGetPointer(X)
Definition: postgres.h:534
RangeVar * relation
Definition: parsenodes.h:673
bool interpretOidsOption(List *defList, bool allowOids)
Definition: parse_clause.c:262
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3449
FormData_pg_class * Form_pg_class
Definition: pg_class.h:93
#define PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:800
List * transformCreateSchemaStmt(CreateSchemaStmt *stmt)
bool concurrent
Definition: parsenodes.h:2737
#define AccessExclusiveLock
Definition: lockdefs.h:45
List * collname
Definition: parsenodes.h:311
List * cteList
Definition: parsenodes.h:135
List * arrayBounds
Definition: parsenodes.h:216
Node * setOperations
Definition: parsenodes.h:165
bool isconstraint
Definition: parsenodes.h:2733
char * indexname
Definition: parsenodes.h:2117
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:1718
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1428
void list_free(List *list)
Definition: list.c:1133
#define SUPPORTS_ATTRS(node)
char * str
Definition: value.h:48
int i
int inhcount
Definition: parsenodes.h:649
RangeVar * relation
Definition: parsenodes.h:2369
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:576
char * nodeToString(const void *obj)
Definition: outfuncs.c:4339
List * p_joinlist
Definition: parse_node.h:176
ConstrType contype
Definition: parsenodes.h:2092
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1124
List * collation
Definition: parsenodes.h:702
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:775
bool for_identity
Definition: parsenodes.h:2496
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:889
DropBehavior behavior
Definition: parsenodes.h:1814
char * defname
Definition: parsenodes.h:730
uint16 num_check
Definition: tupdesc.h:45
char * colname
Definition: parsenodes.h:647
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid)
Definition: indexcmds.c:2013
List * including
Definition: parsenodes.h:2109
#define elog
Definition: elog.h:219
char * cooked_expr
Definition: parsenodes.h:2103
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707
#define copyObject(obj)
Definition: nodes.h:629
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:58
AclResult pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4739
RangeVar * relation
Definition: parsenodes.h:2914
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
PartitionSpec * partspec
Definition: parsenodes.h:2019
List * sequence_options(Oid relid)
Definition: sequence.c:1743
static List * get_collation(Oid collation, Oid actual_datatype)
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:81
Value val
Definition: parsenodes.h:289
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
#define ARR_ELEMTYPE(a)
Definition: array.h:277
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2135
#define RelationGetRelid(relation)
Definition: rel.h:407
void transformRuleStmt(RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
char * access_method
Definition: parsenodes.h:2120
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
List * fk_attrs
Definition: parsenodes.h:2125
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
#define PRS2_NEW_VARNO
Definition: primnodes.h:161
Oid relationId
Definition: parsenodes.h:2719
bool constisnull
Definition: primnodes.h:197
TypeName * ofTypename
Definition: parsenodes.h:2020
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:440
char * indexspace
Definition: parsenodes.h:2118
List * fields
Definition: parsenodes.h:236
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define lfirst_oid(lc)
Definition: pg_list.h:108
List * options
Definition: parsenodes.h:2485
NodeTag type
Definition: value.h:44
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274
bool pct_type
Definition: parsenodes.h:213
Node * arg
Definition: parsenodes.h:299
#define RelationGetNamespace(relation)
Definition: rel.h:448
List * p_rtable
Definition: parse_node.h:174
#define DatumGetArrayTypeP(X)
Definition: array.h:246