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