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