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