PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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-2026, 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/attmap.h"
27#include "access/htup_details.h"
28#include "access/relation.h"
29#include "access/reloptions.h"
30#include "access/table.h"
32#include "catalog/dependency.h"
33#include "catalog/heap.h"
34#include "catalog/index.h"
35#include "catalog/namespace.h"
36#include "catalog/partition.h"
37#include "catalog/pg_am.h"
40#include "catalog/pg_opclass.h"
41#include "catalog/pg_operator.h"
43#include "catalog/pg_type.h"
44#include "commands/comment.h"
45#include "commands/defrem.h"
46#include "commands/sequence.h"
47#include "commands/tablecmds.h"
48#include "commands/tablespace.h"
49#include "miscadmin.h"
50#include "nodes/makefuncs.h"
51#include "nodes/nodeFuncs.h"
52#include "optimizer/optimizer.h"
53#include "parser/analyze.h"
54#include "parser/parse_clause.h"
55#include "parser/parse_coerce.h"
57#include "parser/parse_expr.h"
59#include "parser/parse_target.h"
60#include "parser/parse_type.h"
62#include "parser/parser.h"
66#include "utils/acl.h"
67#include "utils/builtins.h"
68#include "utils/lsyscache.h"
69#include "utils/partcache.h"
70#include "utils/rel.h"
71#include "utils/ruleutils.h"
72#include "utils/syscache.h"
73#include "utils/typcache.h"
74
75
76/* State shared by transformCreateStmt and its subroutines */
77typedef struct
78{
79 ParseState *pstate; /* overall parser state */
80 const char *stmtType; /* "CREATE [FOREIGN] TABLE" or "ALTER TABLE" */
81 RangeVar *relation; /* relation to create */
82 Relation rel; /* opened/locked rel, if ALTER */
83 List *inhRelations; /* relations to inherit from */
84 bool isforeign; /* true if CREATE/ALTER FOREIGN TABLE */
85 bool isalter; /* true if altering existing table */
86 List *columns; /* ColumnDef items */
87 List *ckconstraints; /* CHECK constraints */
88 List *nnconstraints; /* NOT NULL constraints */
89 List *fkconstraints; /* FOREIGN KEY constraints */
90 List *ixconstraints; /* index-creating constraints */
91 List *likeclauses; /* LIKE clauses that need post-processing */
92 List *blist; /* "before list" of things to do before
93 * creating the table */
94 List *alist; /* "after list" of things to do after creating
95 * the table */
96 IndexStmt *pkey; /* PRIMARY KEY index, if any */
97 bool ispartitioned; /* true if table is partitioned */
98 PartitionBoundSpec *partbound; /* transformed FOR VALUES */
99 bool ofType; /* true if statement contains OF typename */
101
102
106 Constraint *constraint);
109static void transformOfType(CreateStmtContext *cxt,
110 TypeName *ofTypename);
114 const AttrMap *attmap);
115static List *get_collation(Oid collation, Oid actual_datatype);
116static List *get_opclass(Oid opclass, Oid actual_datatype);
119 CreateStmtContext *cxt);
121 bool skipValidation,
122 bool isAddConstraint);
124 bool skipValidation);
125static void transformConstraintAttrs(ParseState *pstate,
128static void checkSchemaNameRV(ParseState *pstate, const char *context_schema,
129 RangeVar *relation);
130static void checkSchemaNameList(const char *context_schema,
134 List **fk_elements);
136static List *transformPartitionRangeBounds(ParseState *pstate, List *blist,
137 Relation parent);
138static void validateInfiniteBounds(ParseState *pstate, List *blist);
140 const char *colName, Oid colType, int32 colTypmod,
142
143
144/*
145 * transformCreateStmt -
146 * parse analysis for CREATE TABLE
147 *
148 * Returns a List of utility commands to be done in sequence. One of these
149 * will be the transformed CreateStmt, but there may be additional actions
150 * to be done before and after the actual DefineRelation() call.
151 * In addition to normal utility commands such as AlterTableStmt and
152 * IndexStmt, the result list may contain TableLikeClause(s), representing
153 * the need to perform additional parse analysis after DefineRelation().
154 *
155 * SQL allows constraints to be scattered all over, so thumb through
156 * the columns and collect all constraints into one place.
157 * If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
158 * then expand those into multiple IndexStmt blocks.
159 * - thomas 1997-12-02
160 */
161List *
162transformCreateStmt(CreateStmt *stmt, const char *queryString)
163{
164 ParseState *pstate;
166 List *result;
168 ListCell *elements;
172
173 /* Set up pstate */
174 pstate = make_parsestate(NULL);
175 pstate->p_sourcetext = queryString;
176
177 /*
178 * Look up the creation namespace. This also checks permissions on the
179 * target namespace, locks it against concurrent drops, checks for a
180 * preexisting relation in that namespace with the same name, and updates
181 * stmt->relation->relpersistence if the selected namespace is temporary.
182 */
184 stmt->relation->location);
189
190 /*
191 * If the relation already exists and the user specified "IF NOT EXISTS",
192 * bail out with a NOTICE.
193 */
194 if (stmt->if_not_exists && OidIsValid(existing_relid))
195 {
196 /*
197 * If we are in an extension script, insist that the pre-existing
198 * object be a member of the extension, to avoid security risks.
199 */
200 ObjectAddress address;
201
204
205 /* OK to skip */
208 errmsg("relation \"%s\" already exists, skipping",
209 stmt->relation->relname)));
210 return NIL;
211 }
212
213 /*
214 * If the target relation name isn't schema-qualified, make it so. This
215 * prevents some corner cases in which added-on rewritten commands might
216 * think they should apply to other relations that have the same name and
217 * are earlier in the search path. But a local temp table is effectively
218 * specified to be in pg_temp, so no need for anything extra in that case.
219 */
220 if (stmt->relation->schemaname == NULL
221 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
222 stmt->relation->schemaname = get_namespace_name(namespaceid);
223
224 /* Set up CreateStmtContext */
225 cxt.pstate = pstate;
227 {
228 cxt.stmtType = "CREATE FOREIGN TABLE";
229 cxt.isforeign = true;
230 }
231 else
232 {
233 cxt.stmtType = "CREATE TABLE";
234 cxt.isforeign = false;
235 }
236 cxt.relation = stmt->relation;
237 cxt.rel = NULL;
238 cxt.inhRelations = stmt->inhRelations;
239 cxt.isalter = false;
240 cxt.columns = NIL;
241 cxt.ckconstraints = NIL;
242 cxt.nnconstraints = NIL;
243 cxt.fkconstraints = NIL;
244 cxt.ixconstraints = NIL;
245 cxt.likeclauses = NIL;
246 cxt.blist = NIL;
247 cxt.alist = NIL;
248 cxt.pkey = NULL;
249 cxt.ispartitioned = stmt->partspec != NULL;
250 cxt.partbound = stmt->partbound;
251 cxt.ofType = (stmt->ofTypename != NULL);
252
253 Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
254
255 if (stmt->ofTypename)
256 transformOfType(&cxt, stmt->ofTypename);
257
258 if (stmt->partspec)
259 {
260 if (stmt->inhRelations && !stmt->partbound)
263 errmsg("cannot create partitioned table as inheritance child")));
264 }
265
266 /*
267 * Run through each primary element in the table creation clause. Separate
268 * column defs from constraints, and do preliminary analysis.
269 */
270 foreach(elements, stmt->tableElts)
271 {
272 Node *element = lfirst(elements);
273
274 switch (nodeTag(element))
275 {
276 case T_ColumnDef:
278 break;
279
280 case T_Constraint:
282 break;
283
286 break;
287
288 default:
289 elog(ERROR, "unrecognized node type: %d",
290 (int) nodeTag(element));
291 break;
292 }
293 }
294
295 /*
296 * Transfer anything we already have in cxt.alist into save_alist, to keep
297 * it separate from the output of transformIndexConstraints. (This may
298 * not be necessary anymore, but we'll keep doing it to preserve the
299 * historical order of execution of the alist commands.)
300 */
301 save_alist = cxt.alist;
302 cxt.alist = NIL;
303
304 Assert(stmt->constraints == NIL);
305
306 /*
307 * Before processing index constraints, which could include a primary key,
308 * we must scan all not-null constraints to propagate the is_not_null flag
309 * to each corresponding ColumnDef. This is necessary because table-level
310 * not-null constraints have not been marked in each ColumnDef, and the PK
311 * processing code needs to know whether one constraint has already been
312 * declared in order not to declare a redundant one.
313 */
315 {
316 char *colname = strVal(linitial(nn->keys));
317
319 {
320 /* not our column? */
321 if (strcmp(cd->colname, colname) != 0)
322 continue;
323 /* Already marked not-null? Nothing to do */
324 if (cd->is_not_null)
325 break;
326 /* Bingo, we're done for this constraint */
327 cd->is_not_null = true;
328 break;
329 }
330 }
331
332 /*
333 * Postprocess constraints that give rise to index definitions.
334 */
336
337 /*
338 * Re-consideration of LIKE clauses should happen after creation of
339 * indexes, but before creation of foreign keys. This order is critical
340 * because a LIKE clause may attempt to create a primary key. If there's
341 * also a pkey in the main CREATE TABLE list, creation of that will not
342 * check for a duplicate at runtime (since index_check_primary_key()
343 * expects that we rejected dups here). Creation of the LIKE-generated
344 * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
345 * only works if it happens second. On the other hand, we want to make
346 * pkeys before foreign key constraints, in case the user tries to make a
347 * self-referential FK.
348 */
349 cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
350
351 /*
352 * Postprocess foreign-key constraints.
353 */
354 transformFKConstraints(&cxt, true, false);
355
356 /*
357 * Postprocess check constraints.
358 *
359 * For regular tables all constraints can be marked valid immediately,
360 * because the table is new therefore empty. Not so for foreign tables.
361 */
363
364 /*
365 * Output results.
366 */
367 stmt->tableElts = cxt.columns;
368 stmt->constraints = cxt.ckconstraints;
369 stmt->nnconstraints = cxt.nnconstraints;
370
371 result = lappend(cxt.blist, stmt);
374
375 return result;
376}
377
378/*
379 * generateSerialExtraStmts
380 * Generate CREATE SEQUENCE and ALTER SEQUENCE ... OWNED BY statements
381 * to create the sequence for a serial or identity column.
382 *
383 * This includes determining the name the sequence will have. The caller
384 * can ask to get back the name components by passing non-null pointers
385 * for snamespace_p and sname_p.
386 */
387static void
389 Oid seqtypid, List *seqoptions,
390 bool for_identity, bool col_exists,
391 char **snamespace_p, char **sname_p)
392{
397 char *snamespace;
398 char *sname;
399 char seqpersistence;
403
404 /* Make a copy of this as we may end up modifying it in the code below */
406
407 /*
408 * Check for non-SQL-standard options (not supported within CREATE
409 * SEQUENCE, because they'd be redundant), and remove them from the
410 * seqoptions list if found.
411 */
412 foreach(option, seqoptions)
413 {
415
416 if (strcmp(defel->defname, "sequence_name") == 0)
417 {
418 if (nameEl)
420 nameEl = defel;
422 }
423 else if (strcmp(defel->defname, "logged") == 0 ||
424 strcmp(defel->defname, "unlogged") == 0)
425 {
426 if (loggedEl)
428 loggedEl = defel;
430 }
431 }
432
433 /*
434 * Determine namespace and name to use for the sequence.
435 */
436 if (nameEl)
437 {
438 /* Use specified name */
440
442 if (!snamespace)
443 {
444 /* Given unqualified SEQUENCE NAME, select namespace */
445 if (cxt->rel)
447 else
450 }
451 sname = rv->relname;
452 }
453 else
454 {
455 /*
456 * Generate a name.
457 *
458 * Although we use ChooseRelationName, it's not guaranteed that the
459 * selected sequence name won't conflict; given sufficiently long
460 * field names, two different serial columns in the same table could
461 * be assigned the same sequence name, and we'd not notice since we
462 * aren't creating the sequence quite yet. In practice this seems
463 * quite unlikely to be a problem, especially since few people would
464 * need two serial columns in one table.
465 */
466 if (cxt->rel)
468 else
469 {
472 }
475 column->colname,
476 "seq",
478 false);
479 }
480
482 (errmsg_internal("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
483 cxt->stmtType, sname,
484 cxt->relation->relname, column->colname)));
485
486 /*
487 * Determine the persistence of the sequence. By default we copy the
488 * persistence of the table, but if LOGGED or UNLOGGED was specified, use
489 * that (as long as the table isn't TEMP).
490 *
491 * For CREATE TABLE, we get the persistence from cxt->relation, which
492 * comes from the CreateStmt in progress. For ALTER TABLE, the parser
493 * won't set cxt->relation->relpersistence, but we have cxt->rel as the
494 * existing table, so we copy the persistence from there.
495 */
496 seqpersistence = cxt->rel ? cxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;
497 if (loggedEl)
498 {
502 errmsg("cannot set logged status of a temporary sequence"),
503 parser_errposition(cxt->pstate, loggedEl->location)));
504 else if (strcmp(loggedEl->defname, "logged") == 0)
506 else
508 }
509
510 /*
511 * Build a CREATE SEQUENCE command to create the sequence object, and add
512 * it to the list of things to be done before this CREATE/ALTER TABLE.
513 */
515 seqstmt->for_identity = for_identity;
516 seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
517 seqstmt->sequence->relpersistence = seqpersistence;
518 seqstmt->options = seqoptions;
519
520 /*
521 * If a sequence data type was specified, add it to the options. Prepend
522 * to the list rather than append; in case a user supplied their own AS
523 * clause, the "redundant options" error will point to their occurrence,
524 * not our synthetic one.
525 */
526 if (seqtypid)
527 seqstmt->options = lcons(makeDefElem("as",
528 (Node *) makeTypeNameFromOid(seqtypid, -1),
529 -1),
530 seqstmt->options);
531
532 /*
533 * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
534 * the table's owner. The current user might be someone else (perhaps a
535 * superuser, or someone who's only a member of the owning role), but the
536 * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
537 * exactly the same owning role.
538 */
539 if (cxt->rel)
540 seqstmt->ownerId = cxt->rel->rd_rel->relowner;
541 else
542 seqstmt->ownerId = InvalidOid;
543
544 cxt->blist = lappend(cxt->blist, seqstmt);
545
546 /*
547 * Store the identity sequence name that we decided on. ALTER TABLE ...
548 * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
549 * with values from the sequence, while the association of the sequence
550 * with the table is not set until after the ALTER TABLE.
551 */
552 column->identitySequence = seqstmt->sequence;
553
554 /*
555 * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
556 * owned by this column, and add it to the appropriate list of things to
557 * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
558 * COLUMN, it must be done after the statement because we don't know the
559 * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
560 * we can do the marking immediately, which improves some ALTER TABLE
561 * behaviors.
562 */
564 altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
567 makeString(column->colname));
568 altseqstmt->options = list_make1(makeDefElem("owned_by",
569 (Node *) attnamelist, -1));
570 altseqstmt->for_identity = for_identity;
571
572 if (col_exists)
573 cxt->blist = lappend(cxt->blist, altseqstmt);
574 else
575 cxt->alist = lappend(cxt->alist, altseqstmt);
576
577 if (snamespace_p)
579 if (sname_p)
580 *sname_p = sname;
581}
582
583/*
584 * transformColumnDefinition -
585 * transform a single ColumnDef within CREATE TABLE
586 * Also used in ALTER TABLE ADD COLUMN
587 */
588static void
590{
591 bool is_serial;
592 bool saw_nullable;
593 bool saw_default;
594 bool saw_identity;
595 bool saw_generated;
596 bool need_notnull = false;
597 bool disallow_noinherit_notnull = false;
599
600 cxt->columns = lappend(cxt->columns, column);
601
602 /* Check for SERIAL pseudo-types */
603 is_serial = false;
604 if (column->typeName
605 && list_length(column->typeName->names) == 1
606 && !column->typeName->pct_type)
607 {
608 char *typname = strVal(linitial(column->typeName->names));
609
610 if (strcmp(typname, "smallserial") == 0 ||
611 strcmp(typname, "serial2") == 0)
612 {
613 is_serial = true;
614 column->typeName->names = NIL;
615 column->typeName->typeOid = INT2OID;
616 }
617 else if (strcmp(typname, "serial") == 0 ||
618 strcmp(typname, "serial4") == 0)
619 {
620 is_serial = true;
621 column->typeName->names = NIL;
622 column->typeName->typeOid = INT4OID;
623 }
624 else if (strcmp(typname, "bigserial") == 0 ||
625 strcmp(typname, "serial8") == 0)
626 {
627 is_serial = true;
628 column->typeName->names = NIL;
629 column->typeName->typeOid = INT8OID;
630 }
631
632 /*
633 * We have to reject "serial[]" explicitly, because once we've set
634 * typeid, LookupTypeName won't notice arrayBounds. We don't need any
635 * special coding for serial(typmod) though.
636 */
637 if (is_serial && column->typeName->arrayBounds != NIL)
640 errmsg("array of serial is not implemented"),
642 column->typeName->location)));
643 }
644
645 /* Do necessary work on the column type declaration */
646 if (column->typeName)
648
649 /* Special actions for SERIAL pseudo-types */
650 if (is_serial)
651 {
652 char *snamespace;
653 char *sname;
654 char *qstring;
658 Constraint *constraint;
659
661 column->typeName->typeOid, NIL,
662 false, false,
663 &snamespace, &sname);
664
665 /*
666 * Create appropriate constraints for SERIAL. We do this in full,
667 * rather than shortcutting, so that we will detect any conflicting
668 * constraints the user wrote (like a different DEFAULT).
669 *
670 * Create an expression tree representing the function call
671 * nextval('sequencename'). We cannot reduce the raw tree to cooked
672 * form until after the sequence is created, but there's no need to do
673 * so.
674 */
677 snamenode->val.node.type = T_String;
678 snamenode->val.sval.sval = qstring;
679 snamenode->location = -1;
681 castnode->typeName = SystemTypeName("regclass");
682 castnode->arg = (Node *) snamenode;
683 castnode->location = -1;
687 -1);
688 constraint = makeNode(Constraint);
689 constraint->contype = CONSTR_DEFAULT;
690 constraint->location = -1;
691 constraint->raw_expr = (Node *) funccallnode;
692 constraint->cooked_expr = NULL;
693 column->constraints = lappend(column->constraints, constraint);
694
695 /* have a not-null constraint added later */
696 need_notnull = true;
698 }
699
700 /* Process column constraints, if any... */
701 transformConstraintAttrs(cxt->pstate, column->constraints);
702
703 /*
704 * First, scan the column's constraints to see if a not-null constraint
705 * that we add must be prevented from being NO INHERIT. This should be
706 * enforced only for PRIMARY KEY, not IDENTITY or SERIAL. However, if the
707 * not-null constraint is specified as a table constraint rather than as a
708 * column constraint, AddRelationNotNullConstraints would raise an error
709 * if a NO INHERIT mismatch is found. To avoid inconsistently disallowing
710 * it in the table constraint case but not the column constraint case, we
711 * disallow it here as well. Maybe AddRelationNotNullConstraints can be
712 * improved someday, so that it doesn't complain, and then we can remove
713 * the restriction for SERIAL and IDENTITY here as well.
714 */
716 {
717 foreach_node(Constraint, constraint, column->constraints)
718 {
719 switch (constraint->contype)
720 {
721 case CONSTR_IDENTITY:
722 case CONSTR_PRIMARY:
724 break;
725 default:
726 break;
727 }
728 }
729 }
730
731 /* Now scan them again to do full processing */
732 saw_nullable = false;
733 saw_default = false;
734 saw_identity = false;
735 saw_generated = false;
736
737 foreach_node(Constraint, constraint, column->constraints)
738 {
739 switch (constraint->contype)
740 {
741 case CONSTR_NULL:
742 if ((saw_nullable && column->is_not_null) || need_notnull)
745 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
746 column->colname, cxt->relation->relname),
748 constraint->location)));
749 column->is_not_null = false;
750 saw_nullable = true;
751 break;
752
753 case CONSTR_NOTNULL:
754 if (cxt->ispartitioned && constraint->is_no_inherit)
757 errmsg("not-null constraints on partitioned tables cannot be NO INHERIT"));
758
759 /* Disallow conflicting [NOT] NULL markings */
760 if (saw_nullable && !column->is_not_null)
763 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
764 column->colname, cxt->relation->relname),
766 constraint->location)));
767
768 if (disallow_noinherit_notnull && constraint->is_no_inherit)
771 errmsg("conflicting NO INHERIT declarations for not-null constraints on column \"%s\"",
772 column->colname));
773
774 /*
775 * If this is the first time we see this column being marked
776 * not-null, add the constraint entry and keep track of it.
777 * Also, remove previous markings that we need one.
778 *
779 * If this is a redundant not-null specification, just check
780 * that it doesn't conflict with what was specified earlier.
781 *
782 * Any conflicts with table constraints will be further
783 * checked in AddRelationNotNullConstraints().
784 */
785 if (!column->is_not_null)
786 {
787 column->is_not_null = true;
788 saw_nullable = true;
789 need_notnull = false;
790
791 constraint->keys = list_make1(makeString(column->colname));
792 notnull_constraint = constraint;
793 cxt->nnconstraints = lappend(cxt->nnconstraints, constraint);
794 }
795 else if (notnull_constraint)
796 {
797 if (constraint->conname &&
798 notnull_constraint->conname &&
799 strcmp(notnull_constraint->conname, constraint->conname) != 0)
800 elog(ERROR, "conflicting not-null constraint names \"%s\" and \"%s\"",
801 notnull_constraint->conname, constraint->conname);
802
803 if (notnull_constraint->is_no_inherit != constraint->is_no_inherit)
806 errmsg("conflicting NO INHERIT declarations for not-null constraints on column \"%s\"",
807 column->colname));
808
809 if (!notnull_constraint->conname && constraint->conname)
810 notnull_constraint->conname = constraint->conname;
811 }
812
813 break;
814
815 case CONSTR_DEFAULT:
816 if (saw_default)
819 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
820 column->colname, cxt->relation->relname),
822 constraint->location)));
823 column->raw_default = constraint->raw_expr;
824 Assert(constraint->cooked_expr == NULL);
825 saw_default = true;
826 break;
827
828 case CONSTR_IDENTITY:
829 {
830 Type ctype;
831 Oid typeOid;
832
833 if (cxt->ofType)
836 errmsg("identity columns are not supported on typed tables")));
837 if (cxt->partbound)
840 errmsg("identity columns are not supported on partitions")));
841
842 ctype = typenameType(cxt->pstate, column->typeName, NULL);
843 typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
844 ReleaseSysCache(ctype);
845
846 if (saw_identity)
849 errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
850 column->colname, cxt->relation->relname),
852 constraint->location)));
853
855 typeOid, constraint->options,
856 true, false,
857 NULL, NULL);
858
859 column->identity = constraint->generated_when;
860 saw_identity = true;
861
862 /*
863 * Identity columns are always NOT NULL, but we may have a
864 * constraint already.
865 */
866 if (!saw_nullable)
867 need_notnull = true;
868 else if (!column->is_not_null)
871 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
872 column->colname, cxt->relation->relname),
874 constraint->location)));
875 break;
876 }
877
878 case CONSTR_GENERATED:
879 if (cxt->ofType)
882 errmsg("generated columns are not supported on typed tables")));
883 if (saw_generated)
886 errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
887 column->colname, cxt->relation->relname),
889 constraint->location)));
890 column->generated = constraint->generated_kind;
891 column->raw_default = constraint->raw_expr;
892 Assert(constraint->cooked_expr == NULL);
893 saw_generated = true;
894 break;
895
896 case CONSTR_CHECK:
897 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
898 break;
899
900 case CONSTR_PRIMARY:
901 if (saw_nullable && !column->is_not_null)
904 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
905 column->colname, cxt->relation->relname),
907 constraint->location)));
908 need_notnull = true;
909
910 if (cxt->isforeign)
913 errmsg("primary key constraints are not supported on foreign tables"),
915 constraint->location)));
917
918 case CONSTR_UNIQUE:
919 if (cxt->isforeign)
922 errmsg("unique constraints are not supported on foreign tables"),
924 constraint->location)));
925 if (constraint->keys == NIL)
926 constraint->keys = list_make1(makeString(column->colname));
927 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
928 break;
929
930 case CONSTR_EXCLUSION:
931 /* grammar does not allow EXCLUDE as a column constraint */
932 elog(ERROR, "column exclusion constraints are not supported");
933 break;
934
935 case CONSTR_FOREIGN:
936 if (cxt->isforeign)
939 errmsg("foreign key constraints are not supported on foreign tables"),
941 constraint->location)));
942
943 /*
944 * Fill in the current attribute's name and throw it into the
945 * list of FK constraints to be processed later.
946 */
947 constraint->fk_attrs = list_make1(makeString(column->colname));
948 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
949 break;
950
957 /* transformConstraintAttrs took care of these */
958 break;
959
960 default:
961 elog(ERROR, "unrecognized constraint type: %d",
962 constraint->contype);
963 break;
964 }
965
969 errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
970 column->colname, cxt->relation->relname),
972 constraint->location)));
973
977 errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
978 column->colname, cxt->relation->relname),
980 constraint->location)));
981
985 errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
986 column->colname, cxt->relation->relname),
988 constraint->location)));
989 }
990
991 /*
992 * If we need a not-null constraint for PRIMARY KEY, SERIAL or IDENTITY,
993 * and one was not explicitly specified, add one now.
994 */
995 if (need_notnull && !(saw_nullable && column->is_not_null))
996 {
997 column->is_not_null = true;
1000 }
1001
1002 /*
1003 * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
1004 * per-column foreign data wrapper options to this column after creation.
1005 */
1006 if (column->fdwoptions != NIL)
1007 {
1009 AlterTableCmd *cmd;
1010
1011 cmd = makeNode(AlterTableCmd);
1013 cmd->name = column->colname;
1014 cmd->def = (Node *) column->fdwoptions;
1015 cmd->behavior = DROP_RESTRICT;
1016 cmd->missing_ok = false;
1017
1019 stmt->relation = cxt->relation;
1020 stmt->cmds = NIL;
1021 stmt->objtype = OBJECT_FOREIGN_TABLE;
1022 stmt->cmds = lappend(stmt->cmds, cmd);
1023
1024 cxt->alist = lappend(cxt->alist, stmt);
1025 }
1026}
1027
1028/*
1029 * transformTableConstraint
1030 * transform a Constraint node within CREATE TABLE or ALTER TABLE
1031 */
1032static void
1034{
1035 switch (constraint->contype)
1036 {
1037 case CONSTR_PRIMARY:
1038 if (cxt->isforeign)
1039 ereport(ERROR,
1041 errmsg("primary key constraints are not supported on foreign tables"),
1043 constraint->location)));
1044 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1045 break;
1046
1047 case CONSTR_UNIQUE:
1048 if (cxt->isforeign)
1049 ereport(ERROR,
1051 errmsg("unique constraints are not supported on foreign tables"),
1053 constraint->location)));
1054 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1055 break;
1056
1057 case CONSTR_EXCLUSION:
1058 if (cxt->isforeign)
1059 ereport(ERROR,
1061 errmsg("exclusion constraints are not supported on foreign tables"),
1063 constraint->location)));
1064 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1065 break;
1066
1067 case CONSTR_CHECK:
1068 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1069 break;
1070
1071 case CONSTR_NOTNULL:
1072 if (cxt->ispartitioned && constraint->is_no_inherit)
1073 ereport(ERROR,
1075 errmsg("not-null constraints on partitioned tables cannot be NO INHERIT"));
1076
1077 cxt->nnconstraints = lappend(cxt->nnconstraints, constraint);
1078 break;
1079
1080 case CONSTR_FOREIGN:
1081 if (cxt->isforeign)
1082 ereport(ERROR,
1084 errmsg("foreign key constraints are not supported on foreign tables"),
1086 constraint->location)));
1087 cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
1088 break;
1089
1090 case CONSTR_NULL:
1091 case CONSTR_DEFAULT:
1098 elog(ERROR, "invalid context for constraint type %d",
1099 constraint->contype);
1100 break;
1101
1102 default:
1103 elog(ERROR, "unrecognized constraint type: %d",
1104 constraint->contype);
1105 break;
1106 }
1107}
1108
1109/*
1110 * transformTableLikeClause
1111 *
1112 * Change the LIKE <srctable> portion of a CREATE TABLE statement into
1113 * column definitions that recreate the user defined column portions of
1114 * <srctable>. Also, if there are any LIKE options that we can't fully
1115 * process at this point, add the TableLikeClause to cxt->likeclauses, which
1116 * will cause utility.c to call expandTableLikeClause() after the new
1117 * table has been created.
1118 *
1119 * Some options are ignored. For example, as foreign tables have no storage,
1120 * these INCLUDING options have no effect: STORAGE, COMPRESSION, IDENTITY
1121 * and INDEXES. Similarly, INCLUDING INDEXES is ignored from a view.
1122 */
1123static void
1125{
1127 Relation relation;
1130 char *comment;
1132
1134 table_like_clause->relation->location);
1135
1136 /* Open the relation referenced by the LIKE clause */
1137 relation = relation_openrv(table_like_clause->relation, AccessShareLock);
1138
1139 if (relation->rd_rel->relkind != RELKIND_RELATION &&
1140 relation->rd_rel->relkind != RELKIND_VIEW &&
1141 relation->rd_rel->relkind != RELKIND_MATVIEW &&
1142 relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
1143 relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
1144 relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1145 ereport(ERROR,
1147 errmsg("relation \"%s\" is invalid in LIKE clause",
1148 RelationGetRelationName(relation)),
1149 errdetail_relkind_not_supported(relation->rd_rel->relkind)));
1150
1152
1153 /*
1154 * Check for privileges
1155 */
1156 if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1157 {
1158 aclresult = object_aclcheck(TypeRelationId, relation->rd_rel->reltype, GetUserId(),
1159 ACL_USAGE);
1160 if (aclresult != ACLCHECK_OK)
1162 RelationGetRelationName(relation));
1163 }
1164 else
1165 {
1167 ACL_SELECT);
1168 if (aclresult != ACLCHECK_OK)
1170 RelationGetRelationName(relation));
1171 }
1172
1173 tupleDesc = RelationGetDescr(relation);
1174
1175 /*
1176 * Insert the copied attributes into the cxt for the new table definition.
1177 * We must do this now so that they appear in the table in the relative
1178 * position where the LIKE clause is, as required by SQL99.
1179 */
1180 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1181 parent_attno++)
1182 {
1184 parent_attno - 1);
1185 ColumnDef *def;
1186
1187 /*
1188 * Ignore dropped columns in the parent.
1189 */
1190 if (attribute->attisdropped)
1191 continue;
1192
1193 /*
1194 * Create a new column definition
1195 */
1196 def = makeColumnDef(NameStr(attribute->attname), attribute->atttypid,
1197 attribute->atttypmod, attribute->attcollation);
1198
1199 /*
1200 * Add to column list
1201 */
1202 cxt->columns = lappend(cxt->columns, def);
1203
1204 /*
1205 * Although we don't transfer the column's default/generation
1206 * expression now, we need to mark it GENERATED if appropriate.
1207 */
1208 if (attribute->atthasdef && attribute->attgenerated &&
1210 def->generated = attribute->attgenerated;
1211
1212 /*
1213 * Copy identity if requested
1214 */
1215 if (attribute->attidentity &&
1217 !cxt->isforeign)
1218 {
1219 Oid seq_relid;
1221
1222 /*
1223 * find sequence owned by old column; extract sequence parameters;
1224 * build new create sequence command
1225 */
1226 seq_relid = getIdentitySequence(relation, attribute->attnum, false);
1228 generateSerialExtraStmts(cxt, def,
1230 true, false,
1231 NULL, NULL);
1232 def->identity = attribute->attidentity;
1233 }
1234
1235 /* Likewise, copy storage if requested */
1237 !cxt->isforeign)
1238 def->storage = attribute->attstorage;
1239 else
1240 def->storage = 0;
1241
1242 /* Likewise, copy compression if requested */
1243 if ((table_like_clause->options & CREATE_TABLE_LIKE_COMPRESSION) != 0 &&
1244 CompressionMethodIsValid(attribute->attcompression) &&
1245 !cxt->isforeign)
1246 def->compression =
1247 pstrdup(GetCompressionMethodName(attribute->attcompression));
1248 else
1249 def->compression = NULL;
1250
1251 /* Likewise, copy comment if requested */
1253 (comment = GetComment(attribute->attrelid,
1255 attribute->attnum)) != NULL)
1256 {
1258
1259 stmt->objtype = OBJECT_COLUMN;
1260 stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1262 makeString(def->colname));
1263 stmt->comment = comment;
1264
1265 cxt->alist = lappend(cxt->alist, stmt);
1266 }
1267 }
1268
1269 /*
1270 * Reproduce not-null constraints, if any, by copying them. We do this
1271 * regardless of options given.
1272 */
1273 if (tupleDesc->constr && tupleDesc->constr->has_not_null)
1274 {
1275 List *lst;
1276
1278 true);
1280
1281 /* Copy comments on not-null constraints */
1283 {
1285 {
1287 nnconstr->conname, false),
1289 0)) != NULL)
1290 {
1292
1293 stmt->objtype = OBJECT_TABCONSTRAINT;
1294 stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1296 makeString(nnconstr->conname));
1297 stmt->comment = comment;
1298 cxt->alist = lappend(cxt->alist, stmt);
1299 }
1300 }
1301 }
1302 }
1303
1304 /*
1305 * We cannot yet deal with defaults, CHECK constraints, indexes, or
1306 * statistics, since we don't yet know what column numbers the copied
1307 * columns will have in the finished table. If any of those options are
1308 * specified, add the LIKE clause to cxt->likeclauses so that
1309 * expandTableLikeClause will be called after we do know that.
1310 *
1311 * In order for this to work, we remember the relation OID so that
1312 * expandTableLikeClause is certain to open the same table.
1313 */
1314 if (table_like_clause->options &
1320 {
1321 table_like_clause->relationOid = RelationGetRelid(relation);
1323 }
1324
1325 /*
1326 * Close the parent rel, but keep our AccessShareLock on it until xact
1327 * commit. That will prevent someone else from deleting or ALTERing the
1328 * parent before we can run expandTableLikeClause.
1329 */
1330 table_close(relation, NoLock);
1331}
1332
1333/*
1334 * expandTableLikeClause
1335 *
1336 * Process LIKE options that require knowing the final column numbers
1337 * assigned to the new table's columns. This executes after we have
1338 * run DefineRelation for the new table. It returns a list of utility
1339 * commands that should be run to generate indexes etc.
1340 */
1341List *
1343{
1344 List *result = NIL;
1345 List *atsubcmds = NIL;
1347 Relation relation;
1350 TupleConstr *constr;
1351 AttrMap *attmap;
1352 char *comment;
1353
1354 /*
1355 * Open the relation referenced by the LIKE clause. We should still have
1356 * the table lock obtained by transformTableLikeClause (and this'll throw
1357 * an assertion failure if not). Hence, no need to recheck privileges
1358 * etc. We must open the rel by OID not name, to be sure we get the same
1359 * table.
1360 */
1361 if (!OidIsValid(table_like_clause->relationOid))
1362 elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1363
1364 relation = relation_open(table_like_clause->relationOid, NoLock);
1365
1366 tupleDesc = RelationGetDescr(relation);
1367 constr = tupleDesc->constr;
1368
1369 /*
1370 * Open the newly-created child relation; we have lock on that too.
1371 */
1372 childrel = relation_openrv(heapRel, NoLock);
1373
1374 /*
1375 * Construct a map from the LIKE relation's attnos to the child rel's.
1376 * This re-checks type match etc, although it shouldn't be possible to
1377 * have a failure since both tables are locked.
1378 */
1380 tupleDesc,
1381 false);
1382
1383 /*
1384 * Process defaults, if required.
1385 */
1386 if ((table_like_clause->options &
1388 constr != NULL)
1389 {
1390 for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1391 parent_attno++)
1392 {
1394 parent_attno - 1);
1395
1396 /*
1397 * Ignore dropped columns in the parent.
1398 */
1399 if (attribute->attisdropped)
1400 continue;
1401
1402 /*
1403 * Copy default, if present and it should be copied. We have
1404 * separate options for plain default expressions and GENERATED
1405 * defaults.
1406 */
1407 if (attribute->atthasdef &&
1408 (attribute->attgenerated ?
1411 {
1414 bool found_whole_row;
1415
1417 if (this_default == NULL)
1418 elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1420
1423 atsubcmd->num = attmap->attnums[parent_attno - 1];
1425 1, 0,
1426 attmap,
1427 InvalidOid,
1428 &found_whole_row);
1429
1430 /*
1431 * Prevent this for the same reason as for constraints below.
1432 * Note that defaults cannot contain any vars, so it's OK that
1433 * the error message refers to generated columns.
1434 */
1435 if (found_whole_row)
1436 ereport(ERROR,
1438 errmsg("cannot convert whole-row table reference"),
1439 errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1440 NameStr(attribute->attname),
1441 RelationGetRelationName(relation))));
1442
1444 }
1445 }
1446 }
1447
1448 /*
1449 * Copy CHECK constraints if requested, being careful to adjust attribute
1450 * numbers so they match the child.
1451 */
1453 constr != NULL)
1454 {
1455 int ccnum;
1456
1457 for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1458 {
1459 char *ccname = constr->check[ccnum].ccname;
1460 char *ccbin = constr->check[ccnum].ccbin;
1461 bool ccenforced = constr->check[ccnum].ccenforced;
1462 bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1464 bool found_whole_row;
1465 Constraint *n;
1467
1469 1, 0,
1470 attmap,
1471 InvalidOid, &found_whole_row);
1472
1473 /*
1474 * We reject whole-row variables because the whole point of LIKE
1475 * is that the new table's rowtype might later diverge from the
1476 * parent's. So, while translation might be possible right now,
1477 * it wouldn't be possible to guarantee it would work in future.
1478 */
1479 if (found_whole_row)
1480 ereport(ERROR,
1482 errmsg("cannot convert whole-row table reference"),
1483 errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1484 ccname,
1485 RelationGetRelationName(relation))));
1486
1487 n = makeNode(Constraint);
1488 n->contype = CONSTR_CHECK;
1489 n->conname = pstrdup(ccname);
1490 n->location = -1;
1491 n->is_enforced = ccenforced;
1492 n->initially_valid = ccenforced; /* sic */
1493 n->is_no_inherit = ccnoinherit;
1494 n->raw_expr = NULL;
1496
1497 /* We can skip validation, since the new table should be empty. */
1498 n->skip_validation = true;
1499
1501 atsubcmd->subtype = AT_AddConstraint;
1502 atsubcmd->def = (Node *) n;
1504
1505 /* Copy comment on constraint */
1508 n->conname, false),
1510 0)) != NULL)
1511 {
1513
1514 stmt->objtype = OBJECT_TABCONSTRAINT;
1515 stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1516 makeString(heapRel->relname),
1517 makeString(n->conname));
1518 stmt->comment = comment;
1519
1521 }
1522 }
1523 }
1524
1525 /*
1526 * If we generated any ALTER TABLE actions above, wrap them into a single
1527 * ALTER TABLE command. Stick it at the front of the result, so it runs
1528 * before any CommentStmts we made above.
1529 */
1530 if (atsubcmds)
1531 {
1533
1534 atcmd->relation = copyObject(heapRel);
1535 atcmd->cmds = atsubcmds;
1536 atcmd->objtype = OBJECT_TABLE;
1537 atcmd->missing_ok = false;
1539 }
1540
1541 /*
1542 * Process indexes if required.
1543 */
1545 relation->rd_rel->relhasindex &&
1546 childrel->rd_rel->relkind != RELKIND_FOREIGN_TABLE)
1547 {
1549 ListCell *l;
1550
1552
1553 foreach(l, parent_indexes)
1554 {
1558
1560
1561 /* Build CREATE INDEX statement to recreate the parent_index */
1564 attmap,
1565 NULL);
1566
1567 /* Copy comment on index, if requested */
1569 {
1571
1572 /*
1573 * We make use of IndexStmt's idxcomment option, so as not to
1574 * need to know now what name the index will have.
1575 */
1576 index_stmt->idxcomment = comment;
1577 }
1578
1580
1582 }
1583 }
1584
1585 /*
1586 * Process extended statistics if required.
1587 */
1589 {
1591 ListCell *l;
1592
1594
1595 foreach(l, parent_extstats)
1596 {
1599
1603 attmap);
1604
1605 /* Copy comment on statistics object, if requested */
1607 {
1609
1610 /*
1611 * We make use of CreateStatsStmt's stxcomment option, so as
1612 * not to need to know now what name the statistics will have.
1613 */
1614 stats_stmt->stxcomment = comment;
1615 }
1616
1618 }
1619
1621 }
1622
1623 /* Done with child rel */
1625
1626 /*
1627 * Close the parent rel, but keep our AccessShareLock on it until xact
1628 * commit. That will prevent someone else from deleting or ALTERing the
1629 * parent before the child is committed.
1630 */
1631 table_close(relation, NoLock);
1632
1633 return result;
1634}
1635
1636static void
1638{
1639 HeapTuple tuple;
1640 TupleDesc tupdesc;
1641 int i;
1642 Oid ofTypeId;
1643
1644 Assert(ofTypename);
1645
1646 tuple = typenameType(cxt->pstate, ofTypename, NULL);
1647 check_of_type(tuple);
1648 ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1649 ofTypename->typeOid = ofTypeId; /* cached for later */
1650
1651 tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1652 for (i = 0; i < tupdesc->natts; i++)
1653 {
1654 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1655 ColumnDef *n;
1656
1657 if (attr->attisdropped)
1658 continue;
1659
1660 n = makeColumnDef(NameStr(attr->attname), attr->atttypid,
1661 attr->atttypmod, attr->attcollation);
1662 n->is_from_type = true;
1663
1664 cxt->columns = lappend(cxt->columns, n);
1665 }
1666 ReleaseTupleDesc(tupdesc);
1667
1668 ReleaseSysCache(tuple);
1669}
1670
1671/*
1672 * Generate an IndexStmt node using information from an already existing index
1673 * "source_idx".
1674 *
1675 * heapRel is stored into the IndexStmt's relation field, but we don't use it
1676 * otherwise; some callers pass NULL, if they don't need it to be valid.
1677 * (The target relation might not exist yet, so we mustn't try to access it.)
1678 *
1679 * Attribute numbers in expression Vars are adjusted according to attmap.
1680 *
1681 * If constraintOid isn't NULL, we store the OID of any constraint associated
1682 * with the index there.
1683 *
1684 * Unlike transformIndexConstraint, we don't make any effort to force primary
1685 * key columns to be not-null. The larger cloning process this is part of
1686 * should have cloned their not-null status separately (and DefineIndex will
1687 * complain if that fails to happen).
1688 */
1689IndexStmt *
1691 const AttrMap *attmap,
1693{
1704 List *indexprs;
1706 Oid indrelid;
1707 int keyno;
1709 Datum datum;
1710 bool isnull;
1711
1712 if (constraintOid)
1714
1715 /*
1716 * Fetch pg_class tuple of source index. We can't use the copy in the
1717 * relcache entry because it doesn't include optional fields.
1718 */
1721 elog(ERROR, "cache lookup failed for relation %u", source_relid);
1723
1724 /* Fetch pg_index tuple for source index from relcache entry */
1725 ht_idx = source_idx->rd_indextuple;
1727 indrelid = idxrec->indrelid;
1728
1729 /* Fetch the pg_am tuple of the index' access method */
1731 if (!HeapTupleIsValid(ht_am))
1732 elog(ERROR, "cache lookup failed for access method %u",
1733 idxrelrec->relam);
1735
1736 /* Extract indcollation from the pg_index tuple */
1740
1741 /* Extract indclass from the pg_index tuple */
1743 indclass = (oidvector *) DatumGetPointer(datum);
1744
1745 /* Begin building the IndexStmt */
1747 index->relation = heapRel;
1748 index->accessMethod = pstrdup(NameStr(amrec->amname));
1749 if (OidIsValid(idxrelrec->reltablespace))
1750 index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1751 else
1752 index->tableSpace = NULL;
1753 index->excludeOpNames = NIL;
1754 index->idxcomment = NULL;
1755 index->indexOid = InvalidOid;
1756 index->oldNumber = InvalidRelFileNumber;
1757 index->oldCreateSubid = InvalidSubTransactionId;
1758 index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
1759 index->unique = idxrec->indisunique;
1760 index->nulls_not_distinct = idxrec->indnullsnotdistinct;
1761 index->primary = idxrec->indisprimary;
1762 index->iswithoutoverlaps = (idxrec->indisprimary || idxrec->indisunique) && idxrec->indisexclusion;
1763 index->transformed = true; /* don't need transformIndexStmt */
1764 index->concurrent = false;
1765 index->if_not_exists = false;
1766 index->reset_default_tblspc = false;
1767
1768 /*
1769 * We don't try to preserve the name of the source index; instead, just
1770 * let DefineIndex() choose a reasonable name. (If we tried to preserve
1771 * the name, we'd get duplicate-relation-name failures unless the source
1772 * table was in a different schema.)
1773 */
1774 index->idxname = NULL;
1775
1776 /*
1777 * If the index is marked PRIMARY or has an exclusion condition, it's
1778 * certainly from a constraint; else, if it's not marked UNIQUE, it
1779 * certainly isn't. If it is or might be from a constraint, we have to
1780 * fetch the pg_constraint record.
1781 */
1782 if (index->primary || index->unique || idxrec->indisexclusion)
1783 {
1785
1787 {
1790
1791 if (constraintOid)
1793
1797 elog(ERROR, "cache lookup failed for constraint %u",
1798 constraintId);
1800
1801 index->isconstraint = true;
1802 index->deferrable = conrec->condeferrable;
1803 index->initdeferred = conrec->condeferred;
1804
1805 /* If it's an exclusion constraint, we need the operator names */
1806 if (idxrec->indisexclusion)
1807 {
1808 Datum *elems;
1809 int nElems;
1810 int i;
1811
1812 Assert(conrec->contype == CONSTRAINT_EXCLUSION ||
1813 (index->iswithoutoverlaps &&
1814 (conrec->contype == CONSTRAINT_PRIMARY || conrec->contype == CONSTRAINT_UNIQUE)));
1815 /* Extract operator OIDs from the pg_constraint tuple */
1818 deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
1819
1820 for (i = 0; i < nElems; i++)
1821 {
1822 Oid operid = DatumGetObjectId(elems[i]);
1825 char *oprname;
1826 char *nspname;
1827 List *namelist;
1828
1832 elog(ERROR, "cache lookup failed for operator %u",
1833 operid);
1835 oprname = pstrdup(NameStr(operform->oprname));
1836 /* For simplicity we always schema-qualify the op name */
1837 nspname = get_namespace_name(operform->oprnamespace);
1838 namelist = list_make2(makeString(nspname),
1839 makeString(oprname));
1840 index->excludeOpNames = lappend(index->excludeOpNames,
1841 namelist);
1843 }
1844 }
1845
1847 }
1848 else
1849 index->isconstraint = false;
1850 }
1851 else
1852 index->isconstraint = false;
1853
1854 /* Get the index expressions, if any */
1856 Anum_pg_index_indexprs, &isnull);
1857 if (!isnull)
1858 {
1859 char *exprsString;
1860
1863 }
1864 else
1865 indexprs = NIL;
1866
1867 /* Build the list of IndexElem */
1868 index->indexParams = NIL;
1869 index->indexIncludingParams = NIL;
1870
1872 for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1873 {
1875 AttrNumber attnum = idxrec->indkey.values[keyno];
1877 keyno);
1878 int16 opt = source_idx->rd_indoption[keyno];
1879
1881
1883 {
1884 /* Simple index column */
1885 char *attname;
1886
1889
1890 iparam->name = attname;
1891 iparam->expr = NULL;
1892 }
1893 else
1894 {
1895 /* Expressional index */
1896 Node *indexkey;
1897 bool found_whole_row;
1898
1899 if (indexpr_item == NULL)
1900 elog(ERROR, "too few entries in indexprs list");
1903
1904 /* Adjust Vars to match new table's column numbering */
1906 1, 0,
1907 attmap,
1908 InvalidOid, &found_whole_row);
1909
1910 /* As in expandTableLikeClause, reject whole-row variables */
1911 if (found_whole_row)
1912 ereport(ERROR,
1914 errmsg("cannot convert whole-row table reference"),
1915 errdetail("Index \"%s\" contains a whole-row table reference.",
1917
1918 iparam->name = NULL;
1919 iparam->expr = indexkey;
1920
1922 }
1923
1924 /* Copy the original index column name */
1925 iparam->indexcolname = pstrdup(NameStr(attr->attname));
1926
1927 /* Add the collation name, if non-default */
1928 iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1929
1930 /* Add the operator class name, if non-default */
1931 iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1932 iparam->opclassopts =
1934
1935 iparam->ordering = SORTBY_DEFAULT;
1936 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1937
1938 /* Adjust options if necessary */
1939 if (source_idx->rd_indam->amcanorder)
1940 {
1941 /*
1942 * If it supports sort ordering, copy DESC and NULLS opts. Don't
1943 * set non-default settings unnecessarily, though, so as to
1944 * improve the chance of recognizing equivalence to constraint
1945 * indexes.
1946 */
1947 if (opt & INDOPTION_DESC)
1948 {
1949 iparam->ordering = SORTBY_DESC;
1950 if ((opt & INDOPTION_NULLS_FIRST) == 0)
1951 iparam->nulls_ordering = SORTBY_NULLS_LAST;
1952 }
1953 else
1954 {
1955 if (opt & INDOPTION_NULLS_FIRST)
1956 iparam->nulls_ordering = SORTBY_NULLS_FIRST;
1957 }
1958 }
1959
1960 iparam->location = -1;
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 {
1969 AttrNumber attnum = idxrec->indkey.values[keyno];
1971 keyno);
1972
1974
1976 {
1977 /* Simple index column */
1978 char *attname;
1979
1981
1982 iparam->name = attname;
1983 iparam->expr = NULL;
1984 }
1985 else
1986 ereport(ERROR,
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 iparam->location = -1;
1994
1995 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1996 }
1997 /* Copy reloptions if any */
1999 Anum_pg_class_reloptions, &isnull);
2000 if (!isnull)
2001 index->options = untransformRelOptions(datum);
2002
2003 /* If it's a partial index, decompile and append the predicate */
2005 Anum_pg_index_indpred, &isnull);
2006 if (!isnull)
2007 {
2008 char *pred_str;
2009 Node *pred_tree;
2010 bool found_whole_row;
2011
2012 /* Convert text string to node tree */
2015
2016 /* Adjust Vars to match new table's column numbering */
2018 1, 0,
2019 attmap,
2020 InvalidOid, &found_whole_row);
2021
2022 /* As in expandTableLikeClause, reject whole-row variables */
2023 if (found_whole_row)
2024 ereport(ERROR,
2026 errmsg("cannot convert whole-row table reference"),
2027 errdetail("Index \"%s\" contains a whole-row table reference.",
2029
2030 index->whereClause = pred_tree;
2031 }
2032
2033 /* Clean up */
2036
2037 return index;
2038}
2039
2040/*
2041 * Generate a CreateStatsStmt node using information from an already existing
2042 * extended statistic "source_statsid", for the rel identified by heapRel and
2043 * heapRelid.
2044 *
2045 * Attribute numbers in expression Vars are adjusted according to attmap.
2046 */
2047static CreateStatsStmt *
2050{
2053 CreateStatsStmt *stats;
2054 List *stat_types = NIL;
2055 List *def_names = NIL;
2056 bool isnull;
2057 Datum datum;
2058 ArrayType *arr;
2059 char *enabled;
2060 int i;
2061
2063 Assert(heapRel != NULL);
2064
2065 /*
2066 * Fetch pg_statistic_ext tuple of source statistics object.
2067 */
2070 elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
2072
2073 /* Determine which statistics types exist */
2076 arr = DatumGetArrayTypeP(datum);
2077 if (ARR_NDIM(arr) != 1 ||
2078 ARR_HASNULL(arr) ||
2079 ARR_ELEMTYPE(arr) != CHAROID)
2080 elog(ERROR, "stxkind is not a 1-D char array");
2081 enabled = (char *) ARR_DATA_PTR(arr);
2082 for (i = 0; i < ARR_DIMS(arr)[0]; i++)
2083 {
2084 if (enabled[i] == STATS_EXT_NDISTINCT)
2085 stat_types = lappend(stat_types, makeString("ndistinct"));
2086 else if (enabled[i] == STATS_EXT_DEPENDENCIES)
2087 stat_types = lappend(stat_types, makeString("dependencies"));
2088 else if (enabled[i] == STATS_EXT_MCV)
2089 stat_types = lappend(stat_types, makeString("mcv"));
2090 else if (enabled[i] == STATS_EXT_EXPRESSIONS)
2091 /* expression stats are not exposed to users */
2092 continue;
2093 else
2094 elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
2095 }
2096
2097 /* Determine which columns the statistics are on */
2098 for (i = 0; i < statsrec->stxkeys.dim1; i++)
2099 {
2101 AttrNumber attnum = statsrec->stxkeys.values[i];
2102
2103 selem->name = get_attname(heapRelid, attnum, false);
2104 selem->expr = NULL;
2105
2107 }
2108
2109 /*
2110 * Now handle expressions, if there are any. The order (with respect to
2111 * regular attributes) does not really matter for extended stats, so we
2112 * simply append them after simple column references.
2113 *
2114 * XXX Some places during build/estimation treat expressions as if they
2115 * are before attributes, but for the CREATE command that's entirely
2116 * irrelevant.
2117 */
2120
2121 if (!isnull)
2122 {
2123 ListCell *lc;
2124 List *exprs = NIL;
2125 char *exprsString;
2126
2128 exprs = (List *) stringToNode(exprsString);
2129
2130 foreach(lc, exprs)
2131 {
2132 Node *expr = (Node *) lfirst(lc);
2134 bool found_whole_row;
2135
2136 /* Adjust Vars to match new table's column numbering */
2137 expr = map_variable_attnos(expr,
2138 1, 0,
2139 attmap,
2140 InvalidOid,
2141 &found_whole_row);
2142
2143 selem->name = NULL;
2144 selem->expr = expr;
2145
2147 }
2148
2150 }
2151
2152 /* finally, build the output node */
2153 stats = makeNode(CreateStatsStmt);
2154 stats->defnames = NULL;
2155 stats->stat_types = stat_types;
2156 stats->exprs = def_names;
2157 stats->relations = list_make1(heapRel);
2158 stats->stxcomment = NULL;
2159 stats->transformed = true; /* don't need transformStatsStmt again */
2160 stats->if_not_exists = false;
2161
2162 /* Clean up */
2164
2165 return stats;
2166}
2167
2168/*
2169 * get_collation - fetch qualified name of a collation
2170 *
2171 * If collation is InvalidOid or is the default for the given actual_datatype,
2172 * then the return value is NIL.
2173 */
2174static List *
2176{
2177 List *result;
2180 char *nsp_name;
2181 char *coll_name;
2182
2183 if (!OidIsValid(collation))
2184 return NIL; /* easy case */
2185 if (collation == get_typcollation(actual_datatype))
2186 return NIL; /* just let it default */
2187
2190 elog(ERROR, "cache lookup failed for collation %u", collation);
2192
2193 /* For simplicity, we always schema-qualify the name */
2194 nsp_name = get_namespace_name(coll_rec->collnamespace);
2195 coll_name = pstrdup(NameStr(coll_rec->collname));
2197
2199 return result;
2200}
2201
2202/*
2203 * get_opclass - fetch qualified name of an index operator class
2204 *
2205 * If the opclass is the default for the given actual_datatype, then
2206 * the return value is NIL.
2207 */
2208static List *
2210{
2211 List *result = NIL;
2214
2217 elog(ERROR, "cache lookup failed for opclass %u", opclass);
2219
2220 if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2221 {
2222 /* For simplicity, we always schema-qualify the name */
2223 char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2224 char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2225
2227 }
2228
2230 return result;
2231}
2232
2233
2234/*
2235 * transformIndexConstraints
2236 * Handle UNIQUE, PRIMARY KEY, EXCLUDE constraints, which create indexes.
2237 * We also merge in any index definitions arising from
2238 * LIKE ... INCLUDING INDEXES.
2239 */
2240static void
2242{
2244 List *indexlist = NIL;
2246 ListCell *lc;
2247
2248 /*
2249 * Run through the constraints that need to generate an index, and do so.
2250 *
2251 * For PRIMARY KEY, this queues not-null constraints for each column, if
2252 * needed.
2253 */
2254 foreach(lc, cxt->ixconstraints)
2255 {
2256 Constraint *constraint = lfirst_node(Constraint, lc);
2257
2258 Assert(constraint->contype == CONSTR_PRIMARY ||
2259 constraint->contype == CONSTR_UNIQUE ||
2260 constraint->contype == CONSTR_EXCLUSION);
2261
2262 index = transformIndexConstraint(constraint, cxt);
2263
2264 indexlist = lappend(indexlist, index);
2265 }
2266
2267 /*
2268 * Scan the index list and remove any redundant index specifications. This
2269 * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2270 * strict reading of SQL would suggest raising an error instead, but that
2271 * strikes me as too anal-retentive. - tgl 2001-02-14
2272 *
2273 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2274 * pre-existing indexes, too.
2275 */
2276 if (cxt->pkey != NULL)
2277 {
2278 /* Make sure we keep the PKEY index in preference to others... */
2280 }
2281
2282 foreach(lc, indexlist)
2283 {
2284 bool keep = true;
2285 ListCell *k;
2286
2287 index = lfirst(lc);
2288
2289 /* if it's pkey, it's already in finalindexlist */
2290 if (index == cxt->pkey)
2291 continue;
2292
2293 foreach(k, finalindexlist)
2294 {
2296
2297 if (equal(index->indexParams, priorindex->indexParams) &&
2298 equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2299 equal(index->whereClause, priorindex->whereClause) &&
2300 equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2301 strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2302 index->nulls_not_distinct == priorindex->nulls_not_distinct &&
2303 index->deferrable == priorindex->deferrable &&
2304 index->initdeferred == priorindex->initdeferred)
2305 {
2306 priorindex->unique |= index->unique;
2307
2308 /*
2309 * If the prior index is as yet unnamed, and this one is
2310 * named, then transfer the name to the prior index. This
2311 * ensures that if we have named and unnamed constraints,
2312 * we'll use (at least one of) the names for the index.
2313 */
2314 if (priorindex->idxname == NULL)
2315 priorindex->idxname = index->idxname;
2316 keep = false;
2317 break;
2318 }
2319 }
2320
2321 if (keep)
2323 }
2324
2325 /*
2326 * Now append all the IndexStmts to cxt->alist.
2327 */
2328 cxt->alist = list_concat(cxt->alist, finalindexlist);
2329}
2330
2331/*
2332 * transformIndexConstraint
2333 * Transform one UNIQUE, PRIMARY KEY, or EXCLUDE constraint for
2334 * transformIndexConstraints. An IndexStmt is returned.
2335 *
2336 * For a PRIMARY KEY constraint, we additionally create not-null constraints
2337 * for columns that don't already have them.
2338 */
2339static IndexStmt *
2341{
2343 ListCell *lc;
2344
2346
2347 index->unique = (constraint->contype != CONSTR_EXCLUSION);
2348 index->primary = (constraint->contype == CONSTR_PRIMARY);
2349 if (index->primary)
2350 {
2351 if (cxt->pkey != NULL)
2352 ereport(ERROR,
2354 errmsg("multiple primary keys for table \"%s\" are not allowed",
2355 cxt->relation->relname),
2356 parser_errposition(cxt->pstate, constraint->location)));
2357 cxt->pkey = index;
2358
2359 /*
2360 * In ALTER TABLE case, a primary index might already exist, but
2361 * DefineIndex will check for it.
2362 */
2363 }
2364 index->nulls_not_distinct = constraint->nulls_not_distinct;
2365 index->isconstraint = true;
2366 index->iswithoutoverlaps = constraint->without_overlaps;
2367 index->deferrable = constraint->deferrable;
2368 index->initdeferred = constraint->initdeferred;
2369
2370 if (constraint->conname != NULL)
2371 index->idxname = pstrdup(constraint->conname);
2372 else
2373 index->idxname = NULL; /* DefineIndex will choose name */
2374
2375 index->relation = cxt->relation;
2376 index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2377 index->options = constraint->options;
2378 index->tableSpace = constraint->indexspace;
2379 index->whereClause = constraint->where_clause;
2380 index->indexParams = NIL;
2381 index->indexIncludingParams = NIL;
2382 index->excludeOpNames = NIL;
2383 index->idxcomment = NULL;
2384 index->indexOid = InvalidOid;
2385 index->oldNumber = InvalidRelFileNumber;
2386 index->oldCreateSubid = InvalidSubTransactionId;
2387 index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
2388 index->transformed = false;
2389 index->concurrent = false;
2390 index->if_not_exists = false;
2391 index->reset_default_tblspc = constraint->reset_default_tblspc;
2392
2393 /*
2394 * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2395 * verify it's usable, then extract the implied column name list. (We
2396 * will not actually need the column name list at runtime, but we need it
2397 * now to check for duplicate column entries below.)
2398 */
2399 if (constraint->indexname != NULL)
2400 {
2401 char *index_name = constraint->indexname;
2402 Relation heap_rel = cxt->rel;
2403 Oid index_oid;
2408 int i;
2409
2410 /* Grammar should not allow this with explicit column list */
2411 Assert(constraint->keys == NIL);
2412
2413 /* Grammar should only allow PRIMARY and UNIQUE constraints */
2414 Assert(constraint->contype == CONSTR_PRIMARY ||
2415 constraint->contype == CONSTR_UNIQUE);
2416
2417 /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2418 if (!cxt->isalter)
2419 ereport(ERROR,
2421 errmsg("cannot use an existing index in CREATE TABLE"),
2422 parser_errposition(cxt->pstate, constraint->location)));
2423
2424 /* Look for the index in the same schema as the table */
2426
2427 if (!OidIsValid(index_oid))
2428 ereport(ERROR,
2430 errmsg("index \"%s\" does not exist", index_name),
2431 parser_errposition(cxt->pstate, constraint->location)));
2432
2433 /* Open the index (this will throw an error if it is not an index) */
2435 index_form = index_rel->rd_index;
2436
2437 /* Check that it does not have an associated constraint already */
2439 ereport(ERROR,
2441 errmsg("index \"%s\" is already associated with a constraint",
2442 index_name),
2443 parser_errposition(cxt->pstate, constraint->location)));
2444
2445 /* Perform validity checks on the index */
2446 if (index_form->indrelid != RelationGetRelid(heap_rel))
2447 ereport(ERROR,
2449 errmsg("index \"%s\" does not belong to table \"%s\"",
2451 parser_errposition(cxt->pstate, constraint->location)));
2452
2453 if (!index_form->indisvalid)
2454 ereport(ERROR,
2456 errmsg("index \"%s\" is not valid", index_name),
2457 parser_errposition(cxt->pstate, constraint->location)));
2458
2459 /*
2460 * Today we forbid non-unique indexes, but we could permit GiST
2461 * indexes whose last entry is a range type and use that to create a
2462 * WITHOUT OVERLAPS constraint (i.e. a temporal constraint).
2463 */
2464 if (!index_form->indisunique)
2465 ereport(ERROR,
2467 errmsg("\"%s\" is not a unique index", index_name),
2468 errdetail("Cannot create a primary key or unique constraint using such an index."),
2469 parser_errposition(cxt->pstate, constraint->location)));
2470
2472 ereport(ERROR,
2474 errmsg("index \"%s\" contains expressions", index_name),
2475 errdetail("Cannot create a primary key or unique constraint using such an index."),
2476 parser_errposition(cxt->pstate, constraint->location)));
2477
2479 ereport(ERROR,
2481 errmsg("\"%s\" is a partial index", index_name),
2482 errdetail("Cannot create a primary key or unique constraint using such an index."),
2483 parser_errposition(cxt->pstate, constraint->location)));
2484
2485 /*
2486 * It's probably unsafe to change a deferred index to non-deferred. (A
2487 * non-constraint index couldn't be deferred anyway, so this case
2488 * should never occur; no need to sweat, but let's check it.)
2489 */
2490 if (!index_form->indimmediate && !constraint->deferrable)
2491 ereport(ERROR,
2493 errmsg("\"%s\" is a deferrable index", index_name),
2494 errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2495 parser_errposition(cxt->pstate, constraint->location)));
2496
2497 /*
2498 * Insist on it being a btree. We must have an index that exactly
2499 * matches what you'd get from plain ADD CONSTRAINT syntax, else dump
2500 * and reload will produce a different index (breaking pg_upgrade in
2501 * particular).
2502 */
2503 if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2504 ereport(ERROR,
2506 errmsg("index \"%s\" is not a btree", index_name),
2507 parser_errposition(cxt->pstate, constraint->location)));
2508
2509 /* Must get indclass the hard way */
2511 index_rel->rd_indextuple,
2514
2515 for (i = 0; i < index_form->indnatts; i++)
2516 {
2517 int16 attnum = index_form->indkey.values[i];
2519 char *attname;
2521
2522 /*
2523 * We shouldn't see attnum == 0 here, since we already rejected
2524 * expression indexes. If we do, SystemAttributeDefinition will
2525 * throw an error.
2526 */
2527 if (attnum > 0)
2528 {
2529 Assert(attnum <= heap_rel->rd_att->natts);
2530 attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2531 }
2532 else
2534 attname = pstrdup(NameStr(attform->attname));
2535
2537 {
2538 /*
2539 * Insist on default opclass, collation, and sort options.
2540 * While the index would still work as a constraint with
2541 * non-default settings, it might not provide exactly the same
2542 * uniqueness semantics as you'd get from a normally-created
2543 * constraint; and there's also the dump/reload problem
2544 * mentioned above.
2545 */
2546 Datum attoptions =
2548
2550 index_rel->rd_rel->relam);
2551 if (indclass->values[i] != defopclass ||
2552 attform->attcollation != index_rel->rd_indcollation[i] ||
2553 attoptions != (Datum) 0 ||
2554 index_rel->rd_indoption[i] != 0)
2555 ereport(ERROR,
2557 errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2558 errdetail("Cannot create a primary key or unique constraint using such an index."),
2559 parser_errposition(cxt->pstate, constraint->location)));
2560
2561 /* If a PK, ensure the columns get not null constraints */
2562 if (constraint->contype == CONSTR_PRIMARY)
2563 cxt->nnconstraints =
2566
2567 constraint->keys = lappend(constraint->keys, makeString(attname));
2568 }
2569 else
2570 constraint->including = lappend(constraint->including, makeString(attname));
2571 }
2572
2573 /* Close the index relation but keep the lock */
2575
2576 index->indexOid = index_oid;
2577 }
2578
2579 /*
2580 * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2581 * IndexElems and operator names. We have to break that apart into
2582 * separate lists.
2583 */
2584 if (constraint->contype == CONSTR_EXCLUSION)
2585 {
2586 foreach(lc, constraint->exclusions)
2587 {
2588 List *pair = (List *) lfirst(lc);
2589 IndexElem *elem;
2590 List *opname;
2591
2592 Assert(list_length(pair) == 2);
2593 elem = linitial_node(IndexElem, pair);
2595
2596 index->indexParams = lappend(index->indexParams, elem);
2597 index->excludeOpNames = lappend(index->excludeOpNames, opname);
2598 }
2599 }
2600
2601 /*
2602 * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2603 *
2604 * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2605 * also make sure they are not-null. For WITHOUT OVERLAPS constraints, we
2606 * make sure the last part is a range or multirange.
2607 */
2608 else
2609 {
2610 foreach(lc, constraint->keys)
2611 {
2612 char *key = strVal(lfirst(lc));
2613 bool found = false;
2615 ListCell *columns;
2617 Oid typid = InvalidOid;
2618
2619 /* Make sure referenced column exists. */
2620 foreach(columns, cxt->columns)
2621 {
2622 column = lfirst_node(ColumnDef, columns);
2623 if (strcmp(column->colname, key) == 0)
2624 {
2625 found = true;
2626 break;
2627 }
2628 }
2629 if (!found)
2630 column = NULL;
2631
2632 if (found)
2633 {
2634 /*
2635 * column is defined in the new table. For CREATE TABLE with
2636 * a PRIMARY KEY, we can apply the not-null constraint cheaply
2637 * here. If the not-null constraint already exists, we can
2638 * (albeit not so cheaply) verify that it's not a NO INHERIT
2639 * constraint.
2640 *
2641 * Note that ALTER TABLE never needs either check, because
2642 * those constraints have already been added by
2643 * ATPrepAddPrimaryKey.
2644 */
2645 if (constraint->contype == CONSTR_PRIMARY &&
2646 !cxt->isalter)
2647 {
2648 if (column->is_not_null)
2649 {
2651 {
2652 if (strcmp(strVal(linitial(nn->keys)), key) == 0)
2653 {
2654 if (nn->is_no_inherit)
2655 ereport(ERROR,
2657 errmsg("conflicting NO INHERIT declaration for not-null constraint on column \"%s\"",
2658 key));
2659 break;
2660 }
2661 }
2662 }
2663 else
2664 {
2665 column->is_not_null = true;
2666 cxt->nnconstraints =
2669 }
2670 }
2671 else if (constraint->contype == CONSTR_PRIMARY)
2672 Assert(column->is_not_null);
2673 }
2674 else if (SystemAttributeByName(key) != NULL)
2675 {
2676 /*
2677 * column will be a system column in the new table, so accept
2678 * it. System columns can't ever be null, so no need to worry
2679 * about PRIMARY/NOT NULL constraint.
2680 */
2681 found = true;
2682 }
2683 else if (cxt->inhRelations)
2684 {
2685 /* try inherited tables */
2686 ListCell *inher;
2687
2688 foreach(inher, cxt->inhRelations)
2689 {
2691 Relation rel;
2692 int count;
2693
2694 rel = table_openrv(inh, AccessShareLock);
2695 /* check user requested inheritance from valid relkind */
2696 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2697 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2698 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2699 ereport(ERROR,
2701 errmsg("inherited relation \"%s\" is not a table or foreign table",
2702 inh->relname)));
2703 for (count = 0; count < rel->rd_att->natts; count++)
2704 {
2706 count);
2707 char *inhname = NameStr(inhattr->attname);
2708
2709 if (inhattr->attisdropped)
2710 continue;
2711 if (strcmp(key, inhname) == 0)
2712 {
2713 found = true;
2714 typid = inhattr->atttypid;
2715
2716 if (constraint->contype == CONSTR_PRIMARY)
2717 cxt->nnconstraints =
2720 break;
2721 }
2722 }
2723 table_close(rel, NoLock);
2724 if (found)
2725 break;
2726 }
2727 }
2728
2729 /*
2730 * In the ALTER TABLE case, don't complain about index keys not
2731 * created in the command; they may well exist already.
2732 * DefineIndex will complain about them if not.
2733 */
2734 if (!found && !cxt->isalter)
2735 ereport(ERROR,
2737 errmsg("column \"%s\" named in key does not exist", key),
2738 parser_errposition(cxt->pstate, constraint->location)));
2739
2740 /* Check for PRIMARY KEY(foo, foo) */
2741 foreach(columns, index->indexParams)
2742 {
2743 iparam = (IndexElem *) lfirst(columns);
2744 if (iparam->name && strcmp(key, iparam->name) == 0)
2745 {
2746 if (index->primary)
2747 ereport(ERROR,
2749 errmsg("column \"%s\" appears twice in primary key constraint",
2750 key),
2751 parser_errposition(cxt->pstate, constraint->location)));
2752 else
2753 ereport(ERROR,
2755 errmsg("column \"%s\" appears twice in unique constraint",
2756 key),
2757 parser_errposition(cxt->pstate, constraint->location)));
2758 }
2759 }
2760
2761 /*
2762 * The WITHOUT OVERLAPS part (if any) must be a range or
2763 * multirange type, or a domain over such a type.
2764 */
2765 if (constraint->without_overlaps && lc == list_last_cell(constraint->keys))
2766 {
2767 if (!found && cxt->isalter)
2768 {
2769 /*
2770 * Look up the column type on existing table. If we can't
2771 * find it, let things fail in DefineIndex.
2772 */
2773 Relation rel = cxt->rel;
2774
2775 for (int i = 0; i < rel->rd_att->natts; i++)
2776 {
2778 const char *attname;
2779
2780 if (attr->attisdropped)
2781 continue;
2782 attname = NameStr(attr->attname);
2783 if (strcmp(attname, key) == 0)
2784 {
2785 found = true;
2786 typid = attr->atttypid;
2787 break;
2788 }
2789 }
2790 }
2791 if (found)
2792 {
2793 /* Look up column type if we didn't already */
2794 if (!OidIsValid(typid) && column)
2795 typid = typenameTypeId(cxt->pstate,
2796 column->typeName);
2797 /* Look through any domain */
2798 if (OidIsValid(typid))
2799 typid = getBaseType(typid);
2800 /* Complain if not range/multirange */
2801 if (!OidIsValid(typid) ||
2802 !(type_is_range(typid) || type_is_multirange(typid)))
2803 ereport(ERROR,
2805 errmsg("column \"%s\" in WITHOUT OVERLAPS is not a range or multirange type", key),
2806 parser_errposition(cxt->pstate, constraint->location)));
2807 }
2808 }
2809
2810 /* OK, add it to the index definition */
2812 iparam->name = pstrdup(key);
2813 iparam->expr = NULL;
2814 iparam->indexcolname = NULL;
2815 iparam->collation = NIL;
2816 iparam->opclass = NIL;
2817 iparam->opclassopts = NIL;
2818 iparam->ordering = SORTBY_DEFAULT;
2819 iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
2820 iparam->location = -1;
2821 index->indexParams = lappend(index->indexParams, iparam);
2822 }
2823
2824 if (constraint->without_overlaps)
2825 {
2826 /*
2827 * This enforces that there is at least one equality column
2828 * besides the WITHOUT OVERLAPS columns. This is per SQL
2829 * standard. XXX Do we need this?
2830 */
2831 if (list_length(constraint->keys) < 2)
2832 ereport(ERROR,
2834 errmsg("constraint using WITHOUT OVERLAPS needs at least two columns"));
2835
2836 /* WITHOUT OVERLAPS requires a GiST index */
2837 index->accessMethod = "gist";
2838 }
2839
2840 }
2841
2842 /*
2843 * Add included columns to index definition. This is much like the
2844 * simple-column-name-list code above, except that we don't worry about
2845 * NOT NULL marking; included columns in a primary key should not be
2846 * forced NOT NULL. We don't complain about duplicate columns, either,
2847 * though maybe we should?
2848 */
2849 foreach(lc, constraint->including)
2850 {
2851 char *key = strVal(lfirst(lc));
2852 bool found = false;
2854 ListCell *columns;
2856
2857 foreach(columns, cxt->columns)
2858 {
2859 column = lfirst_node(ColumnDef, columns);
2860 if (strcmp(column->colname, key) == 0)
2861 {
2862 found = true;
2863 break;
2864 }
2865 }
2866
2867 if (!found)
2868 {
2869 if (SystemAttributeByName(key) != NULL)
2870 {
2871 /*
2872 * column will be a system column in the new table, so accept
2873 * it.
2874 */
2875 found = true;
2876 }
2877 else if (cxt->inhRelations)
2878 {
2879 /* try inherited tables */
2880 ListCell *inher;
2881
2882 foreach(inher, cxt->inhRelations)
2883 {
2885 Relation rel;
2886 int count;
2887
2888 rel = table_openrv(inh, AccessShareLock);
2889 /* check user requested inheritance from valid relkind */
2890 if (rel->rd_rel->relkind != RELKIND_RELATION &&
2891 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2892 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2893 ereport(ERROR,
2895 errmsg("inherited relation \"%s\" is not a table or foreign table",
2896 inh->relname)));
2897 for (count = 0; count < rel->rd_att->natts; count++)
2898 {
2900 count);
2901 char *inhname = NameStr(inhattr->attname);
2902
2903 if (inhattr->attisdropped)
2904 continue;
2905 if (strcmp(key, inhname) == 0)
2906 {
2907 found = true;
2908 break;
2909 }
2910 }
2911 table_close(rel, NoLock);
2912 if (found)
2913 break;
2914 }
2915 }
2916 }
2917
2918 /*
2919 * In the ALTER TABLE case, don't complain about index keys not
2920 * created in the command; they may well exist already. DefineIndex
2921 * will complain about them if not.
2922 */
2923 if (!found && !cxt->isalter)
2924 ereport(ERROR,
2926 errmsg("column \"%s\" named in key does not exist", key),
2927 parser_errposition(cxt->pstate, constraint->location)));
2928
2929 /* OK, add it to the index definition */
2931 iparam->name = pstrdup(key);
2932 iparam->expr = NULL;
2933 iparam->indexcolname = NULL;
2934 iparam->collation = NIL;
2935 iparam->opclass = NIL;
2936 iparam->opclassopts = NIL;
2937 iparam->location = -1;
2938 index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2939 }
2940
2941 return index;
2942}
2943
2944/*
2945 * transformCheckConstraints
2946 * handle CHECK constraints
2947 *
2948 * Right now, there's nothing to do here when called from ALTER TABLE,
2949 * but the other constraint-transformation functions are called in both
2950 * the CREATE TABLE and ALTER TABLE paths, so do the same here, and just
2951 * don't do anything if we're not authorized to skip validation.
2952 */
2953static void
2955{
2957
2958 if (cxt->ckconstraints == NIL)
2959 return;
2960
2961 /*
2962 * When creating a new table (but not a foreign table), we can safely skip
2963 * the validation of check constraints and mark them as valid based on the
2964 * constraint enforcement flag, since NOT ENFORCED constraints must always
2965 * be marked as NOT VALID. (This will override any user-supplied NOT VALID
2966 * flag.)
2967 */
2968 if (skipValidation)
2969 {
2970 foreach(ckclist, cxt->ckconstraints)
2971 {
2972 Constraint *constraint = (Constraint *) lfirst(ckclist);
2973
2974 constraint->skip_validation = true;
2975 constraint->initially_valid = constraint->is_enforced;
2976 }
2977 }
2978}
2979
2980/*
2981 * transformFKConstraints
2982 * handle FOREIGN KEY constraints
2983 */
2984static void
2987{
2989
2990 if (cxt->fkconstraints == NIL)
2991 return;
2992
2993 /*
2994 * If CREATE TABLE or adding a column with NULL default, we can safely
2995 * skip validation of FK constraints, and mark them as valid based on the
2996 * constraint enforcement flag, since NOT ENFORCED constraints must always
2997 * be marked as NOT VALID. (This will override any user-supplied NOT VALID
2998 * flag.)
2999 */
3000 if (skipValidation)
3001 {
3002 foreach(fkclist, cxt->fkconstraints)
3003 {
3004 Constraint *constraint = (Constraint *) lfirst(fkclist);
3005
3006 constraint->skip_validation = true;
3007 constraint->initially_valid = constraint->is_enforced;
3008 }
3009 }
3010
3011 /*
3012 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
3013 * CONSTRAINT command to execute after the basic command is complete. (If
3014 * called from ADD CONSTRAINT, that routine will add the FK constraints to
3015 * its own subcommand list.)
3016 *
3017 * Note: the ADD CONSTRAINT command must also execute after any index
3018 * creation commands. Thus, this should run after
3019 * transformIndexConstraints, so that the CREATE INDEX commands are
3020 * already in cxt->alist. See also the handling of cxt->likeclauses.
3021 */
3022 if (!isAddConstraint)
3023 {
3025
3026 alterstmt->relation = cxt->relation;
3027 alterstmt->cmds = NIL;
3028 alterstmt->objtype = OBJECT_TABLE;
3029
3030 foreach(fkclist, cxt->fkconstraints)
3031 {
3032 Constraint *constraint = (Constraint *) lfirst(fkclist);
3034
3035 altercmd->subtype = AT_AddConstraint;
3036 altercmd->name = NULL;
3037 altercmd->def = (Node *) constraint;
3038 alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
3039 }
3040
3041 cxt->alist = lappend(cxt->alist, alterstmt);
3042 }
3043}
3044
3045/*
3046 * transformIndexStmt - parse analysis for CREATE INDEX and ALTER TABLE
3047 *
3048 * Note: this is a no-op for an index not using either index expressions or
3049 * a predicate expression. There are several code paths that create indexes
3050 * without bothering to call this, because they know they don't have any
3051 * such expressions to deal with.
3052 *
3053 * To avoid race conditions, it's important that this function rely only on
3054 * the passed-in relid (and not on stmt->relation) to determine the target
3055 * relation.
3056 */
3057IndexStmt *
3058transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
3059{
3060 ParseState *pstate;
3062 ListCell *l;
3063 Relation rel;
3064
3065 /* Nothing to do if statement already transformed. */
3066 if (stmt->transformed)
3067 return stmt;
3068
3069 /* Set up pstate */
3070 pstate = make_parsestate(NULL);
3071 pstate->p_sourcetext = queryString;
3072
3073 /*
3074 * Put the parent table into the rtable so that the expressions can refer
3075 * to its fields without qualification. Caller is responsible for locking
3076 * relation, but we still need to open it.
3077 */
3078 rel = relation_open(relid, NoLock);
3081 NULL, false, true);
3082
3083 /* no to join list, yes to namespaces */
3084 addNSItemToQuery(pstate, nsitem, false, true, true);
3085
3086 /* take care of the where clause */
3087 if (stmt->whereClause)
3088 {
3089 stmt->whereClause = transformWhereClause(pstate,
3090 stmt->whereClause,
3092 "WHERE");
3093 /* we have to fix its collations too */
3094 assign_expr_collations(pstate, stmt->whereClause);
3095 }
3096
3097 /* take care of any index expressions */
3098 foreach(l, stmt->indexParams)
3099 {
3100 IndexElem *ielem = (IndexElem *) lfirst(l);
3101
3102 if (ielem->expr)
3103 {
3104 /* Extract preliminary index col name before transforming expr */
3105 if (ielem->indexcolname == NULL)
3107
3108 /* Now do parse transformation of the expression */
3109 ielem->expr = transformExpr(pstate, ielem->expr,
3111
3112 /* We have to fix its collations too */
3113 assign_expr_collations(pstate, ielem->expr);
3114
3115 /*
3116 * transformExpr() should have already rejected subqueries,
3117 * aggregates, window functions, and SRFs, based on the EXPR_KIND_
3118 * for an index expression.
3119 *
3120 * DefineIndex() will make more checks.
3121 */
3122 }
3123 }
3124
3125 /*
3126 * Check that only the base rel is mentioned. (This should be dead code
3127 * now that add_missing_from is history.)
3128 */
3129 if (list_length(pstate->p_rtable) != 1)
3130 ereport(ERROR,
3132 errmsg("index expressions and predicates can refer only to the table being indexed")));
3133
3134 free_parsestate(pstate);
3135
3136 /* Close relation */
3137 table_close(rel, NoLock);
3138
3139 /* Mark statement as successfully transformed */
3140 stmt->transformed = true;
3141
3142 return stmt;
3143}
3144
3145/*
3146 * transformStatsStmt - parse analysis for CREATE STATISTICS
3147 *
3148 * To avoid race conditions, it's important that this function relies only on
3149 * the passed-in relid (and not on stmt->relation) to determine the target
3150 * relation.
3151 */
3153transformStatsStmt(Oid relid, CreateStatsStmt *stmt, const char *queryString)
3154{
3155 ParseState *pstate;
3157 ListCell *l;
3158 Relation rel;
3159
3160 /* Nothing to do if statement already transformed. */
3161 if (stmt->transformed)
3162 return stmt;
3163
3164 /* Set up pstate */
3165 pstate = make_parsestate(NULL);
3166 pstate->p_sourcetext = queryString;
3167
3168 /*
3169 * Put the parent table into the rtable so that the expressions can refer
3170 * to its fields without qualification. Caller is responsible for locking
3171 * relation, but we still need to open it.
3172 */
3173 rel = relation_open(relid, NoLock);
3176 NULL, false, true);
3177
3178 /* no to join list, yes to namespaces */
3179 addNSItemToQuery(pstate, nsitem, false, true, true);
3180
3181 /* take care of any expressions */
3182 foreach(l, stmt->exprs)
3183 {
3184 StatsElem *selem = (StatsElem *) lfirst(l);
3185
3186 if (selem->expr)
3187 {
3188 /* Now do parse transformation of the expression */
3189 selem->expr = transformExpr(pstate, selem->expr,
3191
3192 /* We have to fix its collations too */
3193 assign_expr_collations(pstate, selem->expr);
3194 }
3195 }
3196
3197 /*
3198 * Check that only the base rel is mentioned. (This should be dead code
3199 * now that add_missing_from is history.)
3200 */
3201 if (list_length(pstate->p_rtable) != 1)
3202 ereport(ERROR,
3204 errmsg("statistics expressions can refer only to the table being referenced")));
3205
3206 free_parsestate(pstate);
3207
3208 /* Close relation */
3209 table_close(rel, NoLock);
3210
3211 /* Mark statement as successfully transformed */
3212 stmt->transformed = true;
3213
3214 return stmt;
3215}
3216
3217
3218/*
3219 * transformRuleStmt -
3220 * transform a CREATE RULE Statement. The action is a list of parse
3221 * trees which is transformed into a list of query trees, and we also
3222 * transform the WHERE clause if any.
3223 *
3224 * actions and whereClause are output parameters that receive the
3225 * transformed results.
3226 */
3227void
3228transformRuleStmt(RuleStmt *stmt, const char *queryString,
3229 List **actions, Node **whereClause)
3230{
3231 Relation rel;
3232 ParseState *pstate;
3235
3236 /*
3237 * To avoid deadlock, make sure the first thing we do is grab
3238 * AccessExclusiveLock on the target relation. This will be needed by
3239 * DefineQueryRewrite(), and we don't want to grab a lesser lock
3240 * beforehand.
3241 */
3242 rel = table_openrv(stmt->relation, AccessExclusiveLock);
3243
3244 if (rel->rd_rel->relkind == RELKIND_MATVIEW)
3245 ereport(ERROR,
3247 errmsg("rules on materialized views are not supported")));
3248
3249 /* Set up pstate */
3250 pstate = make_parsestate(NULL);
3251 pstate->p_sourcetext = queryString;
3252
3253 /*
3254 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
3255 * Set up their ParseNamespaceItems in the main pstate for use in parsing
3256 * the rule qualification.
3257 */
3260 makeAlias("old", NIL),
3261 false, false);
3264 makeAlias("new", NIL),
3265 false, false);
3266
3267 /*
3268 * They must be in the namespace too for lookup purposes, but only add the
3269 * one(s) that are relevant for the current kind of rule. In an UPDATE
3270 * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
3271 * there's no need to be so picky for INSERT & DELETE. We do not add them
3272 * to the joinlist.
3273 */
3274 switch (stmt->event)
3275 {
3276 case CMD_SELECT:
3277 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3278 break;
3279 case CMD_UPDATE:
3280 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3281 addNSItemToQuery(pstate, newnsitem, false, true, true);
3282 break;
3283 case CMD_INSERT:
3284 addNSItemToQuery(pstate, newnsitem, false, true, true);
3285 break;
3286 case CMD_DELETE:
3287 addNSItemToQuery(pstate, oldnsitem, false, true, true);
3288 break;
3289 default:
3290 elog(ERROR, "unrecognized event type: %d",
3291 (int) stmt->event);
3292 break;
3293 }
3294
3295 /* take care of the where clause */
3296 *whereClause = transformWhereClause(pstate,
3297 stmt->whereClause,
3299 "WHERE");
3300 /* we have to fix its collations too */
3301 assign_expr_collations(pstate, *whereClause);
3302
3303 /* this is probably dead code without add_missing_from: */
3304 if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3305 ereport(ERROR,
3307 errmsg("rule WHERE condition cannot contain references to other relations")));
3308
3309 /*
3310 * 'instead nothing' rules with a qualification need a query rangetable so
3311 * the rewrite handler can add the negated rule qualification to the
3312 * original query. We create a query with the new command type CMD_NOTHING
3313 * here that is treated specially by the rewrite system.
3314 */
3315 if (stmt->actions == NIL)
3316 {
3318
3319 nothing_qry->commandType = CMD_NOTHING;
3320 nothing_qry->rtable = pstate->p_rtable;
3321 nothing_qry->rteperminfos = pstate->p_rteperminfos;
3322 nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3323
3324 *actions = list_make1(nothing_qry);
3325 }
3326 else
3327 {
3328 ListCell *l;
3329 List *newactions = NIL;
3330
3331 /*
3332 * transform each statement, like parse_sub_analyze()
3333 */
3334 foreach(l, stmt->actions)
3335 {
3336 Node *action = (Node *) lfirst(l);
3338 Query *sub_qry,
3339 *top_subqry;
3340 bool has_old,
3341 has_new;
3342
3343 /*
3344 * Since outer ParseState isn't parent of inner, have to pass down
3345 * the query text by hand.
3346 */
3347 sub_pstate->p_sourcetext = queryString;
3348
3349 /*
3350 * Set up OLD/NEW in the rtable for this statement. The entries
3351 * are added only to relnamespace, not varnamespace, because we
3352 * don't want them to be referred to by unqualified field names
3353 * nor "*" in the rule actions. We decide later whether to put
3354 * them in the joinlist.
3355 */
3358 makeAlias("old", NIL),
3359 false, false);
3362 makeAlias("new", NIL),
3363 false, false);
3364 addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3365 addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3366
3367 /* Transform the rule action statement */
3369
3370 /*
3371 * We cannot support utility-statement actions (eg NOTIFY) with
3372 * nonempty rule WHERE conditions, because there's no way to make
3373 * the utility action execute conditionally.
3374 */
3375 if (top_subqry->commandType == CMD_UTILITY &&
3376 *whereClause != NULL)
3377 ereport(ERROR,
3379 errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3380
3381 /*
3382 * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3383 * into the SELECT, and that's what we need to look at. (Ugly
3384 * kluge ... try to fix this when we redesign querytrees.)
3385 */
3387
3388 /*
3389 * If the sub_qry is a setop, we cannot attach any qualifications
3390 * to it, because the planner won't notice them. This could
3391 * perhaps be relaxed someday, but for now, we may as well reject
3392 * such a rule immediately.
3393 */
3394 if (sub_qry->setOperations != NULL && *whereClause != NULL)
3395 ereport(ERROR,
3397 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3398
3399 /*
3400 * Validate action's use of OLD/NEW, qual too
3401 */
3402 has_old =
3404 rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3405 has_new =
3407 rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3408
3409 switch (stmt->event)
3410 {
3411 case CMD_SELECT:
3412 if (has_old)
3413 ereport(ERROR,
3415 errmsg("ON SELECT rule cannot use OLD")));
3416 if (has_new)
3417 ereport(ERROR,
3419 errmsg("ON SELECT rule cannot use NEW")));
3420 break;
3421 case CMD_UPDATE:
3422 /* both are OK */
3423 break;
3424 case CMD_INSERT:
3425 if (has_old)
3426 ereport(ERROR,
3428 errmsg("ON INSERT rule cannot use OLD")));
3429 break;
3430 case CMD_DELETE:
3431 if (has_new)
3432 ereport(ERROR,
3434 errmsg("ON DELETE rule cannot use NEW")));
3435 break;
3436 default:
3437 elog(ERROR, "unrecognized event type: %d",
3438 (int) stmt->event);
3439 break;
3440 }
3441
3442 /*
3443 * OLD/NEW are not allowed in WITH queries, because they would
3444 * amount to outer references for the WITH, which we disallow.
3445 * However, they were already in the outer rangetable when we
3446 * analyzed the query, so we have to check.
3447 *
3448 * Note that in the INSERT...SELECT case, we need to examine the
3449 * CTE lists of both top_subqry and sub_qry.
3450 *
3451 * Note that we aren't digging into the body of the query looking
3452 * for WITHs in nested sub-SELECTs. A WITH down there can
3453 * legitimately refer to OLD/NEW, because it'd be an
3454 * indirect-correlated outer reference.
3455 */
3456 if (rangeTableEntry_used((Node *) top_subqry->cteList,
3457 PRS2_OLD_VARNO, 0) ||
3458 rangeTableEntry_used((Node *) sub_qry->cteList,
3459 PRS2_OLD_VARNO, 0))
3460 ereport(ERROR,
3462 errmsg("cannot refer to OLD within WITH query")));
3463 if (rangeTableEntry_used((Node *) top_subqry->cteList,
3464 PRS2_NEW_VARNO, 0) ||
3465 rangeTableEntry_used((Node *) sub_qry->cteList,
3466 PRS2_NEW_VARNO, 0))
3467 ereport(ERROR,
3469 errmsg("cannot refer to NEW within WITH query")));
3470
3471 /*
3472 * For efficiency's sake, add OLD to the rule action's jointree
3473 * only if it was actually referenced in the statement or qual.
3474 *
3475 * For INSERT, NEW is not really a relation (only a reference to
3476 * the to-be-inserted tuple) and should never be added to the
3477 * jointree.
3478 *
3479 * For UPDATE, we treat NEW as being another kind of reference to
3480 * OLD, because it represents references to *transformed* tuples
3481 * of the existing relation. It would be wrong to enter NEW
3482 * separately in the jointree, since that would cause a double
3483 * join of the updated relation. It's also wrong to fail to make
3484 * a jointree entry if only NEW and not OLD is mentioned.
3485 */
3486 if (has_old || (has_new && stmt->event == CMD_UPDATE))
3487 {
3489
3490 /*
3491 * If sub_qry is a setop, manipulating its jointree will do no
3492 * good at all, because the jointree is dummy. (This should be
3493 * a can't-happen case because of prior tests.)
3494 */
3495 if (sub_qry->setOperations != NULL)
3496 ereport(ERROR,
3498 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3499 /* hackishly add OLD to the already-built FROM clause */
3501 rtr->rtindex = oldnsitem->p_rtindex;
3502 sub_qry->jointree->fromlist =
3503 lappend(sub_qry->jointree->fromlist, rtr);
3504 }
3505
3507
3509 }
3510
3511 *actions = newactions;
3512 }
3513
3514 free_parsestate(pstate);
3515
3516 /* Close relation, but keep the exclusive lock */
3517 table_close(rel, NoLock);
3518}
3519
3520
3521/*
3522 * checkPartition
3523 * Check whether partRelOid is a leaf partition of the parent table (rel).
3524 * isMerge: true indicates the operation is "ALTER TABLE ... MERGE PARTITIONS";
3525 * false indicates the operation is "ALTER TABLE ... SPLIT PARTITION".
3526 */
3527static void
3529{
3530 Relation partRel;
3531
3532 partRel = table_open(partRelOid, NoLock);
3533
3534 if (partRel->rd_rel->relkind != RELKIND_RELATION)
3535 ereport(ERROR,
3537 errmsg("\"%s\" is not a table", RelationGetRelationName(partRel)),
3538 isMerge
3539 ? errhint("ALTER TABLE ... MERGE PARTITIONS can only merge partitions don't have sub-partitions")
3540 : errhint("ALTER TABLE ... SPLIT PARTITION can only split partitions don't have sub-partitions"));
3541
3542 if (!partRel->rd_rel->relispartition)
3543 ereport(ERROR,
3545 errmsg("\"%s\" is not a partition of partitioned table \"%s\"",
3547 isMerge
3548 ? errhint("ALTER TABLE ... MERGE PARTITIONS can only merge partitions don't have sub-partitions")
3549 : errhint("ALTER TABLE ... SPLIT PARTITION can only split partitions don't have sub-partitions"));
3550
3552 ereport(ERROR,
3554 errmsg("relation \"%s\" is not a partition of relation \"%s\"",
3556 isMerge
3557 ? errhint("ALTER TABLE ... MERGE PARTITIONS can only merge partitions don't have sub-partitions")
3558 : errhint("ALTER TABLE ... SPLIT PARTITION can only split partitions don't have sub-partitions"));
3559
3560 table_close(partRel, NoLock);
3561}
3562
3563/*
3564 * transformPartitionCmdForSplit -
3565 * analyze the ALTER TABLE ... SPLIT PARTITION command
3566 *
3567 * For each new partition, sps->bound is set to the transformed value of bound.
3568 * Does checks for bounds of new partitions.
3569 */
3570static void
3572{
3573 Relation parent = cxt->rel;
3574 PartitionKey key;
3575 char strategy;
3578 int default_index = -1;
3579 bool isSplitPartDefault;
3581 *listptr2;
3582 List *splitlist;
3583
3584 splitlist = partcmd->partlist;
3585 key = RelationGetPartitionKey(parent);
3586 strategy = get_partition_strategy(key);
3588
3589 /* Transform partition bounds for all partitions in the list: */
3591 {
3592 cxt->partbound = NULL;
3593 transformPartitionCmd(cxt, sps->bound);
3594 /* Assign the transformed value of the partition bound. */
3595 sps->bound = cxt->partbound;
3596 }
3597
3598 /*
3599 * Open and lock the partition, check ownership along the way. We need to
3600 * use AccessExclusiveLock here because this split partition will be
3601 * detached, then dropped in ATExecSplitPartition.
3602 */
3605 NULL);
3606
3607 checkPartition(parent, splitPartOid, false);
3608
3609 switch (strategy)
3610 {
3613 {
3615 {
3616 if (sps->bound->is_default)
3617 {
3618 if (default_index != -1)
3619 ereport(ERROR,
3621 errmsg("DEFAULT partition should be one"),
3622 parser_errposition(cxt->pstate, sps->name->location));
3623
3624 default_index = foreach_current_index(sps);
3625 }
3626 }
3627 }
3628 break;
3629
3631 ereport(ERROR,
3633 errmsg("partition of hash-partitioned table cannot be split"));
3634 break;
3635
3636 default:
3637 elog(ERROR, "unexpected partition strategy: %d",
3638 (int) key->strategy);
3639 break;
3640 }
3641
3642 /* isSplitPartDefault: is the being split partition a DEFAULT partition? */
3644
3645 if (isSplitPartDefault && default_index == -1)
3646 ereport(ERROR,
3648 errmsg("can not split DEFAULT partition \"%s\"",
3650 errhint("To split DEFAULT partition one of the new partition msut be DEFAULT"),
3652
3653 /*
3654 * If the partition being split is not the DEFAULT partition, but the
3655 * DEFAULT partition exists, then none of the resulting split partitions
3656 * can be the DEFAULT.
3657 */
3658 if (!isSplitPartDefault && (default_index != -1) && OidIsValid(defaultPartOid))
3659 {
3661 (SinglePartitionSpec *) list_nth(splitlist, default_index);
3662
3663 ereport(ERROR,
3665 errmsg("can not split non-DEFAULT partition \"%s\"",
3667 errmsg("new partition cannot be DEFAULT because DEFAULT partition \"%s\" already exists",
3669 parser_errposition(cxt->pstate, spsDef->name->location));
3670 }
3671
3672 foreach(listptr, splitlist)
3673 {
3674 Oid nspid;
3676 RangeVar *name = sps->name;
3677
3679
3680 /* Partitions in the list should have different names. */
3682 {
3683 Oid nspid2;
3685 RangeVar *name2 = sps2->name;
3686
3687 if (equal(name, name2))
3688 ereport(ERROR,
3690 errmsg("partition with name \"%s\" is already used", name->relname),
3691 parser_errposition(cxt->pstate, name2->location));
3692
3694
3695 if (nspid2 == nspid && strcmp(name->relname, name2->relname) == 0)
3696 ereport(ERROR,
3698 errmsg("partition with name \"%s\" is already used", name->relname),
3699 parser_errposition(cxt->pstate, name2->location));
3700 }
3701 }
3702
3703 /* Then we should check partitions with transformed bounds. */
3705}
3706
3707
3708/*
3709 * transformPartitionCmdForMerge -
3710 * analyze the ALTER TABLE ... MERGE PARTITIONS command
3711 *
3712 * Does simple checks for merged partitions. Calculates bound of the resulting
3713 * partition.
3714 */
3715static void
3717{
3719 Oid partOid;
3720 Relation parent = cxt->rel;
3721 PartitionKey key;
3722 char strategy;
3724 *listptr2;
3725 bool isDefaultPart = false;
3726 List *partOids = NIL;
3727
3728 key = RelationGetPartitionKey(parent);
3729 strategy = get_partition_strategy(key);
3730
3731 if (strategy == PARTITION_STRATEGY_HASH)
3732 ereport(ERROR,
3734 errmsg("partition of hash-partitioned table cannot be merged"));
3735
3736 /* Does the partitioned table (parent) have a default partition? */
3738
3739 foreach(listptr, partcmd->partlist)
3740 {
3742
3743 /* Partitions in the list should have different names. */
3744 for_each_cell(listptr2, partcmd->partlist, lnext(partcmd->partlist, listptr))
3745 {
3747
3748 if (equal(name, name2))
3749 ereport(ERROR,
3751 errmsg("partition with name \"%s\" is already used", name->relname),
3752 parser_errposition(cxt->pstate, name2->location));
3753 }
3754
3755 /*
3756 * Search the DEFAULT partition in the list. Open and lock partitions
3757 * before calculating the boundary for resulting partition, we also
3758 * check for ownership along the way. We need to use
3759 * AccessExclusiveLock here, because these merged partitions will be
3760 * detached and then dropped in ATExecMergePartitions.
3761 */
3764 NULL);
3765 /* Is the current partition a DEFAULT partition? */
3766 if (partOid == defaultPartOid)
3767 isDefaultPart = true;
3768
3769 /*
3770 * Extended check because the same partition can have different names
3771 * (for example, "part_name" and "public.part_name").
3772 */
3773 foreach(listptr2, partOids)
3774 {
3776
3777 if (curOid == partOid)
3778 ereport(ERROR,
3780 errmsg("partition with name \"%s\" is already used", name->relname),
3781 parser_errposition(cxt->pstate, name->location));
3782 }
3783
3784 checkPartition(parent, partOid, true);
3785
3787 }
3788
3789 /* Allocate the bound of the resulting partition. */
3790 Assert(partcmd->bound == NULL);
3792
3793 /* Fill the partition bound. */
3794 partcmd->bound->strategy = strategy;
3795 partcmd->bound->location = -1;
3796 partcmd->bound->is_default = isDefaultPart;
3797 if (!isDefaultPart)
3799 partOids, partcmd->bound,
3800 cxt->pstate);
3801}
3802
3803/*
3804 * transformAlterTableStmt -
3805 * parse analysis for ALTER TABLE
3806 *
3807 * Returns the transformed AlterTableStmt. There may be additional actions
3808 * to be done before and after the transformed statement, which are returned
3809 * in *beforeStmts and *afterStmts as lists of utility command parsetrees.
3810 *
3811 * To avoid race conditions, it's important that this function rely only on
3812 * the passed-in relid (and not on stmt->relation) to determine the target
3813 * relation.
3814 */
3817 const char *queryString,
3818 List **beforeStmts, List **afterStmts)
3819{
3820 Relation rel;
3821 TupleDesc tupdesc;
3822 ParseState *pstate;
3825 ListCell *lcmd,
3826 *l;
3827 List *newcmds = NIL;
3828 bool skipValidation = true;
3831
3832 /* Caller is responsible for locking the relation */
3833 rel = relation_open(relid, NoLock);
3834 tupdesc = RelationGetDescr(rel);
3835
3836 /* Set up pstate */
3837 pstate = make_parsestate(NULL);
3838 pstate->p_sourcetext = queryString;
3840 rel,
3842 NULL,
3843 false,
3844 true);
3845 addNSItemToQuery(pstate, nsitem, false, true, true);
3846
3847 /* Set up CreateStmtContext */
3848 cxt.pstate = pstate;
3849 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3850 {
3851 cxt.stmtType = "ALTER FOREIGN TABLE";
3852 cxt.isforeign = true;
3853 }
3854 else
3855 {
3856 cxt.stmtType = "ALTER TABLE";
3857 cxt.isforeign = false;
3858 }
3859 cxt.relation = stmt->relation;
3860 cxt.rel = rel;
3861 cxt.inhRelations = NIL;
3862 cxt.isalter = true;
3863 cxt.columns = NIL;
3864 cxt.ckconstraints = NIL;
3865 cxt.nnconstraints = NIL;
3866 cxt.fkconstraints = NIL;
3867 cxt.ixconstraints = NIL;
3868 cxt.likeclauses = NIL;
3869 cxt.blist = NIL;
3870 cxt.alist = NIL;
3871 cxt.pkey = NULL;
3872 cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3873 cxt.partbound = NULL;
3874 cxt.ofType = false;
3875
3876 /*
3877 * Transform ALTER subcommands that need it (most don't). These largely
3878 * re-use code from CREATE TABLE.
3879 */
3880 foreach(lcmd, stmt->cmds)
3881 {
3883
3884 switch (cmd->subtype)
3885 {
3886 case AT_AddColumn:
3887 {
3888 ColumnDef *def = castNode(ColumnDef, cmd->def);
3889
3890 transformColumnDefinition(&cxt, def);
3891
3892 /*
3893 * If the column has a non-null default, we can't skip
3894 * validation of foreign keys.
3895 */
3896 if (def->raw_default != NULL)
3897 skipValidation = false;
3898
3899 /*
3900 * All constraints are processed in other ways. Remove the
3901 * original list
3902 */
3903 def->constraints = NIL;
3904
3905 newcmds = lappend(newcmds, cmd);
3906 break;
3907 }
3908
3909 case AT_AddConstraint:
3910
3911 /*
3912 * The original AddConstraint cmd node doesn't go to newcmds
3913 */
3914 if (IsA(cmd->def, Constraint))
3915 {
3916 transformTableConstraint(&cxt, (Constraint *) cmd->def);
3917 if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3918 skipValidation = false;
3919 }
3920 else
3921 elog(ERROR, "unrecognized node type: %d",
3922 (int) nodeTag(cmd->def));
3923 break;
3924
3925 case AT_AlterColumnType:
3926 {
3927 ColumnDef *def = castNode(ColumnDef, cmd->def);
3929
3930 /*
3931 * For ALTER COLUMN TYPE, transform the USING clause if
3932 * one was specified.
3933 */
3934 if (def->raw_default)
3935 {
3936 def->cooked_default =
3937 transformExpr(pstate, def->raw_default,
3939 }
3940
3941 /*
3942 * For identity column, create ALTER SEQUENCE command to
3943 * change the data type of the sequence. Identity sequence
3944 * is associated with the top level partitioned table.
3945 * Hence ignore partitions.
3946 */
3948 {
3949 attnum = get_attnum(relid, cmd->name);
3951 ereport(ERROR,
3953 errmsg("column \"%s\" of relation \"%s\" does not exist",
3954 cmd->name, RelationGetRelationName(rel))));
3955
3956 if (attnum > 0 &&
3957 TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3958 {
3959 Oid seq_relid = getIdentitySequence(rel, attnum, false);
3960 Oid typeOid = typenameTypeId(pstate, def->typeName);
3962
3963 altseqstmt->sequence
3966 -1);
3967 altseqstmt->options = list_make1(makeDefElem("as",
3968 (Node *) makeTypeNameFromOid(typeOid, -1),
3969 -1));
3970 altseqstmt->for_identity = true;
3971 cxt.blist = lappend(cxt.blist, altseqstmt);
3972 }
3973 }
3974
3975 newcmds = lappend(newcmds, cmd);
3976 break;
3977 }
3978
3979 case AT_AddIdentity:
3980 {
3981 Constraint *def = castNode(Constraint, cmd->def);
3984
3985 newdef->colname = cmd->name;
3986 newdef->identity = def->generated_when;
3987 cmd->def = (Node *) newdef;
3988
3989 attnum = get_attnum(relid, cmd->name);
3991 ereport(ERROR,
3993 errmsg("column \"%s\" of relation \"%s\" does not exist",
3994 cmd->name, RelationGetRelationName(rel))));
3995
3997 get_atttype(relid, attnum),
3998 def->options, true, true,
3999 NULL, NULL);
4000
4001 newcmds = lappend(newcmds, cmd);
4002 break;
4003 }
4004
4005 case AT_SetIdentity:
4006 {
4007 /*
4008 * Create an ALTER SEQUENCE statement for the internal
4009 * sequence of the identity column.
4010 */
4011 ListCell *lc;
4012 List *newseqopts = NIL;
4013 List *newdef = NIL;
4015 Oid seq_relid;
4016
4017 /*
4018 * Split options into those handled by ALTER SEQUENCE and
4019 * those for ALTER TABLE proper.
4020 */
4021 foreach(lc, castNode(List, cmd->def))
4022 {
4023 DefElem *def = lfirst_node(DefElem, lc);
4024
4025 if (strcmp(def->defname, "generated") == 0)
4026 newdef = lappend(newdef, def);
4027 else
4029 }
4030
4031 attnum = get_attnum(relid, cmd->name);
4033 ereport(ERROR,
4035 errmsg("column \"%s\" of relation \"%s\" does not exist",
4036 cmd->name, RelationGetRelationName(rel))));
4037
4038 seq_relid = getIdentitySequence(rel, attnum, true);
4039
4040 if (seq_relid)
4041 {
4043
4046 get_rel_name(seq_relid), -1);
4047 seqstmt->options = newseqopts;
4048 seqstmt->for_identity = true;
4049 seqstmt->missing_ok = false;
4050
4051 cxt.blist = lappend(cxt.blist, seqstmt);
4052 }
4053
4054 /*
4055 * If column was not an identity column, we just let the
4056 * ALTER TABLE command error out later. (There are cases
4057 * this fails to cover, but we'll need to restructure
4058 * where creation of the sequence dependency linkage
4059 * happens before we can fix it.)
4060 */
4061
4062 cmd->def = (Node *) newdef;
4063 newcmds = lappend(newcmds, cmd);
4064 break;
4065 }
4066
4067 case AT_AttachPartition:
4068 case AT_DetachPartition:
4069 {
4071
4072 transformPartitionCmd(&cxt, partcmd->bound);
4073 /* assign the transformed value of the partition bound */
4074 partcmd->bound = cxt.partbound;
4075 }
4076
4077 newcmds = lappend(newcmds, cmd);
4078 break;
4079
4080 case AT_MergePartitions:
4081 {
4083
4084 if (list_length(partcmd->partlist) < 2)
4085 ereport(ERROR,
4087 errmsg("list of partitions to be merged should include at least two partitions"));
4088
4090 newcmds = lappend(newcmds, cmd);
4091 break;
4092 }
4093
4094 case AT_SplitPartition:
4095 {
4097
4098 if (list_length(partcmd->partlist) < 2)
4099 ereport(ERROR,
4101 errmsg("list of new partitions should contain at least two partitions"));
4102
4104 newcmds = lappend(newcmds, cmd);
4105 break;
4106 }
4107
4108 default:
4109
4110 /*
4111 * Currently, we shouldn't actually get here for the
4112 * subcommand types that don't require transformation; but if
4113 * we do, just emit them unchanged.
4114 */
4115 newcmds = lappend(newcmds, cmd);
4116 break;
4117 }
4118 }
4119
4120 /*
4121 * Transfer anything we already have in cxt.alist into save_alist, to keep
4122 * it separate from the output of transformIndexConstraints.
4123 */
4124 save_alist = cxt.alist;
4125 cxt.alist = NIL;
4126
4127 /* Postprocess constraints */
4130 transformCheckConstraints(&cxt, false);
4131
4132 /*
4133 * Push any index-creation commands into the ALTER, so that they can be
4134 * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
4135 * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
4136 * subcommand has already been through transformIndexStmt.
4137 */
4138 foreach(l, cxt.alist)
4139 {
4140 Node *istmt = (Node *) lfirst(l);
4141
4142 /*
4143 * We assume here that cxt.alist contains only IndexStmts generated
4144 * from primary key constraints.
4145 */
4146 if (IsA(istmt, IndexStmt))
4147 {
4148 IndexStmt *idxstmt = (IndexStmt *) istmt;
4149
4150 idxstmt = transformIndexStmt(relid, idxstmt, queryString);
4152 newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex;
4153 newcmd->def = (Node *) idxstmt;
4155 }
4156 else
4157 elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
4158 }
4159 cxt.alist = NIL;
4160
4161 /* Append any CHECK, NOT NULL or FK constraints to the commands list */
4163 {
4165 newcmd->subtype = AT_AddConstraint;
4166 newcmd->def = (Node *) def;
4168 }
4170 {
4172 newcmd->subtype = AT_AddConstraint;
4173 newcmd->def = (Node *) def;
4175 }
4177 {
4179 newcmd->subtype = AT_AddConstraint;
4180 newcmd->def = (Node *) def;
4182 }
4183
4184 /* Close rel */
4185 relation_close(rel, NoLock);
4186
4187 /*
4188 * Output results.
4189 */
4190 stmt->cmds = newcmds;
4191
4192 *beforeStmts = cxt.blist;
4193 *afterStmts = list_concat(cxt.alist, save_alist);
4194
4195 return stmt;
4196}
4197
4198
4199/*
4200 * Preprocess a list of column constraint clauses
4201 * to attach constraint attributes to their primary constraint nodes
4202 * and detect inconsistent/misplaced constraint attributes.
4203 *
4204 * NOTE: currently, attributes are only supported for FOREIGN KEY, UNIQUE,
4205 * EXCLUSION, and PRIMARY KEY constraints, but someday they ought to be
4206 * supported for other constraint types.
4207 *
4208 * NOTE: this must be idempotent in non-error cases; see
4209 * transformCreateSchemaCreateTable.
4210 */
4211static void
4213{
4215 bool saw_deferrability = false;
4216 bool saw_initially = false;
4217 bool saw_enforced = false;
4218 ListCell *clist;
4219
4220#define SUPPORTS_ATTRS(node) \
4221 ((node) != NULL && \
4222 ((node)->contype == CONSTR_PRIMARY || \
4223 (node)->contype == CONSTR_UNIQUE || \
4224 (node)->contype == CONSTR_EXCLUSION || \
4225 (node)->contype == CONSTR_FOREIGN))
4226
4227 foreach(clist, constraintList)
4228 {
4229 Constraint *con = (Constraint *) lfirst(clist);
4230
4231 if (!IsA(con, Constraint))
4232 elog(ERROR, "unrecognized node type: %d",
4233 (int) nodeTag(con));
4234 switch (con->contype)
4235 {
4238 ereport(ERROR,
4240 errmsg("misplaced DEFERRABLE clause"),
4241 parser_errposition(pstate, con->location)));
4243 ereport(ERROR,
4245 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
4246 parser_errposition(pstate, con->location)));
4247 saw_deferrability = true;
4248 lastprimarycon->deferrable = true;
4249 break;
4250
4253 ereport(ERROR,
4255 errmsg("misplaced NOT DEFERRABLE clause"),
4256 parser_errposition(pstate, con->location)));
4258 ereport(ERROR,
4260 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
4261 parser_errposition(pstate, con->location)));
4262 saw_deferrability = true;
4263 lastprimarycon->deferrable = false;
4264 if (saw_initially &&
4265 lastprimarycon->initdeferred)
4266 ereport(ERROR,
4268 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
4269 parser_errposition(pstate, con->location)));
4270 break;
4271
4274 ereport(ERROR,
4276 errmsg("misplaced INITIALLY DEFERRED clause"),
4277 parser_errposition(pstate, con->location)));
4278 if (saw_initially)
4279 ereport(ERROR,
4281 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
4282 parser_errposition(pstate, con->location)));
4283 saw_initially = true;
4284 lastprimarycon->initdeferred = true;
4285
4286 /*
4287 * If only INITIALLY DEFERRED appears, assume DEFERRABLE
4288 */
4289 if (!saw_deferrability)
4290 lastprimarycon->deferrable = true;
4291 else if (!lastprimarycon->deferrable)
4292 ereport(ERROR,
4294 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
4295 parser_errposition(pstate, con->location)));
4296 break;
4297
4300 ereport(ERROR,
4302 errmsg("misplaced INITIALLY IMMEDIATE clause"),
4303 parser_errposition(pstate, con->location)));
4304 if (saw_initially)
4305 ereport(ERROR,
4307 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
4308 parser_errposition(pstate, con->location)));
4309 saw_initially = true;
4310 lastprimarycon->initdeferred = false;
4311 break;
4312
4314 if (lastprimarycon == NULL ||
4315 (lastprimarycon->contype != CONSTR_CHECK &&
4316 lastprimarycon->contype != CONSTR_FOREIGN))
4317 ereport(ERROR,
4319 errmsg("misplaced ENFORCED clause"),
4320 parser_errposition(pstate, con->location)));
4321 if (saw_enforced)
4322 ereport(ERROR,
4324 errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
4325 parser_errposition(pstate, con->location)));
4326 saw_enforced = true;
4327 lastprimarycon->is_enforced = true;
4328 break;
4329
4331 if (lastprimarycon == NULL ||
4332 (lastprimarycon->contype != CONSTR_CHECK &&
4333 lastprimarycon->contype != CONSTR_FOREIGN))
4334 ereport(ERROR,
4336 errmsg("misplaced NOT ENFORCED clause"),
4337 parser_errposition(pstate, con->location)));
4338 if (saw_enforced)
4339 ereport(ERROR,
4341 errmsg("multiple ENFORCED/NOT ENFORCED clauses not allowed"),
4342 parser_errposition(pstate, con->location)));
4343 saw_enforced = true;
4344 lastprimarycon->is_enforced = false;
4345
4346 /* A NOT ENFORCED constraint must be marked as invalid. */
4347 lastprimarycon->skip_validation = true;
4348 lastprimarycon->initially_valid = false;
4349 break;
4350
4351 default:
4352 /* Otherwise it's not an attribute */
4353 lastprimarycon = con;
4354 /* reset flags for new primary node */
4355 saw_deferrability = false;
4356 saw_initially = false;
4357 saw_enforced = false;
4358 break;
4359 }
4360 }
4361}
4362
4363/*
4364 * Special handling of type definition for a column
4365 */
4366static void
4368{
4369 /*
4370 * All we really need to do here is verify that the type is valid,
4371 * including any collation spec that might be present.
4372 */
4373 Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
4374
4375 if (column->collClause)
4376 {
4378
4380 column->collClause->collname,
4381 column->collClause->location);
4382 /* Complain if COLLATE is applied to an uncollatable type */
4383 if (!OidIsValid(typtup->typcollation))
4384 ereport(ERROR,
4386 errmsg("collations are not supported by type %s",
4387 format_type_be(typtup->oid)),
4389 column->collClause->location)));
4390 }
4391
4392 ReleaseSysCache(ctype);
4393}
4394
4395
4396/*
4397 * transformCreateSchemaStmtElements -
4398 * analyzes the elements of a CREATE SCHEMA statement
4399 *
4400 * This presently has two responsibilities. We verify that no subcommands are
4401 * trying to create objects outside the new schema. We also pull out any
4402 * foreign-key constraint clauses embedded in CREATE TABLE subcommands, and
4403 * convert them to ALTER TABLE ADD CONSTRAINT commands appended to the list.
4404 * This supports forward references in foreign keys, which is required by the
4405 * SQL standard.
4406 *
4407 * We used to try to re-order the commands in a way that would work even if
4408 * the user-written order would not, but that's too hard (perhaps impossible)
4409 * to do correctly with not-yet-parse-analyzed commands. Now we'll just
4410 * execute the elements in the order given, except for foreign keys.
4411 *
4412 * "schemaName" is the name of the schema that will be used for the creation
4413 * of the objects listed. It may be obtained from the schema name defined
4414 * in the statement or a role specification.
4415 *
4416 * The result is a list of parse nodes that still need to be analyzed ---
4417 * but we can't analyze the later commands until we've executed the earlier
4418 * ones, because of possible inter-object references.
4419 *
4420 * Note it's important that we not modify the input data structure. We create
4421 * a new result List, and we copy any CREATE TABLE subcommands that we might
4422 * modify.
4423 */
4424List *
4426 const char *schemaName)
4427{
4428 List *elements = NIL;
4429 List *fk_elements = NIL;
4430 ListCell *lc;
4431
4432 /*
4433 * Run through each schema element in the schema element list. Check
4434 * target schema names, and collect the list of actions to be done.
4435 */
4436 foreach(lc, schemaElts)
4437 {
4438 Node *element = lfirst(lc);
4439
4440 switch (nodeTag(element))
4441 {
4442 case T_CreateSeqStmt:
4443 {
4445
4446 checkSchemaNameRV(pstate, schemaName, elp->sequence);
4447 elements = lappend(elements, element);
4448 }
4449 break;
4450
4451 case T_CreateStmt:
4452 {
4454
4455 checkSchemaNameRV(pstate, schemaName, elp->relation);
4456 /* Pull out any foreign key clauses, add to fk_elements */
4458 elp,
4459 &fk_elements);
4460 elements = lappend(elements, elp);
4461 }
4462 break;
4463
4464 case T_ViewStmt:
4465 {
4467
4468 checkSchemaNameRV(pstate, schemaName, elp->view);
4469 elements = lappend(elements, element);
4470 }
4471 break;
4472
4473 case T_IndexStmt:
4474 {
4476
4477 checkSchemaNameRV(pstate, schemaName, elp->relation);
4478 elements = lappend(elements, element);
4479 }
4480 break;
4481
4482 case T_CreateTrigStmt:
4483 {
4485
4486 checkSchemaNameRV(pstate, schemaName, elp->relation);
4487 elements = lappend(elements, element);
4488 }
4489 break;
4490
4491 case T_CreateDomainStmt:
4492 {
4494
4495 checkSchemaNameList(schemaName, elp->domainname);
4496 elements = lappend(elements, element);
4497 }
4498 break;
4499
4501 {
4503
4505 elements = lappend(elements, element);
4506 }
4507 break;
4508
4509 /*
4510 * CREATE TYPE can produce a DefineStmt, but also
4511 * CreateEnumStmt, CreateRangeStmt, and CompositeTypeStmt.
4512 * Allowing DefineStmt also provides support for several other
4513 * commands: currently, CREATE AGGREGATE, CREATE COLLATION,
4514 * CREATE OPERATOR, and text search objects.
4515 */
4516
4517 case T_DefineStmt:
4518 {
4520
4522 elements = lappend(elements, element);
4523 }
4524 break;
4525
4526 case T_CreateEnumStmt:
4527 {
4529
4531 elements = lappend(elements, element);
4532 }
4533 break;
4534
4535 case T_CreateRangeStmt:
4536 {
4538
4540 elements = lappend(elements, element);
4541 }
4542 break;
4543
4545 {
4547
4548 checkSchemaNameRV(pstate, schemaName, elp->typevar);
4549 elements = lappend(elements, element);
4550 }
4551 break;
4552
4553 case T_GrantStmt:
4554 elements = lappend(elements, element);
4555 break;
4556
4557 default:
4558 elog(ERROR, "unrecognized node type: %d",
4559 (int) nodeTag(element));
4560 }
4561 }
4562
4563 return list_concat(elements, fk_elements);
4564}
4565
4566/*
4567 * checkSchemaNameRV
4568 * Check schema name in an element of a CREATE SCHEMA command,
4569 * where the element's name is given by a RangeVar
4570 *
4571 * It's okay if the command doesn't specify a target schema name, because
4572 * CreateSchemaCommand will set up the default creation schema to be the
4573 * new schema. But if a target schema name is given, it had better match.
4574 * We also have to check that the command doesn't say CREATE TEMP, since
4575 * that would likewise put the object into the wrong schema.
4576 */
4577static void
4579 RangeVar *relation)
4580{
4581 if (relation->schemaname != NULL &&
4582 strcmp(context_schema, relation->schemaname) != 0)
4583 ereport(ERROR,
4585 errmsg("CREATE specifies a schema (%s) "
4586 "different from the one being created (%s)",
4587 relation->schemaname, context_schema),
4588 parser_errposition(pstate, relation->location)));
4589
4590 if (relation->relpersistence == RELPERSISTENCE_TEMP)
4591 {
4592 /* spell this error the same as in RangeVarAdjustRelationPersistence */
4593 ereport(ERROR,
4595 errmsg("cannot create temporary relation in non-temporary schema"),
4596 parser_errposition(pstate, relation->location)));
4597 }
4598}
4599
4600/*
4601 * checkSchemaNameList
4602 * Check schema name in an element of a CREATE SCHEMA command,
4603 * where the element's name is given by a List
4604 *
4605 * Much as above, but we don't have to worry about TEMP.
4606 * Sadly, this also means we don't have a parse location to report.
4607 */
4608static void
4610{
4611 char *obj_schema;
4612 char *obj_name;
4613
4615 if (obj_schema != NULL &&
4617 ereport(ERROR,
4619 errmsg("CREATE specifies a schema (%s) "
4620 "different from the one being created (%s)",
4622}
4623
4624/*
4625 * transformCreateSchemaCreateTable
4626 * Process one CreateStmt for transformCreateSchemaStmtElements.
4627 *
4628 * We remove any foreign-key clauses in the statement and convert them into
4629 * ALTER TABLE commands, which we append to *fk_elements.
4630 */
4631static CreateStmt *
4634 List **fk_elements)
4635{
4637 List *newElts = NIL;
4638 ListCell *lc;
4639
4640 /*
4641 * Flat-copy the CreateStmt node, allowing us to replace its tableElts
4642 * list without damaging the input data structure. Most sub-nodes will be
4643 * shared with the input, though.
4644 */
4646 memcpy(newstmt, stmt, sizeof(CreateStmt));
4647
4648 /* Scan for foreign-key constraints */
4649 foreach(lc, stmt->tableElts)
4650 {
4651 Node *element = lfirst(lc);
4654
4655 if (IsA(element, Constraint))
4656 {
4657 Constraint *constr = (Constraint *) element;
4658
4659 if (constr->contype != CONSTR_FOREIGN)
4660 {
4661 /* Other constraint types pass through unchanged */
4662 newElts = lappend(newElts, constr);
4663 continue;
4664 }
4665
4666 /* Make it into an ALTER TABLE ADD CONSTRAINT command */
4668 altercmd->subtype = AT_AddConstraint;
4669 altercmd->name = NULL;
4670 altercmd->def = (Node *) copyObject(constr);
4671
4673 alterstmt->relation = copyObject(stmt->relation);
4674 alterstmt->cmds = list_make1(altercmd);
4675 alterstmt->objtype = OBJECT_TABLE;
4676
4678 }
4679 else if (IsA(element, ColumnDef))
4680 {
4681 ColumnDef *entry = (ColumnDef *) element;
4684 bool afterFK = false;
4685
4686 /*
4687 * We must preprocess the list of column constraints to attach
4688 * attributes such as DEFERRED to the appropriate constraint node.
4689 * Do this on a copy. (But execution of the CreateStmt will run
4690 * transformConstraintAttrs on the copy, so we are nonetheless
4691 * relying on transformConstraintAttrs to be idempotent.)
4692 */
4695
4696 /* Scan the column constraints ... */
4698 {
4699 switch (colconstr->contype)
4700 {
4701 case CONSTR_FOREIGN:
4702 /* colconstr is already a copy, OK to modify */
4703 colconstr->fk_attrs = list_make1(makeString(entry->colname));
4704
4705 /* Make it into an ALTER TABLE ADD CONSTRAINT command */
4707 altercmd->subtype = AT_AddConstraint;
4708 altercmd->name = NULL;
4709 altercmd->def = (Node *) colconstr;
4710
4712 alterstmt->relation = copyObject(stmt->relation);
4713 alterstmt->cmds = list_make1(altercmd);
4714 alterstmt->objtype = OBJECT_TABLE;
4715
4717
4718 /* Remove the Constraint node from entryconstraints */
4721
4722 /*
4723 * Immediately-following attribute constraints should
4724 * be dropped, too.
4725 */
4726 afterFK = true;
4727 break;
4728
4729 /*
4730 * Column constraint lists separate a Constraint node
4731 * from its attributes (e.g. NOT ENFORCED); so a
4732 * column-level foreign key constraint may be
4733 * represented by multiple Constraint nodes. After
4734 * transformConstraintAttrs, the foreign key
4735 * Constraint node contains all required information,
4736 * making it okay to put into *fk_elements as a
4737 * stand-alone Constraint. But since we removed the
4738 * foreign key Constraint node from entryconstraints,
4739 * we must remove any dependent attribute nodes too,
4740 * else the later re-execution of
4741 * transformConstraintAttrs will misbehave.
4742 */
4749 if (afterFK)
4752 colconstr);
4753 break;
4754
4755 default:
4756 /* Any following constraint attributes are unrelated */
4757 afterFK = false;
4758 break;
4759 }
4760 }
4761
4762 /* Now make a modified ColumnDef to put into newElts */
4764 memcpy(newentry, entry, sizeof(ColumnDef));
4765 newentry->constraints = entryconstraints;
4767 }
4768 else
4769 {
4770 /* Other node types pass through unchanged */
4772 }
4773 }
4774
4775 newstmt->tableElts = newElts;
4776 return newstmt;
4777}
4778
4779/*
4780 * transformPartitionCmd
4781 * Analyze the ATTACH/DETACH/SPLIT PARTITION command
4782 *
4783 * In case of the ATTACH/SPLIT PARTITION command, cxt->partbound is set to the
4784 * transformed value of bound.
4785 */
4786static void
4788{
4789 Relation parentRel = cxt->rel;
4790
4791 switch (parentRel->rd_rel->relkind)
4792 {
4794 /* transform the partition bound, if any */
4796 if (bound != NULL)
4798 bound);
4799 break;
4801
4802 /*
4803 * A partitioned index cannot have a partition bound set. ALTER
4804 * INDEX prevents that with its grammar, but not ALTER TABLE.
4805 */
4806 if (bound != NULL)
4807 ereport(ERROR,
4809 errmsg("\"%s\" is not a partitioned table",
4811 break;
4812 case RELKIND_RELATION:
4813 /* the table must be partitioned */
4814 ereport(ERROR,
4816 errmsg("table \"%s\" is not partitioned",
4818 break;
4819 case RELKIND_INDEX:
4820 /* the index must be partitioned */
4821 ereport(ERROR,
4823 errmsg("index \"%s\" is not partitioned",
4825 break;
4826 default:
4827 /* parser shouldn't let this case through */
4828 elog(ERROR, "\"%s\" is not a partitioned table or index",
4830 break;
4831 }
4832}
4833
4834/*
4835 * transformPartitionBound
4836 *
4837 * Transform a partition bound specification
4838 */
4842{
4845 char strategy = get_partition_strategy(key);
4846 int partnatts = get_partition_natts(key);
4847 List *partexprs = get_partition_exprs(key);
4848
4849 /* Avoid scribbling on input */
4851
4852 if (spec->is_default)
4853 {
4854 /*
4855 * Hash partitioning does not support a default partition; there's no
4856 * use case for it (since the set of partitions to create is perfectly
4857 * defined), and if users do get into it accidentally, it's hard to
4858 * back out from it afterwards.
4859 */
4860 if (strategy == PARTITION_STRATEGY_HASH)
4861 ereport(ERROR,
4863 errmsg("a hash-partitioned table may not have a default partition")));
4864
4865 /*
4866 * In case of the default partition, parser had no way to identify the
4867 * partition strategy. Assign the parent's strategy to the default
4868 * partition bound spec.
4869 */
4870 result_spec->strategy = strategy;
4871
4872 return result_spec;
4873 }
4874
4875 if (strategy == PARTITION_STRATEGY_HASH)
4876 {
4877 if (spec->strategy != PARTITION_STRATEGY_HASH)
4878 ereport(ERROR,
4880 errmsg("invalid bound specification for a hash partition"),
4881 parser_errposition(pstate, exprLocation((Node *) spec))));
4882
4883 if (spec->modulus <= 0)
4884 ereport(ERROR,
4886 errmsg("modulus for hash partition must be an integer value greater than zero")));
4887
4888 Assert(spec->remainder >= 0);
4889
4890 if (spec->remainder >= spec->modulus)
4891 ereport(ERROR,
4893 errmsg("remainder for hash partition must be less than modulus")));
4894 }
4895 else if (strategy == PARTITION_STRATEGY_LIST)
4896 {
4897 ListCell *cell;
4898 char *colname;
4899 Oid coltype;
4901 Oid partcollation;
4902
4903 if (spec->strategy != PARTITION_STRATEGY_LIST)
4904 ereport(ERROR,
4906 errmsg("invalid bound specification for a list partition"),
4907 parser_errposition(pstate, exprLocation((Node *) spec))));
4908
4909 /* Get the only column's name in case we need to output an error */
4910 if (key->partattrs[0] != 0)
4911 colname = get_attname(RelationGetRelid(parent),
4912 key->partattrs[0], false);
4913 else
4914 colname = deparse_expression((Node *) linitial(partexprs),
4916 RelationGetRelid(parent)),
4917 false, false);
4918 /* Need its type data too */
4919 coltype = get_partition_col_typid(key, 0);
4921 partcollation = get_partition_col_collation(key, 0);
4922
4923 result_spec->listdatums = NIL;
4924 foreach(cell, spec->listdatums)
4925 {
4926 Node *expr = lfirst(cell);
4927 Const *value;
4928 ListCell *cell2;
4929 bool duplicate;
4930
4931 value = transformPartitionBoundValue(pstate, expr,
4932 colname, coltype, coltypmod,
4933 partcollation);
4934
4935 /* Don't add to the result if the value is a duplicate */
4936 duplicate = false;
4937 foreach(cell2, result_spec->listdatums)
4938 {
4940
4941 if (equal(value, value2))
4942 {
4943 duplicate = true;
4944 break;
4945 }
4946 }
4947 if (duplicate)
4948 continue;
4949
4950 result_spec->listdatums = lappend(result_spec->listdatums,
4951 value);
4952 }
4953 }
4954 else if (strategy == PARTITION_STRATEGY_RANGE)
4955 {
4956 if (spec->strategy != PARTITION_STRATEGY_RANGE)
4957 ereport(ERROR,
4959 errmsg("invalid bound specification for a range partition"),
4960 parser_errposition(pstate, exprLocation((Node *) spec))));
4961
4962 if (list_length(spec->lowerdatums) != partnatts)
4963 ereport(ERROR,
4965 errmsg("FROM must specify exactly one value per partitioning column")));
4966 if (list_length(spec->upperdatums) != partnatts)
4967 ereport(ERROR,
4969 errmsg("TO must specify exactly one value per partitioning column")));
4970
4971 /*
4972 * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4973 * any necessary validation.
4974 */
4975 result_spec->lowerdatums =
4976 transformPartitionRangeBounds(pstate, spec->lowerdatums,
4977 parent);
4978 result_spec->upperdatums =
4979 transformPartitionRangeBounds(pstate, spec->upperdatums,
4980 parent);
4981 }
4982 else
4983 elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4984
4985 return result_spec;
4986}
4987
4988/*
4989 * transformPartitionRangeBounds
4990 * This converts the expressions for range partition bounds from the raw
4991 * grammar representation to PartitionRangeDatum structs
4992 */
4993static List *
4995 Relation parent)
4996{
4997 List *result = NIL;
4999 List *partexprs = get_partition_exprs(key);
5000 ListCell *lc;
5001 int i,
5002 j;
5003
5004 j = 0;
5005 foreach(lc, blist)
5006 {
5007 Node *expr = lfirst(lc);
5009
5011
5012 /*
5013 * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
5014 * as ColumnRefs.
5015 */
5016 if (IsA(expr, ColumnRef))
5017 {
5018 ColumnRef *cref = (ColumnRef *) expr;
5019 char *cname = NULL;
5020
5021 /*
5022 * There should be a single field named either "minvalue" or
5023 * "maxvalue".
5024 */
5025 if (list_length(cref->fields) == 1 &&
5026 IsA(linitial(cref->fields), String))
5027 cname = strVal(linitial(cref->fields));
5028
5029 if (cname == NULL)
5030 {
5031 /*
5032 * ColumnRef is not in the desired single-field-name form. For
5033 * consistency between all partition strategies, let the
5034 * expression transformation report any errors rather than
5035 * doing it ourselves.
5036 */
5037 }
5038 else if (strcmp("minvalue", cname) == 0)
5039 {
5042 prd->value = NULL;
5043 }
5044 else if (strcmp("maxvalue", cname) == 0)
5045 {
5048 prd->value = NULL;
5049 }
5050 }
5051
5052 if (prd == NULL)
5053 {
5054 char *colname;
5055 Oid coltype;
5057 Oid partcollation;
5058 Const *value;
5059
5060 /* Get the column's name in case we need to output an error */
5061 if (key->partattrs[i] != 0)
5062 colname = get_attname(RelationGetRelid(parent),
5063 key->partattrs[i], false);
5064 else
5065 {
5066 colname = deparse_expression((Node *) list_nth(partexprs, j),
5068 RelationGetRelid(parent)),
5069 false, false);
5070 ++j;
5071 }
5072
5073 /* Need its type data too */
5074 coltype = get_partition_col_typid(key, i);
5076 partcollation = get_partition_col_collation(key, i);
5077
5078 value = transformPartitionBoundValue(pstate, expr,
5079 colname,
5080 coltype, coltypmod,
5081 partcollation);
5082 if (value->constisnull)
5083 ereport(ERROR,
5085 errmsg("cannot specify NULL in range bound")));
5088 prd->value = (Node *) value;
5089 }
5090
5091 prd->location = exprLocation(expr);
5092
5094 }
5095
5096 /*
5097 * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
5098 * must be the same.
5099 */
5101
5102 return result;
5103}
5104
5105/*
5106 * validateInfiniteBounds
5107 *
5108 * Check that a MAXVALUE or MINVALUE specification in a partition bound is
5109 * followed only by more of the same.
5110 */
5111static void
5113{
5114 ListCell *lc;
5116
5117 foreach(lc, blist)
5118 {
5120
5121 if (kind == prd->kind)
5122 continue;
5123
5124 switch (kind)
5125 {
5127 kind = prd->kind;
5128 break;
5129
5131 ereport(ERROR,
5133 errmsg("every bound following MAXVALUE must also be MAXVALUE"),
5134 parser_errposition(pstate, exprLocation((Node *) prd))));
5135 break;
5136
5138 ereport(ERROR,
5140 errmsg("every bound following MINVALUE must also be MINVALUE"),
5141 parser_errposition(pstate, exprLocation((Node *) prd))));
5142 break;
5143 }
5144 }
5145}
5146
5147/*
5148 * Transform one entry in a partition bound spec, producing a constant.
5149 */
5150static Const *
5152 const char *colName, Oid colType, int32 colTypmod,
5154{
5155 Node *value;
5156
5157 /* Transform raw parsetree */
5159
5160 /*
5161 * transformExpr() should have already rejected column references,
5162 * subqueries, aggregates, window functions, and SRFs, based on the
5163 * EXPR_KIND_ of a partition bound expression.
5164 */
5166
5167 /*
5168 * Coerce to the correct type. This might cause an explicit coercion step
5169 * to be added on top of the expression, which must be evaluated before
5170 * returning the result to the caller.
5171 */
5174 colType,
5175 colTypmod,
5178 -1);
5179
5180 if (value == NULL)
5181 ereport(ERROR,
5183 errmsg("specified value cannot be cast to type %s for column \"%s\"",
5186
5187 /*
5188 * Evaluate the expression, if needed, assigning the partition key's data
5189 * type and collation to the resulting Const node.
5190 */
5191 if (!IsA(value, Const))
5192 {
5197 if (!IsA(value, Const))
5198 elog(ERROR, "could not evaluate partition bound expression");
5199 }
5200 else
5201 {
5202 /*
5203 * If the expression is already a Const, as is often the case, we can
5204 * skip the rather expensive steps above. But we still have to insert
5205 * the right collation, since coerce_to_target_type doesn't handle
5206 * that.
5207 */
5208 ((Const *) value)->constcollid = partCollation;
5209 }
5210
5211 /*
5212 * Attach original expression's parse location to the Const, so that
5213 * that's what will be reported for any later errors related to this
5214 * partition bound.
5215 */
5216 ((Const *) value)->location = exprLocation(val);
5217
5218 return (Const *) value;
5219}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4082
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(const ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
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)
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:835
#define InvalidSubTransactionId
Definition c.h:742
#define Assert(condition)
Definition c.h:943
int16_t int16
Definition c.h:619
int32_t int32
Definition c.h:620
#define pg_fallthrough
Definition c.h:161
#define OidIsValid(objectId)
Definition c.h:858
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition clauses.c:5688
int nspid
List * sequence_options(Oid relid)
Definition sequence.c:1712
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition comment.c:420
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition define.c:370
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG1
Definition elog.h:31
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define NOTICE
Definition elog.h:36
#define ereport(elevel,...)
Definition elog.h:152
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
char * format_type_be(Oid type_oid)
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)
#define stmt
#define comment
#define DEFAULT_INDEX_TYPE
Definition index.h:27
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition indexcmds.c:2634
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition indexcmds.c:2371
long val
Definition informix.c:689
static struct @177 value
int j
Definition isn.c:78
int i
Definition isn.c:77
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 * lappend_oid(List *list, Oid datum)
Definition list.c:375
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:2148
AttrNumber get_attnum(Oid relid, const char *attname)
Definition lsyscache.c:977
bool type_is_range(Oid typid)
Definition lsyscache.c:2910
Datum get_attoptions(Oid relid, int16 attnum)
Definition lsyscache.c:1089
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2172
Oid get_typcollation(Oid typid)
Definition lsyscache.c:3278
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition lsyscache.c:946
Oid getBaseType(Oid typid)
Definition lsyscache.c:2743
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3588
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition lsyscache.c:1032
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition lsyscache.c:2105
bool type_is_multirange(Oid typid)
Definition lsyscache.c:2920
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:1781
void pfree(void *pointer)
Definition mcxt.c:1616
Oid GetUserId(void)
Definition miscinit.c:470
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition namespace.c:740
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition namespace.c:847
void DeconstructQualifiedName(const List *names, char **nspname_p, char **objname_p)
Definition namespace.c:3373
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition namespace.c:655
RangeVar * makeRangeVarFromNameList(const List *names)
Definition namespace.c:3626
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition namespace.c:442
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1392
#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
static char * errmsg
ObjectType get_relkind_objtype(char relkind)
#define ObjectAddressSet(addr, class_id, object_id)
char * nodeToString(const void *obj)
Definition outfuncs.c:811
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)
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition parse_expr.c:121
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition parse_node.c:156
void free_parsestate(ParseState *pstate)
Definition parse_node.c:72
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition parse_node.c:140
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
@ EXPR_KIND_STATS_EXPRESSION
Definition parse_node.h:75
@ EXPR_KIND_INDEX_EXPRESSION
Definition parse_node.h:73
@ EXPR_KIND_PARTITION_BOUND
Definition parse_node.h:80
@ EXPR_KIND_INDEX_PREDICATE
Definition parse_node.h:74
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition parse_node.h:76
@ EXPR_KIND_WHERE
Definition parse_node.h:46
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, LOCKMODE lockmode, Alias *alias, bool inh, bool inFromCl)
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(ParseState *pstate, List *schemaElts, const char *schemaName)
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static CreateStmt * transformCreateSchemaCreateTable(ParseState *pstate, CreateStmt *stmt, List **fk_elements)
void transformRuleStmt(RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
static void transformConstraintAttrs(ParseState *pstate, List *constraintList)
static void transformIndexConstraints(CreateStmtContext *cxt)
static List * get_collation(Oid collation, Oid actual_datatype)
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
static void checkSchemaNameRV(ParseState *pstate, const char *context_schema, RangeVar *relation)
AlterTableStmt * transformAlterTableStmt(Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
List * expandTableLikeClause(RangeVar *heapRel, TableLikeClause *table_like_clause)
static void transformPartitionCmdForSplit(CreateStmtContext *cxt, PartitionCmd *partcmd)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static List * get_opclass(Oid opclass, Oid actual_datatype)
static void transformPartitionCmdForMerge(CreateStmtContext *cxt, PartitionCmd *partcmd)
static void checkPartition(Relation rel, Oid partRelOid, bool isMerge)
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
CreateStatsStmt * transformStatsStmt(Oid relid, CreateStatsStmt *stmt, const char *queryString)
static void validateInfiniteBounds(ParseState *pstate, List *blist)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionBoundSpec *bound)
static Const * transformPartitionBoundValue(ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
static 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)
static void checkSchemaNameList(const char *context_schema, List *qualified_name)
#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:919
@ PARTITION_STRATEGY_LIST
Definition parsenodes.h:917
@ PARTITION_STRATEGY_RANGE
Definition parsenodes.h:918
@ CONSTR_ATTR_ENFORCED
@ CONSTR_FOREIGN
@ CONSTR_ATTR_DEFERRED
@ CONSTR_IDENTITY
@ CONSTR_UNIQUE
@ CONSTR_ATTR_NOT_DEFERRABLE
@ CONSTR_DEFAULT
@ CONSTR_NOTNULL
@ CONSTR_ATTR_IMMEDIATE
@ CONSTR_CHECK
@ CONSTR_NULL
@ CONSTR_GENERATED
@ CONSTR_EXCLUSION
@ CONSTR_ATTR_DEFERRABLE
@ CONSTR_ATTR_NOT_ENFORCED
@ CONSTR_PRIMARY
PartitionRangeDatumKind
Definition parsenodes.h:968
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition parsenodes.h:971
@ PARTITION_RANGE_DATUM_VALUE
Definition parsenodes.h:970
@ PARTITION_RANGE_DATUM_MINVALUE
Definition parsenodes.h:969
@ DROP_RESTRICT
@ OBJECT_FOREIGN_TABLE
@ OBJECT_COLUMN
@ OBJECT_TABLE
@ OBJECT_TYPE
@ OBJECT_TABCONSTRAINT
@ AT_AddIndexConstraint
@ AT_MergePartitions
@ AT_SetIdentity
@ AT_AddIndex
@ AT_AddIdentity
@ AT_AlterColumnType
@ AT_AlterColumnGenericOptions
@ AT_DetachPartition
@ AT_AttachPartition
@ AT_AddConstraint
@ AT_CookedColumnDefault
@ AT_SplitPartition
@ AT_AddColumn
#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:805
@ CREATE_TABLE_LIKE_GENERATED
Definition parsenodes.h:809
@ CREATE_TABLE_LIKE_IDENTITY
Definition parsenodes.h:810
@ CREATE_TABLE_LIKE_COMPRESSION
Definition parsenodes.h:806
@ CREATE_TABLE_LIKE_STORAGE
Definition parsenodes.h:813
@ CREATE_TABLE_LIKE_INDEXES
Definition parsenodes.h:811
@ CREATE_TABLE_LIKE_DEFAULTS
Definition parsenodes.h:808
@ CREATE_TABLE_LIKE_STATISTICS
Definition parsenodes.h:812
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition parsenodes.h:807
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition analyze.c:334
List * SystemFuncName(char *name)
TypeName * SystemTypeName(char *name)
void check_partitions_for_split(Relation parent, Oid splitPartOid, List *partlist, ParseState *pstate)
void calculate_partition_bound_for_merge(Relation parent, List *partNames, List *partOids, PartitionBoundSpec *spec, ParseState *pstate)
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
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition partdesc.c:71
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition partdesc.c:501
Oid get_partition_parent(Oid relid, bool even_if_detached)
Definition partition.c:53
END_CATALOG_STRUCT typedef FormData_pg_am * Form_pg_am
Definition pg_am.h:52
FormData_pg_attribute
NameData attname
int16 attnum
FormData_pg_attribute * Form_pg_attribute
int errdetail_relkind_not_supported(char relkind)
Definition pg_class.c:24
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
END_CATALOG_STRUCT typedef FormData_pg_collation * Form_pg_collation
List * RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
END_CATALOG_STRUCT typedef FormData_pg_constraint * Form_pg_constraint
void checkMembershipInCurrentExtension(const ObjectAddress *object)
Definition pg_depend.c:260
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition pg_depend.c:1018
Oid get_index_constraint(Oid indexId)
Definition pg_depend.c:1061
END_CATALOG_STRUCT typedef FormData_pg_index * Form_pg_index
Definition pg_index.h:74
#define lfirst(lc)
Definition pg_list.h:172
#define lfirst_node(type, lc)
Definition pg_list.h:176
static int list_length(const List *l)
Definition pg_list.h:152
#define linitial_node(type, l)
Definition pg_list.h:181
#define NIL
Definition pg_list.h:68
#define lsecond_node(type, l)
Definition pg_list.h:186
#define foreach_current_index(var_or_cell)
Definition pg_list.h:435
#define foreach_delete_current(lst, var_or_cell)
Definition pg_list.h:423
#define list_make1(x1)
Definition pg_list.h:244
#define for_each_cell(cell, lst, initcell)
Definition pg_list.h:470
static void * list_nth(const List *list, int n)
Definition pg_list.h:331
#define linitial(l)
Definition pg_list.h:178
#define list_make3(x1, x2, x3)
Definition pg_list.h:248
#define foreach_node(type, var, lst)
Definition pg_list.h:528
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:375
#define lfirst_oid(lc)
Definition pg_list.h:174
#define list_make2(x1, x2)
Definition pg_list.h:246
static ListCell * list_last_cell(const List *list)
Definition pg_list.h:320
END_CATALOG_STRUCT typedef FormData_pg_opclass * Form_pg_opclass
Definition pg_opclass.h:87
END_CATALOG_STRUCT typedef FormData_pg_operator * Form_pg_operator
Definition pg_operator.h:87
END_CATALOG_STRUCT typedef FormData_pg_statistic_ext * Form_pg_statistic_ext
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265
NameData typname
Definition pg_type.h:43
Expr * expression_planner(Expr *expr)
Definition planner.c:6839
static Oid DatumGetObjectId(Datum X)
Definition postgres.h:242
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define InvalidOid
unsigned int Oid
static int fb(int x)
#define PRS2_OLD_VARNO
Definition primnodes.h:251
#define PRS2_NEW_VARNO
Definition primnodes.h:252
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:769
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
@ COERCION_ASSIGNMENT
Definition primnodes.h:748
void * stringToNode(const char *str)
Definition read.c:90
static chr element(struct vars *v, const chr *startp, const chr *endp)
#define RelationGetForm(relation)
Definition rel.h:510
#define RelationGetRelid(relation)
Definition rel.h:516
#define RelationGetDescr(relation)
Definition rel.h:542
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RelationGetNamespace(relation)
Definition rel.h:557
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4827
List * RelationGetIndexPredicate(Relation relation)
Definition relcache.c:5201
List * RelationGetStatExtList(Relation relation)
Definition relcache.c:4968
List * RelationGetIndexExpressions(Relation relation)
Definition relcache.c:5088
List * untransformRelOptions(Datum options)
#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)
List * deparse_context_for(const char *aliasname, Oid relid)
Definition ruleutils.c:4070
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition ruleutils.c:4007
void relation_close(Relation relation, LOCKMODE lockmode)
Definition relation.c:206
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition relation.c:138
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition relation.c:48
DropBehavior behavior
AlterTableType subtype
char identity
Definition parsenodes.h:781
List * constraints
Definition parsenodes.h:787
Node * cooked_default
Definition parsenodes.h:780
char * colname
Definition parsenodes.h:770
TypeName * typeName
Definition parsenodes.h:771
char generated
Definition parsenodes.h:784
bool is_from_type
Definition parsenodes.h:776
Node * raw_default
Definition parsenodes.h:779
char storage
Definition parsenodes.h:777
char * compression
Definition parsenodes.h:772
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
List * exclusions
ParseLoc location
bool reset_default_tblspc
List * keys
Node * where_clause
char * indexname
char * indexspace
ConstrType contype
char * access_method
bool is_no_inherit
List * options
bool is_enforced
bool nulls_not_distinct
char * cooked_expr
bool initially_valid
bool skip_validation
bool without_overlaps
bool deferrable
Node * raw_expr
char * conname
char generated_when
List * including
const char * stmtType
RangeVar * relation
ParseState * pstate
PartitionBoundSpec * partbound
char * defname
Definition parsenodes.h:860
char * indexcolname
Definition parsenodes.h:829
Definition pg_list.h:54
Definition nodes.h:135
const char * p_sourcetext
Definition parse_node.h:214
List * p_rteperminfos
Definition parse_node.h:216
List * p_rtable
Definition parse_node.h:215
char * relname
Definition primnodes.h:84
char relpersistence
Definition primnodes.h:90
ParseLoc location
Definition primnodes.h:96
char * schemaname
Definition primnodes.h:81
TupleDesc rd_att
Definition rel.h:112
Form_pg_class rd_rel
Definition rel.h:111
Node * expr
Definition value.h:64
ConstrCheck * check
Definition tupdesc.h:41
uint16 num_check
Definition tupdesc.h:44
Oid typeOid
Definition parsenodes.h:289
Definition type.h:96
Definition c.h:815
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition table.c:83
void check_of_type(HeapTuple typetuple)
Definition tablecmds.c:7207
void RangeVarCallbackOwnsRelation(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
const char * GetCompressionMethodName(char method)
#define CompressionMethodIsValid(cm)
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition tupdesc.c:1152
#define ReleaseTupleDesc(tupdesc)
Definition tupdesc.h:240
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition typcache.c:1947
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
const char * name