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