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