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