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