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