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