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