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