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