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