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