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