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