PostgreSQL Source Code git master
parse_utilcmd.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * parse_utilcmd.c
4 * Perform parse analysis work for various utility commands
5 *
6 * Formerly we did this work during parse_analyze_*() in analyze.c. However
7 * that is fairly unsafe in the presence of querytree caching, since any
8 * database state that we depend on in making the transformations might be
9 * obsolete by the time the utility command is executed; and utility commands
10 * have no infrastructure for holding locks or rechecking plan validity.
11 * Hence these functions are now called at the start of execution of their
12 * respective utility commands.
13 *
14 *
15 * Portions Copyright (c) 1996-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 = ATTRIBUTE_GENERATED_STORED;
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 */
1121static void
1123{
1124 AttrNumber parent_attno;
1125 Relation relation;
1126 TupleDesc tupleDesc;
1127 AclResult aclresult;
1128 char *comment;
1129 ParseCallbackState pcbstate;
1130
1132 table_like_clause->relation->location);
1133
1134 /* we could support LIKE in many cases, but worry about it another day */
1135 if (cxt->isforeign)
1136 ereport(ERROR,
1137 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1138 errmsg("LIKE is not supported for creating foreign tables")));
1139
1140 /* Open the relation referenced by the LIKE clause */
1141 relation = relation_openrv(table_like_clause->relation, AccessShareLock);
1142
1143 if (relation->rd_rel->relkind != RELKIND_RELATION &&
1144 relation->rd_rel->relkind != RELKIND_VIEW &&
1145 relation->rd_rel->relkind != RELKIND_MATVIEW &&
1146 relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1147 relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
1148 relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1149 ereport(ERROR,
1150 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1151 errmsg("relation \"%s\" is invalid in LIKE clause",
1152 RelationGetRelationName(relation)),
1153 errdetail_relkind_not_supported(relation->rd_rel->relkind)));
1154
1156
1157 /*
1158 * Check for privileges
1159 */
1160 if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1161 {
1162 aclresult = object_aclcheck(TypeRelationId, relation->rd_rel->reltype, GetUserId(),
1163 ACL_USAGE);
1164 if (aclresult != ACLCHECK_OK)
1165 aclcheck_error(aclresult, OBJECT_TYPE,
1166 RelationGetRelationName(relation));
1167 }
1168 else
1169 {
1170 aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1171 ACL_SELECT);
1172 if (aclresult != ACLCHECK_OK)
1173 aclcheck_error(aclresult, get_relkind_objtype(relation->rd_rel->relkind),
1174 RelationGetRelationName(relation));
1175 }
1176
1177 tupleDesc = RelationGetDescr(relation);
1178
1179 /*
1180 * Insert the copied attributes into the cxt for the new table definition.
1181 * We must do this now so that they appear in the table in the relative
1182 * position where the LIKE clause is, as required by SQL99.
1183 */
1184 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1185 parent_attno++)
1186 {
1187 Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1188 parent_attno - 1);
1189 ColumnDef *def;
1190
1191 /*
1192 * Ignore dropped columns in the parent.
1193 */
1194 if (attribute->attisdropped)
1195 continue;
1196
1197 /*
1198 * Create a new column definition
1199 */
1200 def = makeColumnDef(NameStr(attribute->attname), attribute->atttypid,
1201 attribute->atttypmod, attribute->attcollation);
1202
1203 /*
1204 * Add to column list
1205 */
1206 cxt->columns = lappend(cxt->columns, def);
1207
1208 /*
1209 * Although we don't transfer the column's default/generation
1210 * expression now, we need to mark it GENERATED if appropriate.
1211 */
1212 if (attribute->atthasdef && attribute->attgenerated &&
1213 (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED))
1214 def->generated = attribute->attgenerated;
1215
1216 /*
1217 * Copy identity if requested
1218 */
1219 if (attribute->attidentity &&
1220 (table_like_clause->options & CREATE_TABLE_LIKE_IDENTITY))
1221 {
1222 Oid seq_relid;
1223 List *seq_options;
1224
1225 /*
1226 * find sequence owned by old column; extract sequence parameters;
1227 * build new create sequence command
1228 */
1229 seq_relid = getIdentitySequence(relation, attribute->attnum, false);
1230 seq_options = sequence_options(seq_relid);
1231 generateSerialExtraStmts(cxt, def,
1232 InvalidOid, seq_options,
1233 true, false,
1234 NULL, NULL);
1235 def->identity = attribute->attidentity;
1236 }
1237
1238 /* Likewise, copy storage if requested */
1239 if (table_like_clause->options & CREATE_TABLE_LIKE_STORAGE)
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 def->compression =
1248 pstrdup(GetCompressionMethodName(attribute->attcompression));
1249 else
1250 def->compression = NULL;
1251
1252 /* Likewise, copy comment if requested */
1253 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1254 (comment = GetComment(attribute->attrelid,
1255 RelationRelationId,
1256 attribute->attnum)) != NULL)
1257 {
1259
1260 stmt->objtype = OBJECT_COLUMN;
1261 stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1263 makeString(def->colname));
1264 stmt->comment = comment;
1265
1266 cxt->alist = lappend(cxt->alist, stmt);
1267 }
1268 }
1269
1270 /*
1271 * Reproduce not-null constraints, if any, by copying them. We do this
1272 * regardless of options given.
1273 */
1274 if (tupleDesc->constr && tupleDesc->constr->has_not_null)
1275 {
1276 List *lst;
1277
1278 lst = RelationGetNotNullConstraints(RelationGetRelid(relation), false,
1279 true);
1280 cxt->nnconstraints = list_concat(cxt->nnconstraints, lst);
1281 }
1282
1283 /*
1284 * We cannot yet deal with defaults, CHECK constraints, indexes, or
1285 * statistics, since we don't yet know what column numbers the copied
1286 * columns will have in the finished table. If any of those options are
1287 * specified, add the LIKE clause to cxt->likeclauses so that
1288 * expandTableLikeClause will be called after we do know that.
1289 *
1290 * In order for this to work, we remember the relation OID so that
1291 * expandTableLikeClause is certain to open the same table.
1292 */
1293 if (table_like_clause->options &
1299 {
1300 table_like_clause->relationOid = RelationGetRelid(relation);
1301 cxt->likeclauses = lappend(cxt->likeclauses, table_like_clause);
1302 }
1303
1304 /*
1305 * Close the parent rel, but keep our AccessShareLock on it until xact
1306 * commit. That will prevent someone else from deleting or ALTERing the
1307 * parent before we can run expandTableLikeClause.
1308 */
1309 table_close(relation, NoLock);
1310}
1311
1312/*
1313 * expandTableLikeClause
1314 *
1315 * Process LIKE options that require knowing the final column numbers
1316 * assigned to the new table's columns. This executes after we have
1317 * run DefineRelation for the new table. It returns a list of utility
1318 * commands that should be run to generate indexes etc.
1319 */
1320List *
1322{
1323 List *result = NIL;
1324 List *atsubcmds = NIL;
1325 AttrNumber parent_attno;
1326 Relation relation;
1327 Relation childrel;
1328 TupleDesc tupleDesc;
1329 TupleConstr *constr;
1330 AttrMap *attmap;
1331 char *comment;
1332
1333 /*
1334 * Open the relation referenced by the LIKE clause. We should still have
1335 * the table lock obtained by transformTableLikeClause (and this'll throw
1336 * an assertion failure if not). Hence, no need to recheck privileges
1337 * etc. We must open the rel by OID not name, to be sure we get the same
1338 * table.
1339 */
1340 if (!OidIsValid(table_like_clause->relationOid))
1341 elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1342
1343 relation = relation_open(table_like_clause->relationOid, NoLock);
1344
1345 tupleDesc = RelationGetDescr(relation);
1346 constr = tupleDesc->constr;
1347
1348 /*
1349 * Open the newly-created child relation; we have lock on that too.
1350 */
1351 childrel = relation_openrv(heapRel, NoLock);
1352
1353 /*
1354 * Construct a map from the LIKE relation's attnos to the child rel's.
1355 * This re-checks type match etc, although it shouldn't be possible to
1356 * have a failure since both tables are locked.
1357 */
1358 attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1359 tupleDesc,
1360 false);
1361
1362 /*
1363 * Process defaults, if required.
1364 */
1365 if ((table_like_clause->options &
1367 constr != NULL)
1368 {
1369 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1370 parent_attno++)
1371 {
1372 Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1373 parent_attno - 1);
1374
1375 /*
1376 * Ignore dropped columns in the parent.
1377 */
1378 if (attribute->attisdropped)
1379 continue;
1380
1381 /*
1382 * Copy default, if present and it should be copied. We have
1383 * separate options for plain default expressions and GENERATED
1384 * defaults.
1385 */
1386 if (attribute->atthasdef &&
1387 (attribute->attgenerated ?
1388 (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1389 (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1390 {
1391 Node *this_default;
1392 AlterTableCmd *atsubcmd;
1393 bool found_whole_row;
1394
1395 this_default = TupleDescGetDefault(tupleDesc, parent_attno);
1396 if (this_default == NULL)
1397 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1398 parent_attno, RelationGetRelationName(relation));
1399
1400 atsubcmd = makeNode(AlterTableCmd);
1401 atsubcmd->subtype = AT_CookedColumnDefault;
1402 atsubcmd->num = attmap->attnums[parent_attno - 1];
1403 atsubcmd->def = map_variable_attnos(this_default,
1404 1, 0,
1405 attmap,
1406 InvalidOid,
1407 &found_whole_row);
1408
1409 /*
1410 * Prevent this for the same reason as for constraints below.
1411 * Note that defaults cannot contain any vars, so it's OK that
1412 * the error message refers to generated columns.
1413 */
1414 if (found_whole_row)
1415 ereport(ERROR,
1416 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1417 errmsg("cannot convert whole-row table reference"),
1418 errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1419 NameStr(attribute->attname),
1420 RelationGetRelationName(relation))));
1421
1422 atsubcmds = lappend(atsubcmds, atsubcmd);
1423 }
1424 }
1425 }
1426
1427 /*
1428 * Copy CHECK constraints if requested, being careful to adjust attribute
1429 * numbers so they match the child.
1430 */
1431 if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1432 constr != NULL)
1433 {
1434 int ccnum;
1435
1436 for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1437 {
1438 char *ccname = constr->check[ccnum].ccname;
1439 char *ccbin = constr->check[ccnum].ccbin;
1440 bool ccenforced = constr->check[ccnum].ccenforced;
1441 bool ccvalid = constr->check[ccnum].ccvalid;
1442 bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1443 Node *ccbin_node;
1444 bool found_whole_row;
1445 Constraint *n;
1446 AlterTableCmd *atsubcmd;
1447
1448 ccbin_node = map_variable_attnos(stringToNode(ccbin),
1449 1, 0,
1450 attmap,
1451 InvalidOid, &found_whole_row);
1452
1453 /*
1454 * We reject whole-row variables because the whole point of LIKE
1455 * is that the new table's rowtype might later diverge from the
1456 * parent's. So, while translation might be possible right now,
1457 * it wouldn't be possible to guarantee it would work in future.
1458 */
1459 if (found_whole_row)
1460 ereport(ERROR,
1461 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1462 errmsg("cannot convert whole-row table reference"),
1463 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1464 ccname,
1465 RelationGetRelationName(relation))));
1466
1467 n = makeNode(Constraint);
1468 n->contype = CONSTR_CHECK;
1469 n->conname = pstrdup(ccname);
1470 n->location = -1;
1471 n->is_enforced = ccenforced;
1472 n->initially_valid = ccvalid;
1473 n->is_no_inherit = ccnoinherit;
1474 n->raw_expr = NULL;
1475 n->cooked_expr = nodeToString(ccbin_node);
1476
1477 /* We can skip validation, since the new table should be empty. */
1478 n->skip_validation = true;
1479
1480 atsubcmd = makeNode(AlterTableCmd);
1481 atsubcmd->subtype = AT_AddConstraint;
1482 atsubcmd->def = (Node *) n;
1483 atsubcmds = lappend(atsubcmds, atsubcmd);
1484
1485 /* Copy comment on constraint */
1486 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1488 n->conname, false),
1489 ConstraintRelationId,
1490 0)) != NULL)
1491 {
1493
1494 stmt->objtype = OBJECT_TABCONSTRAINT;
1495 stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1496 makeString(heapRel->relname),
1497 makeString(n->conname));
1498 stmt->comment = comment;
1499
1500 result = lappend(result, stmt);
1501 }
1502 }
1503 }
1504
1505 /*
1506 * If we generated any ALTER TABLE actions above, wrap them into a single
1507 * ALTER TABLE command. Stick it at the front of the result, so it runs
1508 * before any CommentStmts we made above.
1509 */
1510 if (atsubcmds)
1511 {
1513
1514 atcmd->relation = copyObject(heapRel);
1515 atcmd->cmds = atsubcmds;
1516 atcmd->objtype = OBJECT_TABLE;
1517 atcmd->missing_ok = false;
1518 result = lcons(atcmd, result);
1519 }
1520
1521 /*
1522 * Process indexes if required.
1523 */
1524 if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1525 relation->rd_rel->relhasindex)
1526 {
1527 List *parent_indexes;
1528 ListCell *l;
1529
1530 parent_indexes = RelationGetIndexList(relation);
1531
1532 foreach(l, parent_indexes)
1533 {
1534 Oid parent_index_oid = lfirst_oid(l);
1535 Relation parent_index;
1536 IndexStmt *index_stmt;
1537
1538 parent_index = index_open(parent_index_oid, AccessShareLock);
1539
1540 /* Build CREATE INDEX statement to recreate the parent_index */
1541 index_stmt = generateClonedIndexStmt(heapRel,
1542 parent_index,
1543 attmap,
1544 NULL);
1545
1546 /* Copy comment on index, if requested */
1547 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1548 {
1549 comment = GetComment(parent_index_oid, RelationRelationId, 0);
1550
1551 /*
1552 * We make use of IndexStmt's idxcomment option, so as not to
1553 * need to know now what name the index will have.
1554 */
1555 index_stmt->idxcomment = comment;
1556 }
1557
1558 result = lappend(result, index_stmt);
1559
1560 index_close(parent_index, AccessShareLock);
1561 }
1562 }
1563
1564 /*
1565 * Process extended statistics if required.
1566 */
1567 if (table_like_clause->options & CREATE_TABLE_LIKE_STATISTICS)
1568 {
1569 List *parent_extstats;
1570 ListCell *l;
1571
1572 parent_extstats = RelationGetStatExtList(relation);
1573
1574 foreach(l, parent_extstats)
1575 {
1576 Oid parent_stat_oid = lfirst_oid(l);
1577 CreateStatsStmt *stats_stmt;
1578
1579 stats_stmt = generateClonedExtStatsStmt(heapRel,
1580 RelationGetRelid(childrel),
1581 parent_stat_oid,
1582 attmap);
1583
1584 /* Copy comment on statistics object, if requested */
1585 if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1586 {
1587 comment = GetComment(parent_stat_oid, StatisticExtRelationId, 0);
1588
1589 /*
1590 * We make use of CreateStatsStmt's stxcomment option, so as
1591 * not to need to know now what name the statistics will have.
1592 */
1593 stats_stmt->stxcomment = comment;
1594 }
1595
1596 result = lappend(result, stats_stmt);
1597 }
1598
1599 list_free(parent_extstats);
1600 }
1601
1602 /* Done with child rel */
1603 table_close(childrel, NoLock);
1604
1605 /*
1606 * Close the parent rel, but keep our AccessShareLock on it until xact
1607 * commit. That will prevent someone else from deleting or ALTERing the
1608 * parent before the child is committed.
1609 */
1610 table_close(relation, NoLock);
1611
1612 return result;
1613}
1614
1615static void
1617{
1618 HeapTuple tuple;
1619 TupleDesc tupdesc;
1620 int i;
1621 Oid ofTypeId;
1622
1623 Assert(ofTypename);
1624
1625 tuple = typenameType(cxt->pstate, ofTypename, NULL);
1626 check_of_type(tuple);
1627 ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1628 ofTypename->typeOid = ofTypeId; /* cached for later */
1629
1630 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1631 for (i = 0; i < tupdesc->natts; i++)
1632 {
1633 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1634 ColumnDef *n;
1635
1636 if (attr->attisdropped)
1637 continue;
1638
1639 n = makeColumnDef(NameStr(attr->attname), attr->atttypid,
1640 attr->atttypmod, attr->attcollation);
1641 n->is_from_type = true;
1642
1643 cxt->columns = lappend(cxt->columns, n);
1644 }
1645 ReleaseTupleDesc(tupdesc);
1646
1647 ReleaseSysCache(tuple);
1648}
1649
1650/*
1651 * Generate an IndexStmt node using information from an already existing index
1652 * "source_idx".
1653 *
1654 * heapRel is stored into the IndexStmt's relation field, but we don't use it
1655 * otherwise; some callers pass NULL, if they don't need it to be valid.
1656 * (The target relation might not exist yet, so we mustn't try to access it.)
1657 *
1658 * Attribute numbers in expression Vars are adjusted according to attmap.
1659 *
1660 * If constraintOid isn't NULL, we store the OID of any constraint associated
1661 * with the index there.
1662 *
1663 * Unlike transformIndexConstraint, we don't make any effort to force primary
1664 * key columns to be not-null. The larger cloning process this is part of
1665 * should have cloned their not-null status separately (and DefineIndex will
1666 * complain if that fails to happen).
1667 */
1668IndexStmt *
1670 const AttrMap *attmap,
1671 Oid *constraintOid)
1672{
1673 Oid source_relid = RelationGetRelid(source_idx);
1674 HeapTuple ht_idxrel;
1675 HeapTuple ht_idx;
1676 HeapTuple ht_am;
1677 Form_pg_class idxrelrec;
1678 Form_pg_index idxrec;
1679 Form_pg_am amrec;
1680 oidvector *indcollation;
1681 oidvector *indclass;
1683 List *indexprs;
1684 ListCell *indexpr_item;
1685 Oid indrelid;
1686 int keyno;
1687 Oid keycoltype;
1688 Datum datum;
1689 bool isnull;
1690
1691 if (constraintOid)
1692 *constraintOid = InvalidOid;
1693
1694 /*
1695 * Fetch pg_class tuple of source index. We can't use the copy in the
1696 * relcache entry because it doesn't include optional fields.
1697 */
1698 ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1699 if (!HeapTupleIsValid(ht_idxrel))
1700 elog(ERROR, "cache lookup failed for relation %u", source_relid);
1701 idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1702
1703 /* Fetch pg_index tuple for source index from relcache entry */
1704 ht_idx = source_idx->rd_indextuple;
1705 idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1706 indrelid = idxrec->indrelid;
1707
1708 /* Fetch the pg_am tuple of the index' access method */
1709 ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1710 if (!HeapTupleIsValid(ht_am))
1711 elog(ERROR, "cache lookup failed for access method %u",
1712 idxrelrec->relam);
1713 amrec = (Form_pg_am) GETSTRUCT(ht_am);
1714
1715 /* Extract indcollation from the pg_index tuple */
1716 datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1717 Anum_pg_index_indcollation);
1718 indcollation = (oidvector *) DatumGetPointer(datum);
1719
1720 /* Extract indclass from the pg_index tuple */
1721 datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx, Anum_pg_index_indclass);
1722 indclass = (oidvector *) DatumGetPointer(datum);
1723
1724 /* Begin building the IndexStmt */
1726 index->relation = heapRel;
1727 index->accessMethod = pstrdup(NameStr(amrec->amname));
1728 if (OidIsValid(idxrelrec->reltablespace))
1729 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1730 else
1731 index->tableSpace = NULL;
1732 index->excludeOpNames = NIL;
1733 index->idxcomment = NULL;
1734 index->indexOid = InvalidOid;
1735 index->oldNumber = InvalidRelFileNumber;
1736 index->oldCreateSubid = InvalidSubTransactionId;
1737 index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
1738 index->unique = idxrec->indisunique;
1739 index->nulls_not_distinct = idxrec->indnullsnotdistinct;
1740 index->primary = idxrec->indisprimary;
1741 index->iswithoutoverlaps = (idxrec->indisprimary || idxrec->indisunique) && idxrec->indisexclusion;
1742 index->transformed = true; /* don't need transformIndexStmt */
1743 index->concurrent = false;
1744 index->if_not_exists = false;
1745 index->reset_default_tblspc = false;
1746
1747 /*
1748 * We don't try to preserve the name of the source index; instead, just
1749 * let DefineIndex() choose a reasonable name. (If we tried to preserve
1750 * the name, we'd get duplicate-relation-name failures unless the source
1751 * table was in a different schema.)
1752 */
1753 index->idxname = NULL;
1754
1755 /*
1756 * If the index is marked PRIMARY or has an exclusion condition, it's
1757 * certainly from a constraint; else, if it's not marked UNIQUE, it
1758 * certainly isn't. If it is or might be from a constraint, we have to
1759 * fetch the pg_constraint record.
1760 */
1761 if (index->primary || index->unique || idxrec->indisexclusion)
1762 {
1763 Oid constraintId = get_index_constraint(source_relid);
1764
1765 if (OidIsValid(constraintId))
1766 {
1767 HeapTuple ht_constr;
1768 Form_pg_constraint conrec;
1769
1770 if (constraintOid)
1771 *constraintOid = constraintId;
1772
1773 ht_constr = SearchSysCache1(CONSTROID,
1774 ObjectIdGetDatum(constraintId));
1775 if (!HeapTupleIsValid(ht_constr))
1776 elog(ERROR, "cache lookup failed for constraint %u",
1777 constraintId);
1778 conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1779
1780 index->isconstraint = true;
1781 index->deferrable = conrec->condeferrable;
1782 index->initdeferred = conrec->condeferred;
1783
1784 /* If it's an exclusion constraint, we need the operator names */
1785 if (idxrec->indisexclusion)
1786 {
1787 Datum *elems;
1788 int nElems;
1789 int i;
1790
1791 Assert(conrec->contype == CONSTRAINT_EXCLUSION ||
1792 (index->iswithoutoverlaps &&
1793 (conrec->contype == CONSTRAINT_PRIMARY || conrec->contype == CONSTRAINT_UNIQUE)));
1794 /* Extract operator OIDs from the pg_constraint tuple */
1795 datum = SysCacheGetAttrNotNull(CONSTROID, ht_constr,
1796 Anum_pg_constraint_conexclop);
1797 deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
1798
1799 for (i = 0; i < nElems; i++)
1800 {
1801 Oid operid = DatumGetObjectId(elems[i]);
1802 HeapTuple opertup;
1803 Form_pg_operator operform;
1804 char *oprname;
1805 char *nspname;
1806 List *namelist;
1807
1808 opertup = SearchSysCache1(OPEROID,
1809 ObjectIdGetDatum(operid));
1810 if (!HeapTupleIsValid(opertup))
1811 elog(ERROR, "cache lookup failed for operator %u",
1812 operid);
1813 operform = (Form_pg_operator) GETSTRUCT(opertup);
1814 oprname = pstrdup(NameStr(operform->oprname));
1815 /* For simplicity we always schema-qualify the op name */
1816 nspname = get_namespace_name(operform->oprnamespace);
1817 namelist = list_make2(makeString(nspname),
1818 makeString(oprname));
1819 index->excludeOpNames = lappend(index->excludeOpNames,
1820 namelist);
1821 ReleaseSysCache(opertup);
1822 }
1823 }
1824
1825 ReleaseSysCache(ht_constr);
1826 }
1827 else
1828 index->isconstraint = false;
1829 }
1830 else
1831 index->isconstraint = false;
1832
1833 /* Get the index expressions, if any */
1834 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1835 Anum_pg_index_indexprs, &isnull);
1836 if (!isnull)
1837 {
1838 char *exprsString;
1839
1840 exprsString = TextDatumGetCString(datum);
1841 indexprs = (List *) stringToNode(exprsString);
1842 }
1843 else
1844 indexprs = NIL;
1845
1846 /* Build the list of IndexElem */
1847 index->indexParams = NIL;
1848 index->indexIncludingParams = NIL;
1849
1850 indexpr_item = list_head(indexprs);
1851 for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1852 {
1853 IndexElem *iparam;
1854 AttrNumber attnum = idxrec->indkey.values[keyno];
1856 keyno);
1857 int16 opt = source_idx->rd_indoption[keyno];
1858
1859 iparam = makeNode(IndexElem);
1860
1862 {
1863 /* Simple index column */
1864 char *attname;
1865
1866 attname = get_attname(indrelid, attnum, false);
1867 keycoltype = get_atttype(indrelid, attnum);
1868
1869 iparam->name = attname;
1870 iparam->expr = NULL;
1871 }
1872 else
1873 {
1874 /* Expressional index */
1875 Node *indexkey;
1876 bool found_whole_row;
1877
1878 if (indexpr_item == NULL)
1879 elog(ERROR, "too few entries in indexprs list");
1880 indexkey = (Node *) lfirst(indexpr_item);
1881 indexpr_item = lnext(indexprs, indexpr_item);
1882
1883 /* Adjust Vars to match new table's column numbering */
1884 indexkey = map_variable_attnos(indexkey,
1885 1, 0,
1886 attmap,
1887 InvalidOid, &found_whole_row);
1888
1889 /* As in expandTableLikeClause, reject whole-row variables */
1890 if (found_whole_row)
1891 ereport(ERROR,
1892 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1893 errmsg("cannot convert whole-row table reference"),
1894 errdetail("Index \"%s\" contains a whole-row table reference.",
1895 RelationGetRelationName(source_idx))));
1896
1897 iparam->name = NULL;
1898 iparam->expr = indexkey;
1899
1900 keycoltype = exprType(indexkey);
1901 }
1902
1903 /* Copy the original index column name */
1904 iparam->indexcolname = pstrdup(NameStr(attr->attname));
1905
1906 /* Add the collation name, if non-default */
1907 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1908
1909 /* Add the operator class name, if non-default */
1910 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1911 iparam->opclassopts =
1912 untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1913
1914 iparam->ordering = SORTBY_DEFAULT;
1916
1917 /* Adjust options if necessary */
1918 if (source_idx->rd_indam->amcanorder)
1919 {
1920 /*
1921 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1922 * set non-default settings unnecessarily, though, so as to
1923 * improve the chance of recognizing equivalence to constraint
1924 * indexes.
1925 */
1926 if (opt & INDOPTION_DESC)
1927 {
1928 iparam->ordering = SORTBY_DESC;
1929 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1931 }
1932 else
1933 {
1934 if (opt & INDOPTION_NULLS_FIRST)
1936 }
1937 }
1938
1939 index->indexParams = lappend(index->indexParams, iparam);
1940 }
1941
1942 /* Handle included columns separately */
1943 for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1944 {
1945 IndexElem *iparam;
1946 AttrNumber attnum = idxrec->indkey.values[keyno];
1948 keyno);
1949
1950 iparam = makeNode(IndexElem);
1951
1953 {
1954 /* Simple index column */
1955 char *attname;
1956
1957 attname = get_attname(indrelid, attnum, false);
1958
1959 iparam->name = attname;
1960 iparam->expr = NULL;
1961 }
1962 else
1963 ereport(ERROR,
1964 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1965 errmsg("expressions are not supported in included columns")));
1966
1967 /* Copy the original index column name */
1968 iparam->indexcolname = pstrdup(NameStr(attr->attname));
1969
1970 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1971 }
1972 /* Copy reloptions if any */
1973 datum = SysCacheGetAttr(RELOID, ht_idxrel,
1974 Anum_pg_class_reloptions, &isnull);
1975 if (!isnull)
1976 index->options = untransformRelOptions(datum);
1977
1978 /* If it's a partial index, decompile and append the predicate */
1979 datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1980 Anum_pg_index_indpred, &isnull);
1981 if (!isnull)
1982 {
1983 char *pred_str;
1984 Node *pred_tree;
1985 bool found_whole_row;
1986
1987 /* Convert text string to node tree */
1988 pred_str = TextDatumGetCString(datum);
1989 pred_tree = (Node *) stringToNode(pred_str);
1990
1991 /* Adjust Vars to match new table's column numbering */
1992 pred_tree = map_variable_attnos(pred_tree,
1993 1, 0,
1994 attmap,
1995 InvalidOid, &found_whole_row);
1996
1997 /* As in expandTableLikeClause, reject whole-row variables */
1998 if (found_whole_row)
1999 ereport(ERROR,
2000 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2001 errmsg("cannot convert whole-row table reference"),
2002 errdetail("Index \"%s\" contains a whole-row table reference.",
2003 RelationGetRelationName(source_idx))));
2004
2005 index->whereClause = pred_tree;
2006 }
2007
2008 /* Clean up */
2009 ReleaseSysCache(ht_idxrel);
2010 ReleaseSysCache(ht_am);
2011
2012 return index;
2013}
2014
2015/*
2016 * Generate a CreateStatsStmt node using information from an already existing
2017 * extended statistic "source_statsid", for the rel identified by heapRel and
2018 * heapRelid.
2019 *
2020 * Attribute numbers in expression Vars are adjusted according to attmap.
2021 */
2022static CreateStatsStmt *
2024 Oid source_statsid, const AttrMap *attmap)
2025{
2026 HeapTuple ht_stats;
2027 Form_pg_statistic_ext statsrec;
2028 CreateStatsStmt *stats;
2029 List *stat_types = NIL;
2030 List *def_names = NIL;
2031 bool isnull;
2032 Datum datum;
2033 ArrayType *arr;
2034 char *enabled;
2035 int i;
2036
2037 Assert(OidIsValid(heapRelid));
2038 Assert(heapRel != NULL);
2039
2040 /*
2041 * Fetch pg_statistic_ext tuple of source statistics object.
2042 */
2043 ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
2044 if (!HeapTupleIsValid(ht_stats))
2045 elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
2046 statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
2047
2048 /* Determine which statistics types exist */
2049 datum = SysCacheGetAttrNotNull(STATEXTOID, ht_stats,
2050 Anum_pg_statistic_ext_stxkind);
2051 arr = DatumGetArrayTypeP(datum);
2052 if (ARR_NDIM(arr) != 1 ||
2053 ARR_HASNULL(arr) ||
2054 ARR_ELEMTYPE(arr) != CHAROID)
2055 elog(ERROR, "stxkind is not a 1-D char array");
2056 enabled = (char *) ARR_DATA_PTR(arr);
2057 for (i = 0; i < ARR_DIMS(arr)[0]; i++)
2058 {
2059 if (enabled[i] == STATS_EXT_NDISTINCT)
2060 stat_types = lappend(stat_types, makeString("ndistinct"));
2061 else if (enabled[i] == STATS_EXT_DEPENDENCIES)
2062 stat_types = lappend(stat_types, makeString("dependencies"));
2063 else if (enabled[i] == STATS_EXT_MCV)
2064 stat_types = lappend(stat_types, makeString("mcv"));
2065 else if (enabled[i] == STATS_EXT_EXPRESSIONS)
2066 /* expression stats are not exposed to users */
2067 continue;
2068 else
2069 elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
2070 }
2071
2072 /* Determine which columns the statistics are on */
2073 for (i = 0; i < statsrec->stxkeys.dim1; i++)
2074 {
2075 StatsElem *selem = makeNode(StatsElem);
2076 AttrNumber attnum = statsrec->stxkeys.values[i];
2077
2078 selem->name = get_attname(heapRelid, attnum, false);
2079 selem->expr = NULL;
2080
2081 def_names = lappend(def_names, selem);
2082 }
2083
2084 /*
2085 * Now handle expressions, if there are any. The order (with respect to
2086 * regular attributes) does not really matter for extended stats, so we
2087 * simply append them after simple column references.
2088 *
2089 * XXX Some places during build/estimation treat expressions as if they
2090 * are before attributes, but for the CREATE command that's entirely
2091 * irrelevant.
2092 */
2093 datum = SysCacheGetAttr(STATEXTOID, ht_stats,
2094 Anum_pg_statistic_ext_stxexprs, &isnull);
2095
2096 if (!isnull)
2097 {
2098 ListCell *lc;
2099 List *exprs = NIL;
2100 char *exprsString;
2101
2102 exprsString = TextDatumGetCString(datum);
2103 exprs = (List *) stringToNode(exprsString);
2104
2105 foreach(lc, exprs)
2106 {
2107 Node *expr = (Node *) lfirst(lc);
2108 StatsElem *selem = makeNode(StatsElem);
2109 bool found_whole_row;
2110
2111 /* Adjust Vars to match new table's column numbering */
2112 expr = map_variable_attnos(expr,
2113 1, 0,
2114 attmap,
2115 InvalidOid,
2116 &found_whole_row);
2117
2118 selem->name = NULL;
2119 selem->expr = expr;
2120
2121 def_names = lappend(def_names, selem);
2122 }
2123
2124 pfree(exprsString);
2125 }
2126
2127 /* finally, build the output node */
2128 stats = makeNode(CreateStatsStmt);
2129 stats->defnames = NULL;
2130 stats->stat_types = stat_types;
2131 stats->exprs = def_names;
2132 stats->relations = list_make1(heapRel);
2133 stats->stxcomment = NULL;
2134 stats->transformed = true; /* don't need transformStatsStmt again */
2135 stats->if_not_exists = false;
2136
2137 /* Clean up */
2138 ReleaseSysCache(ht_stats);
2139
2140 return stats;
2141}
2142
2143/*
2144 * get_collation - fetch qualified name of a collation
2145 *
2146 * If collation is InvalidOid or is the default for the given actual_datatype,
2147 * then the return value is NIL.
2148 */
2149static List *
2150get_collation(Oid collation, Oid actual_datatype)
2151{
2152 List *result;
2153 HeapTuple ht_coll;
2154 Form_pg_collation coll_rec;
2155 char *nsp_name;
2156 char *coll_name;
2157
2158 if (!OidIsValid(collation))
2159 return NIL; /* easy case */
2160 if (collation == get_typcollation(actual_datatype))
2161 return NIL; /* just let it default */
2162
2163 ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
2164 if (!HeapTupleIsValid(ht_coll))
2165 elog(ERROR, "cache lookup failed for collation %u", collation);
2166 coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
2167
2168 /* For simplicity, we always schema-qualify the name */
2169 nsp_name = get_namespace_name(coll_rec->collnamespace);
2170 coll_name = pstrdup(NameStr(coll_rec->collname));
2171 result = list_make2(makeString(nsp_name), makeString(coll_name));
2172
2173 ReleaseSysCache(ht_coll);
2174 return result;
2175}
2176
2177/*
2178 * get_opclass - fetch qualified name of an index operator class
2179 *
2180 * If the opclass is the default for the given actual_datatype, then
2181 * the return value is NIL.
2182 */
2183static List *
2184get_opclass(Oid opclass, Oid actual_datatype)
2185{
2186 List *result = NIL;
2187 HeapTuple ht_opc;
2188 Form_pg_opclass opc_rec;
2189
2190 ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
2191 if (!HeapTupleIsValid(ht_opc))
2192 elog(ERROR, "cache lookup failed for opclass %u", opclass);
2193 opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
2194
2195 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2196 {
2197 /* For simplicity, we always schema-qualify the name */
2198 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2199 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2200
2201 result = list_make2(makeString(nsp_name), makeString(opc_name));
2202 }
2203
2204 ReleaseSysCache(ht_opc);
2205 return result;
2206}
2207
2208
2209/*
2210 * transformIndexConstraints
2211 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
2212 * We also merge in any index definitions arising from
2213 * LIKE ... INCLUDING INDEXES.
2214 */
2215static void
2217{
2219 List *indexlist = NIL;
2220 List *finalindexlist = NIL;
2221 ListCell *lc;
2222
2223 /*
2224 * Run through the constraints that need to generate an index, and do so.
2225 *
2226 * For PRIMARY KEY, this queues not-null constraints for each column, if
2227 * needed.
2228 */
2229 foreach(lc, cxt->ixconstraints)
2230 {
2231 Constraint *constraint = lfirst_node(Constraint, lc);
2232
2233 Assert(constraint->contype == CONSTR_PRIMARY ||
2234 constraint->contype == CONSTR_UNIQUE ||
2235 constraint->contype == CONSTR_EXCLUSION);
2236
2237 index = transformIndexConstraint(constraint, cxt);
2238
2239 indexlist = lappend(indexlist, index);
2240 }
2241
2242 /*
2243 * Scan the index list and remove any redundant index specifications. This
2244 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2245 * strict reading of SQL would suggest raising an error instead, but that
2246 * strikes me as too anal-retentive. - tgl 2001-02-14
2247 *
2248 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2249 * pre-existing indexes, too.
2250 */
2251 if (cxt->pkey != NULL)
2252 {
2253 /* Make sure we keep the PKEY index in preference to others... */
2254 finalindexlist = list_make1(cxt->pkey);
2255 }
2256
2257 foreach(lc, indexlist)
2258 {
2259 bool keep = true;
2260 ListCell *k;
2261
2262 index = lfirst(lc);
2263
2264 /* if it's pkey, it's already in finalindexlist */
2265 if (index == cxt->pkey)
2266 continue;
2267
2268 foreach(k, finalindexlist)
2269 {
2270 IndexStmt *priorindex = lfirst(k);
2271
2272 if (equal(index->indexParams, priorindex->indexParams) &&
2273 equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2274 equal(index->whereClause, priorindex->whereClause) &&
2275 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2276 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2277 index->nulls_not_distinct == priorindex->nulls_not_distinct &&
2278 index->deferrable == priorindex->deferrable &&
2279 index->initdeferred == priorindex->initdeferred)
2280 {
2281 priorindex->unique |= index->unique;
2282
2283 /*
2284 * If the prior index is as yet unnamed, and this one is
2285 * named, then transfer the name to the prior index. This
2286 * ensures that if we have named and unnamed constraints,
2287 * we'll use (at least one of) the names for the index.
2288 */
2289 if (priorindex->idxname == NULL)
2290 priorindex->idxname = index->idxname;
2291 keep = false;
2292 break;
2293 }
2294 }
2295
2296 if (keep)
2297 finalindexlist = lappend(finalindexlist, index);
2298 }
2299
2300 /*
2301 * Now append all the IndexStmts to cxt->alist.
2302 */
2303 cxt->alist = list_concat(cxt->alist, finalindexlist);
2304}
2305
2306/*
2307 * transformIndexConstraint
2308 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
2309 * transformIndexConstraints. An IndexStmt is returned.
2310 *
2311 * For a PRIMARY KEY constraint, we additionally create not-null constraints
2312 * for columns that don't already have them.
2313 */
2314static IndexStmt *
2316{
2318 ListCell *lc;
2319
2321
2322 index->unique = (constraint->contype != CONSTR_EXCLUSION);
2323 index->primary = (constraint->contype == CONSTR_PRIMARY);
2324 if (index->primary)
2325 {
2326 if (cxt->pkey != NULL)
2327 ereport(ERROR,
2328 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2329 errmsg("multiple primary keys for table \"%s\" are not allowed",
2330 cxt->relation->relname),
2331 parser_errposition(cxt->pstate, constraint->location)));
2332 cxt->pkey = index;
2333
2334 /*
2335 * In ALTER TABLE case, a primary index might already exist, but
2336 * DefineIndex will check for it.
2337 */
2338 }
2339 index->nulls_not_distinct = constraint->nulls_not_distinct;
2340 index->isconstraint = true;
2341 index->iswithoutoverlaps = constraint->without_overlaps;
2342 index->deferrable = constraint->deferrable;
2343 index->initdeferred = constraint->initdeferred;
2344
2345 if (constraint->conname != NULL)
2346 index->idxname = pstrdup(constraint->conname);
2347 else
2348 index->idxname = NULL; /* DefineIndex will choose name */
2349
2350 index->relation = cxt->relation;
2351 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2352 index->options = constraint->options;
2353 index->tableSpace = constraint->indexspace;
2354 index->whereClause = constraint->where_clause;
2355 index->indexParams = NIL;
2356 index->indexIncludingParams = NIL;
2357 index->excludeOpNames = NIL;
2358 index->idxcomment = NULL;
2359 index->indexOid = InvalidOid;
2360 index->oldNumber = InvalidRelFileNumber;
2361 index->oldCreateSubid = InvalidSubTransactionId;
2362 index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
2363 index->transformed = false;
2364 index->concurrent = false;
2365 index->if_not_exists = false;
2366 index->reset_default_tblspc = constraint->reset_default_tblspc;
2367
2368 /*
2369 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2370 * verify it's usable, then extract the implied column name list. (We
2371 * will not actually need the column name list at runtime, but we need it
2372 * now to check for duplicate column entries below.)
2373 */
2374 if (constraint->indexname != NULL)
2375 {
2376 char *index_name = constraint->indexname;
2377 Relation heap_rel = cxt->rel;
2378 Oid index_oid;
2379 Relation index_rel;
2380 Form_pg_index index_form;
2381 oidvector *indclass;
2382 Datum indclassDatum;
2383 int i;
2384
2385 /* Grammar should not allow this with explicit column list */
2386 Assert(constraint->keys == NIL);
2387
2388 /* Grammar should only allow PRIMARY and UNIQUE constraints */
2389 Assert(constraint->contype == CONSTR_PRIMARY ||
2390 constraint->contype == CONSTR_UNIQUE);
2391
2392 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2393 if (!cxt->isalter)
2394 ereport(ERROR,
2395 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2396 errmsg("cannot use an existing index in CREATE TABLE"),
2397 parser_errposition(cxt->pstate, constraint->location)));
2398
2399 /* Look for the index in the same schema as the table */
2400 index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
2401
2402 if (!OidIsValid(index_oid))
2403 ereport(ERROR,
2404 (errcode(ERRCODE_UNDEFINED_OBJECT),
2405 errmsg("index \"%s\" does not exist", index_name),
2406 parser_errposition(cxt->pstate, constraint->location)));
2407
2408 /* Open the index (this will throw an error if it is not an index) */
2409 index_rel = index_open(index_oid, AccessShareLock);
2410 index_form = index_rel->rd_index;
2411
2412 /* Check that it does not have an associated constraint already */
2413 if (OidIsValid(get_index_constraint(index_oid)))
2414 ereport(ERROR,
2415 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2416 errmsg("index \"%s\" is already associated with a constraint",
2417 index_name),
2418 parser_errposition(cxt->pstate, constraint->location)));
2419
2420 /* Perform validity checks on the index */
2421 if (index_form->indrelid != RelationGetRelid(heap_rel))
2422 ereport(ERROR,
2423 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2424 errmsg("index \"%s\" does not belong to table \"%s\"",
2425 index_name, RelationGetRelationName(heap_rel)),
2426 parser_errposition(cxt->pstate, constraint->location)));
2427
2428 if (!index_form->indisvalid)
2429 ereport(ERROR,
2430 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2431 errmsg("index \"%s\" is not valid", index_name),
2432 parser_errposition(cxt->pstate, constraint->location)));
2433
2434 /*
2435 * Today we forbid non-unique indexes, but we could permit GiST
2436 * indexes whose last entry is a range type and use that to create a
2437 * WITHOUT OVERLAPS constraint (i.e. a temporal constraint).
2438 */
2439 if (!index_form->indisunique)
2440 ereport(ERROR,
2441 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2442 errmsg("\"%s\" is not a unique index", index_name),
2443 errdetail("Cannot create a primary key or unique constraint using such an index."),
2444 parser_errposition(cxt->pstate, constraint->location)));
2445
2446 if (RelationGetIndexExpressions(index_rel) != NIL)
2447 ereport(ERROR,
2448 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2449 errmsg("index \"%s\" contains expressions", index_name),
2450 errdetail("Cannot create a primary key or unique constraint using such an index."),
2451 parser_errposition(cxt->pstate, constraint->location)));
2452
2453 if (RelationGetIndexPredicate(index_rel) != NIL)
2454 ereport(ERROR,
2455 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2456 errmsg("\"%s\" is a partial index", index_name),
2457 errdetail("Cannot create a primary key or unique constraint using such an index."),
2458 parser_errposition(cxt->pstate, constraint->location)));
2459
2460 /*
2461 * It's probably unsafe to change a deferred index to non-deferred. (A
2462 * non-constraint index couldn't be deferred anyway, so this case
2463 * should never occur; no need to sweat, but let's check it.)
2464 */
2465 if (!index_form->indimmediate && !constraint->deferrable)
2466 ereport(ERROR,
2467 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2468 errmsg("\"%s\" is a deferrable index", index_name),
2469 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2470 parser_errposition(cxt->pstate, constraint->location)));
2471
2472 /*
2473 * Insist on it being a btree. That's the only kind that supports
2474 * uniqueness at the moment anyway; but we must have an index that
2475 * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2476 * else dump and reload will produce a different index (breaking
2477 * pg_upgrade in particular).
2478 */
2479 if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2480 ereport(ERROR,
2481 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2482 errmsg("index \"%s\" is not a btree", index_name),
2483 parser_errposition(cxt->pstate, constraint->location)));
2484
2485 /* Must get indclass the hard way */
2486 indclassDatum = SysCacheGetAttrNotNull(INDEXRELID,
2487 index_rel->rd_indextuple,
2488 Anum_pg_index_indclass);
2489 indclass = (oidvector *) DatumGetPointer(indclassDatum);
2490
2491 for (i = 0; i < index_form->indnatts; i++)
2492 {
2493 int16 attnum = index_form->indkey.values[i];
2494 const FormData_pg_attribute *attform;
2495 char *attname;
2496 Oid defopclass;
2497
2498 /*
2499 * We shouldn't see attnum == 0 here, since we already rejected
2500 * expression indexes. If we do, SystemAttributeDefinition will
2501 * throw an error.
2502 */
2503 if (attnum > 0)
2504 {
2505 Assert(attnum <= heap_rel->rd_att->natts);
2506 attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2507 }
2508 else
2510 attname = pstrdup(NameStr(attform->attname));
2511
2512 if (i < index_form->indnkeyatts)
2513 {
2514 /*
2515 * Insist on default opclass, collation, and sort options.
2516 * While the index would still work as a constraint with
2517 * non-default settings, it might not provide exactly the same
2518 * uniqueness semantics as you'd get from a normally-created
2519 * constraint; and there's also the dump/reload problem
2520 * mentioned above.
2521 */
2522 Datum attoptions =
2523 get_attoptions(RelationGetRelid(index_rel), i + 1);
2524
2525 defopclass = GetDefaultOpClass(attform->atttypid,
2526 index_rel->rd_rel->relam);
2527 if (indclass->values[i] != defopclass ||
2528 attform->attcollation != index_rel->rd_indcollation[i] ||
2529 attoptions != (Datum) 0 ||
2530 index_rel->rd_indoption[i] != 0)
2531 ereport(ERROR,
2532 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2533 errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2534 errdetail("Cannot create a primary key or unique constraint using such an index."),
2535 parser_errposition(cxt->pstate, constraint->location)));
2536
2537 /* If a PK, ensure the columns get not null constraints */
2538 if (constraint->contype == CONSTR_PRIMARY)
2539 cxt->nnconstraints =
2542
2543 constraint->keys = lappend(constraint->keys, makeString(attname));
2544 }
2545 else
2546 constraint->including = lappend(constraint->including, makeString(attname));
2547 }
2548
2549 /* Close the index relation but keep the lock */
2550 relation_close(index_rel, NoLock);
2551
2552 index->indexOid = index_oid;
2553 }
2554
2555 /*
2556 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2557 * IndexElems and operator names. We have to break that apart into
2558 * separate lists.
2559 */
2560 if (constraint->contype == CONSTR_EXCLUSION)
2561 {
2562 foreach(lc, constraint->exclusions)
2563 {
2564 List *pair = (List *) lfirst(lc);
2565 IndexElem *elem;
2566 List *opname;
2567
2568 Assert(list_length(pair) == 2);
2569 elem = linitial_node(IndexElem, pair);
2570 opname = lsecond_node(List, pair);
2571
2572 index->indexParams = lappend(index->indexParams, elem);
2573 index->excludeOpNames = lappend(index->excludeOpNames, opname);
2574 }
2575 }
2576
2577 /*
2578 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2579 *
2580 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2581 * also make sure they are not-null. For WITHOUT OVERLAPS constraints, we
2582 * make sure the last part is a range or multirange.
2583 */
2584 else
2585 {
2586 foreach(lc, constraint->keys)
2587 {
2588 char *key = strVal(lfirst(lc));
2589 bool found = false;
2590 ColumnDef *column = NULL;
2591 ListCell *columns;
2592 IndexElem *iparam;
2593 Oid typid = InvalidOid;
2594
2595 /* Make sure referenced column exists. */
2596 foreach(columns, cxt->columns)
2597 {
2598 column = lfirst_node(ColumnDef, columns);
2599 if (strcmp(column->colname, key) == 0)
2600 {
2601 found = true;
2602 break;
2603 }
2604 }
2605 if (!found)
2606 column = NULL;
2607
2608 if (found)
2609 {
2610 /*
2611 * column is defined in the new table. For CREATE TABLE with
2612 * a PRIMARY KEY, we can apply the not-null constraint cheaply
2613 * here. If the not-null constraint already exists, we can
2614 * (albeit not so cheaply) verify that it's not a NO INHERIT
2615 * constraint.
2616 *
2617 * Note that ALTER TABLE never needs either check, because
2618 * those constraints have already been added by
2619 * ATPrepAddPrimaryKey.
2620 */
2621 if (constraint->contype == CONSTR_PRIMARY &&
2622 !cxt->isalter)
2623 {
2624 if (column->is_not_null)
2625 {
2627 {
2628 if (strcmp(strVal(linitial(nn->keys)), key) == 0)
2629 {
2630 if (nn->is_no_inherit)
2631 ereport(ERROR,
2632 errcode(ERRCODE_SYNTAX_ERROR),
2633 errmsg("conflicting NO INHERIT declaration for not-null constraint on column \"%s\"",
2634 key));
2635 break;
2636 }
2637 }
2638 }
2639 else
2640 {
2641 column->is_not_null = true;
2642 cxt->nnconstraints =
2645 }
2646 }
2647 else if (constraint->contype == CONSTR_PRIMARY)
2648 Assert(column->is_not_null);
2649 }
2650 else if (SystemAttributeByName(key) != NULL)
2651 {
2652 /*
2653 * column will be a system column in the new table, so accept
2654 * it. System columns can't ever be null, so no need to worry
2655 * about PRIMARY/NOT NULL constraint.
2656 */
2657 found = true;
2658 }
2659 else if (cxt->inhRelations)
2660 {
2661 /* try inherited tables */
2662 ListCell *inher;
2663
2664 foreach(inher, cxt->inhRelations)
2665 {
2666 RangeVar *inh = lfirst_node(RangeVar, inher);
2667 Relation rel;
2668 int count;
2669
2670 rel = table_openrv(inh, AccessShareLock);
2671 /* check user requested inheritance from valid relkind */
2672 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2673 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2674 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2675 ereport(ERROR,
2676 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2677 errmsg("inherited relation \"%s\" is not a table or foreign table",
2678 inh->relname)));
2679 for (count = 0; count < rel->rd_att->natts; count++)
2680 {
2681 Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2682 count);
2683 char *inhname = NameStr(inhattr->attname);
2684
2685 if (inhattr->attisdropped)
2686 continue;
2687 if (strcmp(key, inhname) == 0)
2688 {
2689 found = true;
2690 typid = inhattr->atttypid;
2691
2692 if (constraint->contype == CONSTR_PRIMARY)
2693 cxt->nnconstraints =
2696 break;
2697 }
2698 }
2699 table_close(rel, NoLock);
2700 if (found)
2701 break;
2702 }
2703 }
2704
2705 /*
2706 * In the ALTER TABLE case, don't complain about index keys not
2707 * created in the command; they may well exist already.
2708 * DefineIndex will complain about them if not.
2709 */
2710 if (!found && !cxt->isalter)
2711 ereport(ERROR,
2712 (errcode(ERRCODE_UNDEFINED_COLUMN),
2713 errmsg("column \"%s\" named in key does not exist", key),
2714 parser_errposition(cxt->pstate, constraint->location)));
2715
2716 /* Check for PRIMARY KEY(foo, foo) */
2717 foreach(columns, index->indexParams)
2718 {
2719 iparam = (IndexElem *) lfirst(columns);
2720 if (iparam->name && strcmp(key, iparam->name) == 0)
2721 {
2722 if (index->primary)
2723 ereport(ERROR,
2724 (errcode(ERRCODE_DUPLICATE_COLUMN),
2725 errmsg("column \"%s\" appears twice in primary key constraint",
2726 key),
2727 parser_errposition(cxt->pstate, constraint->location)));
2728 else
2729 ereport(ERROR,
2730 (errcode(ERRCODE_DUPLICATE_COLUMN),
2731 errmsg("column \"%s\" appears twice in unique constraint",
2732 key),
2733 parser_errposition(cxt->pstate, constraint->location)));
2734 }
2735 }
2736
2737 /*
2738 * The WITHOUT OVERLAPS part (if any) must be a range or
2739 * multirange type.
2740 */
2741 if (constraint->without_overlaps && lc == list_last_cell(constraint->keys))
2742 {
2743 if (!found && cxt->isalter)
2744 {
2745 /*
2746 * Look up the column type on existing table. If we can't
2747 * find it, let things fail in DefineIndex.
2748 */
2749 Relation rel = cxt->rel;
2750
2751 for (int i = 0; i < rel->rd_att->natts; i++)
2752 {
2754 const char *attname;
2755
2756 if (attr->attisdropped)
2757 break;
2758
2759 attname = NameStr(attr->attname);
2760 if (strcmp(attname, key) == 0)
2761 {
2762 found = true;
2763 typid = attr->atttypid;
2764 break;
2765 }
2766 }
2767 }
2768 if (found)
2769 {
2770 if (!OidIsValid(typid) && column)
2771 typid = typenameTypeId(NULL, column->typeName);
2772
2773 if (!OidIsValid(typid) || !(type_is_range(typid) || type_is_multirange(typid)))
2774 ereport(ERROR,
2775 (errcode(ERRCODE_DATATYPE_MISMATCH),
2776 errmsg("column \"%s\" in WITHOUT OVERLAPS is not a range or multirange type", key),
2777 parser_errposition(cxt->pstate, constraint->location)));
2778 }
2779 }
2780
2781 /* OK, add it to the index definition */
2782 iparam = makeNode(IndexElem);
2783 iparam->name = pstrdup(key);
2784 iparam->expr = NULL;
2785 iparam->indexcolname = NULL;
2786 iparam->collation = NIL;
2787 iparam->opclass = NIL;
2788 iparam->opclassopts = NIL;
2789 iparam->ordering = SORTBY_DEFAULT;
2791 index->indexParams = lappend(index->indexParams, iparam);
2792 }
2793
2794 if (constraint->without_overlaps)
2795 {
2796 /*
2797 * This enforces that there is at least one equality column
2798 * besides the WITHOUT OVERLAPS columns. This is per SQL
2799 * standard. XXX Do we need this?
2800 */
2801 if (list_length(constraint->keys) < 2)
2802 ereport(ERROR,
2803 errcode(ERRCODE_SYNTAX_ERROR),
2804 errmsg("constraint using WITHOUT OVERLAPS needs at least two columns"));
2805
2806 /* WITHOUT OVERLAPS requires a GiST index */
2807 index->accessMethod = "gist";
2808 }
2809
2810 }
2811
2812 /*
2813 * Add included columns to index definition. This is much like the
2814 * simple-column-name-list code above, except that we don't worry about
2815 * NOT NULL marking; included columns in a primary key should not be
2816 * forced NOT NULL. We don't complain about duplicate columns, either,
2817 * though maybe we should?
2818 */
2819 foreach(lc, constraint->including)
2820 {
2821 char *key = strVal(lfirst(lc));
2822 bool found = false;
2823 ColumnDef *column = NULL;
2824 ListCell *columns;
2825 IndexElem *iparam;
2826
2827 foreach(columns, cxt->columns)
2828 {
2829 column = lfirst_node(ColumnDef, columns);
2830 if (strcmp(column->colname, key) == 0)
2831 {
2832 found = true;
2833 break;
2834 }
2835 }
2836
2837 if (!found)
2838 {
2839 if (SystemAttributeByName(key) != NULL)
2840 {
2841 /*
2842 * column will be a system column in the new table, so accept
2843 * it.
2844 */
2845 found = true;
2846 }
2847 else if (cxt->inhRelations)
2848 {
2849 /* try inherited tables */
2850 ListCell *inher;
2851
2852 foreach(inher, cxt->inhRelations)
2853 {
2854 RangeVar *inh = lfirst_node(RangeVar, inher);
2855 Relation rel;
2856 int count;
2857
2858 rel = table_openrv(inh, AccessShareLock);
2859 /* check user requested inheritance from valid relkind */
2860 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2861 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2862 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2863 ereport(ERROR,
2864 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2865 errmsg("inherited relation \"%s\" is not a table or foreign table",
2866 inh->relname)));
2867 for (count = 0; count < rel->rd_att->natts; count++)
2868 {
2869 Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2870 count);
2871 char *inhname = NameStr(inhattr->attname);
2872
2873 if (inhattr->attisdropped)
2874 continue;
2875 if (strcmp(key, inhname) == 0)
2876 {
2877 found = true;
2878 break;
2879 }
2880 }
2881 table_close(rel, NoLock);
2882 if (found)
2883 break;
2884 }
2885 }
2886 }
2887
2888 /*
2889 * In the ALTER TABLE case, don't complain about index keys not
2890 * created in the command; they may well exist already. DefineIndex
2891 * will complain about them if not.
2892 */
2893 if (!found && !cxt->isalter)
2894 ereport(ERROR,
2895 (errcode(ERRCODE_UNDEFINED_COLUMN),
2896 errmsg("column \"%s\" named in key does not exist", key),
2897 parser_errposition(cxt->pstate, constraint->location)));
2898
2899 /* OK, add it to the index definition */
2900 iparam = makeNode(IndexElem);
2901 iparam->name = pstrdup(key);
2902 iparam->expr = NULL;
2903 iparam->indexcolname = NULL;
2904 iparam->collation = NIL;
2905 iparam->opclass = NIL;
2906 iparam->opclassopts = NIL;
2907 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2908 }
2909
2910 return index;
2911}
2912
2913/*
2914 * transformCheckConstraints
2915 * handle CHECK constraints
2916 *
2917 * Right now, there's nothing to do here when called from ALTER TABLE,
2918 * but the other constraint-transformation functions are called in both
2919 * the CREATE TABLE and ALTER TABLE paths, so do the same here, and just
2920 * don't do anything if we're not authorized to skip validation.
2921 */
2922static void
2924{
2925 ListCell *ckclist;
2926
2927 if (cxt->ckconstraints == NIL)
2928 return;
2929
2930 /*
2931 * When creating a new table (but not a foreign table), we can safely skip
2932 * the validation of check constraints and mark them as valid based on the
2933 * constraint enforcement flag, since NOT ENFORCED constraints must always
2934 * be marked as NOT VALID. (This will override any user-supplied NOT VALID
2935 * flag.)
2936 */
2937 if (skipValidation)
2938 {
2939 foreach(ckclist, cxt->ckconstraints)
2940 {
2941 Constraint *constraint = (Constraint *) lfirst(ckclist);
2942
2943 constraint->skip_validation = true;
2944 constraint->initially_valid = constraint->is_enforced;
2945 }
2946 }
2947}
2948
2949/*
2950 * transformFKConstraints
2951 * handle FOREIGN KEY constraints
2952 */
2953static void
2955 bool skipValidation, bool isAddConstraint)
2956{
2957 ListCell *fkclist;
2958
2959 if (cxt->fkconstraints == NIL)
2960 return;
2961
2962 /*
2963 * If CREATE TABLE or adding a column with NULL default, we can safely
2964 * skip validation of FK constraints, and nonetheless mark them valid.
2965 * (This will override any user-supplied NOT VALID flag.)
2966 */
2967 if (skipValidation)
2968 {
2969 foreach(fkclist, cxt->fkconstraints)
2970 {
2971 Constraint *constraint = (Constraint *) lfirst(fkclist);
2972
2973 constraint->skip_validation = true;
2974 constraint->initially_valid = true;
2975 }
2976 }
2977
2978 /*
2979 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2980 * CONSTRAINT command to execute after the basic command is complete. (If
2981 * called from ADD CONSTRAINT, that routine will add the FK constraints to
2982 * its own subcommand list.)
2983 *
2984 * Note: the ADD CONSTRAINT command must also execute after any index
2985 * creation commands. Thus, this should run after
2986 * transformIndexConstraints, so that the CREATE INDEX commands are
2987 * already in cxt->alist. See also the handling of cxt->likeclauses.
2988 */
2989 if (!isAddConstraint)
2990 {
2992
2993 alterstmt->relation = cxt->relation;
2994 alterstmt->cmds = NIL;
2995 alterstmt->objtype = OBJECT_TABLE;
2996
2997 foreach(fkclist, cxt->fkconstraints)
2998 {
2999 Constraint *constraint = (Constraint *) lfirst(fkclist);
3001
3002 altercmd->subtype = AT_AddConstraint;
3003 altercmd->name = NULL;
3004 altercmd->def = (Node *) constraint;
3005 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
3006 }
3007
3008 cxt->alist = lappend(cxt->alist, alterstmt);
3009 }
3010}
3011
3012/*
3013 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
3014 *
3015 * Note: this is a no-op for an index not using either index expressions or
3016 * a predicate expression. There are several code paths that create indexes
3017 * without bothering to call this, because they know they don't have any
3018 * such expressions to deal with.
3019 *
3020 * To avoid race conditions, it's important that this function rely only on
3021 * the passed-in relid (and not on stmt->relation) to determine the target
3022 * relation.
3023 */
3024IndexStmt *
3025transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
3026{
3027 ParseState *pstate;
3028 ParseNamespaceItem *nsitem;
3029 ListCell *l;
3030 Relation rel;
3031
3032 /* Nothing to do if statement already transformed. */
3033 if (stmt->transformed)
3034 return stmt;
3035
3036 /* Set up pstate */
3037 pstate = make_parsestate(NULL);
3038 pstate->p_sourcetext = queryString;
3039
3040 /*
3041 * Put the parent table into the rtable so that the expressions can refer
3042 * to its fields without qualification. Caller is responsible for locking
3043 * relation, but we still need to open it.
3044 */
3045 rel = relation_open(relid, NoLock);
3046 nsitem = addRangeTableEntryForRelation(pstate, rel,
3048 NULL, false, true);
3049
3050 /* no to join list, yes to namespaces */
3051 addNSItemToQuery(pstate, nsitem, false, true, true);
3052
3053 /* take care of the where clause */
3054 if (stmt->whereClause)
3055 {
3056 stmt->whereClause = transformWhereClause(pstate,
3057 stmt->whereClause,
3059 "WHERE");
3060 /* we have to fix its collations too */
3061 assign_expr_collations(pstate, stmt->whereClause);
3062 }
3063
3064 /* take care of any index expressions */
3065 foreach(l, stmt->indexParams)
3066 {
3067 IndexElem *ielem = (IndexElem *) lfirst(l);
3068
3069 if (ielem->expr)
3070 {
3071 /* Extract preliminary index col name before transforming expr */
3072 if (ielem->indexcolname == NULL)
3073 ielem->indexcolname = FigureIndexColname(ielem->expr);
3074
3075 /* Now do parse transformation of the expression */
3076 ielem->expr = transformExpr(pstate, ielem->expr,
3078
3079 /* We have to fix its collations too */
3080 assign_expr_collations(pstate, ielem->expr);
3081
3082 /*
3083 * transformExpr() should have already rejected subqueries,
3084 * aggregates, window functions, and SRFs, based on the EXPR_KIND_
3085 * for an index expression.
3086 *
3087 * DefineIndex() will make more checks.
3088 */
3089 }
3090 }
3091
3092 /*
3093 * Check that only the base rel is mentioned. (This should be dead code
3094 * now that add_missing_from is history.)
3095 */
3096 if (list_length(pstate->p_rtable) != 1)
3097 ereport(ERROR,
3098 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3099 errmsg("index expressions and predicates can refer only to the table being indexed")));
3100
3101 free_parsestate(pstate);
3102
3103 /* Close relation */
3104 table_close(rel, NoLock);
3105
3106 /* Mark statement as successfully transformed */
3107 stmt->transformed = true;
3108
3109 return stmt;
3110}
3111
3112/*
3113 * transformStatsStmt - parse analysis for CREATE STATISTICS
3114 *
3115 * To avoid race conditions, it's important that this function relies only on
3116 * the passed-in relid (and not on stmt->relation) to determine the target
3117 * relation.
3118 */
3120transformStatsStmt(Oid relid, CreateStatsStmt *stmt, const char *queryString)
3121{
3122 ParseState *pstate;
3123 ParseNamespaceItem *nsitem;
3124 ListCell *l;
3125 Relation rel;
3126
3127 /* Nothing to do if statement already transformed. */
3128 if (stmt->transformed)
3129 return stmt;
3130
3131 /* Set up pstate */
3132 pstate = make_parsestate(NULL);
3133 pstate->p_sourcetext = queryString;
3134
3135 /*
3136 * Put the parent table into the rtable so that the expressions can refer
3137 * to its fields without qualification. Caller is responsible for locking
3138 * relation, but we still need to open it.
3139 */
3140 rel = relation_open(relid, NoLock);
3141 nsitem = addRangeTableEntryForRelation(pstate, rel,
3143 NULL, false, true);
3144
3145 /* no to join list, yes to namespaces */
3146 addNSItemToQuery(pstate, nsitem, false, true, true);
3147
3148 /* take care of any expressions */
3149 foreach(l, stmt->exprs)
3150 {
3151 StatsElem *selem = (StatsElem *) lfirst(l);
3152
3153 if (selem->expr)
3154 {
3155 /* Now do parse transformation of the expression */
3156 selem->expr = transformExpr(pstate, selem->expr,
3158
3159 /* We have to fix its collations too */
3160 assign_expr_collations(pstate, selem->expr);
3161 }
3162 }
3163
3164 /*
3165 * Check that only the base rel is mentioned. (This should be dead code
3166 * now that add_missing_from is history.)
3167 */
3168 if (list_length(pstate->p_rtable) != 1)
3169 ereport(ERROR,
3170 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
3171 errmsg("statistics expressions can refer only to the table being referenced")));
3172
3173 free_parsestate(pstate);
3174
3175 /* Close relation */
3176 table_close(rel, NoLock);
3177
3178 /* Mark statement as successfully transformed */
3179 stmt->transformed = true;
3180
3181 return stmt;
3182}
3183
3184
3185/*
3186 * transformRuleStmt -
3187 * transform a CREATE RULE Statement. The action is a list of parse
3188 * trees which is transformed into a list of query trees, and we also
3189 * transform the WHERE clause if any.
3190 *
3191 * actions and whereClause are output parameters that receive the
3192 * transformed results.
3193 */
3194void
3195transformRuleStmt(RuleStmt *stmt, const char *queryString,
3196 List **actions, Node **whereClause)
3197{
3198 Relation rel;
3199 ParseState *pstate;
3200 ParseNamespaceItem *oldnsitem;
3201 ParseNamespaceItem *newnsitem;
3202
3203 /*
3204 * To avoid deadlock, make sure the first thing we do is grab
3205 * AccessExclusiveLock on the target relation. This will be needed by
3206 * DefineQueryRewrite(), and we don't want to grab a lesser lock
3207 * beforehand.
3208 */
3209 rel = table_openrv(stmt->relation, AccessExclusiveLock);
3210
3211 if (rel->rd_rel->relkind == RELKIND_MATVIEW)
3212 ereport(ERROR,
3213 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3214 errmsg("rules on materialized views are not supported")));
3215
3216 /* Set up pstate */
3217 pstate = make_parsestate(NULL);
3218 pstate->p_sourcetext = queryString;
3219
3220 /*
3221 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
3222 * Set up their ParseNamespaceItems in the main pstate for use in parsing
3223 * the rule qualification.
3224 */
3225 oldnsitem = addRangeTableEntryForRelation(pstate, rel,
3227 makeAlias("old", NIL),
3228 false, false);
3229 newnsitem = addRangeTableEntryForRelation(pstate, rel,
3231 makeAlias("new", NIL),
3232 false, false);
3233
3234 /*
3235 * They must be in the namespace too for lookup purposes, but only add the
3236 * one(s) that are relevant for the current kind of rule. In an UPDATE
3237 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
3238 * there's no need to be so picky for INSERT & DELETE. We do not add them
3239 * to the joinlist.
3240 */
3241 switch (stmt->event)
3242 {
3243 case CMD_SELECT:
3244 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3245 break;
3246 case CMD_UPDATE:
3247 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3248 addNSItemToQuery(pstate, newnsitem, false, true, true);
3249 break;
3250 case CMD_INSERT:
3251 addNSItemToQuery(pstate, newnsitem, false, true, true);
3252 break;
3253 case CMD_DELETE:
3254 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3255 break;
3256 default:
3257 elog(ERROR, "unrecognized event type: %d",
3258 (int) stmt->event);
3259 break;
3260 }
3261
3262 /* take care of the where clause */
3263 *whereClause = transformWhereClause(pstate,
3264 stmt->whereClause,
3266 "WHERE");
3267 /* we have to fix its collations too */
3268 assign_expr_collations(pstate, *whereClause);
3269
3270 /* this is probably dead code without add_missing_from: */
3271 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3272 ereport(ERROR,
3273 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3274 errmsg("rule WHERE condition cannot contain references to other relations")));
3275
3276 /*
3277 * 'instead nothing' rules with a qualification need a query rangetable so
3278 * the rewrite handler can add the negated rule qualification to the
3279 * original query. We create a query with the new command type CMD_NOTHING
3280 * here that is treated specially by the rewrite system.
3281 */
3282 if (stmt->actions == NIL)
3283 {
3284 Query *nothing_qry = makeNode(Query);
3285
3286 nothing_qry->commandType = CMD_NOTHING;
3287 nothing_qry->rtable = pstate->p_rtable;
3288 nothing_qry->rteperminfos = pstate->p_rteperminfos;
3289 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3290
3291 *actions = list_make1(nothing_qry);
3292 }
3293 else
3294 {
3295 ListCell *l;
3296 List *newactions = NIL;
3297
3298 /*
3299 * transform each statement, like parse_sub_analyze()
3300 */
3301 foreach(l, stmt->actions)
3302 {
3303 Node *action = (Node *) lfirst(l);
3304 ParseState *sub_pstate = make_parsestate(NULL);
3305 Query *sub_qry,
3306 *top_subqry;
3307 bool has_old,
3308 has_new;
3309
3310 /*
3311 * Since outer ParseState isn't parent of inner, have to pass down
3312 * the query text by hand.
3313 */
3314 sub_pstate->p_sourcetext = queryString;
3315
3316 /*
3317 * Set up OLD/NEW in the rtable for this statement. The entries
3318 * are added only to relnamespace, not varnamespace, because we
3319 * don't want them to be referred to by unqualified field names
3320 * nor "*" in the rule actions. We decide later whether to put
3321 * them in the joinlist.
3322 */
3323 oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3325 makeAlias("old", NIL),
3326 false, false);
3327 newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3329 makeAlias("new", NIL),
3330 false, false);
3331 addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3332 addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3333
3334 /* Transform the rule action statement */
3335 top_subqry = transformStmt(sub_pstate, action);
3336
3337 /*
3338 * We cannot support utility-statement actions (eg NOTIFY) with
3339 * nonempty rule WHERE conditions, because there's no way to make
3340 * the utility action execute conditionally.
3341 */
3342 if (top_subqry->commandType == CMD_UTILITY &&
3343 *whereClause != NULL)
3344 ereport(ERROR,
3345 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3346 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3347
3348 /*
3349 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3350 * into the SELECT, and that's what we need to look at. (Ugly
3351 * kluge ... try to fix this when we redesign querytrees.)
3352 */
3353 sub_qry = getInsertSelectQuery(top_subqry, NULL);
3354
3355 /*
3356 * If the sub_qry is a setop, we cannot attach any qualifications
3357 * to it, because the planner won't notice them. This could
3358 * perhaps be relaxed someday, but for now, we may as well reject
3359 * such a rule immediately.
3360 */
3361 if (sub_qry->setOperations != NULL && *whereClause != NULL)
3362 ereport(ERROR,
3363 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3364 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3365
3366 /*
3367 * Validate action's use of OLD/NEW, qual too
3368 */
3369 has_old =
3370 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
3371 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3372 has_new =
3373 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
3374 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3375
3376 switch (stmt->event)
3377 {
3378 case CMD_SELECT:
3379 if (has_old)
3380 ereport(ERROR,
3381 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3382 errmsg("ON SELECT rule cannot use OLD")));
3383 if (has_new)
3384 ereport(ERROR,
3385 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3386 errmsg("ON SELECT rule cannot use NEW")));
3387 break;
3388 case CMD_UPDATE:
3389 /* both are OK */
3390 break;
3391 case CMD_INSERT:
3392 if (has_old)
3393 ereport(ERROR,
3394 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3395 errmsg("ON INSERT rule cannot use OLD")));
3396 break;
3397 case CMD_DELETE:
3398 if (has_new)
3399 ereport(ERROR,
3400 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3401 errmsg("ON DELETE rule cannot use NEW")));
3402 break;
3403 default:
3404 elog(ERROR, "unrecognized event type: %d",
3405 (int) stmt->event);
3406 break;
3407 }
3408
3409 /*
3410 * OLD/NEW are not allowed in WITH queries, because they would
3411 * amount to outer references for the WITH, which we disallow.
3412 * However, they were already in the outer rangetable when we
3413 * analyzed the query, so we have to check.
3414 *
3415 * Note that in the INSERT...SELECT case, we need to examine the
3416 * CTE lists of both top_subqry and sub_qry.
3417 *
3418 * Note that we aren't digging into the body of the query looking
3419 * for WITHs in nested sub-SELECTs. A WITH down there can
3420 * legitimately refer to OLD/NEW, because it'd be an
3421 * indirect-correlated outer reference.
3422 */
3423 if (rangeTableEntry_used((Node *) top_subqry->cteList,
3424 PRS2_OLD_VARNO, 0) ||
3425 rangeTableEntry_used((Node *) sub_qry->cteList,
3426 PRS2_OLD_VARNO, 0))
3427 ereport(ERROR,
3428 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3429 errmsg("cannot refer to OLD within WITH query")));
3430 if (rangeTableEntry_used((Node *) top_subqry->cteList,
3431 PRS2_NEW_VARNO, 0) ||
3432 rangeTableEntry_used((Node *) sub_qry->cteList,
3433 PRS2_NEW_VARNO, 0))
3434 ereport(ERROR,
3435 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3436 errmsg("cannot refer to NEW within WITH query")));
3437
3438 /*
3439 * For efficiency's sake, add OLD to the rule action's jointree
3440 * only if it was actually referenced in the statement or qual.
3441 *
3442 * For INSERT, NEW is not really a relation (only a reference to
3443 * the to-be-inserted tuple) and should never be added to the
3444 * jointree.
3445 *
3446 * For UPDATE, we treat NEW as being another kind of reference to
3447 * OLD, because it represents references to *transformed* tuples
3448 * of the existing relation. It would be wrong to enter NEW
3449 * separately in the jointree, since that would cause a double
3450 * join of the updated relation. It's also wrong to fail to make
3451 * a jointree entry if only NEW and not OLD is mentioned.
3452 */
3453 if (has_old || (has_new && stmt->event == CMD_UPDATE))
3454 {
3455 RangeTblRef *rtr;
3456
3457 /*
3458 * If sub_qry is a setop, manipulating its jointree will do no
3459 * good at all, because the jointree is dummy. (This should be
3460 * a can't-happen case because of prior tests.)
3461 */
3462 if (sub_qry->setOperations != NULL)
3463 ereport(ERROR,
3464 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3465 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3466 /* hackishly add OLD to the already-built FROM clause */
3467 rtr = makeNode(RangeTblRef);
3468 rtr->rtindex = oldnsitem->p_rtindex;
3469 sub_qry->jointree->fromlist =
3470 lappend(sub_qry->jointree->fromlist, rtr);
3471 }
3472
3473 newactions = lappend(newactions, top_subqry);
3474
3475 free_parsestate(sub_pstate);
3476 }
3477
3478 *actions = newactions;
3479 }
3480
3481 free_parsestate(pstate);
3482
3483 /* Close relation, but keep the exclusive lock */
3484 table_close(rel, NoLock);
3485}
3486
3487
3488/*
3489 * transformAlterTableStmt -
3490 * parse analysis for ALTER TABLE
3491 *
3492 * Returns the transformed AlterTableStmt. There may be additional actions
3493 * to be done before and after the transformed statement, which are returned
3494 * in *beforeStmts and *afterStmts as lists of utility command parsetrees.
3495 *
3496 * To avoid race conditions, it's important that this function rely only on
3497 * the passed-in relid (and not on stmt->relation) to determine the target
3498 * relation.
3499 */
3502 const char *queryString,
3503 List **beforeStmts, List **afterStmts)
3504{
3505 Relation rel;
3506 TupleDesc tupdesc;
3507 ParseState *pstate;
3509 List *save_alist;
3510 ListCell *lcmd,
3511 *l;
3512 List *newcmds = NIL;
3513 bool skipValidation = true;
3514 AlterTableCmd *newcmd;
3515 ParseNamespaceItem *nsitem;
3516
3517 /* Caller is responsible for locking the relation */
3518 rel = relation_open(relid, NoLock);
3519 tupdesc = RelationGetDescr(rel);
3520
3521 /* Set up pstate */
3522 pstate = make_parsestate(NULL);
3523 pstate->p_sourcetext = queryString;
3524 nsitem = addRangeTableEntryForRelation(pstate,
3525 rel,
3527 NULL,
3528 false,
3529 true);
3530 addNSItemToQuery(pstate, nsitem, false, true, true);
3531
3532 /* Set up CreateStmtContext */
3533 cxt.pstate = pstate;
3534 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3535 {
3536 cxt.stmtType = "ALTER FOREIGN TABLE";
3537 cxt.isforeign = true;
3538 }
3539 else
3540 {
3541 cxt.stmtType = "ALTER TABLE";
3542 cxt.isforeign = false;
3543 }
3544 cxt.relation = stmt->relation;
3545 cxt.rel = rel;
3546 cxt.inhRelations = NIL;
3547 cxt.isalter = true;
3548 cxt.columns = NIL;
3549 cxt.ckconstraints = NIL;
3550 cxt.nnconstraints = NIL;
3551 cxt.fkconstraints = NIL;
3552 cxt.ixconstraints = NIL;
3553 cxt.likeclauses = NIL;
3554 cxt.blist = NIL;
3555 cxt.alist = NIL;
3556 cxt.pkey = NULL;
3557 cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3558 cxt.partbound = NULL;
3559 cxt.ofType = false;
3560
3561 /*
3562 * Transform ALTER subcommands that need it (most don't). These largely
3563 * re-use code from CREATE TABLE.
3564 */
3565 foreach(lcmd, stmt->cmds)
3566 {
3567 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3568
3569 switch (cmd->subtype)
3570 {
3571 case AT_AddColumn:
3572 {
3573 ColumnDef *def = castNode(ColumnDef, cmd->def);
3574
3575 transformColumnDefinition(&cxt, def);
3576
3577 /*
3578 * If the column has a non-null default, we can't skip
3579 * validation of foreign keys.
3580 */
3581 if (def->raw_default != NULL)
3582 skipValidation = false;
3583
3584 /*
3585 * All constraints are processed in other ways. Remove the
3586 * original list
3587 */
3588 def->constraints = NIL;
3589
3590 newcmds = lappend(newcmds, cmd);
3591 break;
3592 }
3593
3594 case AT_AddConstraint:
3595
3596 /*
3597 * The original AddConstraint cmd node doesn't go to newcmds
3598 */
3599 if (IsA(cmd->def, Constraint))
3600 {
3601 transformTableConstraint(&cxt, (Constraint *) cmd->def);
3602 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3603 skipValidation = false;
3604 }
3605 else
3606 elog(ERROR, "unrecognized node type: %d",
3607 (int) nodeTag(cmd->def));
3608 break;
3609
3610 case AT_AlterColumnType:
3611 {
3612 ColumnDef *def = castNode(ColumnDef, cmd->def);
3614
3615 /*
3616 * For ALTER COLUMN TYPE, transform the USING clause if
3617 * one was specified.
3618 */
3619 if (def->raw_default)
3620 {
3621 def->cooked_default =
3622 transformExpr(pstate, def->raw_default,
3624 }
3625
3626 /*
3627 * For identity column, create ALTER SEQUENCE command to
3628 * change the data type of the sequence. Identity sequence
3629 * is associated with the top level partitioned table.
3630 * Hence ignore partitions.
3631 */
3632 if (!RelationGetForm(rel)->relispartition)
3633 {
3634 attnum = get_attnum(relid, cmd->name);
3636 ereport(ERROR,
3637 (errcode(ERRCODE_UNDEFINED_COLUMN),
3638 errmsg("column \"%s\" of relation \"%s\" does not exist",
3639 cmd->name, RelationGetRelationName(rel))));
3640
3641 if (attnum > 0 &&
3642 TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3643 {
3644 Oid seq_relid = getIdentitySequence(rel, attnum, false);
3645 Oid typeOid = typenameTypeId(pstate, def->typeName);
3646 AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3647
3648 altseqstmt->sequence
3650 get_rel_name(seq_relid),
3651 -1);
3652 altseqstmt->options = list_make1(makeDefElem("as",
3653 (Node *) makeTypeNameFromOid(typeOid, -1),
3654 -1));
3655 altseqstmt->for_identity = true;
3656 cxt.blist = lappend(cxt.blist, altseqstmt);
3657 }
3658 }
3659
3660 newcmds = lappend(newcmds, cmd);
3661 break;
3662 }
3663
3664 case AT_AddIdentity:
3665 {
3666 Constraint *def = castNode(Constraint, cmd->def);
3667 ColumnDef *newdef = makeNode(ColumnDef);
3669
3670 newdef->colname = cmd->name;
3671 newdef->identity = def->generated_when;
3672 cmd->def = (Node *) newdef;
3673
3674 attnum = get_attnum(relid, cmd->name);
3676 ereport(ERROR,
3677 (errcode(ERRCODE_UNDEFINED_COLUMN),
3678 errmsg("column \"%s\" of relation \"%s\" does not exist",
3679 cmd->name, RelationGetRelationName(rel))));
3680
3681 generateSerialExtraStmts(&cxt, newdef,
3682 get_atttype(relid, attnum),
3683 def->options, true, true,
3684 NULL, NULL);
3685
3686 newcmds = lappend(newcmds, cmd);
3687 break;
3688 }
3689
3690 case AT_SetIdentity:
3691 {
3692 /*
3693 * Create an ALTER SEQUENCE statement for the internal
3694 * sequence of the identity column.
3695 */
3696 ListCell *lc;
3697 List *newseqopts = NIL;
3698 List *newdef = NIL;
3700 Oid seq_relid;
3701
3702 /*
3703 * Split options into those handled by ALTER SEQUENCE and
3704 * those for ALTER TABLE proper.
3705 */
3706 foreach(lc, castNode(List, cmd->def))
3707 {
3708 DefElem *def = lfirst_node(DefElem, lc);
3709
3710 if (strcmp(def->defname, "generated") == 0)
3711 newdef = lappend(newdef, def);
3712 else
3713 newseqopts = lappend(newseqopts, def);
3714 }
3715
3716 attnum = get_attnum(relid, cmd->name);
3718 ereport(ERROR,
3719 (errcode(ERRCODE_UNDEFINED_COLUMN),
3720 errmsg("column \"%s\" of relation \"%s\" does not exist",
3721 cmd->name, RelationGetRelationName(rel))));
3722
3723 seq_relid = getIdentitySequence(rel, attnum, true);
3724
3725 if (seq_relid)
3726 {
3727 AlterSeqStmt *seqstmt;
3728
3729 seqstmt = makeNode(AlterSeqStmt);
3731 get_rel_name(seq_relid), -1);
3732 seqstmt->options = newseqopts;
3733 seqstmt->for_identity = true;
3734 seqstmt->missing_ok = false;
3735
3736 cxt.blist = lappend(cxt.blist, seqstmt);
3737 }
3738
3739 /*
3740 * If column was not an identity column, we just let the
3741 * ALTER TABLE command error out later. (There are cases
3742 * this fails to cover, but we'll need to restructure
3743 * where creation of the sequence dependency linkage
3744 * happens before we can fix it.)
3745 */
3746
3747 cmd->def = (Node *) newdef;
3748 newcmds = lappend(newcmds, cmd);
3749 break;
3750 }
3751
3752 case AT_AttachPartition:
3753 case AT_DetachPartition:
3754 {
3755 PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3756
3757 transformPartitionCmd(&cxt, partcmd);
3758 /* assign transformed value of the partition bound */
3759 partcmd->bound = cxt.partbound;
3760 }
3761
3762 newcmds = lappend(newcmds, cmd);
3763 break;
3764
3765 default:
3766
3767 /*
3768 * Currently, we shouldn't actually get here for subcommand
3769 * types that don't require transformation; but if we do, just
3770 * emit them unchanged.
3771 */
3772 newcmds = lappend(newcmds, cmd);
3773 break;
3774 }
3775 }
3776
3777 /*
3778 * Transfer anything we already have in cxt.alist into save_alist, to keep
3779 * it separate from the output of transformIndexConstraints.
3780 */
3781 save_alist = cxt.alist;
3782 cxt.alist = NIL;
3783
3784 /* Postprocess constraints */
3786 transformFKConstraints(&cxt, skipValidation, true);
3787 transformCheckConstraints(&cxt, false);
3788
3789 /*
3790 * Push any index-creation commands into the ALTER, so that they can be
3791 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3792 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3793 * subcommand has already been through transformIndexStmt.
3794 */
3795 foreach(l, cxt.alist)
3796 {
3797 Node *istmt = (Node *) lfirst(l);
3798
3799 /*
3800 * We assume here that cxt.alist contains only IndexStmts generated
3801 * from primary key constraints.
3802 */
3803 if (IsA(istmt, IndexStmt))
3804 {
3805 IndexStmt *idxstmt = (IndexStmt *) istmt;
3806
3807 idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3808 newcmd = makeNode(AlterTableCmd);
3810 newcmd->def = (Node *) idxstmt;
3811 newcmds = lappend(newcmds, newcmd);
3812 }
3813 else
3814 elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3815 }
3816 cxt.alist = NIL;
3817
3818 /* Append any CHECK, NOT NULL or FK constraints to the commands list */
3820 {
3821 newcmd = makeNode(AlterTableCmd);
3822 newcmd->subtype = AT_AddConstraint;
3823 newcmd->def = (Node *) def;
3824 newcmds = lappend(newcmds, newcmd);
3825 }
3827 {
3828 newcmd = makeNode(AlterTableCmd);
3829 newcmd->subtype = AT_AddConstraint;
3830 newcmd->def = (Node *) def;
3831 newcmds = lappend(newcmds, newcmd);
3832 }
3834 {
3835 newcmd = makeNode(AlterTableCmd);
3836 newcmd->subtype = AT_AddConstraint;
3837 newcmd->def = (Node *) def;
3838 newcmds = lappend(newcmds, newcmd);
3839 }
3840
3841 /* Close rel */
3842 relation_close(rel, NoLock);
3843
3844 /*
3845 * Output results.
3846 */
3847 stmt->cmds = newcmds;
3848
3849 *beforeStmts = cxt.blist;
3850 *afterStmts = list_concat(cxt.alist, save_alist);
3851
3852 return stmt;
3853}
3854
3855
3856/*
3857 * Preprocess a list of column constraint clauses
3858 * to attach constraint attributes to their primary constraint nodes
3859 * and detect inconsistent/misplaced constraint attributes.
3860 *
3861 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
3862 * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
3863 * supported for other constraint types.
3864 */
3865static void
3867{
3868 Constraint *lastprimarycon = NULL;
3869 bool saw_deferrability = false;
3870 bool saw_initially = false;
3871 bool saw_enforced = false;
3872 ListCell *clist;
3873
3874#define SUPPORTS_ATTRS(node) \
3875 ((node) != NULL && \
3876 ((node)->contype == CONSTR_PRIMARY || \
3877 (node)->contype == CONSTR_UNIQUE || \
3878 (node)->contype == CONSTR_EXCLUSION || \
3879 (node)->contype == CONSTR_FOREIGN))
3880
3881 foreach(clist, constraintList)
3882 {
3883 Constraint *con = (Constraint *) lfirst(clist);
3884
3885 if (!IsA(con, Constraint))
3886 elog(ERROR, "unrecognized node type: %d",
3887 (int) nodeTag(con));
3888 switch (con->contype)
3889 {
3891 if (!SUPPORTS_ATTRS(lastprimarycon))
3892 ereport(ERROR,
3893 (errcode(ERRCODE_SYNTAX_ERROR),
3894 errmsg("misplaced DEFERRABLE clause"),
3895 parser_errposition(cxt->pstate, con->location)));
3896 if (saw_deferrability)
3897 ereport(ERROR,
3898 (errcode(ERRCODE_SYNTAX_ERROR),
3899 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3900 parser_errposition(cxt->pstate, con->location)));
3901 saw_deferrability = true;
3902 lastprimarycon->deferrable = true;
3903 break;
3904
3906 if (!SUPPORTS_ATTRS(lastprimarycon))
3907 ereport(ERROR,
3908 (errcode(ERRCODE_SYNTAX_ERROR),
3909 errmsg("misplaced NOT DEFERRABLE clause"),
3910 parser_errposition(cxt->pstate, con->location)));
3911 if (saw_deferrability)
3912 ereport(ERROR,
3913 (errcode(ERRCODE_SYNTAX_ERROR),
3914 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3915 parser_errposition(cxt->pstate, con->location)));
3916 saw_deferrability = true;
3917 lastprimarycon->deferrable = false;
3918 if (saw_initially &&
3919 lastprimarycon->initdeferred)
3920 ereport(ERROR,
3921 (errcode(ERRCODE_SYNTAX_ERROR),
3922 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3923 parser_errposition(cxt->pstate, con->location)));
3924 break;
3925
3927 if (!SUPPORTS_ATTRS(lastprimarycon))
3928 ereport(ERROR,
3929 (errcode(ERRCODE_SYNTAX_ERROR),
3930 errmsg("misplaced INITIALLY DEFERRED clause"),
3931 parser_errposition(cxt->pstate, con->location)));
3932 if (saw_initially)
3933 ereport(ERROR,
3934 (errcode(ERRCODE_SYNTAX_ERROR),
3935 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3936 parser_errposition(cxt->pstate, con->location)));
3937 saw_initially = true;
3938 lastprimarycon->initdeferred = true;
3939
3940 /*
3941 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3942 */
3943 if (!saw_deferrability)
3944 lastprimarycon->deferrable = true;
3945 else if (!lastprimarycon->deferrable)
3946 ereport(ERROR,
3947 (errcode(ERRCODE_SYNTAX_ERROR),
3948 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3949 parser_errposition(cxt->pstate, con->location)));
3950 break;
3951
3953 if (!SUPPORTS_ATTRS(lastprimarycon))
3954 ereport(ERROR,
3955 (errcode(ERRCODE_SYNTAX_ERROR),
3956 errmsg("misplaced INITIALLY IMMEDIATE clause"),
3957 parser_errposition(cxt->pstate, con->location)));
3958 if (saw_initially)
3959 ereport(ERROR,
3960 (errcode(ERRCODE_SYNTAX_ERROR),
3961 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3962 parser_errposition(cxt->pstate, con->location)));
3963 saw_initially = true;
3964 lastprimarycon->initdeferred = false;
3965 break;
3966
3968 if (lastprimarycon == NULL ||
3969 lastprimarycon->contype != CONSTR_CHECK)
3970 ereport(ERROR,
3971 (errcode(ERRCODE_SYNTAX_ERROR),
3972 errmsg("misplaced ENFORCED clause"),
3973 parser_errposition(cxt->pstate, con->location)));
3974 if (saw_enforced)
3975 ereport(ERROR,
3976 (errcode(ERRCODE_SYNTAX_ERROR),
3977 errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
3978 parser_errposition(cxt->pstate, con->location)));
3979 saw_enforced = true;
3980 lastprimarycon->is_enforced = true;
3981 break;
3982
3984 if (lastprimarycon == NULL ||
3985 lastprimarycon->contype != CONSTR_CHECK)
3986 ereport(ERROR,
3987 (errcode(ERRCODE_SYNTAX_ERROR),
3988 errmsg("misplaced NOT ENFORCED clause"),
3989 parser_errposition(cxt->pstate, con->location)));
3990 if (saw_enforced)
3991 ereport(ERROR,
3992 (errcode(ERRCODE_SYNTAX_ERROR),
3993 errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
3994 parser_errposition(cxt->pstate, con->location)));
3995 saw_enforced = true;
3996 lastprimarycon->is_enforced = false;
3997
3998 /* A NOT ENFORCED constraint must be marked as invalid. */
3999 lastprimarycon->skip_validation = true;
4000 lastprimarycon->initially_valid = false;
4001 break;
4002
4003 default:
4004 /* Otherwise it's not an attribute */
4005 lastprimarycon = con;
4006 /* reset flags for new primary node */
4007 saw_deferrability = false;
4008 saw_initially = false;
4009 saw_enforced = false;
4010 break;
4011 }
4012 }
4013}
4014
4015/*
4016 * Special handling of type definition for a column
4017 */
4018static void
4020{
4021 /*
4022 * All we really need to do here is verify that the type is valid,
4023 * including any collation spec that might be present.
4024 */
4025 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
4026
4027 if (column->collClause)
4028 {
4029 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
4030
4032 column->collClause->collname,
4033 column->collClause->location);
4034 /* Complain if COLLATE is applied to an uncollatable type */
4035 if (!OidIsValid(typtup->typcollation))
4036 ereport(ERROR,
4037 (errcode(ERRCODE_DATATYPE_MISMATCH),
4038 errmsg("collations are not supported by type %s",
4039 format_type_be(typtup->oid)),
4041 column->collClause->location)));
4042 }
4043
4044 ReleaseSysCache(ctype);
4045}
4046
4047
4048/*
4049 * transformCreateSchemaStmtElements -
4050 * analyzes the elements of a CREATE SCHEMA statement
4051 *
4052 * Split the schema element list from a CREATE SCHEMA statement into
4053 * individual commands and place them in the result list in an order
4054 * such that there are no forward references (e.g. GRANT to a table
4055 * created later in the list). Note that the logic we use for determining
4056 * forward references is presently quite incomplete.
4057 *
4058 * "schemaName" is the name of the schema that will be used for the creation
4059 * of the objects listed, that may be compiled from the schema name defined
4060 * in the statement or a role specification.
4061 *
4062 * SQL also allows constraints to make forward references, so thumb through
4063 * the table columns and move forward references to a posterior alter-table
4064 * command.
4065 *
4066 * The result is a list of parse nodes that still need to be analyzed ---
4067 * but we can't analyze the later commands until we've executed the earlier
4068 * ones, because of possible inter-object references.
4069 *
4070 * Note: this breaks the rules a little bit by modifying schema-name fields
4071 * within passed-in structs. However, the transformation would be the same
4072 * if done over, so it should be all right to scribble on the input to this
4073 * extent.
4074 */
4075List *
4076transformCreateSchemaStmtElements(List *schemaElts, const char *schemaName)
4077{
4079 List *result;
4080 ListCell *elements;
4081
4082 cxt.schemaname = schemaName;
4083 cxt.sequences = NIL;
4084 cxt.tables = NIL;
4085 cxt.views = NIL;
4086 cxt.indexes = NIL;
4087 cxt.triggers = NIL;
4088 cxt.grants = NIL;
4089
4090 /*
4091 * Run through each schema element in the schema element list. Separate
4092 * statements by type, and do preliminary analysis.
4093 */
4094 foreach(elements, schemaElts)
4095 {
4096 Node *element = lfirst(elements);
4097
4098 switch (nodeTag(element))
4099 {
4100 case T_CreateSeqStmt:
4101 {
4103
4105 cxt.sequences = lappend(cxt.sequences, element);
4106 }
4107 break;
4108
4109 case T_CreateStmt:
4110 {
4111 CreateStmt *elp = (CreateStmt *) element;
4112
4114
4115 /*
4116 * XXX todo: deal with constraints
4117 */
4118 cxt.tables = lappend(cxt.tables, element);
4119 }
4120 break;
4121
4122 case T_ViewStmt:
4123 {
4124 ViewStmt *elp = (ViewStmt *) element;
4125
4127
4128 /*
4129 * XXX todo: deal with references between views
4130 */
4131 cxt.views = lappend(cxt.views, element);
4132 }
4133 break;
4134
4135 case T_IndexStmt:
4136 {
4137 IndexStmt *elp = (IndexStmt *) element;
4138
4140 cxt.indexes = lappend(cxt.indexes, element);
4141 }
4142 break;
4143
4144 case T_CreateTrigStmt:
4145 {
4147
4149 cxt.triggers = lappend(cxt.triggers, element);
4150 }
4151 break;
4152
4153 case T_GrantStmt:
4154 cxt.grants = lappend(cxt.grants, element);
4155 break;
4156
4157 default:
4158 elog(ERROR, "unrecognized node type: %d",
4159 (int) nodeTag(element));
4160 }
4161 }
4162
4163 result = NIL;
4164 result = list_concat(result, cxt.sequences);
4165 result = list_concat(result, cxt.tables);
4166 result = list_concat(result, cxt.views);
4167 result = list_concat(result, cxt.indexes);
4168 result = list_concat(result, cxt.triggers);
4169 result = list_concat(result, cxt.grants);
4170
4171 return result;
4172}
4173
4174/*
4175 * setSchemaName
4176 * Set or check schema name in an element of a CREATE SCHEMA command
4177 */
4178static void
4179setSchemaName(const char *context_schema, char **stmt_schema_name)
4180{
4181 if (*stmt_schema_name == NULL)
4182 *stmt_schema_name = unconstify(char *, context_schema);
4183 else if (strcmp(context_schema, *stmt_schema_name) != 0)
4184 ereport(ERROR,
4185 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
4186 errmsg("CREATE specifies a schema (%s) "
4187 "different from the one being created (%s)",
4188 *stmt_schema_name, context_schema)));
4189}
4190
4191/*
4192 * transformPartitionCmd
4193 * Analyze the ATTACH/DETACH PARTITION command
4194 *
4195 * In case of the ATTACH PARTITION command, cxt->partbound is set to the
4196 * transformed value of cmd->bound.
4197 */
4198static void
4200{
4201 Relation parentRel = cxt->rel;
4202
4203 switch (parentRel->rd_rel->relkind)
4204 {
4205 case RELKIND_PARTITIONED_TABLE:
4206 /* transform the partition bound, if any */
4207 Assert(RelationGetPartitionKey(parentRel) != NULL);
4208 if (cmd->bound != NULL)
4209 cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
4210 cmd->bound);
4211 break;
4212 case RELKIND_PARTITIONED_INDEX:
4213
4214 /*
4215 * A partitioned index cannot have a partition bound set. ALTER
4216 * INDEX prevents that with its grammar, but not ALTER TABLE.
4217 */
4218 if (cmd->bound != NULL)
4219 ereport(ERROR,
4220 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4221 errmsg("\"%s\" is not a partitioned table",
4222 RelationGetRelationName(parentRel))));
4223 break;
4224 case RELKIND_RELATION:
4225 /* the table must be partitioned */
4226 ereport(ERROR,
4227 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4228 errmsg("table \"%s\" is not partitioned",
4229 RelationGetRelationName(parentRel))));
4230 break;
4231 case RELKIND_INDEX:
4232 /* the index must be partitioned */
4233 ereport(ERROR,
4234 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4235 errmsg("index \"%s\" is not partitioned",
4236 RelationGetRelationName(parentRel))));
4237 break;
4238 default:
4239 /* parser shouldn't let this case through */
4240 elog(ERROR, "\"%s\" is not a partitioned table or index",
4241 RelationGetRelationName(parentRel));
4242 break;
4243 }
4244}
4245
4246/*
4247 * transformPartitionBound
4248 *
4249 * Transform a partition bound specification
4250 */
4253 PartitionBoundSpec *spec)
4254{
4255 PartitionBoundSpec *result_spec;
4257 char strategy = get_partition_strategy(key);
4258 int partnatts = get_partition_natts(key);
4259 List *partexprs = get_partition_exprs(key);
4260
4261 /* Avoid scribbling on input */
4262 result_spec = copyObject(spec);
4263
4264 if (spec->is_default)
4265 {
4266 /*
4267 * Hash partitioning does not support a default partition; there's no
4268 * use case for it (since the set of partitions to create is perfectly
4269 * defined), and if users do get into it accidentally, it's hard to
4270 * back out from it afterwards.
4271 */
4272 if (strategy == PARTITION_STRATEGY_HASH)
4273 ereport(ERROR,
4274 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4275 errmsg("a hash-partitioned table may not have a default partition")));
4276
4277 /*
4278 * In case of the default partition, parser had no way to identify the
4279 * partition strategy. Assign the parent's strategy to the default
4280 * partition bound spec.
4281 */
4282 result_spec->strategy = strategy;
4283
4284 return result_spec;
4285 }
4286
4287 if (strategy == PARTITION_STRATEGY_HASH)
4288 {
4289 if (spec->strategy != PARTITION_STRATEGY_HASH)
4290 ereport(ERROR,
4291 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4292 errmsg("invalid bound specification for a hash partition"),
4293 parser_errposition(pstate, exprLocation((Node *) spec))));
4294
4295 if (spec->modulus <= 0)
4296 ereport(ERROR,
4297 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4298 errmsg("modulus for hash partition must be an integer value greater than zero")));
4299
4300 Assert(spec->remainder >= 0);
4301
4302 if (spec->remainder >= spec->modulus)
4303 ereport(ERROR,
4304 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4305 errmsg("remainder for hash partition must be less than modulus")));
4306 }
4307 else if (strategy == PARTITION_STRATEGY_LIST)
4308 {
4309 ListCell *cell;
4310 char *colname;
4311 Oid coltype;
4312 int32 coltypmod;
4313 Oid partcollation;
4314
4315 if (spec->strategy != PARTITION_STRATEGY_LIST)
4316 ereport(ERROR,
4317 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4318 errmsg("invalid bound specification for a list partition"),
4319 parser_errposition(pstate, exprLocation((Node *) spec))));
4320
4321 /* Get the only column's name in case we need to output an error */
4322 if (key->partattrs[0] != 0)
4323 colname = get_attname(RelationGetRelid(parent),
4324 key->partattrs[0], false);
4325 else
4326 colname = deparse_expression((Node *) linitial(partexprs),
4328 RelationGetRelid(parent)),
4329 false, false);
4330 /* Need its type data too */
4331 coltype = get_partition_col_typid(key, 0);
4332 coltypmod = get_partition_col_typmod(key, 0);
4333 partcollation = get_partition_col_collation(key, 0);
4334
4335 result_spec->listdatums = NIL;
4336 foreach(cell, spec->listdatums)
4337 {
4338 Node *expr = lfirst(cell);
4339 Const *value;
4340 ListCell *cell2;
4341 bool duplicate;
4342
4343 value = transformPartitionBoundValue(pstate, expr,
4344 colname, coltype, coltypmod,
4345 partcollation);
4346
4347 /* Don't add to the result if the value is a duplicate */
4348 duplicate = false;
4349 foreach(cell2, result_spec->listdatums)
4350 {
4351 Const *value2 = lfirst_node(Const, cell2);
4352
4353 if (equal(value, value2))
4354 {
4355 duplicate = true;
4356 break;
4357 }
4358 }
4359 if (duplicate)
4360 continue;
4361
4362 result_spec->listdatums = lappend(result_spec->listdatums,
4363 value);
4364 }
4365 }
4366 else if (strategy == PARTITION_STRATEGY_RANGE)
4367 {
4369 ereport(ERROR,
4370 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4371 errmsg("invalid bound specification for a range partition"),
4372 parser_errposition(pstate, exprLocation((Node *) spec))));
4373
4374 if (list_length(spec->lowerdatums) != partnatts)
4375 ereport(ERROR,
4376 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4377 errmsg("FROM must specify exactly one value per partitioning column")));
4378 if (list_length(spec->upperdatums) != partnatts)
4379 ereport(ERROR,
4380 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4381 errmsg("TO must specify exactly one value per partitioning column")));
4382
4383 /*
4384 * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4385 * any necessary validation.
4386 */
4387 result_spec->lowerdatums =
4388 transformPartitionRangeBounds(pstate, spec->lowerdatums,
4389 parent);
4390 result_spec->upperdatums =
4391 transformPartitionRangeBounds(pstate, spec->upperdatums,
4392 parent);
4393 }
4394 else
4395 elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4396
4397 return result_spec;
4398}
4399
4400/*
4401 * transformPartitionRangeBounds
4402 * This converts the expressions for range partition bounds from the raw
4403 * grammar representation to PartitionRangeDatum structs
4404 */
4405static List *
4407 Relation parent)
4408{
4409 List *result = NIL;
4411 List *partexprs = get_partition_exprs(key);
4412 ListCell *lc;
4413 int i,
4414 j;
4415
4416 i = j = 0;
4417 foreach(lc, blist)
4418 {
4419 Node *expr = lfirst(lc);
4420 PartitionRangeDatum *prd = NULL;
4421
4422 /*
4423 * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
4424 * as ColumnRefs.
4425 */
4426 if (IsA(expr, ColumnRef))
4427 {
4428 ColumnRef *cref = (ColumnRef *) expr;
4429 char *cname = NULL;
4430
4431 /*
4432 * There should be a single field named either "minvalue" or
4433 * "maxvalue".
4434 */
4435 if (list_length(cref->fields) == 1 &&
4436 IsA(linitial(cref->fields), String))
4437 cname = strVal(linitial(cref->fields));
4438
4439 if (cname == NULL)
4440 {
4441 /*
4442 * ColumnRef is not in the desired single-field-name form. For
4443 * consistency between all partition strategies, let the
4444 * expression transformation report any errors rather than
4445 * doing it ourselves.
4446 */
4447 }
4448 else if (strcmp("minvalue", cname) == 0)
4449 {
4452 prd->value = NULL;
4453 }
4454 else if (strcmp("maxvalue", cname) == 0)
4455 {
4458 prd->value = NULL;
4459 }
4460 }
4461
4462 if (prd == NULL)
4463 {
4464 char *colname;
4465 Oid coltype;
4466 int32 coltypmod;
4467 Oid partcollation;
4468 Const *value;
4469
4470 /* Get the column's name in case we need to output an error */
4471 if (key->partattrs[i] != 0)
4472 colname = get_attname(RelationGetRelid(parent),
4473 key->partattrs[i], false);
4474 else
4475 {
4476 colname = deparse_expression((Node *) list_nth(partexprs, j),
4478 RelationGetRelid(parent)),
4479 false, false);
4480 ++j;
4481 }
4482
4483 /* Need its type data too */
4484 coltype = get_partition_col_typid(key, i);
4485 coltypmod = get_partition_col_typmod(key, i);
4486 partcollation = get_partition_col_collation(key, i);
4487
4488 value = transformPartitionBoundValue(pstate, expr,
4489 colname,
4490 coltype, coltypmod,
4491 partcollation);
4492 if (value->constisnull)
4493 ereport(ERROR,
4494 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4495 errmsg("cannot specify NULL in range bound")));
4498 prd->value = (Node *) value;
4499 ++i;
4500 }
4501
4502 prd->location = exprLocation(expr);
4503
4504 result = lappend(result, prd);
4505 }
4506
4507 /*
4508 * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
4509 * must be the same.
4510 */
4511 validateInfiniteBounds(pstate, result);
4512
4513 return result;
4514}
4515
4516/*
4517 * validateInfiniteBounds
4518 *
4519 * Check that a MAXVALUE or MINVALUE specification in a partition bound is
4520 * followed only by more of the same.
4521 */
4522static void
4524{
4525 ListCell *lc;
4527
4528 foreach(lc, blist)
4529 {
4531
4532 if (kind == prd->kind)
4533 continue;
4534
4535 switch (kind)
4536 {
4538 kind = prd->kind;
4539 break;
4540
4542 ereport(ERROR,
4543 (errcode(ERRCODE_DATATYPE_MISMATCH),
4544 errmsg("every bound following MAXVALUE must also be MAXVALUE"),
4545 parser_errposition(pstate, exprLocation((Node *) prd))));
4546 break;
4547
4549 ereport(ERROR,
4550 (errcode(ERRCODE_DATATYPE_MISMATCH),
4551 errmsg("every bound following MINVALUE must also be MINVALUE"),
4552 parser_errposition(pstate, exprLocation((Node *) prd))));
4553 break;
4554 }
4555 }
4556}
4557
4558/*
4559 * Transform one entry in a partition bound spec, producing a constant.
4560 */
4561static Const *
4563 const char *colName, Oid colType, int32 colTypmod,
4564 Oid partCollation)
4565{
4566 Node *value;
4567
4568 /* Transform raw parsetree */
4570
4571 /*
4572 * transformExpr() should have already rejected column references,
4573 * subqueries, aggregates, window functions, and SRFs, based on the
4574 * EXPR_KIND_ of a partition bound expression.
4575 */
4577
4578 /*
4579 * Coerce to the correct type. This might cause an explicit coercion step
4580 * to be added on top of the expression, which must be evaluated before
4581 * returning the result to the caller.
4582 */
4585 colType,
4586 colTypmod,
4589 -1);
4590
4591 if (value == NULL)
4592 ereport(ERROR,
4593 (errcode(ERRCODE_DATATYPE_MISMATCH),
4594 errmsg("specified value cannot be cast to type %s for column \"%s\"",
4595 format_type_be(colType), colName),
4597
4598 /*
4599 * Evaluate the expression, if needed, assigning the partition key's data
4600 * type and collation to the resulting Const node.
4601 */
4602 if (!IsA(value, Const))
4603 {
4606 value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4607 partCollation);
4608 if (!IsA(value, Const))
4609 elog(ERROR, "could not evaluate partition bound expression");
4610 }
4611 else
4612 {
4613 /*
4614 * If the expression is already a Const, as is often the case, we can
4615 * skip the rather expensive steps above. But we still have to insert
4616 * the right collation, since coerce_to_target_type doesn't handle
4617 * that.
4618 */
4619 ((Const *) value)->constcollid = partCollation;
4620 }
4621
4622 /*
4623 * Attach original expression's parse location to the Const, so that
4624 * that's what will be reported for any later errors related to this
4625 * partition bound.
4626 */
4627 ((Const *) value)->location = exprLocation(val);
4628
4629 return (Const *) value;
4630}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2622
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3804
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4007
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:177
int16 AttrNumber
Definition: attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define InvalidAttrNumber
Definition: attnum.h:23
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:703
#define unconstify(underlying_type, expr)
Definition: c.h:1202
#define InvalidSubTransactionId
Definition: c.h:615
#define Assert(condition)
Definition: c.h:815
int16_t int16
Definition: c.h:483
int32_t int32
Definition: c.h:484
#define OidIsValid(objectId)
Definition: c.h:732
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4974
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:1157
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#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
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:247
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:235
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
#define stmt
Definition: indent_codes.h:59
#define comment
Definition: indent_codes.h:49
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2613
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2338
static struct @162 value
long val
Definition: informix.c:689
int j
Definition: isn.c:73
int i
Definition: isn.c:72
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
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:1928
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:858
bool type_is_range(Oid typid)
Definition: lsyscache.c:2688
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:970
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1952
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3056
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:827
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:913
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1885
bool type_is_multirange(Oid typid)
Definition: lsyscache.c:2698
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:391
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:590
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:289
ColumnDef * makeColumnDef(const char *colname, Oid typeOid, int32 typmod, Oid collOid)
Definition: makefuncs.c:518
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:426
FuncCall * makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
Definition: makefuncs.c:629
Constraint * makeNotNullConstraint(String *colname)
Definition: makefuncs.c:446
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:500
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
Oid GetUserId(void)
Definition: miscinit.c:517
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:158
#define copyObject(obj)
Definition: nodes.h:224
#define nodeTag(nodeptr)
Definition: nodes.h:133
@ CMD_UTILITY
Definition: nodes.h:270
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
@ CMD_NOTHING
Definition: nodes.h:272
#define makeNode(_type_)
Definition: nodes.h:155
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
ObjectType get_relkind_objtype(char relkind)
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
char * nodeToString(const void *obj)
Definition: outfuncs.c:794
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:2783
@ CONSTR_FOREIGN
Definition: parsenodes.h:2778
@ CONSTR_ATTR_DEFERRED
Definition: parsenodes.h:2781
@ CONSTR_IDENTITY
Definition: parsenodes.h:2772
@ CONSTR_UNIQUE
Definition: parsenodes.h:2776
@ CONSTR_ATTR_NOT_DEFERRABLE
Definition: parsenodes.h:2780
@ CONSTR_DEFAULT
Definition: parsenodes.h:2771
@ CONSTR_NOTNULL
Definition: parsenodes.h:2770
@ CONSTR_ATTR_IMMEDIATE
Definition: parsenodes.h:2782
@ CONSTR_CHECK
Definition: parsenodes.h:2774
@ CONSTR_NULL
Definition: parsenodes.h:2768