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