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