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