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