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