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