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