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