PostgreSQL Source Code  git master
parse_utilcmd.c File Reference
Include dependency graph for parse_utilcmd.c:

Go to the source code of this file.

Data Structures

struct  CreateStmtContext
 
struct  CreateSchemaStmtContext
 

Macros

#define SUPPORTS_ATTRS(node)
 

Functions

static void transformColumnDefinition (CreateStmtContext *cxt, ColumnDef *column)
 
static void transformTableConstraint (CreateStmtContext *cxt, Constraint *constraint)
 
static void transformTableLikeClause (CreateStmtContext *cxt, TableLikeClause *table_like_clause)
 
static void transformOfType (CreateStmtContext *cxt, TypeName *ofTypename)
 
static CreateStatsStmtgenerateClonedExtStatsStmt (RangeVar *heapRel, Oid heapRelid, Oid source_statsid, const AttrMap *attmap)
 
static Listget_collation (Oid collation, Oid actual_datatype)
 
static Listget_opclass (Oid opclass, Oid actual_datatype)
 
static void transformIndexConstraints (CreateStmtContext *cxt)
 
static IndexStmttransformIndexConstraint (Constraint *constraint, CreateStmtContext *cxt)
 
static void transformFKConstraints (CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
 
static void transformCheckConstraints (CreateStmtContext *cxt, bool skipValidation)
 
static void transformConstraintAttrs (CreateStmtContext *cxt, List *constraintList)
 
static void transformColumnType (CreateStmtContext *cxt, ColumnDef *column)
 
static void setSchemaName (const char *context_schema, char **stmt_schema_name)
 
static void transformPartitionCmd (CreateStmtContext *cxt, PartitionBoundSpec *bound)
 
static ListtransformPartitionRangeBounds (ParseState *pstate, List *blist, Relation parent)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
 
ListtransformCreateStmt (CreateStmt *stmt, const char *queryString)
 
static void generateSerialExtraStmts (CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
 
ListexpandTableLikeClause (RangeVar *heapRel, TableLikeClause *table_like_clause)
 
IndexStmtgenerateClonedIndexStmt (RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
 
IndexStmttransformIndexStmt (Oid relid, IndexStmt *stmt, const char *queryString)
 
CreateStatsStmttransformStatsStmt (Oid relid, CreateStatsStmt *stmt, const char *queryString)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
static void checkPartition (Relation rel, Oid partRelOid)
 
static void transformPartitionCmdForSplit (CreateStmtContext *cxt, PartitionCmd *partcmd)
 
static void transformPartitionCmdForMerge (CreateStmtContext *cxt, PartitionCmd *partcmd)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
ListtransformCreateSchemaStmtElements (List *schemaElts, const char *schemaName)
 
PartitionBoundSpectransformPartitionBound (ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
 

Macro Definition Documentation

◆ SUPPORTS_ATTRS

#define SUPPORTS_ATTRS (   node)
Value:
((node) != NULL && \
((node)->contype == CONSTR_PRIMARY || \
(node)->contype == CONSTR_UNIQUE || \
(node)->contype == CONSTR_EXCLUSION || \
(node)->contype == CONSTR_FOREIGN))
@ CONSTR_FOREIGN
Definition: parsenodes.h:2714
@ CONSTR_UNIQUE
Definition: parsenodes.h:2712
@ CONSTR_EXCLUSION
Definition: parsenodes.h:2713
@ CONSTR_PRIMARY
Definition: parsenodes.h:2711

Function Documentation

◆ checkPartition()

static void checkPartition ( Relation  rel,
Oid  partRelOid 
)
static

Definition at line 3240 of file parse_utilcmd.c.

3241 {
3242  Relation partRel;
3243 
3244  partRel = relation_open(partRelOid, AccessShareLock);
3245 
3246  if (partRel->rd_rel->relkind != RELKIND_RELATION)
3247  ereport(ERROR,
3248  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3249  errmsg("\"%s\" is not a table",
3250  RelationGetRelationName(partRel))));
3251 
3252  if (!partRel->rd_rel->relispartition)
3253  ereport(ERROR,
3254  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3255  errmsg("\"%s\" is not a partition",
3256  RelationGetRelationName(partRel))));
3257 
3258  if (get_partition_parent(partRelOid, false) != RelationGetRelid(rel))
3259  ereport(ERROR,
3261  errmsg("relation \"%s\" is not a partition of relation \"%s\"",
3262  RelationGetRelationName(partRel),
3263  RelationGetRelationName(rel))));
3264 
3265  /* Permissions checks */
3266  if (!object_ownercheck(RelationRelationId, RelationGetRelid(partRel), GetUserId()))
3268  RelationGetRelationName(partRel));
3269 
3270  relation_close(partRel, AccessShareLock);
3271 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2700
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4142
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define AccessShareLock
Definition: lockdefs.h:36
Oid GetUserId(void)
Definition: miscinit.c:514
ObjectType get_relkind_objtype(char relkind)
Oid get_partition_parent(Oid relid, bool even_if_detached)
Definition: partition.c:53
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationGetRelationName(relation)
Definition: rel.h:539
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
Form_pg_class rd_rel
Definition: rel.h:111

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), ERROR, get_partition_parent(), get_relkind_objtype(), GetUserId(), object_ownercheck(), RelationData::rd_rel, relation_close(), relation_open(), RelationGetRelationName, and RelationGetRelid.

Referenced by transformPartitionCmdForMerge(), and transformPartitionCmdForSplit().

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1144 of file parse_utilcmd.c.

1145 {
1146  List *result = NIL;
1147  List *atsubcmds = NIL;
1148  AttrNumber parent_attno;
1149  Relation relation;
1150  Relation childrel;
1151  TupleDesc tupleDesc;
1152  TupleConstr *constr;
1153  AttrMap *attmap;
1154  char *comment;
1155 
1156  /*
1157  * Open the relation referenced by the LIKE clause. We should still have
1158  * the table lock obtained by transformTableLikeClause (and this'll throw
1159  * an assertion failure if not). Hence, no need to recheck privileges
1160  * etc. We must open the rel by OID not name, to be sure we get the same
1161  * table.
1162  */
1163  if (!OidIsValid(table_like_clause->relationOid))
1164  elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1165 
1166  relation = relation_open(table_like_clause->relationOid, NoLock);
1167 
1168  tupleDesc = RelationGetDescr(relation);
1169  constr = tupleDesc->constr;
1170 
1171  /*
1172  * Open the newly-created child relation; we have lock on that too.
1173  */
1174  childrel = relation_openrv(heapRel, NoLock);
1175 
1176  /*
1177  * Construct a map from the LIKE relation's attnos to the child rel's.
1178  * This re-checks type match etc, although it shouldn't be possible to
1179  * have a failure since both tables are locked.
1180  */
1181  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1182  tupleDesc,
1183  false);
1184 
1185  /*
1186  * Process defaults, if required.
1187  */
1188  if ((table_like_clause->options &
1190  constr != NULL)
1191  {
1192  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1193  parent_attno++)
1194  {
1195  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1196  parent_attno - 1);
1197 
1198  /*
1199  * Ignore dropped columns in the parent.
1200  */
1201  if (attribute->attisdropped)
1202  continue;
1203 
1204  /*
1205  * Copy default, if present and it should be copied. We have
1206  * separate options for plain default expressions and GENERATED
1207  * defaults.
1208  */
1209  if (attribute->atthasdef &&
1210  (attribute->attgenerated ?
1211  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1212  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1213  {
1214  Node *this_default;
1215  AlterTableCmd *atsubcmd;
1216  bool found_whole_row;
1217 
1218  this_default = TupleDescGetDefault(tupleDesc, parent_attno);
1219  if (this_default == NULL)
1220  elog(ERROR, "default expression not found for attribute %d of relation \"%s\"",
1221  parent_attno, RelationGetRelationName(relation));
1222 
1223  atsubcmd = makeNode(AlterTableCmd);
1224  atsubcmd->subtype = AT_CookedColumnDefault;
1225  atsubcmd->num = attmap->attnums[parent_attno - 1];
1226  atsubcmd->def = map_variable_attnos(this_default,
1227  1, 0,
1228  attmap,
1229  InvalidOid,
1230  &found_whole_row);
1231 
1232  /*
1233  * Prevent this for the same reason as for constraints below.
1234  * Note that defaults cannot contain any vars, so it's OK that
1235  * the error message refers to generated columns.
1236  */
1237  if (found_whole_row)
1238  ereport(ERROR,
1239  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1240  errmsg("cannot convert whole-row table reference"),
1241  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1242  NameStr(attribute->attname),
1243  RelationGetRelationName(relation))));
1244 
1245  atsubcmds = lappend(atsubcmds, atsubcmd);
1246  }
1247  }
1248  }
1249 
1250  /*
1251  * Copy CHECK constraints if requested, being careful to adjust attribute
1252  * numbers so they match the child.
1253  */
1254  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1255  constr != NULL)
1256  {
1257  int ccnum;
1258 
1259  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1260  {
1261  char *ccname = constr->check[ccnum].ccname;
1262  char *ccbin = constr->check[ccnum].ccbin;
1263  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1264  Node *ccbin_node;
1265  bool found_whole_row;
1266  Constraint *n;
1267  AlterTableCmd *atsubcmd;
1268 
1269  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1270  1, 0,
1271  attmap,
1272  InvalidOid, &found_whole_row);
1273 
1274  /*
1275  * We reject whole-row variables because the whole point of LIKE
1276  * is that the new table's rowtype might later diverge from the
1277  * parent's. So, while translation might be possible right now,
1278  * it wouldn't be possible to guarantee it would work in future.
1279  */
1280  if (found_whole_row)
1281  ereport(ERROR,
1282  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1283  errmsg("cannot convert whole-row table reference"),
1284  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1285  ccname,
1286  RelationGetRelationName(relation))));
1287 
1288  n = makeNode(Constraint);
1289  n->contype = CONSTR_CHECK;
1290  n->conname = pstrdup(ccname);
1291  n->location = -1;
1292  n->is_no_inherit = ccnoinherit;
1293  n->raw_expr = NULL;
1294  n->cooked_expr = nodeToString(ccbin_node);
1295 
1296  /* We can skip validation, since the new table should be empty. */
1297  n->skip_validation = true;
1298  n->initially_valid = true;
1299 
1300  atsubcmd = makeNode(AlterTableCmd);
1301  atsubcmd->subtype = AT_AddConstraint;
1302  atsubcmd->def = (Node *) n;
1303  atsubcmds = lappend(atsubcmds, atsubcmd);
1304 
1305  /* Copy comment on constraint */
1306  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1308  n->conname, false),
1309  ConstraintRelationId,
1310  0)) != NULL)
1311  {
1313 
1314  stmt->objtype = OBJECT_TABCONSTRAINT;
1315  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1316  makeString(heapRel->relname),
1317  makeString(n->conname));
1318  stmt->comment = comment;
1319 
1320  result = lappend(result, stmt);
1321  }
1322  }
1323  }
1324 
1325  /*
1326  * If we generated any ALTER TABLE actions above, wrap them into a single
1327  * ALTER TABLE command. Stick it at the front of the result, so it runs
1328  * before any CommentStmts we made above.
1329  */
1330  if (atsubcmds)
1331  {
1333 
1334  atcmd->relation = copyObject(heapRel);
1335  atcmd->cmds = atsubcmds;
1336  atcmd->objtype = OBJECT_TABLE;
1337  atcmd->missing_ok = false;
1338  result = lcons(atcmd, result);
1339  }
1340 
1341  /*
1342  * Process indexes if required.
1343  */
1344  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1345  relation->rd_rel->relhasindex)
1346  {
1347  List *parent_indexes;
1348  ListCell *l;
1349 
1350  parent_indexes = RelationGetIndexList(relation);
1351 
1352  foreach(l, parent_indexes)
1353  {
1354  Oid parent_index_oid = lfirst_oid(l);
1355  Relation parent_index;
1356  IndexStmt *index_stmt;
1357 
1358  parent_index = index_open(parent_index_oid, AccessShareLock);
1359 
1360  /* Build CREATE INDEX statement to recreate the parent_index */
1361  index_stmt = generateClonedIndexStmt(heapRel,
1362  parent_index,
1363  attmap,
1364  NULL);
1365 
1366  /* Copy comment on index, if requested */
1367  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1368  {
1369  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1370 
1371  /*
1372  * We make use of IndexStmt's idxcomment option, so as not to
1373  * need to know now what name the index will have.
1374  */
1375  index_stmt->idxcomment = comment;
1376  }
1377 
1378  result = lappend(result, index_stmt);
1379 
1380  index_close(parent_index, AccessShareLock);
1381  }
1382  }
1383 
1384  /*
1385  * Process extended statistics if required.
1386  */
1387  if (table_like_clause->options & CREATE_TABLE_LIKE_STATISTICS)
1388  {
1389  List *parent_extstats;
1390  ListCell *l;
1391 
1392  parent_extstats = RelationGetStatExtList(relation);
1393 
1394  foreach(l, parent_extstats)
1395  {
1396  Oid parent_stat_oid = lfirst_oid(l);
1397  CreateStatsStmt *stats_stmt;
1398 
1399  stats_stmt = generateClonedExtStatsStmt(heapRel,
1400  RelationGetRelid(childrel),
1401  parent_stat_oid,
1402  attmap);
1403 
1404  /* Copy comment on statistics object, if requested */
1405  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1406  {
1407  comment = GetComment(parent_stat_oid, StatisticExtRelationId, 0);
1408 
1409  /*
1410  * We make use of CreateStatsStmt's stxcomment option, so as
1411  * not to need to know now what name the statistics will have.
1412  */
1413  stats_stmt->stxcomment = comment;
1414  }
1415 
1416  result = lappend(result, stats_stmt);
1417  }
1418 
1419  list_free(parent_extstats);
1420  }
1421 
1422  /* Done with child rel */
1423  table_close(childrel, NoLock);
1424 
1425  /*
1426  * Close the parent rel, but keep our AccessShareLock on it until xact
1427  * commit. That will prevent someone else from deleting or ALTERing the
1428  * parent before the child is committed.
1429  */
1430  table_close(relation, NoLock);
1431 
1432  return result;
1433 }
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition: attmap.c:177
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:746
#define OidIsValid(objectId)
Definition: c.h:775
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:410
int errdetail(const char *fmt,...)
Definition: elog.c:1203
#define elog(elevel,...)
Definition: elog.h:224
#define stmt
Definition: indent_codes.h:59
#define comment
Definition: indent_codes.h:49
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
List * lappend(List *list, void *datum)
Definition: list.c:339
void list_free(List *list)
Definition: list.c:1546
List * lcons(void *datum, List *list)
Definition: list.c:495
#define NoLock
Definition: lockdefs.h:34
char * pstrdup(const char *in)
Definition: mcxt.c:1696
#define copyObject(obj)
Definition: nodes.h:224
#define makeNode(_type_)
Definition: nodes.h:155
char * nodeToString(const void *obj)
Definition: outfuncs.c:791
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
static CreateStatsStmt * generateClonedExtStatsStmt(RangeVar *heapRel, Oid heapRelid, Oid source_statsid, const AttrMap *attmap)
@ CONSTR_CHECK
Definition: parsenodes.h:2710
@ OBJECT_TABLE
Definition: parsenodes.h:2302
@ OBJECT_TABCONSTRAINT
Definition: parsenodes.h:2301
@ AT_AddConstraint
Definition: parsenodes.h:2370
@ AT_CookedColumnDefault
Definition: parsenodes.h:2356
@ CREATE_TABLE_LIKE_COMMENTS
Definition: parsenodes.h:761
@ CREATE_TABLE_LIKE_GENERATED
Definition: parsenodes.h:765
@ CREATE_TABLE_LIKE_INDEXES
Definition: parsenodes.h:767
@ CREATE_TABLE_LIKE_DEFAULTS
Definition: parsenodes.h:764
@ CREATE_TABLE_LIKE_STATISTICS
Definition: parsenodes.h:768
@ CREATE_TABLE_LIKE_CONSTRAINTS
Definition: parsenodes.h:763
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define NIL
Definition: pg_list.h:68
#define list_make3(x1, x2, x3)
Definition: pg_list.h:216
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetDescr(relation)
Definition: rel.h:531
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4801
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4922
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:137
AlterTableType subtype
Definition: parsenodes.h:2434
RangeVar * relation
Definition: parsenodes.h:2345
ObjectType objtype
Definition: parsenodes.h:2347
Definition: attmap.h:35
AttrNumber * attnums
Definition: attmap.h:36
char * ccname
Definition: tupdesc.h:30
bool ccnoinherit
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
ParseLoc location
Definition: parsenodes.h:2777
ConstrType contype
Definition: parsenodes.h:2736
bool is_no_inherit
Definition: parsenodes.h:2742
char * cooked_expr
Definition: parsenodes.h:2745
bool initially_valid
Definition: parsenodes.h:2741
bool skip_validation
Definition: parsenodes.h:2740
Node * raw_expr
Definition: parsenodes.h:2743
char * conname
Definition: parsenodes.h:2737
char * idxcomment
Definition: parsenodes.h:3366
Definition: pg_list.h:54
Definition: nodes.h:129
char * relname
Definition: primnodes.h:82
char * schemaname
Definition: primnodes.h:79
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Node * TupleDescGetDefault(TupleDesc tupdesc, AttrNumber attnum)
Definition: tupdesc.c:899
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
String * makeString(char *str)
Definition: value.c:63

References AccessShareLock, AT_AddConstraint, AT_CookedColumnDefault, AttrMap::attnums, build_attrmap_by_name(), ConstrCheck::ccbin, ConstrCheck::ccname, ConstrCheck::ccnoinherit, TupleConstr::check, AlterTableStmt::cmds, comment, Constraint::conname, TupleDescData::constr, CONSTR_CHECK, Constraint::contype, Constraint::cooked_expr, copyObject, CREATE_TABLE_LIKE_COMMENTS, CREATE_TABLE_LIKE_CONSTRAINTS, CREATE_TABLE_LIKE_DEFAULTS, CREATE_TABLE_LIKE_GENERATED, CREATE_TABLE_LIKE_INDEXES, CREATE_TABLE_LIKE_STATISTICS, AlterTableCmd::def, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, generateClonedExtStatsStmt(), generateClonedIndexStmt(), get_relation_constraint_oid(), GetComment(), IndexStmt::idxcomment, index_close(), index_open(), Constraint::initially_valid, InvalidOid, Constraint::is_no_inherit, lappend(), lcons(), lfirst_oid, list_free(), list_make3, Constraint::location, makeNode, makeString(), map_variable_attnos(), AlterTableStmt::missing_ok, NameStr, TupleDescData::natts, NIL, nodeToString(), NoLock, AlterTableCmd::num, TupleConstr::num_check, OBJECT_TABCONSTRAINT, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, TableLikeClause::options, pstrdup(), Constraint::raw_expr, RelationData::rd_rel, AlterTableStmt::relation, relation_open(), relation_openrv(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, RelationGetRelid, RelationGetStatExtList(), TableLikeClause::relationOid, RangeVar::relname, RangeVar::schemaname, Constraint::skip_validation, stmt, stringToNode(), CreateStatsStmt::stxcomment, AlterTableCmd::subtype, table_close(), TupleDescAttr, and TupleDescGetDefault().

Referenced by ProcessUtilitySlow().

◆ generateClonedExtStatsStmt()

static CreateStatsStmt * generateClonedExtStatsStmt ( RangeVar heapRel,
Oid  heapRelid,
Oid  source_statsid,
const AttrMap attmap 
)
static

Definition at line 1840 of file parse_utilcmd.c.

1842 {
1843  HeapTuple ht_stats;
1844  Form_pg_statistic_ext statsrec;
1845  CreateStatsStmt *stats;
1846  List *stat_types = NIL;
1847  List *def_names = NIL;
1848  bool isnull;
1849  Datum datum;
1850  ArrayType *arr;
1851  char *enabled;
1852  int i;
1853 
1854  Assert(OidIsValid(heapRelid));
1855  Assert(heapRel != NULL);
1856 
1857  /*
1858  * Fetch pg_statistic_ext tuple of source statistics object.
1859  */
1860  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1861  if (!HeapTupleIsValid(ht_stats))
1862  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1863  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1864 
1865  /* Determine which statistics types exist */
1866  datum = SysCacheGetAttrNotNull(STATEXTOID, ht_stats,
1867  Anum_pg_statistic_ext_stxkind);
1868  arr = DatumGetArrayTypeP(datum);
1869  if (ARR_NDIM(arr) != 1 ||
1870  ARR_HASNULL(arr) ||
1871  ARR_ELEMTYPE(arr) != CHAROID)
1872  elog(ERROR, "stxkind is not a 1-D char array");
1873  enabled = (char *) ARR_DATA_PTR(arr);
1874  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1875  {
1876  if (enabled[i] == STATS_EXT_NDISTINCT)
1877  stat_types = lappend(stat_types, makeString("ndistinct"));
1878  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1879  stat_types = lappend(stat_types, makeString("dependencies"));
1880  else if (enabled[i] == STATS_EXT_MCV)
1881  stat_types = lappend(stat_types, makeString("mcv"));
1882  else if (enabled[i] == STATS_EXT_EXPRESSIONS)
1883  /* expression stats are not exposed to users */
1884  continue;
1885  else
1886  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1887  }
1888 
1889  /* Determine which columns the statistics are on */
1890  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1891  {
1892  StatsElem *selem = makeNode(StatsElem);
1893  AttrNumber attnum = statsrec->stxkeys.values[i];
1894 
1895  selem->name = get_attname(heapRelid, attnum, false);
1896  selem->expr = NULL;
1897 
1898  def_names = lappend(def_names, selem);
1899  }
1900 
1901  /*
1902  * Now handle expressions, if there are any. The order (with respect to
1903  * regular attributes) does not really matter for extended stats, so we
1904  * simply append them after simple column references.
1905  *
1906  * XXX Some places during build/estimation treat expressions as if they
1907  * are before attributes, but for the CREATE command that's entirely
1908  * irrelevant.
1909  */
1910  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1911  Anum_pg_statistic_ext_stxexprs, &isnull);
1912 
1913  if (!isnull)
1914  {
1915  ListCell *lc;
1916  List *exprs = NIL;
1917  char *exprsString;
1918 
1919  exprsString = TextDatumGetCString(datum);
1920  exprs = (List *) stringToNode(exprsString);
1921 
1922  foreach(lc, exprs)
1923  {
1924  Node *expr = (Node *) lfirst(lc);
1925  StatsElem *selem = makeNode(StatsElem);
1926  bool found_whole_row;
1927 
1928  /* Adjust Vars to match new table's column numbering */
1929  expr = map_variable_attnos(expr,
1930  1, 0,
1931  attmap,
1932  InvalidOid,
1933  &found_whole_row);
1934 
1935  selem->name = NULL;
1936  selem->expr = expr;
1937 
1938  def_names = lappend(def_names, selem);
1939  }
1940 
1941  pfree(exprsString);
1942  }
1943 
1944  /* finally, build the output node */
1945  stats = makeNode(CreateStatsStmt);
1946  stats->defnames = NULL;
1947  stats->stat_types = stat_types;
1948  stats->exprs = def_names;
1949  stats->relations = list_make1(heapRel);
1950  stats->stxcomment = NULL;
1951  stats->transformed = true; /* don't need transformStatsStmt again */
1952  stats->if_not_exists = false;
1953 
1954  /* Clean up */
1955  ReleaseSysCache(ht_stats);
1956 
1957  return stats;
1958 }
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
#define ARR_HASNULL(a)
Definition: array.h:291
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define Assert(condition)
Definition: c.h:858
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
int i
Definition: isn.c:73
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:827
void pfree(void *pointer)
Definition: mcxt.c:1521
int16 attnum
Definition: pg_attribute.h:74
#define lfirst(lc)
Definition: pg_list.h:172
#define list_make1(x1)
Definition: pg_list.h:212
FormData_pg_statistic_ext * Form_pg_statistic_ext
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
char * name
Definition: parsenodes.h:3411
Node * expr
Definition: parsenodes.h:3412
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, attnum, DatumGetArrayTypeP, CreateStatsStmt::defnames, elog, ERROR, StatsElem::expr, CreateStatsStmt::exprs, get_attname(), GETSTRUCT, HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, InvalidOid, lappend(), lfirst, list_make1, makeNode, makeString(), map_variable_attnos(), StatsElem::name, NIL, ObjectIdGetDatum(), OidIsValid, pfree(), CreateStatsStmt::relations, ReleaseSysCache(), SearchSysCache1(), CreateStatsStmt::stat_types, stringToNode(), CreateStatsStmt::stxcomment, SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, and CreateStatsStmt::transformed.

Referenced by expandTableLikeClause().

◆ generateClonedIndexStmt()

IndexStmt* generateClonedIndexStmt ( RangeVar heapRel,
Relation  source_idx,
const AttrMap attmap,
Oid constraintOid 
)

Definition at line 1489 of file parse_utilcmd.c.

1492 {
1493  Oid source_relid = RelationGetRelid(source_idx);
1494  HeapTuple ht_idxrel;
1495  HeapTuple ht_idx;
1496  HeapTuple ht_am;
1497  Form_pg_class idxrelrec;
1498  Form_pg_index idxrec;
1499  Form_pg_am amrec;
1500  oidvector *indcollation;
1501  oidvector *indclass;
1502  IndexStmt *index;
1503  List *indexprs;
1504  ListCell *indexpr_item;
1505  Oid indrelid;
1506  int keyno;
1507  Oid keycoltype;
1508  Datum datum;
1509  bool isnull;
1510 
1511  if (constraintOid)
1512  *constraintOid = InvalidOid;
1513 
1514  /*
1515  * Fetch pg_class tuple of source index. We can't use the copy in the
1516  * relcache entry because it doesn't include optional fields.
1517  */
1518  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1519  if (!HeapTupleIsValid(ht_idxrel))
1520  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1521  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1522 
1523  /* Fetch pg_index tuple for source index from relcache entry */
1524  ht_idx = source_idx->rd_indextuple;
1525  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1526  indrelid = idxrec->indrelid;
1527 
1528  /* Fetch the pg_am tuple of the index' access method */
1529  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1530  if (!HeapTupleIsValid(ht_am))
1531  elog(ERROR, "cache lookup failed for access method %u",
1532  idxrelrec->relam);
1533  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1534 
1535  /* Extract indcollation from the pg_index tuple */
1536  datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx,
1537  Anum_pg_index_indcollation);
1538  indcollation = (oidvector *) DatumGetPointer(datum);
1539 
1540  /* Extract indclass from the pg_index tuple */
1541  datum = SysCacheGetAttrNotNull(INDEXRELID, ht_idx, Anum_pg_index_indclass);
1542  indclass = (oidvector *) DatumGetPointer(datum);
1543 
1544  /* Begin building the IndexStmt */
1546  index->relation = heapRel;
1547  index->accessMethod = pstrdup(NameStr(amrec->amname));
1548  if (OidIsValid(idxrelrec->reltablespace))
1549  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1550  else
1551  index->tableSpace = NULL;
1552  index->excludeOpNames = NIL;
1553  index->idxcomment = NULL;
1554  index->indexOid = InvalidOid;
1555  index->oldNumber = InvalidRelFileNumber;
1556  index->oldCreateSubid = InvalidSubTransactionId;
1557  index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
1558  index->unique = idxrec->indisunique;
1559  index->nulls_not_distinct = idxrec->indnullsnotdistinct;
1560  index->primary = idxrec->indisprimary;
1561  index->transformed = true; /* don't need transformIndexStmt */
1562  index->concurrent = false;
1563  index->if_not_exists = false;
1564  index->reset_default_tblspc = false;
1565 
1566  /*
1567  * We don't try to preserve the name of the source index; instead, just
1568  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1569  * the name, we'd get duplicate-relation-name failures unless the source
1570  * table was in a different schema.)
1571  */
1572  index->idxname = NULL;
1573 
1574  /*
1575  * If the index is marked PRIMARY or has an exclusion condition, it's
1576  * certainly from a constraint; else, if it's not marked UNIQUE, it
1577  * certainly isn't. If it is or might be from a constraint, we have to
1578  * fetch the pg_constraint record.
1579  */
1580  if (index->primary || index->unique || idxrec->indisexclusion)
1581  {
1582  Oid constraintId = get_index_constraint(source_relid);
1583 
1584  if (OidIsValid(constraintId))
1585  {
1586  HeapTuple ht_constr;
1587  Form_pg_constraint conrec;
1588 
1589  if (constraintOid)
1590  *constraintOid = constraintId;
1591 
1592  ht_constr = SearchSysCache1(CONSTROID,
1593  ObjectIdGetDatum(constraintId));
1594  if (!HeapTupleIsValid(ht_constr))
1595  elog(ERROR, "cache lookup failed for constraint %u",
1596  constraintId);
1597  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1598 
1599  index->isconstraint = true;
1600  index->deferrable = conrec->condeferrable;
1601  index->initdeferred = conrec->condeferred;
1602 
1603  /* If it's an exclusion constraint, we need the operator names */
1604  if (idxrec->indisexclusion)
1605  {
1606  Datum *elems;
1607  int nElems;
1608  int i;
1609 
1610  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1611  /* Extract operator OIDs from the pg_constraint tuple */
1612  datum = SysCacheGetAttrNotNull(CONSTROID, ht_constr,
1613  Anum_pg_constraint_conexclop);
1614  deconstruct_array_builtin(DatumGetArrayTypeP(datum), OIDOID, &elems, NULL, &nElems);
1615 
1616  for (i = 0; i < nElems; i++)
1617  {
1618  Oid operid = DatumGetObjectId(elems[i]);
1619  HeapTuple opertup;
1620  Form_pg_operator operform;
1621  char *oprname;
1622  char *nspname;
1623  List *namelist;
1624 
1625  opertup = SearchSysCache1(OPEROID,
1626  ObjectIdGetDatum(operid));
1627  if (!HeapTupleIsValid(opertup))
1628  elog(ERROR, "cache lookup failed for operator %u",
1629  operid);
1630  operform = (Form_pg_operator) GETSTRUCT(opertup);
1631  oprname = pstrdup(NameStr(operform->oprname));
1632  /* For simplicity we always schema-qualify the op name */
1633  nspname = get_namespace_name(operform->oprnamespace);
1634  namelist = list_make2(makeString(nspname),
1635  makeString(oprname));
1636  index->excludeOpNames = lappend(index->excludeOpNames,
1637  namelist);
1638  ReleaseSysCache(opertup);
1639  }
1640  }
1641 
1642  ReleaseSysCache(ht_constr);
1643  }
1644  else
1645  index->isconstraint = false;
1646  }
1647  else
1648  index->isconstraint = false;
1649 
1650  /* Get the index expressions, if any */
1651  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1652  Anum_pg_index_indexprs, &isnull);
1653  if (!isnull)
1654  {
1655  char *exprsString;
1656 
1657  exprsString = TextDatumGetCString(datum);
1658  indexprs = (List *) stringToNode(exprsString);
1659  }
1660  else
1661  indexprs = NIL;
1662 
1663  /* Build the list of IndexElem */
1664  index->indexParams = NIL;
1665  index->indexIncludingParams = NIL;
1666 
1667  indexpr_item = list_head(indexprs);
1668  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1669  {
1670  IndexElem *iparam;
1671  AttrNumber attnum = idxrec->indkey.values[keyno];
1673  keyno);
1674  int16 opt = source_idx->rd_indoption[keyno];
1675 
1676  iparam = makeNode(IndexElem);
1677 
1679  {
1680  /* Simple index column */
1681  char *attname;
1682 
1683  attname = get_attname(indrelid, attnum, false);
1684  keycoltype = get_atttype(indrelid, attnum);
1685 
1686  iparam->name = attname;
1687  iparam->expr = NULL;
1688  }
1689  else
1690  {
1691  /* Expressional index */
1692  Node *indexkey;
1693  bool found_whole_row;
1694 
1695  if (indexpr_item == NULL)
1696  elog(ERROR, "too few entries in indexprs list");
1697  indexkey = (Node *) lfirst(indexpr_item);
1698  indexpr_item = lnext(indexprs, indexpr_item);
1699 
1700  /* Adjust Vars to match new table's column numbering */
1701  indexkey = map_variable_attnos(indexkey,
1702  1, 0,
1703  attmap,
1704  InvalidOid, &found_whole_row);
1705 
1706  /* As in expandTableLikeClause, reject whole-row variables */
1707  if (found_whole_row)
1708  ereport(ERROR,
1709  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1710  errmsg("cannot convert whole-row table reference"),
1711  errdetail("Index \"%s\" contains a whole-row table reference.",
1712  RelationGetRelationName(source_idx))));
1713 
1714  iparam->name = NULL;
1715  iparam->expr = indexkey;
1716 
1717  keycoltype = exprType(indexkey);
1718  }
1719 
1720  /* Copy the original index column name */
1721  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1722 
1723  /* Add the collation name, if non-default */
1724  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1725 
1726  /* Add the operator class name, if non-default */
1727  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1728  iparam->opclassopts =
1729  untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1730 
1731  iparam->ordering = SORTBY_DEFAULT;
1733 
1734  /* Adjust options if necessary */
1735  if (source_idx->rd_indam->amcanorder)
1736  {
1737  /*
1738  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1739  * set non-default settings unnecessarily, though, so as to
1740  * improve the chance of recognizing equivalence to constraint
1741  * indexes.
1742  */
1743  if (opt & INDOPTION_DESC)
1744  {
1745  iparam->ordering = SORTBY_DESC;
1746  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1748  }
1749  else
1750  {
1751  if (opt & INDOPTION_NULLS_FIRST)
1753  }
1754  }
1755 
1756  index->indexParams = lappend(index->indexParams, iparam);
1757  }
1758 
1759  /* Handle included columns separately */
1760  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1761  {
1762  IndexElem *iparam;
1763  AttrNumber attnum = idxrec->indkey.values[keyno];
1765  keyno);
1766 
1767  iparam = makeNode(IndexElem);
1768 
1770  {
1771  /* Simple index column */
1772  char *attname;
1773 
1774  attname = get_attname(indrelid, attnum, false);
1775 
1776  iparam->name = attname;
1777  iparam->expr = NULL;
1778  }
1779  else
1780  ereport(ERROR,
1781  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1782  errmsg("expressions are not supported in included columns")));
1783 
1784  /* Copy the original index column name */
1785  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1786 
1787  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1788  }
1789  /* Copy reloptions if any */
1790  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1791  Anum_pg_class_reloptions, &isnull);
1792  if (!isnull)
1793  index->options = untransformRelOptions(datum);
1794 
1795  /* If it's a partial index, decompile and append the predicate */
1796  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1797  Anum_pg_index_indpred, &isnull);
1798  if (!isnull)
1799  {
1800  char *pred_str;
1801  Node *pred_tree;
1802  bool found_whole_row;
1803 
1804  /* Convert text string to node tree */
1805  pred_str = TextDatumGetCString(datum);
1806  pred_tree = (Node *) stringToNode(pred_str);
1807 
1808  /* Adjust Vars to match new table's column numbering */
1809  pred_tree = map_variable_attnos(pred_tree,
1810  1, 0,
1811  attmap,
1812  InvalidOid, &found_whole_row);
1813 
1814  /* As in expandTableLikeClause, reject whole-row variables */
1815  if (found_whole_row)
1816  ereport(ERROR,
1817  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1818  errmsg("cannot convert whole-row table reference"),
1819  errdetail("Index \"%s\" contains a whole-row table reference.",
1820  RelationGetRelationName(source_idx))));
1821 
1822  index->whereClause = pred_tree;
1823  }
1824 
1825  /* Clean up */
1826  ReleaseSysCache(ht_idxrel);
1827  ReleaseSysCache(ht_am);
1828 
1829  return index;
1830 }
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3685
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1472
signed short int16
Definition: c.h:493
#define InvalidSubTransactionId
Definition: c.h:658
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:970
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:913
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static List * get_collation(Oid collation, Oid actual_datatype)
static List * get_opclass(Oid opclass, Oid actual_datatype)
@ SORTBY_NULLS_DEFAULT
Definition: parsenodes.h:54
@ SORTBY_NULLS_LAST
Definition: parsenodes.h:56
@ SORTBY_NULLS_FIRST
Definition: parsenodes.h:55
@ SORTBY_DESC
Definition: parsenodes.h:48
@ SORTBY_DEFAULT
Definition: parsenodes.h:46
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
NameData attname
Definition: pg_attribute.h:41
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
FormData_pg_constraint * Form_pg_constraint
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:989
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define list_make2(x1, x2)
Definition: pg_list.h:214
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1331
#define InvalidRelFileNumber
Definition: relpath.h:26
bool amcanorder
Definition: amapi.h:224
Node * expr
Definition: parsenodes.h:784
SortByDir ordering
Definition: parsenodes.h:789
List * opclassopts
Definition: parsenodes.h:788
char * indexcolname
Definition: parsenodes.h:785
SortByNulls nulls_ordering
Definition: parsenodes.h:790
List * opclass
Definition: parsenodes.h:787
char * name
Definition: parsenodes.h:783
List * collation
Definition: parsenodes.h:786
struct IndexAmRoutine * rd_indam
Definition: rel.h:206
struct HeapTupleData * rd_indextuple
Definition: rel.h:194
int16 * rd_indoption
Definition: rel.h:211
Definition: type.h:95
Definition: c.h:726
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:733

References IndexAmRoutine::amcanorder, Assert, attname, attnum, AttributeNumberIsValid, IndexElem::collation, DatumGetArrayTypeP, DatumGetObjectId(), DatumGetPointer(), deconstruct_array_builtin(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexElem::expr, exprType(), get_attname(), get_attoptions(), get_atttype(), get_collation(), get_index_constraint(), get_namespace_name(), get_opclass(), get_tablespace_name(), GETSTRUCT, HeapTupleIsValid, i, IndexElem::indexcolname, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), IndexElem::name, NameStr, NIL, IndexElem::nulls_ordering, ObjectIdGetDatum(), OidIsValid, IndexElem::opclass, IndexElem::opclassopts, IndexElem::ordering, pstrdup(), RelationData::rd_indam, RelationData::rd_indextuple, RelationData::rd_indoption, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, TupleDescAttr, untransformRelOptions(), and oidvector::values.

Referenced by AttachPartitionEnsureIndexes(), DefineRelation(), and expandTableLikeClause().

◆ generateSerialExtraStmts()

static void generateSerialExtraStmts ( CreateStmtContext cxt,
ColumnDef column,
Oid  seqtypid,
List seqoptions,
bool  for_identity,
bool  col_exists,
char **  snamespace_p,
char **  sname_p 
)
static

Definition at line 364 of file parse_utilcmd.c.

368 {
369  ListCell *option;
370  DefElem *nameEl = NULL;
371  Oid snamespaceid;
372  char *snamespace;
373  char *sname;
374  CreateSeqStmt *seqstmt;
375  AlterSeqStmt *altseqstmt;
376  List *attnamelist;
377  int nameEl_idx = -1;
378 
379  /* Make a copy of this as we may end up modifying it in the code below */
380  seqoptions = list_copy(seqoptions);
381 
382  /*
383  * Determine namespace and name to use for the sequence.
384  *
385  * First, check if a sequence name was passed in as an option. This is
386  * used by pg_dump. Else, generate a name.
387  *
388  * Although we use ChooseRelationName, it's not guaranteed that the
389  * selected sequence name won't conflict; given sufficiently long field
390  * names, two different serial columns in the same table could be assigned
391  * the same sequence name, and we'd not notice since we aren't creating
392  * the sequence quite yet. In practice this seems quite unlikely to be a
393  * problem, especially since few people would need two serial columns in
394  * one table.
395  */
396  foreach(option, seqoptions)
397  {
398  DefElem *defel = lfirst_node(DefElem, option);
399 
400  if (strcmp(defel->defname, "sequence_name") == 0)
401  {
402  if (nameEl)
403  errorConflictingDefElem(defel, cxt->pstate);
404  nameEl = defel;
405  nameEl_idx = foreach_current_index(option);
406  }
407  }
408 
409  if (nameEl)
410  {
412 
413  snamespace = rv->schemaname;
414  if (!snamespace)
415  {
416  /* Given unqualified SEQUENCE NAME, select namespace */
417  if (cxt->rel)
418  snamespaceid = RelationGetNamespace(cxt->rel);
419  else
420  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
421  snamespace = get_namespace_name(snamespaceid);
422  }
423  sname = rv->relname;
424  /* Remove the SEQUENCE NAME item from seqoptions */
425  seqoptions = list_delete_nth_cell(seqoptions, nameEl_idx);
426  }
427  else
428  {
429  if (cxt->rel)
430  snamespaceid = RelationGetNamespace(cxt->rel);
431  else
432  {
433  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
434  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
435  }
436  snamespace = get_namespace_name(snamespaceid);
437  sname = ChooseRelationName(cxt->relation->relname,
438  column->colname,
439  "seq",
440  snamespaceid,
441  false);
442  }
443 
444  ereport(DEBUG1,
445  (errmsg_internal("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
446  cxt->stmtType, sname,
447  cxt->relation->relname, column->colname)));
448 
449  /*
450  * Build a CREATE SEQUENCE command to create the sequence object, and add
451  * it to the list of things to be done before this CREATE/ALTER TABLE.
452  */
453  seqstmt = makeNode(CreateSeqStmt);
454  seqstmt->for_identity = for_identity;
455  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
456 
457  /*
458  * Copy the persistence of the table. For CREATE TABLE, we get the
459  * persistence from cxt->relation, which comes from the CreateStmt in
460  * progress. For ALTER TABLE, the parser won't set
461  * cxt->relation->relpersistence, but we have cxt->rel as the existing
462  * table, so we copy the persistence from there.
463  */
464  seqstmt->sequence->relpersistence = cxt->rel ? cxt->rel->rd_rel->relpersistence : cxt->relation->relpersistence;
465 
466  seqstmt->options = seqoptions;
467 
468  /*
469  * If a sequence data type was specified, add it to the options. Prepend
470  * to the list rather than append; in case a user supplied their own AS
471  * clause, the "redundant options" error will point to their occurrence,
472  * not our synthetic one.
473  */
474  if (seqtypid)
475  seqstmt->options = lcons(makeDefElem("as",
476  (Node *) makeTypeNameFromOid(seqtypid, -1),
477  -1),
478  seqstmt->options);
479 
480  /*
481  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
482  * the table's owner. The current user might be someone else (perhaps a
483  * superuser, or someone who's only a member of the owning role), but the
484  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
485  * exactly the same owning role.
486  */
487  if (cxt->rel)
488  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
489  else
490  seqstmt->ownerId = InvalidOid;
491 
492  cxt->blist = lappend(cxt->blist, seqstmt);
493 
494  /*
495  * Store the identity sequence name that we decided on. ALTER TABLE ...
496  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
497  * with values from the sequence, while the association of the sequence
498  * with the table is not set until after the ALTER TABLE.
499  */
500  column->identitySequence = seqstmt->sequence;
501 
502  /*
503  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
504  * owned by this column, and add it to the appropriate list of things to
505  * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
506  * COLUMN, it must be done after the statement because we don't know the
507  * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
508  * we can do the marking immediately, which improves some ALTER TABLE
509  * behaviors.
510  */
511  altseqstmt = makeNode(AlterSeqStmt);
512  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
513  attnamelist = list_make3(makeString(snamespace),
514  makeString(cxt->relation->relname),
515  makeString(column->colname));
516  altseqstmt->options = list_make1(makeDefElem("owned_by",
517  (Node *) attnamelist, -1));
518  altseqstmt->for_identity = for_identity;
519 
520  if (col_exists)
521  cxt->blist = lappend(cxt->blist, altseqstmt);
522  else
523  cxt->alist = lappend(cxt->alist, altseqstmt);
524 
525  if (snamespace_p)
526  *snamespace_p = snamespace;
527  if (sname_p)
528  *sname_p = sname;
529 }
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:384
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
#define DEBUG1
Definition: elog.h:30
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2499
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * list_delete_nth_cell(List *list, int n)
Definition: list.c:767
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:564
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:474
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:831
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:639
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3539
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define RelationGetNamespace(relation)
Definition: rel.h:546
List * options
Definition: parsenodes.h:3136
RangeVar * sequence
Definition: parsenodes.h:3135
bool for_identity
Definition: parsenodes.h:3137
RangeVar * identitySequence
Definition: parsenodes.h:738
char * colname
Definition: parsenodes.h:726
List * options
Definition: parsenodes.h:3126
RangeVar * sequence
Definition: parsenodes.h:3125
const char * stmtType
Definition: parse_utilcmd.c:79
RangeVar * relation
Definition: parse_utilcmd.c:80
ParseState * pstate
Definition: parse_utilcmd.c:78
char * defname
Definition: parsenodes.h:815
Node * arg
Definition: parsenodes.h:816
char relpersistence
Definition: primnodes.h:88

References CreateStmtContext::alist, DefElem::arg, CreateStmtContext::blist, castNode, ChooseRelationName(), ColumnDef::colname, DEBUG1, DefElem::defname, ereport, errmsg_internal(), errorConflictingDefElem(), CreateSeqStmt::for_identity, AlterSeqStmt::for_identity, foreach_current_index, get_namespace_name(), ColumnDef::identitySequence, InvalidOid, lappend(), lcons(), lfirst_node, list_copy(), list_delete_nth_cell(), list_make1, list_make3, makeDefElem(), makeNode, makeRangeVar(), makeRangeVarFromNameList(), makeString(), makeTypeNameFromOid(), CreateSeqStmt::options, AlterSeqStmt::options, CreateSeqStmt::ownerId, CreateStmtContext::pstate, RangeVarAdjustRelationPersistence(), RangeVarGetCreationNamespace(), RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, RelationGetNamespace, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, CreateSeqStmt::sequence, AlterSeqStmt::sequence, and CreateStmtContext::stmtType.

Referenced by transformAlterTableStmt(), transformColumnDefinition(), and transformTableLikeClause().

◆ get_collation()

static List * get_collation ( Oid  collation,
Oid  actual_datatype 
)
static

Definition at line 1967 of file parse_utilcmd.c.

1968 {
1969  List *result;
1970  HeapTuple ht_coll;
1971  Form_pg_collation coll_rec;
1972  char *nsp_name;
1973  char *coll_name;
1974 
1975  if (!OidIsValid(collation))
1976  return NIL; /* easy case */
1977  if (collation == get_typcollation(actual_datatype))
1978  return NIL; /* just let it default */
1979 
1980  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1981  if (!HeapTupleIsValid(ht_coll))
1982  elog(ERROR, "cache lookup failed for collation %u", collation);
1983  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1984 
1985  /* For simplicity, we always schema-qualify the name */
1986  nsp_name = get_namespace_name(coll_rec->collnamespace);
1987  coll_name = pstrdup(NameStr(coll_rec->collname));
1988  result = list_make2(makeString(nsp_name), makeString(coll_name));
1989 
1990  ReleaseSysCache(ht_coll);
1991  return result;
1992 }
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:3056
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58

References elog, ERROR, get_namespace_name(), get_typcollation(), GETSTRUCT, HeapTupleIsValid, list_make2, makeString(), NameStr, NIL, ObjectIdGetDatum(), OidIsValid, pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by generateClonedIndexStmt().

◆ get_opclass()

static List * get_opclass ( Oid  opclass,
Oid  actual_datatype 
)
static

Definition at line 2001 of file parse_utilcmd.c.

2002 {
2003  List *result = NIL;
2004  HeapTuple ht_opc;
2005  Form_pg_opclass opc_rec;
2006 
2007  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
2008  if (!HeapTupleIsValid(ht_opc))
2009  elog(ERROR, "cache lookup failed for opclass %u", opclass);
2010  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
2011 
2012  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
2013  {
2014  /* For simplicity, we always schema-qualify the name */
2015  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
2016  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
2017 
2018  result = list_make2(makeString(nsp_name), makeString(opc_name));
2019  }
2020 
2021  ReleaseSysCache(ht_opc);
2022  return result;
2023 }
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2304
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83

References elog, ERROR, get_namespace_name(), GetDefaultOpClass(), GETSTRUCT, HeapTupleIsValid, list_make2, makeString(), NameStr, NIL, ObjectIdGetDatum(), pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by generateClonedIndexStmt().

◆ setSchemaName()

static void setSchemaName ( const char *  context_schema,
char **  stmt_schema_name 
)
static

Definition at line 4059 of file parse_utilcmd.c.

4060 {
4061  if (*stmt_schema_name == NULL)
4062  *stmt_schema_name = unconstify(char *, context_schema);
4063  else if (strcmp(context_schema, *stmt_schema_name) != 0)
4064  ereport(ERROR,
4065  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
4066  errmsg("CREATE specifies a schema (%s) "
4067  "different from the one being created (%s)",
4068  *stmt_schema_name, context_schema)));
4069 }
#define unconstify(underlying_type, expr)
Definition: c.h:1245

References ereport, errcode(), errmsg(), ERROR, and unconstify.

Referenced by transformCreateSchemaStmtElements().

◆ transformAlterTableStmt()

AlterTableStmt* transformAlterTableStmt ( Oid  relid,
AlterTableStmt stmt,
const char *  queryString,
List **  beforeStmts,
List **  afterStmts 
)

Definition at line 3402 of file parse_utilcmd.c.

3405 {
3406  Relation rel;
3407  TupleDesc tupdesc;
3408  ParseState *pstate;
3409  CreateStmtContext cxt;
3410  List *save_alist;
3411  ListCell *lcmd,
3412  *l;
3413  List *newcmds = NIL;
3414  bool skipValidation = true;
3415  AlterTableCmd *newcmd;
3416  ParseNamespaceItem *nsitem;
3417 
3418  /* Caller is responsible for locking the relation */
3419  rel = relation_open(relid, NoLock);
3420  tupdesc = RelationGetDescr(rel);
3421 
3422  /* Set up pstate */
3423  pstate = make_parsestate(NULL);
3424  pstate->p_sourcetext = queryString;
3425  nsitem = addRangeTableEntryForRelation(pstate,
3426  rel,
3428  NULL,
3429  false,
3430  true);
3431  addNSItemToQuery(pstate, nsitem, false, true, true);
3432 
3433  /* Set up CreateStmtContext */
3434  cxt.pstate = pstate;
3435  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3436  {
3437  cxt.stmtType = "ALTER FOREIGN TABLE";
3438  cxt.isforeign = true;
3439  }
3440  else
3441  {
3442  cxt.stmtType = "ALTER TABLE";
3443  cxt.isforeign = false;
3444  }
3445  cxt.relation = stmt->relation;
3446  cxt.rel = rel;
3447  cxt.inhRelations = NIL;
3448  cxt.isalter = true;
3449  cxt.columns = NIL;
3450  cxt.ckconstraints = NIL;
3451  cxt.fkconstraints = NIL;
3452  cxt.ixconstraints = NIL;
3453  cxt.likeclauses = NIL;
3454  cxt.blist = NIL;
3455  cxt.alist = NIL;
3456  cxt.pkey = NULL;
3457  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3458  cxt.partbound = NULL;
3459  cxt.ofType = false;
3460 
3461  /*
3462  * Transform ALTER subcommands that need it (most don't). These largely
3463  * re-use code from CREATE TABLE.
3464  */
3465  foreach(lcmd, stmt->cmds)
3466  {
3467  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3468 
3469  switch (cmd->subtype)
3470  {
3471  case AT_AddColumn:
3472  {
3473  ColumnDef *def = castNode(ColumnDef, cmd->def);
3474 
3475  transformColumnDefinition(&cxt, def);
3476 
3477  /*
3478  * If the column has a non-null default, we can't skip
3479  * validation of foreign keys.
3480  */
3481  if (def->raw_default != NULL)
3482  skipValidation = false;
3483 
3484  /*
3485  * All constraints are processed in other ways. Remove the
3486  * original list
3487  */
3488  def->constraints = NIL;
3489 
3490  newcmds = lappend(newcmds, cmd);
3491  break;
3492  }
3493 
3494  case AT_AddConstraint:
3495 
3496  /*
3497  * The original AddConstraint cmd node doesn't go to newcmds
3498  */
3499  if (IsA(cmd->def, Constraint))
3500  {
3501  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3502  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3503  skipValidation = false;
3504  }
3505  else
3506  elog(ERROR, "unrecognized node type: %d",
3507  (int) nodeTag(cmd->def));
3508  break;
3509 
3510  case AT_AlterColumnType:
3511  {
3512  ColumnDef *def = castNode(ColumnDef, cmd->def);
3514 
3515  /*
3516  * For ALTER COLUMN TYPE, transform the USING clause if
3517  * one was specified.
3518  */
3519  if (def->raw_default)
3520  {
3521  def->cooked_default =
3522  transformExpr(pstate, def->raw_default,
3524  }
3525 
3526  /*
3527  * For identity column, create ALTER SEQUENCE command to
3528  * change the data type of the sequence. Identity sequence
3529  * is associated with the top level partitioned table.
3530  * Hence ignore partitions.
3531  */
3532  if (!RelationGetForm(rel)->relispartition)
3533  {
3534  attnum = get_attnum(relid, cmd->name);
3535  if (attnum == InvalidAttrNumber)
3536  ereport(ERROR,
3537  (errcode(ERRCODE_UNDEFINED_COLUMN),
3538  errmsg("column \"%s\" of relation \"%s\" does not exist",
3539  cmd->name, RelationGetRelationName(rel))));
3540 
3541  if (attnum > 0 &&
3542  TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3543  {
3544  Oid seq_relid = getIdentitySequence(rel, attnum, false);
3545  Oid typeOid = typenameTypeId(pstate, def->typeName);
3546  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3547 
3548  altseqstmt->sequence
3550  get_rel_name(seq_relid),
3551  -1);
3552  altseqstmt->options = list_make1(makeDefElem("as",
3553  (Node *) makeTypeNameFromOid(typeOid, -1),
3554  -1));
3555  altseqstmt->for_identity = true;
3556  cxt.blist = lappend(cxt.blist, altseqstmt);
3557  }
3558  }
3559 
3560  newcmds = lappend(newcmds, cmd);
3561  break;
3562  }
3563 
3564  case AT_AddIdentity:
3565  {
3566  Constraint *def = castNode(Constraint, cmd->def);
3567  ColumnDef *newdef = makeNode(ColumnDef);
3569 
3570  newdef->colname = cmd->name;
3571  newdef->identity = def->generated_when;
3572  cmd->def = (Node *) newdef;
3573 
3574  attnum = get_attnum(relid, cmd->name);
3575  if (attnum == InvalidAttrNumber)
3576  ereport(ERROR,
3577  (errcode(ERRCODE_UNDEFINED_COLUMN),
3578  errmsg("column \"%s\" of relation \"%s\" does not exist",
3579  cmd->name, RelationGetRelationName(rel))));
3580 
3581  generateSerialExtraStmts(&cxt, newdef,
3582  get_atttype(relid, attnum),
3583  def->options, true, true,
3584  NULL, NULL);
3585 
3586  newcmds = lappend(newcmds, cmd);
3587  break;
3588  }
3589 
3590  case AT_SetIdentity:
3591  {
3592  /*
3593  * Create an ALTER SEQUENCE statement for the internal
3594  * sequence of the identity column.
3595  */
3596  ListCell *lc;
3597  List *newseqopts = NIL;
3598  List *newdef = NIL;
3600  Oid seq_relid;
3601 
3602  /*
3603  * Split options into those handled by ALTER SEQUENCE and
3604  * those for ALTER TABLE proper.
3605  */
3606  foreach(lc, castNode(List, cmd->def))
3607  {
3608  DefElem *def = lfirst_node(DefElem, lc);
3609 
3610  if (strcmp(def->defname, "generated") == 0)
3611  newdef = lappend(newdef, def);
3612  else
3613  newseqopts = lappend(newseqopts, def);
3614  }
3615 
3616  attnum = get_attnum(relid, cmd->name);
3617  if (attnum == InvalidAttrNumber)
3618  ereport(ERROR,
3619  (errcode(ERRCODE_UNDEFINED_COLUMN),
3620  errmsg("column \"%s\" of relation \"%s\" does not exist",
3621  cmd->name, RelationGetRelationName(rel))));
3622 
3623  seq_relid = getIdentitySequence(rel, attnum, true);
3624 
3625  if (seq_relid)
3626  {
3627  AlterSeqStmt *seqstmt;
3628 
3629  seqstmt = makeNode(AlterSeqStmt);
3631  get_rel_name(seq_relid), -1);
3632  seqstmt->options = newseqopts;
3633  seqstmt->for_identity = true;
3634  seqstmt->missing_ok = false;
3635 
3636  cxt.blist = lappend(cxt.blist, seqstmt);
3637  }
3638 
3639  /*
3640  * If column was not an identity column, we just let the
3641  * ALTER TABLE command error out later. (There are cases
3642  * this fails to cover, but we'll need to restructure
3643  * where creation of the sequence dependency linkage
3644  * happens before we can fix it.)
3645  */
3646 
3647  cmd->def = (Node *) newdef;
3648  newcmds = lappend(newcmds, cmd);
3649  break;
3650  }
3651 
3652  case AT_AttachPartition:
3653  case AT_DetachPartition:
3654  {
3655  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3656 
3657  transformPartitionCmd(&cxt, partcmd->bound);
3658  /* assign transformed value of the partition bound */
3659  partcmd->bound = cxt.partbound;
3660  }
3661 
3662  newcmds = lappend(newcmds, cmd);
3663  break;
3664 
3665  case AT_SplitPartition:
3666  case AT_MergePartitions:
3667  {
3668  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3669 
3670  if (list_length(partcmd->partlist) < 2)
3671  ereport(ERROR,
3672  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3673  errmsg("list of new partitions should contain at least two items")));
3674 
3675  if (cmd->subtype == AT_SplitPartition)
3676  transformPartitionCmdForSplit(&cxt, partcmd);
3677  else
3678  transformPartitionCmdForMerge(&cxt, partcmd);
3679  newcmds = lappend(newcmds, cmd);
3680  break;
3681  }
3682 
3683  default:
3684 
3685  /*
3686  * Currently, we shouldn't actually get here for subcommand
3687  * types that don't require transformation; but if we do, just
3688  * emit them unchanged.
3689  */
3690  newcmds = lappend(newcmds, cmd);
3691  break;
3692  }
3693  }
3694 
3695  /*
3696  * Transfer anything we already have in cxt.alist into save_alist, to keep
3697  * it separate from the output of transformIndexConstraints.
3698  */
3699  save_alist = cxt.alist;
3700  cxt.alist = NIL;
3701 
3702  /* Postprocess constraints */
3704  transformFKConstraints(&cxt, skipValidation, true);
3705  transformCheckConstraints(&cxt, false);
3706 
3707  /*
3708  * Push any index-creation commands into the ALTER, so that they can be
3709  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3710  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3711  * subcommand has already been through transformIndexStmt.
3712  */
3713  foreach(l, cxt.alist)
3714  {
3715  Node *istmt = (Node *) lfirst(l);
3716 
3717  /*
3718  * We assume here that cxt.alist contains only IndexStmts and possibly
3719  * ALTER TABLE SET NOT NULL statements generated from primary key
3720  * constraints. We absorb the subcommands of the latter directly.
3721  */
3722  if (IsA(istmt, IndexStmt))
3723  {
3724  IndexStmt *idxstmt = (IndexStmt *) istmt;
3725 
3726  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3727  newcmd = makeNode(AlterTableCmd);
3729  newcmd->def = (Node *) idxstmt;
3730  newcmds = lappend(newcmds, newcmd);
3731  }
3732  else if (IsA(istmt, AlterTableStmt))
3733  {
3734  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3735 
3736  newcmds = list_concat(newcmds, alterstmt->cmds);
3737  }
3738  else
3739  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3740  }
3741  cxt.alist = NIL;
3742 
3743  /* Append any CHECK or FK constraints to the commands list */
3744  foreach(l, cxt.ckconstraints)
3745  {
3746  newcmd = makeNode(AlterTableCmd);
3747  newcmd->subtype = AT_AddConstraint;
3748  newcmd->def = (Node *) lfirst_node(Constraint, l);
3749  newcmds = lappend(newcmds, newcmd);
3750  }
3751  foreach(l, cxt.fkconstraints)
3752  {
3753  newcmd = makeNode(AlterTableCmd);
3754  newcmd->subtype = AT_AddConstraint;
3755  newcmd->def = (Node *) lfirst_node(Constraint, l);
3756  newcmds = lappend(newcmds, newcmd);
3757  }
3758 
3759  /* Close rel */
3760  relation_close(rel, NoLock);
3761 
3762  /*
3763  * Output results.
3764  */
3765  stmt->cmds = newcmds;
3766 
3767  *beforeStmts = cxt.blist;
3768  *afterStmts = list_concat(cxt.alist, save_alist);
3769 
3770  return stmt;
3771 }
#define InvalidAttrNumber
Definition: attnum.h:23
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:858
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1952
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:120
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:75
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformIndexConstraints(CreateStmtContext *cxt)
static void transformPartitionCmdForSplit(CreateStmtContext *cxt, PartitionCmd *partcmd)
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformPartitionCmdForMerge(CreateStmtContext *cxt, PartitionCmd *partcmd)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionBoundSpec *bound)
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
@ AT_AddIndexConstraint
Definition: parsenodes.h:2375
@ AT_MergePartitions
Definition: parsenodes.h:2417
@ AT_SetIdentity
Definition: parsenodes.h:2419
@ AT_AddIndex
Definition: parsenodes.h:2368
@ AT_AddIdentity
Definition: parsenodes.h:2418
@ AT_AlterColumnType
Definition: parsenodes.h:2378
@ AT_DetachPartition
Definition: parsenodes.h:2414
@ AT_AttachPartition
Definition: parsenodes.h:2413
@ AT_SplitPartition
Definition: parsenodes.h:2416
@ AT_AddColumn
Definition: parsenodes.h:2353
Oid getIdentitySequence(Relation rel, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:946
static int list_length(const List *l)
Definition: pg_list.h:152
#define RelationGetForm(relation)
Definition: rel.h:499
char identity
Definition: parsenodes.h:737
List * constraints
Definition: parsenodes.h:743
Node * cooked_default
Definition: parsenodes.h:736
TypeName * typeName
Definition: parsenodes.h:727
Node * raw_default
Definition: parsenodes.h:735
List * options
Definition: parsenodes.h:2757
char generated_when
Definition: parsenodes.h:2747
IndexStmt * pkey
Definition: parse_utilcmd.c:94
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
Oid indexOid
Definition: parsenodes.h:3367
const char * p_sourcetext
Definition: parse_node.h:193
PartitionBoundSpec * bound
Definition: parsenodes.h:958
List * partlist
Definition: parsenodes.h:959

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_MergePartitions, AT_SetIdentity, AT_SplitPartition, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, AlterTableCmd::def, DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::fkconstraints, AlterSeqStmt::for_identity, Constraint::generated_when, generateSerialExtraStmts(), get_attnum(), get_atttype(), get_namespace_name(), get_rel_name(), get_rel_namespace(), getIdentitySequence(), ColumnDef::identity, if(), IndexStmt::indexOid, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, CreateStmtContext::likeclauses, list_concat(), list_length(), list_make1, make_parsestate(), makeDefElem(), makeNode, makeRangeVar(), makeTypeNameFromOid(), AlterSeqStmt::missing_ok, AlterTableCmd::name, NIL, nodeTag, NoLock, CreateStmtContext::ofType, OidIsValid, Constraint::options, AlterSeqStmt::options, ParseState::p_sourcetext, CreateStmtContext::partbound, PartitionCmd::partlist, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetForm, RelationGetRelationName, AlterSeqStmt::sequence, stmt, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformPartitionCmdForMerge(), transformPartitionCmdForSplit(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2672 of file parse_utilcmd.c.

2673 {
2674  ListCell *ckclist;
2675 
2676  if (cxt->ckconstraints == NIL)
2677  return;
2678 
2679  /*
2680  * If creating a new table (but not a foreign table), we can safely skip
2681  * validation of check constraints, and nonetheless mark them valid. (This
2682  * will override any user-supplied NOT VALID flag.)
2683  */
2684  if (skipValidation)
2685  {
2686  foreach(ckclist, cxt->ckconstraints)
2687  {
2688  Constraint *constraint = (Constraint *) lfirst(ckclist);
2689 
2690  constraint->skip_validation = true;
2691  constraint->initially_valid = true;
2692  }
2693  }
2694 }

References CreateStmtContext::ckconstraints, Constraint::initially_valid, lfirst, NIL, and Constraint::skip_validation.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 537 of file parse_utilcmd.c.

538 {
539  bool is_serial;
540  bool saw_nullable;
541  bool saw_default;
542  bool saw_identity;
543  bool saw_generated;
544  ListCell *clist;
545 
546  cxt->columns = lappend(cxt->columns, column);
547 
548  /* Check for SERIAL pseudo-types */
549  is_serial = false;
550  if (column->typeName
551  && list_length(column->typeName->names) == 1
552  && !column->typeName->pct_type)
553  {
554  char *typname = strVal(linitial(column->typeName->names));
555 
556  if (strcmp(typname, "smallserial") == 0 ||
557  strcmp(typname, "serial2") == 0)
558  {
559  is_serial = true;
560  column->typeName->names = NIL;
561  column->typeName->typeOid = INT2OID;
562  }
563  else if (strcmp(typname, "serial") == 0 ||
564  strcmp(typname, "serial4") == 0)
565  {
566  is_serial = true;
567  column->typeName->names = NIL;
568  column->typeName->typeOid = INT4OID;
569  }
570  else if (strcmp(typname, "bigserial") == 0 ||
571  strcmp(typname, "serial8") == 0)
572  {
573  is_serial = true;
574  column->typeName->names = NIL;
575  column->typeName->typeOid = INT8OID;
576  }
577 
578  /*
579  * We have to reject "serial[]" explicitly, because once we've set
580  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
581  * special coding for serial(typmod) though.
582  */
583  if (is_serial && column->typeName->arrayBounds != NIL)
584  ereport(ERROR,
585  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
586  errmsg("array of serial is not implemented"),
588  column->typeName->location)));
589  }
590 
591  /* Do necessary work on the column type declaration */
592  if (column->typeName)
593  transformColumnType(cxt, column);
594 
595  /* Special actions for SERIAL pseudo-types */
596  if (is_serial)
597  {
598  char *snamespace;
599  char *sname;
600  char *qstring;
601  A_Const *snamenode;
602  TypeCast *castnode;
603  FuncCall *funccallnode;
604  Constraint *constraint;
605 
606  generateSerialExtraStmts(cxt, column,
607  column->typeName->typeOid, NIL,
608  false, false,
609  &snamespace, &sname);
610 
611  /*
612  * Create appropriate constraints for SERIAL. We do this in full,
613  * rather than shortcutting, so that we will detect any conflicting
614  * constraints the user wrote (like a different DEFAULT).
615  *
616  * Create an expression tree representing the function call
617  * nextval('sequencename'). We cannot reduce the raw tree to cooked
618  * form until after the sequence is created, but there's no need to do
619  * so.
620  */
621  qstring = quote_qualified_identifier(snamespace, sname);
622  snamenode = makeNode(A_Const);
623  snamenode->val.node.type = T_String;
624  snamenode->val.sval.sval = qstring;
625  snamenode->location = -1;
626  castnode = makeNode(TypeCast);
627  castnode->typeName = SystemTypeName("regclass");
628  castnode->arg = (Node *) snamenode;
629  castnode->location = -1;
630  funccallnode = makeFuncCall(SystemFuncName("nextval"),
631  list_make1(castnode),
633  -1);
634  constraint = makeNode(Constraint);
635  constraint->contype = CONSTR_DEFAULT;
636  constraint->location = -1;
637  constraint->raw_expr = (Node *) funccallnode;
638  constraint->cooked_expr = NULL;
639  column->constraints = lappend(column->constraints, constraint);
640 
641  constraint = makeNode(Constraint);
642  constraint->contype = CONSTR_NOTNULL;
643  constraint->location = -1;
644  column->constraints = lappend(column->constraints, constraint);
645  }
646 
647  /* Process column constraints, if any... */
649 
650  saw_nullable = false;
651  saw_default = false;
652  saw_identity = false;
653  saw_generated = false;
654 
655  foreach(clist, column->constraints)
656  {
657  Constraint *constraint = lfirst_node(Constraint, clist);
658 
659  switch (constraint->contype)
660  {
661  case CONSTR_NULL:
662  if (saw_nullable && column->is_not_null)
663  ereport(ERROR,
664  (errcode(ERRCODE_SYNTAX_ERROR),
665  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
666  column->colname, cxt->relation->relname),
668  constraint->location)));
669  column->is_not_null = false;
670  saw_nullable = true;
671  break;
672 
673  case CONSTR_NOTNULL:
674  if (saw_nullable && !column->is_not_null)
675  ereport(ERROR,
676  (errcode(ERRCODE_SYNTAX_ERROR),
677  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
678  column->colname, cxt->relation->relname),
680  constraint->location)));
681  column->is_not_null = true;
682  saw_nullable = true;
683  break;
684 
685  case CONSTR_DEFAULT:
686  if (saw_default)
687  ereport(ERROR,
688  (errcode(ERRCODE_SYNTAX_ERROR),
689  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
690  column->colname, cxt->relation->relname),
692  constraint->location)));
693  column->raw_default = constraint->raw_expr;
694  Assert(constraint->cooked_expr == NULL);
695  saw_default = true;
696  break;
697 
698  case CONSTR_IDENTITY:
699  {
700  Type ctype;
701  Oid typeOid;
702 
703  if (cxt->ofType)
704  ereport(ERROR,
705  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
706  errmsg("identity columns are not supported on typed tables")));
707  if (cxt->partbound)
708  ereport(ERROR,
709  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
710  errmsg("identity columns are not supported on partitions")));
711 
712  ctype = typenameType(cxt->pstate, column->typeName, NULL);
713  typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
714  ReleaseSysCache(ctype);
715 
716  if (saw_identity)
717  ereport(ERROR,
718  (errcode(ERRCODE_SYNTAX_ERROR),
719  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
720  column->colname, cxt->relation->relname),
722  constraint->location)));
723 
724  generateSerialExtraStmts(cxt, column,
725  typeOid, constraint->options,
726  true, false,
727  NULL, NULL);
728 
729  column->identity = constraint->generated_when;
730  saw_identity = true;
731 
732  /* An identity column is implicitly NOT NULL */
733  if (saw_nullable && !column->is_not_null)
734  ereport(ERROR,
735  (errcode(ERRCODE_SYNTAX_ERROR),
736  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
737  column->colname, cxt->relation->relname),
739  constraint->location)));
740  column->is_not_null = true;
741  saw_nullable = true;
742  break;
743  }
744 
745  case CONSTR_GENERATED:
746  if (cxt->ofType)
747  ereport(ERROR,
748  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
749  errmsg("generated columns are not supported on typed tables")));
750  if (saw_generated)
751  ereport(ERROR,
752  (errcode(ERRCODE_SYNTAX_ERROR),
753  errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
754  column->colname, cxt->relation->relname),
756  constraint->location)));
757  column->generated = ATTRIBUTE_GENERATED_STORED;
758  column->raw_default = constraint->raw_expr;
759  Assert(constraint->cooked_expr == NULL);
760  saw_generated = true;
761  break;
762 
763  case CONSTR_CHECK:
764  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
765  break;
766 
767  case CONSTR_PRIMARY:
768  if (cxt->isforeign)
769  ereport(ERROR,
770  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
771  errmsg("primary key constraints are not supported on foreign tables"),
773  constraint->location)));
774  /* FALL THRU */
775 
776  case CONSTR_UNIQUE:
777  if (cxt->isforeign)
778  ereport(ERROR,
779  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
780  errmsg("unique constraints are not supported on foreign tables"),
782  constraint->location)));
783  if (constraint->keys == NIL)
784  constraint->keys = list_make1(makeString(column->colname));
785  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
786  break;
787 
788  case CONSTR_EXCLUSION:
789  /* grammar does not allow EXCLUDE as a column constraint */
790  elog(ERROR, "column exclusion constraints are not supported");
791  break;
792 
793  case CONSTR_FOREIGN:
794  if (cxt->isforeign)
795  ereport(ERROR,
796  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
797  errmsg("foreign key constraints are not supported on foreign tables"),
799  constraint->location)));
800 
801  /*
802  * Fill in the current attribute's name and throw it into the
803  * list of FK constraints to be processed later.
804  */
805  constraint->fk_attrs = list_make1(makeString(column->colname));
806  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
807  break;
808 
813  /* transformConstraintAttrs took care of these */
814  break;
815 
816  default:
817  elog(ERROR, "unrecognized constraint type: %d",
818  constraint->contype);
819  break;
820  }
821 
822  if (saw_default && saw_identity)
823  ereport(ERROR,
824  (errcode(ERRCODE_SYNTAX_ERROR),
825  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
826  column->colname, cxt->relation->relname),
828  constraint->location)));
829 
830  if (saw_default && saw_generated)
831  ereport(ERROR,
832  (errcode(ERRCODE_SYNTAX_ERROR),
833  errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
834  column->colname, cxt->relation->relname),
836  constraint->location)));
837 
838  if (saw_identity && saw_generated)
839  ereport(ERROR,
840  (errcode(ERRCODE_SYNTAX_ERROR),
841  errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
842  column->colname, cxt->relation->relname),
844  constraint->location)));
845  }
846 
847  /*
848  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
849  * per-column foreign data wrapper options to this column after creation.
850  */
851  if (column->fdwoptions != NIL)
852  {
854  AlterTableCmd *cmd;
855 
856  cmd = makeNode(AlterTableCmd);
858  cmd->name = column->colname;
859  cmd->def = (Node *) column->fdwoptions;
860  cmd->behavior = DROP_RESTRICT;
861  cmd->missing_ok = false;
862 
864  stmt->relation = cxt->relation;
865  stmt->cmds = NIL;
866  stmt->objtype = OBJECT_FOREIGN_TABLE;
867  stmt->cmds = lappend(stmt->cmds, cmd);
868 
869  cxt->alist = lappend(cxt->alist, stmt);
870  }
871 }
FuncCall * makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
Definition: makefuncs.c:603
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
@ CONSTR_ATTR_DEFERRED
Definition: parsenodes.h:2717
@ CONSTR_IDENTITY
Definition: parsenodes.h:2708
@ CONSTR_ATTR_NOT_DEFERRABLE
Definition: parsenodes.h:2716
@ CONSTR_DEFAULT
Definition: parsenodes.h:2707
@ CONSTR_NOTNULL
Definition: parsenodes.h:2706
@ CONSTR_ATTR_IMMEDIATE
Definition: parsenodes.h:2718
@ CONSTR_NULL
Definition: parsenodes.h:2704
@ CONSTR_GENERATED
Definition: parsenodes.h:2709
@ CONSTR_ATTR_DEFERRABLE
Definition: parsenodes.h:2715
@ DROP_RESTRICT
Definition: parsenodes.h:2334
@ OBJECT_FOREIGN_TABLE
Definition: parsenodes.h:2279
@ AT_AlterColumnGenericOptions
Definition: parsenodes.h:2379
TypeName * SystemTypeName(char *name)
List * SystemFuncName(char *name)
#define linitial(l)
Definition: pg_list.h:178
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
NameData typname
Definition: pg_type.h:41
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:734
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12680
union ValUnion val
Definition: parsenodes.h:362
ParseLoc location
Definition: parsenodes.h:364
DropBehavior behavior
Definition: parsenodes.h:2442
bool is_not_null
Definition: parsenodes.h:731
char generated
Definition: parsenodes.h:740
List * fdwoptions
Definition: parsenodes.h:744
List * keys
Definition: parsenodes.h:2751
List * fk_attrs
Definition: parsenodes.h:2767
NodeTag type
Definition: nodes.h:130
char * sval
Definition: value.h:68
TypeName * typeName
Definition: parsenodes.h:374
ParseLoc location
Definition: parsenodes.h:375
Node * arg
Definition: parsenodes.h:373
Oid typeOid
Definition: parsenodes.h:269
bool pct_type
Definition: parsenodes.h:271
List * names
Definition: parsenodes.h:268
List * arrayBounds
Definition: parsenodes.h:274
ParseLoc location
Definition: parsenodes.h:275
Node node
Definition: parsenodes.h:349
String sval
Definition: parsenodes.h:353
#define strVal(v)
Definition: value.h:82

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, COERCE_EXPLICIT_CALL, ColumnDef::colname, CreateStmtContext::columns, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_GENERATED, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, ColumnDef::constraints, Constraint::contype, Constraint::cooked_expr, AlterTableCmd::def, DROP_RESTRICT, elog, ereport, errcode(), errmsg(), ERROR, ColumnDef::fdwoptions, Constraint::fk_attrs, CreateStmtContext::fkconstraints, ColumnDef::generated, Constraint::generated_when, generateSerialExtraStmts(), GETSTRUCT, ColumnDef::identity, ColumnDef::is_not_null, CreateStmtContext::isforeign, CreateStmtContext::ixconstraints, Constraint::keys, lappend(), lfirst_node, linitial, list_length(), list_make1, TypeName::location, A_Const::location, TypeCast::location, Constraint::location, makeFuncCall(), makeNode, makeString(), AlterTableCmd::missing_ok, AlterTableCmd::name, TypeName::names, NIL, ValUnion::node, OBJECT_FOREIGN_TABLE, CreateStmtContext::ofType, Constraint::options, parser_errposition(), CreateStmtContext::partbound, TypeName::pct_type, CreateStmtContext::pstate, quote_qualified_identifier(), ColumnDef::raw_default, Constraint::raw_expr, CreateStmtContext::relation, ReleaseSysCache(), RangeVar::relname, stmt, strVal, AlterTableCmd::subtype, ValUnion::sval, String::sval, SystemFuncName(), SystemTypeName(), transformColumnType(), transformConstraintAttrs(), Node::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, typname, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3899 of file parse_utilcmd.c.

3900 {
3901  /*
3902  * All we really need to do here is verify that the type is valid,
3903  * including any collation spec that might be present.
3904  */
3905  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3906 
3907  if (column->collClause)
3908  {
3909  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3910 
3911  LookupCollation(cxt->pstate,
3912  column->collClause->collname,
3913  column->collClause->location);
3914  /* Complain if COLLATE is applied to an uncollatable type */
3915  if (!OidIsValid(typtup->typcollation))
3916  ereport(ERROR,
3917  (errcode(ERRCODE_DATATYPE_MISMATCH),
3918  errmsg("collations are not supported by type %s",
3919  format_type_be(typtup->oid)),
3921  column->collClause->location)));
3922  }
3923 
3924  ReleaseSysCache(ctype);
3925 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:515
List * collname
Definition: parsenodes.h:385
ParseLoc location
Definition: parsenodes.h:386
CollateClause * collClause
Definition: parsenodes.h:741

References ColumnDef::collClause, CollateClause::collname, ereport, errcode(), errmsg(), ERROR, format_type_be(), GETSTRUCT, CollateClause::location, LookupCollation(), OidIsValid, parser_errposition(), CreateStmtContext::pstate, ReleaseSysCache(), ColumnDef::typeName, and typenameType().

Referenced by transformColumnDefinition().

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3784 of file parse_utilcmd.c.

3785 {
3786  Constraint *lastprimarycon = NULL;
3787  bool saw_deferrability = false;
3788  bool saw_initially = false;
3789  ListCell *clist;
3790 
3791 #define SUPPORTS_ATTRS(node) \
3792  ((node) != NULL && \
3793  ((node)->contype == CONSTR_PRIMARY || \
3794  (node)->contype == CONSTR_UNIQUE || \
3795  (node)->contype == CONSTR_EXCLUSION || \
3796  (node)->contype == CONSTR_FOREIGN))
3797 
3798  foreach(clist, constraintList)
3799  {
3800  Constraint *con = (Constraint *) lfirst(clist);
3801 
3802  if (!IsA(con, Constraint))
3803  elog(ERROR, "unrecognized node type: %d",
3804  (int) nodeTag(con));
3805  switch (con->contype)
3806  {
3808  if (!SUPPORTS_ATTRS(lastprimarycon))
3809  ereport(ERROR,
3810  (errcode(ERRCODE_SYNTAX_ERROR),
3811  errmsg("misplaced DEFERRABLE clause"),
3812  parser_errposition(cxt->pstate, con->location)));
3813  if (saw_deferrability)
3814  ereport(ERROR,
3815  (errcode(ERRCODE_SYNTAX_ERROR),
3816  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3817  parser_errposition(cxt->pstate, con->location)));
3818  saw_deferrability = true;
3819  lastprimarycon->deferrable = true;
3820  break;
3821 
3823  if (!SUPPORTS_ATTRS(lastprimarycon))
3824  ereport(ERROR,
3825  (errcode(ERRCODE_SYNTAX_ERROR),
3826  errmsg("misplaced NOT DEFERRABLE clause"),
3827  parser_errposition(cxt->pstate, con->location)));
3828  if (saw_deferrability)
3829  ereport(ERROR,
3830  (errcode(ERRCODE_SYNTAX_ERROR),
3831  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3832  parser_errposition(cxt->pstate, con->location)));
3833  saw_deferrability = true;
3834  lastprimarycon->deferrable = false;
3835  if (saw_initially &&
3836  lastprimarycon->initdeferred)
3837  ereport(ERROR,
3838  (errcode(ERRCODE_SYNTAX_ERROR),
3839  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3840  parser_errposition(cxt->pstate, con->location)));
3841  break;
3842 
3843  case CONSTR_ATTR_DEFERRED:
3844  if (!SUPPORTS_ATTRS(lastprimarycon))
3845  ereport(ERROR,
3846  (errcode(ERRCODE_SYNTAX_ERROR),
3847  errmsg("misplaced INITIALLY DEFERRED clause"),
3848  parser_errposition(cxt->pstate, con->location)));
3849  if (saw_initially)
3850  ereport(ERROR,
3851  (errcode(ERRCODE_SYNTAX_ERROR),
3852  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3853  parser_errposition(cxt->pstate, con->location)));
3854  saw_initially = true;
3855  lastprimarycon->initdeferred = true;
3856 
3857  /*
3858  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3859  */
3860  if (!saw_deferrability)
3861  lastprimarycon->deferrable = true;
3862  else if (!lastprimarycon->deferrable)
3863  ereport(ERROR,
3864  (errcode(ERRCODE_SYNTAX_ERROR),
3865  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3866  parser_errposition(cxt->pstate, con->location)));
3867  break;
3868 
3869  case CONSTR_ATTR_IMMEDIATE:
3870  if (!SUPPORTS_ATTRS(lastprimarycon))
3871  ereport(ERROR,
3872  (errcode(ERRCODE_SYNTAX_ERROR),
3873  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3874  parser_errposition(cxt->pstate, con->location)));
3875  if (saw_initially)
3876  ereport(ERROR,
3877  (errcode(ERRCODE_SYNTAX_ERROR),
3878  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3879  parser_errposition(cxt->pstate, con->location)));
3880  saw_initially = true;
3881  lastprimarycon->initdeferred = false;
3882  break;
3883 
3884  default:
3885  /* Otherwise it's not an attribute */
3886  lastprimarycon = con;
3887  /* reset flags for new primary node */
3888  saw_deferrability = false;
3889  saw_initially = false;
3890  break;
3891  }
3892  }
3893 }
#define SUPPORTS_ATTRS(node)
bool initdeferred
Definition: parsenodes.h:2739
bool deferrable
Definition: parsenodes.h:2738

References CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, Constraint::contype, Constraint::deferrable, elog, ereport, errcode(), errmsg(), ERROR, Constraint::initdeferred, IsA, lfirst, Constraint::location, nodeTag, parser_errposition(), CreateStmtContext::pstate, and SUPPORTS_ATTRS.

Referenced by transformColumnDefinition().

◆ transformCreateSchemaStmtElements()

List* transformCreateSchemaStmtElements ( List schemaElts,
const char *  schemaName 
)

Definition at line 3956 of file parse_utilcmd.c.

3957 {
3959  List *result;
3960  ListCell *elements;
3961 
3962  cxt.schemaname = schemaName;
3963  cxt.sequences = NIL;
3964  cxt.tables = NIL;
3965  cxt.views = NIL;
3966  cxt.indexes = NIL;
3967  cxt.triggers = NIL;
3968  cxt.grants = NIL;
3969 
3970  /*
3971  * Run through each schema element in the schema element list. Separate
3972  * statements by type, and do preliminary analysis.
3973  */
3974  foreach(elements, schemaElts)
3975  {
3976  Node *element = lfirst(elements);
3977 
3978  switch (nodeTag(element))
3979  {
3980  case T_CreateSeqStmt:
3981  {
3982  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3983 
3985  cxt.sequences = lappend(cxt.sequences, element);
3986  }
3987  break;
3988 
3989  case T_CreateStmt:
3990  {
3991  CreateStmt *elp = (CreateStmt *) element;
3992 
3994 
3995  /*
3996  * XXX todo: deal with constraints
3997  */
3998  cxt.tables = lappend(cxt.tables, element);
3999  }
4000  break;
4001 
4002  case T_ViewStmt:
4003  {
4004  ViewStmt *elp = (ViewStmt *) element;
4005 
4006  setSchemaName(cxt.schemaname, &elp->view->schemaname);
4007 
4008  /*
4009  * XXX todo: deal with references between views
4010  */
4011  cxt.views = lappend(cxt.views, element);
4012  }
4013  break;
4014 
4015  case T_IndexStmt:
4016  {
4017  IndexStmt *elp = (IndexStmt *) element;
4018 
4020  cxt.indexes = lappend(cxt.indexes, element);
4021  }
4022  break;
4023 
4024  case T_CreateTrigStmt:
4025  {
4027 
4029  cxt.triggers = lappend(cxt.triggers, element);
4030  }
4031  break;
4032 
4033  case T_GrantStmt:
4034  cxt.grants = lappend(cxt.grants, element);
4035  break;
4036 
4037  default:
4038  elog(ERROR, "unrecognized node type: %d",
4039  (int) nodeTag(element));
4040  }
4041  }
4042 
4043  result = NIL;
4044  result = list_concat(result, cxt.sequences);
4045  result = list_concat(result, cxt.tables);
4046  result = list_concat(result, cxt.views);
4047  result = list_concat(result, cxt.indexes);
4048  result = list_concat(result, cxt.triggers);
4049  result = list_concat(result, cxt.grants);
4050 
4051  return result;
4052 }
static void setSchemaName(const char *context_schema, char **stmt_schema_name)
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:376
RangeVar * relation
Definition: parsenodes.h:2656
RangeVar * relation
Definition: parsenodes.h:3012
RangeVar * relation
Definition: parsenodes.h:3357
RangeVar * view
Definition: parsenodes.h:3748

References element(), elog, ERROR, CreateSchemaStmtContext::grants, CreateSchemaStmtContext::indexes, lappend(), lfirst, list_concat(), NIL, nodeTag, CreateStmt::relation, CreateTrigStmt::relation, IndexStmt::relation, CreateSchemaStmtContext::schemaname, RangeVar::schemaname, CreateSeqStmt::sequence, CreateSchemaStmtContext::sequences, setSchemaName(), CreateSchemaStmtContext::tables, CreateSchemaStmtContext::triggers, ViewStmt::view, and CreateSchemaStmtContext::views.

Referenced by CreateSchemaCommand().

◆ transformCreateStmt()

List* transformCreateStmt ( CreateStmt stmt,
const char *  queryString 
)

Definition at line 166 of file parse_utilcmd.c.

167 {
168  ParseState *pstate;
169  CreateStmtContext cxt;
170  List *result;
171  List *save_alist;
172  ListCell *elements;
173  Oid namespaceid;
174  Oid existing_relid;
175  ParseCallbackState pcbstate;
176 
177  /* Set up pstate */
178  pstate = make_parsestate(NULL);
179  pstate->p_sourcetext = queryString;
180 
181  /*
182  * Look up the creation namespace. This also checks permissions on the
183  * target namespace, locks it against concurrent drops, checks for a
184  * preexisting relation in that namespace with the same name, and updates
185  * stmt->relation->relpersistence if the selected namespace is temporary.
186  */
187  setup_parser_errposition_callback(&pcbstate, pstate,
188  stmt->relation->location);
189  namespaceid =
191  &existing_relid);
193 
194  /*
195  * If the relation already exists and the user specified "IF NOT EXISTS",
196  * bail out with a NOTICE.
197  */
198  if (stmt->if_not_exists && OidIsValid(existing_relid))
199  {
200  /*
201  * If we are in an extension script, insist that the pre-existing
202  * object be a member of the extension, to avoid security risks.
203  */
204  ObjectAddress address;
205 
206  ObjectAddressSet(address, RelationRelationId, existing_relid);
208 
209  /* OK to skip */
210  ereport(NOTICE,
211  (errcode(ERRCODE_DUPLICATE_TABLE),
212  errmsg("relation \"%s\" already exists, skipping",
213  stmt->relation->relname)));
214  return NIL;
215  }
216 
217  /*
218  * If the target relation name isn't schema-qualified, make it so. This
219  * prevents some corner cases in which added-on rewritten commands might
220  * think they should apply to other relations that have the same name and
221  * are earlier in the search path. But a local temp table is effectively
222  * specified to be in pg_temp, so no need for anything extra in that case.
223  */
224  if (stmt->relation->schemaname == NULL
225  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
226  stmt->relation->schemaname = get_namespace_name(namespaceid);
227 
228  /* Set up CreateStmtContext */
229  cxt.pstate = pstate;
231  {
232  cxt.stmtType = "CREATE FOREIGN TABLE";
233  cxt.isforeign = true;
234  }
235  else
236  {
237  cxt.stmtType = "CREATE TABLE";
238  cxt.isforeign = false;
239  }
240  cxt.relation = stmt->relation;
241  cxt.rel = NULL;
242  cxt.inhRelations = stmt->inhRelations;
243  cxt.isalter = false;
244  cxt.columns = NIL;
245  cxt.ckconstraints = NIL;
246  cxt.fkconstraints = NIL;
247  cxt.ixconstraints = NIL;
248  cxt.likeclauses = NIL;
249  cxt.blist = NIL;
250  cxt.alist = NIL;
251  cxt.pkey = NULL;
252  cxt.ispartitioned = stmt->partspec != NULL;
253  cxt.partbound = stmt->partbound;
254  cxt.ofType = (stmt->ofTypename != NULL);
255 
256  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
257 
258  if (stmt->ofTypename)
259  transformOfType(&cxt, stmt->ofTypename);
260 
261  if (stmt->partspec)
262  {
263  if (stmt->inhRelations && !stmt->partbound)
264  ereport(ERROR,
265  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
266  errmsg("cannot create partitioned table as inheritance child")));
267  }
268 
269  /*
270  * Run through each primary element in the table creation clause. Separate
271  * column defs from constraints, and do preliminary analysis.
272  */
273  foreach(elements, stmt->tableElts)
274  {
275  Node *element = lfirst(elements);
276 
277  switch (nodeTag(element))
278  {
279  case T_ColumnDef:
281  break;
282 
283  case T_Constraint:
285  break;
286 
287  case T_TableLikeClause:
289  break;
290 
291  default:
292  elog(ERROR, "unrecognized node type: %d",
293  (int) nodeTag(element));
294  break;
295  }
296  }
297 
298  /*
299  * Transfer anything we already have in cxt.alist into save_alist, to keep
300  * it separate from the output of transformIndexConstraints. (This may
301  * not be necessary anymore, but we'll keep doing it to preserve the
302  * historical order of execution of the alist commands.)
303  */
304  save_alist = cxt.alist;
305  cxt.alist = NIL;
306 
307  Assert(stmt->constraints == NIL);
308 
309  /*
310  * Postprocess constraints that give rise to index definitions.
311  */
313 
314  /*
315  * Re-consideration of LIKE clauses should happen after creation of
316  * indexes, but before creation of foreign keys. This order is critical
317  * because a LIKE clause may attempt to create a primary key. If there's
318  * also a pkey in the main CREATE TABLE list, creation of that will not
319  * check for a duplicate at runtime (since index_check_primary_key()
320  * expects that we rejected dups here). Creation of the LIKE-generated
321  * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
322  * only works if it happens second. On the other hand, we want to make
323  * pkeys before foreign key constraints, in case the user tries to make a
324  * self-referential FK.
325  */
326  cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
327 
328  /*
329  * Postprocess foreign-key constraints.
330  */
331  transformFKConstraints(&cxt, true, false);
332 
333  /*
334  * Postprocess check constraints.
335  *
336  * For regular tables all constraints can be marked valid immediately,
337  * because the table is new therefore empty. Not so for foreign tables.
338  */
340 
341  /*
342  * Output results.
343  */
344  stmt->tableElts = cxt.columns;
345  stmt->constraints = cxt.ckconstraints;
346 
347  result = lappend(cxt.blist, stmt);
348  result = list_concat(result, cxt.alist);
349  result = list_concat(result, save_alist);
350 
351  return result;
352 }
#define NOTICE
Definition: elog.h:35
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:724
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:156
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:140
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
void checkMembershipInCurrentExtension(const ObjectAddress *object)
Definition: pg_depend.c:259

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), checkMembershipInCurrentExtension(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmtContext::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, CreateStmtContext::likeclauses, list_concat(), make_parsestate(), NIL, nodeTag, NoLock, NOTICE, ObjectAddressSet, CreateStmtContext::ofType, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, setup_parser_errposition_callback(), stmt, CreateStmtContext::stmtType, transformCheckConstraints(), transformColumnDefinition(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

◆ transformFKConstraints()

static void transformFKConstraints ( CreateStmtContext cxt,
bool  skipValidation,
bool  isAddConstraint 
)
static

Definition at line 2701 of file parse_utilcmd.c.

2703 {
2704  ListCell *fkclist;
2705 
2706  if (cxt->fkconstraints == NIL)
2707  return;
2708 
2709  /*
2710  * If CREATE TABLE or adding a column with NULL default, we can safely
2711  * skip validation of FK constraints, and nonetheless mark them valid.
2712  * (This will override any user-supplied NOT VALID flag.)
2713  */
2714  if (skipValidation)
2715  {
2716  foreach(fkclist, cxt->fkconstraints)
2717  {
2718  Constraint *constraint = (Constraint *) lfirst(fkclist);
2719 
2720  constraint->skip_validation = true;
2721  constraint->initially_valid = true;
2722  }
2723  }
2724 
2725  /*
2726  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2727  * CONSTRAINT command to execute after the basic command is complete. (If
2728  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2729  * its own subcommand list.)
2730  *
2731  * Note: the ADD CONSTRAINT command must also execute after any index
2732  * creation commands. Thus, this should run after
2733  * transformIndexConstraints, so that the CREATE INDEX commands are
2734  * already in cxt->alist. See also the handling of cxt->likeclauses.
2735  */
2736  if (!isAddConstraint)
2737  {
2738  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2739 
2740  alterstmt->relation = cxt->relation;
2741  alterstmt->cmds = NIL;
2742  alterstmt->objtype = OBJECT_TABLE;
2743 
2744  foreach(fkclist, cxt->fkconstraints)
2745  {
2746  Constraint *constraint = (Constraint *) lfirst(fkclist);
2747  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2748 
2749  altercmd->subtype = AT_AddConstraint;
2750  altercmd->name = NULL;
2751  altercmd->def = (Node *) constraint;
2752  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2753  }
2754 
2755  cxt->alist = lappend(cxt->alist, alterstmt);
2756  }
2757 }

References CreateStmtContext::alist, AT_AddConstraint, AlterTableStmt::cmds, AlterTableCmd::def, CreateStmtContext::fkconstraints, Constraint::initially_valid, lappend(), lfirst, makeNode, AlterTableCmd::name, NIL, OBJECT_TABLE, AlterTableStmt::objtype, CreateStmtContext::relation, AlterTableStmt::relation, Constraint::skip_validation, and AlterTableCmd::subtype.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexConstraint()

static IndexStmt * transformIndexConstraint ( Constraint constraint,
CreateStmtContext cxt 
)
static

Definition at line 2136 of file parse_utilcmd.c.

2137 {
2138  IndexStmt *index;
2139  List *notnullcmds = NIL;
2140  ListCell *lc;
2141 
2143 
2144  index->unique = (constraint->contype != CONSTR_EXCLUSION);
2145  index->primary = (constraint->contype == CONSTR_PRIMARY);
2146  if (index->primary)
2147  {
2148  if (cxt->pkey != NULL)
2149  ereport(ERROR,
2150  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2151  errmsg("multiple primary keys for table \"%s\" are not allowed",
2152  cxt->relation->relname),
2153  parser_errposition(cxt->pstate, constraint->location)));
2154  cxt->pkey = index;
2155 
2156  /*
2157  * In ALTER TABLE case, a primary index might already exist, but
2158  * DefineIndex will check for it.
2159  */
2160  }
2161  index->nulls_not_distinct = constraint->nulls_not_distinct;
2162  index->isconstraint = true;
2163  index->deferrable = constraint->deferrable;
2164  index->initdeferred = constraint->initdeferred;
2165 
2166  if (constraint->conname != NULL)
2167  index->idxname = pstrdup(constraint->conname);
2168  else
2169  index->idxname = NULL; /* DefineIndex will choose name */
2170 
2171  index->relation = cxt->relation;
2172  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2173  index->options = constraint->options;
2174  index->tableSpace = constraint->indexspace;
2175  index->whereClause = constraint->where_clause;
2176  index->indexParams = NIL;
2177  index->indexIncludingParams = NIL;
2178  index->excludeOpNames = NIL;
2179  index->idxcomment = NULL;
2180  index->indexOid = InvalidOid;
2181  index->oldNumber = InvalidRelFileNumber;
2182  index->oldCreateSubid = InvalidSubTransactionId;
2183  index->oldFirstRelfilelocatorSubid = InvalidSubTransactionId;
2184  index->transformed = false;
2185  index->concurrent = false;
2186  index->if_not_exists = false;
2187  index->reset_default_tblspc = constraint->reset_default_tblspc;
2188 
2189  /*
2190  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2191  * verify it's usable, then extract the implied column name list. (We
2192  * will not actually need the column name list at runtime, but we need it
2193  * now to check for duplicate column entries below.)
2194  */
2195  if (constraint->indexname != NULL)
2196  {
2197  char *index_name = constraint->indexname;
2198  Relation heap_rel = cxt->rel;
2199  Oid index_oid;
2200  Relation index_rel;
2201  Form_pg_index index_form;
2202  oidvector *indclass;
2203  Datum indclassDatum;
2204  int i;
2205 
2206  /* Grammar should not allow this with explicit column list */
2207  Assert(constraint->keys == NIL);
2208 
2209  /* Grammar should only allow PRIMARY and UNIQUE constraints */
2210  Assert(constraint->contype == CONSTR_PRIMARY ||
2211  constraint->contype == CONSTR_UNIQUE);
2212 
2213  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2214  if (!cxt->isalter)
2215  ereport(ERROR,
2216  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2217  errmsg("cannot use an existing index in CREATE TABLE"),
2218  parser_errposition(cxt->pstate, constraint->location)));
2219 
2220  /* Look for the index in the same schema as the table */
2221  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
2222 
2223  if (!OidIsValid(index_oid))
2224  ereport(ERROR,
2225  (errcode(ERRCODE_UNDEFINED_OBJECT),
2226  errmsg("index \"%s\" does not exist", index_name),
2227  parser_errposition(cxt->pstate, constraint->location)));
2228 
2229  /* Open the index (this will throw an error if it is not an index) */
2230  index_rel = index_open(index_oid, AccessShareLock);
2231  index_form = index_rel->rd_index;
2232 
2233  /* Check that it does not have an associated constraint already */
2234  if (OidIsValid(get_index_constraint(index_oid)))
2235  ereport(ERROR,
2236  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2237  errmsg("index \"%s\" is already associated with a constraint",
2238  index_name),
2239  parser_errposition(cxt->pstate, constraint->location)));
2240 
2241  /* Perform validity checks on the index */
2242  if (index_form->indrelid != RelationGetRelid(heap_rel))
2243  ereport(ERROR,
2244  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2245  errmsg("index \"%s\" does not belong to table \"%s\"",
2246  index_name, RelationGetRelationName(heap_rel)),
2247  parser_errposition(cxt->pstate, constraint->location)));
2248 
2249  if (!index_form->indisvalid)
2250  ereport(ERROR,
2251  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2252  errmsg("index \"%s\" is not valid", index_name),
2253  parser_errposition(cxt->pstate, constraint->location)));
2254 
2255  if (!index_form->indisunique)
2256  ereport(ERROR,
2257  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2258  errmsg("\"%s\" is not a unique index", index_name),
2259  errdetail("Cannot create a primary key or unique constraint using such an index."),
2260  parser_errposition(cxt->pstate, constraint->location)));
2261 
2262  if (RelationGetIndexExpressions(index_rel) != NIL)
2263  ereport(ERROR,
2264  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2265  errmsg("index \"%s\" contains expressions", index_name),
2266  errdetail("Cannot create a primary key or unique constraint using such an index."),
2267  parser_errposition(cxt->pstate, constraint->location)));
2268 
2269  if (RelationGetIndexPredicate(index_rel) != NIL)
2270  ereport(ERROR,
2271  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2272  errmsg("\"%s\" is a partial index", index_name),
2273  errdetail("Cannot create a primary key or unique constraint using such an index."),
2274  parser_errposition(cxt->pstate, constraint->location)));
2275 
2276  /*
2277  * It's probably unsafe to change a deferred index to non-deferred. (A
2278  * non-constraint index couldn't be deferred anyway, so this case
2279  * should never occur; no need to sweat, but let's check it.)
2280  */
2281  if (!index_form->indimmediate && !constraint->deferrable)
2282  ereport(ERROR,
2283  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2284  errmsg("\"%s\" is a deferrable index", index_name),
2285  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2286  parser_errposition(cxt->pstate, constraint->location)));
2287 
2288  /*
2289  * Insist on it being a btree. That's the only kind that supports
2290  * uniqueness at the moment anyway; but we must have an index that
2291  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2292  * else dump and reload will produce a different index (breaking
2293  * pg_upgrade in particular).
2294  */
2295  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2296  ereport(ERROR,
2297  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2298  errmsg("index \"%s\" is not a btree", index_name),
2299  parser_errposition(cxt->pstate, constraint->location)));
2300 
2301  /* Must get indclass the hard way */
2302  indclassDatum = SysCacheGetAttrNotNull(INDEXRELID,
2303  index_rel->rd_indextuple,
2304  Anum_pg_index_indclass);
2305  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2306 
2307  for (i = 0; i < index_form->indnatts; i++)
2308  {
2309  int16 attnum = index_form->indkey.values[i];
2310  const FormData_pg_attribute *attform;
2311  char *attname;
2312  Oid defopclass;
2313 
2314  /*
2315  * We shouldn't see attnum == 0 here, since we already rejected
2316  * expression indexes. If we do, SystemAttributeDefinition will
2317  * throw an error.
2318  */
2319  if (attnum > 0)
2320  {
2321  Assert(attnum <= heap_rel->rd_att->natts);
2322  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2323  }
2324  else
2325  attform = SystemAttributeDefinition(attnum);
2326  attname = pstrdup(NameStr(attform->attname));
2327 
2328  if (i < index_form->indnkeyatts)
2329  {
2330  /*
2331  * Insist on default opclass, collation, and sort options.
2332  * While the index would still work as a constraint with
2333  * non-default settings, it might not provide exactly the same
2334  * uniqueness semantics as you'd get from a normally-created
2335  * constraint; and there's also the dump/reload problem
2336  * mentioned above.
2337  */
2338  Datum attoptions =
2339  get_attoptions(RelationGetRelid(index_rel), i + 1);
2340 
2341  defopclass = GetDefaultOpClass(attform->atttypid,
2342  index_rel->rd_rel->relam);
2343  if (indclass->values[i] != defopclass ||
2344  attform->attcollation != index_rel->rd_indcollation[i] ||
2345  attoptions != (Datum) 0 ||
2346  index_rel->rd_indoption[i] != 0)
2347  ereport(ERROR,
2348  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2349  errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2350  errdetail("Cannot create a primary key or unique constraint using such an index."),
2351  parser_errposition(cxt->pstate, constraint->location)));
2352 
2353  constraint->keys = lappend(constraint->keys, makeString(attname));
2354  }
2355  else
2356  constraint->including = lappend(constraint->including, makeString(attname));
2357  }
2358 
2359  /* Close the index relation but keep the lock */
2360  relation_close(index_rel, NoLock);
2361 
2362  index->indexOid = index_oid;
2363  }
2364 
2365  /*
2366  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2367  * IndexElems and operator names. We have to break that apart into
2368  * separate lists.
2369  */
2370  if (constraint->contype == CONSTR_EXCLUSION)
2371  {
2372  foreach(lc, constraint->exclusions)
2373  {
2374  List *pair = (List *) lfirst(lc);
2375  IndexElem *elem;
2376  List *opname;
2377 
2378  Assert(list_length(pair) == 2);
2379  elem = linitial_node(IndexElem, pair);
2380  opname = lsecond_node(List, pair);
2381 
2382  index->indexParams = lappend(index->indexParams, elem);
2383  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2384  }
2385  }
2386 
2387  /*
2388  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2389  *
2390  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2391  * also make sure they are NOT NULL.
2392  */
2393  else
2394  {
2395  foreach(lc, constraint->keys)
2396  {
2397  char *key = strVal(lfirst(lc));
2398  bool found = false;
2399  bool forced_not_null = false;
2400  ColumnDef *column = NULL;
2401  ListCell *columns;
2402  IndexElem *iparam;
2403 
2404  /* Make sure referenced column exists. */
2405  foreach(columns, cxt->columns)
2406  {
2407  column = lfirst_node(ColumnDef, columns);
2408  if (strcmp(column->colname, key) == 0)
2409  {
2410  found = true;
2411  break;
2412  }
2413  }
2414  if (found)
2415  {
2416  /*
2417  * column is defined in the new table. For PRIMARY KEY, we
2418  * can apply the not-null constraint cheaply here ... unless
2419  * the column is marked is_from_type, in which case marking it
2420  * here would be ineffective (see MergeAttributes).
2421  */
2422  if (constraint->contype == CONSTR_PRIMARY &&
2423  !column->is_from_type)
2424  {
2425  column->is_not_null = true;
2426  forced_not_null = true;
2427  }
2428  }
2429  else if (SystemAttributeByName(key) != NULL)
2430  {
2431  /*
2432  * column will be a system column in the new table, so accept
2433  * it. System columns can't ever be null, so no need to worry
2434  * about PRIMARY/not-null constraint.
2435  */
2436  found = true;
2437  }
2438  else if (cxt->inhRelations)
2439  {
2440  /* try inherited tables */
2441  ListCell *inher;
2442 
2443  foreach(inher, cxt->inhRelations)
2444  {
2445  RangeVar *inh = lfirst_node(RangeVar, inher);
2446  Relation rel;
2447  int count;
2448 
2449  rel = table_openrv(inh, AccessShareLock);
2450  /* check user requested inheritance from valid relkind */
2451  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2452  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2453  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2454  ereport(ERROR,
2455  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2456  errmsg("inherited relation \"%s\" is not a table or foreign table",
2457  inh->relname)));
2458  for (count = 0; count < rel->rd_att->natts; count++)
2459  {
2460  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2461  count);
2462  char *inhname = NameStr(inhattr->attname);
2463 
2464  if (inhattr->attisdropped)
2465  continue;
2466  if (strcmp(key, inhname) == 0)
2467  {
2468  found = true;
2469 
2470  /*
2471  * It's tempting to set forced_not_null if the
2472  * parent column is already NOT NULL, but that
2473  * seems unsafe because the column's NOT NULL
2474  * marking might disappear between now and
2475  * execution. Do the runtime check to be safe.
2476  */
2477  break;
2478  }
2479  }
2480  table_close(rel, NoLock);
2481  if (found)
2482  break;
2483  }
2484  }
2485 
2486  /*
2487  * In the ALTER TABLE case, don't complain about index keys not
2488  * created in the command; they may well exist already.
2489  * DefineIndex will complain about them if not.
2490  */
2491  if (!found && !cxt->isalter)
2492  ereport(ERROR,
2493  (errcode(ERRCODE_UNDEFINED_COLUMN),
2494  errmsg("column \"%s\" named in key does not exist", key),
2495  parser_errposition(cxt->pstate, constraint->location)));
2496 
2497  /* Check for PRIMARY KEY(foo, foo) */
2498  foreach(columns, index->indexParams)
2499  {
2500  iparam = (IndexElem *) lfirst(columns);
2501  if (iparam->name && strcmp(key, iparam->name) == 0)
2502  {
2503  if (index->primary)
2504  ereport(ERROR,
2505  (errcode(ERRCODE_DUPLICATE_COLUMN),
2506  errmsg("column \"%s\" appears twice in primary key constraint",
2507  key),
2508  parser_errposition(cxt->pstate, constraint->location)));
2509  else
2510  ereport(ERROR,
2511  (errcode(ERRCODE_DUPLICATE_COLUMN),
2512  errmsg("column \"%s\" appears twice in unique constraint",
2513  key),
2514  parser_errposition(cxt->pstate, constraint->location)));
2515  }
2516  }
2517 
2518  /* OK, add it to the index definition */
2519  iparam = makeNode(IndexElem);
2520  iparam->name = pstrdup(key);
2521  iparam->expr = NULL;
2522  iparam->indexcolname = NULL;
2523  iparam->collation = NIL;
2524  iparam->opclass = NIL;
2525  iparam->opclassopts = NIL;
2526  iparam->ordering = SORTBY_DEFAULT;
2528  index->indexParams = lappend(index->indexParams, iparam);
2529 
2530  /*
2531  * For a primary-key column, also create an item for ALTER TABLE
2532  * SET NOT NULL if we couldn't ensure it via is_not_null above.
2533  */
2534  if (constraint->contype == CONSTR_PRIMARY && !forced_not_null)
2535  {
2536  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
2537 
2538  notnullcmd->subtype = AT_SetNotNull;
2539  notnullcmd->name = pstrdup(key);
2540  notnullcmds = lappend(notnullcmds, notnullcmd);
2541  }
2542  }
2543  }
2544 
2545  /*
2546  * Add included columns to index definition. This is much like the
2547  * simple-column-name-list code above, except that we don't worry about
2548  * NOT NULL marking; included columns in a primary key should not be
2549  * forced NOT NULL. We don't complain about duplicate columns, either,
2550  * though maybe we should?
2551  */
2552  foreach(lc, constraint->including)
2553  {
2554  char *key = strVal(lfirst(lc));
2555  bool found = false;
2556  ColumnDef *column = NULL;
2557  ListCell *columns;
2558  IndexElem *iparam;
2559 
2560  foreach(columns, cxt->columns)
2561  {
2562  column = lfirst_node(ColumnDef, columns);
2563  if (strcmp(column->colname, key) == 0)
2564  {
2565  found = true;
2566  break;
2567  }
2568  }
2569 
2570  if (!found)
2571  {
2572  if (SystemAttributeByName(key) != NULL)
2573  {
2574  /*
2575  * column will be a system column in the new table, so accept
2576  * it.
2577  */
2578  found = true;
2579  }
2580  else if (cxt->inhRelations)
2581  {
2582  /* try inherited tables */
2583  ListCell *inher;
2584 
2585  foreach(inher, cxt->inhRelations)
2586  {
2587  RangeVar *inh = lfirst_node(RangeVar, inher);
2588  Relation rel;
2589  int count;
2590 
2591  rel = table_openrv(inh, AccessShareLock);
2592  /* check user requested inheritance from valid relkind */
2593  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2594  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2595  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2596  ereport(ERROR,
2597  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2598  errmsg("inherited relation \"%s\" is not a table or foreign table",
2599  inh->relname)));
2600  for (count = 0; count < rel->rd_att->natts; count++)
2601  {
2602  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2603  count);
2604  char *inhname = NameStr(inhattr->attname);
2605 
2606  if (inhattr->attisdropped)
2607  continue;
2608  if (strcmp(key, inhname) == 0)
2609  {
2610  found = true;
2611  break;
2612  }
2613  }
2614  table_close(rel, NoLock);
2615  if (found)
2616  break;
2617  }
2618  }
2619  }
2620 
2621  /*
2622  * In the ALTER TABLE case, don't complain about index keys not
2623  * created in the command; they may well exist already. DefineIndex
2624  * will complain about them if not.
2625  */
2626  if (!found && !cxt->isalter)
2627  ereport(ERROR,
2628  (errcode(ERRCODE_UNDEFINED_COLUMN),
2629  errmsg("column \"%s\" named in key does not exist", key),
2630  parser_errposition(cxt->pstate, constraint->location)));
2631 
2632  /* OK, add it to the index definition */
2633  iparam = makeNode(IndexElem);
2634  iparam->name = pstrdup(key);
2635  iparam->expr = NULL;
2636  iparam->indexcolname = NULL;
2637  iparam->collation = NIL;
2638  iparam->opclass = NIL;
2639  iparam->opclassopts = NIL;
2640  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2641  }
2642 
2643  /*
2644  * If we found anything that requires run-time SET NOT NULL, build a full
2645  * ALTER TABLE command for that and add it to cxt->alist.
2646  */
2647  if (notnullcmds)
2648  {
2649  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2650 
2651  alterstmt->relation = copyObject(cxt->relation);
2652  alterstmt->cmds = notnullcmds;
2653  alterstmt->objtype = OBJECT_TABLE;
2654  alterstmt->missing_ok = false;
2655 
2656  cxt->alist = lappend(cxt->alist, alterstmt);
2657  }
2658 
2659  return index;
2660 }
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:163
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:240
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:252
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1885
@ AT_SetNotNull
Definition: parsenodes.h:2358
FormData_pg_attribute
Definition: pg_attribute.h:193
#define linitial_node(type, l)
Definition: pg_list.h:181
#define lsecond_node(type, l)
Definition: pg_list.h:186
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5151
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:5038
bool is_from_type
Definition: parsenodes.h:732
List * exclusions
Definition: parsenodes.h:2755
bool reset_default_tblspc
Definition: parsenodes.h:2760
Node * where_clause
Definition: parsenodes.h:2763
char * indexname
Definition: parsenodes.h:2758
char * indexspace
Definition: parsenodes.h:2759
char * access_method
Definition: parsenodes.h:2762
bool nulls_not_distinct
Definition: parsenodes.h:2750
List * including
Definition: parsenodes.h:2753
TupleDesc rd_att
Definition: rel.h:112
Form_pg_index rd_index
Definition: rel.h:192
Oid * rd_indcollation
Definition: rel.h:217
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83

References Constraint::access_method, AccessShareLock, CreateStmtContext::alist, Assert, AT_SetNotNull, attname, attnum, AlterTableStmt::cmds, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, copyObject, DatumGetPointer(), DEFAULT_INDEX_TYPE, Constraint::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, Constraint::exclusions, IndexElem::expr, FormData_pg_attribute, get_attoptions(), get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), i, Constraint::including, index_open(), IndexElem::indexcolname, Constraint::indexname, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, InvalidOid, InvalidRelFileNumber, InvalidSubTransactionId, ColumnDef::is_from_type, ColumnDef::is_not_null, CreateStmtContext::isalter, sort-test::key, Constraint::keys, lappend(), lfirst, lfirst_node, linitial_node, list_length(), Constraint::location, lsecond_node, makeNode, makeString(), AlterTableStmt::missing_ok, IndexElem::name, AlterTableCmd::name, NameStr, TupleDescData::natts, NIL, NoLock, Constraint::nulls_not_distinct, IndexElem::nulls_ordering, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, IndexElem::opclass, IndexElem::opclassopts, Constraint::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, CreateStmtContext::pstate, pstrdup(), RelationData::rd_att, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, Constraint::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, AlterTableCmd::subtype, SysCacheGetAttrNotNull(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), TupleDescAttr, oidvector::values, and Constraint::where_clause.

Referenced by transformIndexConstraints().

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 2033 of file parse_utilcmd.c.

2034 {
2035  IndexStmt *index;
2036  List *indexlist = NIL;
2037  List *finalindexlist = NIL;
2038  ListCell *lc;
2039 
2040  /*
2041  * Run through the constraints that need to generate an index. For PRIMARY
2042  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
2043  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
2044  * NULL.
2045  */
2046  foreach(lc, cxt->ixconstraints)
2047  {
2048  Constraint *constraint = lfirst_node(Constraint, lc);
2049 
2050  Assert(constraint->contype == CONSTR_PRIMARY ||
2051  constraint->contype == CONSTR_UNIQUE ||
2052  constraint->contype == CONSTR_EXCLUSION);
2053 
2054  index = transformIndexConstraint(constraint, cxt);
2055 
2056  indexlist = lappend(indexlist, index);
2057  }
2058 
2059  /*
2060  * Scan the index list and remove any redundant index specifications. This
2061  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2062  * strict reading of SQL would suggest raising an error instead, but that
2063  * strikes me as too anal-retentive. - tgl 2001-02-14
2064  *
2065  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2066  * pre-existing indexes, too.
2067  */
2068  if (cxt->pkey != NULL)
2069  {
2070  /* Make sure we keep the PKEY index in preference to others... */
2071  finalindexlist = list_make1(cxt->pkey);
2072  }
2073 
2074  foreach(lc, indexlist)
2075  {
2076  bool keep = true;
2077  ListCell *k;
2078 
2079  index = lfirst(lc);
2080 
2081  /* if it's pkey, it's already in finalindexlist */
2082  if (index == cxt->pkey)
2083  continue;
2084 
2085  foreach(k, finalindexlist)
2086  {
2087  IndexStmt *priorindex = lfirst(k);
2088 
2089  if (equal(index->indexParams, priorindex->indexParams) &&
2090  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2091  equal(index->whereClause, priorindex->whereClause) &&
2092  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2093  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2094  index->nulls_not_distinct == priorindex->nulls_not_distinct &&
2095  index->deferrable == priorindex->deferrable &&
2096  index->initdeferred == priorindex->initdeferred)
2097  {
2098  priorindex->unique |= index->unique;
2099 
2100  /*
2101  * If the prior index is as yet unnamed, and this one is
2102  * named, then transfer the name to the prior index. This
2103  * ensures that if we have named and unnamed constraints,
2104  * we'll use (at least one of) the names for the index.
2105  */
2106  if (priorindex->idxname == NULL)
2107  priorindex->idxname = index->idxname;
2108  keep = false;
2109  break;
2110  }
2111  }
2112 
2113  if (keep)
2114  finalindexlist = lappend(finalindexlist, index);
2115  }
2116 
2117  /*
2118  * Now append all the IndexStmts to cxt->alist. If we generated an ALTER
2119  * TABLE SET NOT NULL statement to support a primary key, it's already in
2120  * cxt->alist.
2121  */
2122  cxt->alist = list_concat(cxt->alist, finalindexlist);
2123 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:3372
bool deferrable
Definition: parsenodes.h:3376
List * indexParams
Definition: parsenodes.h:3360
bool initdeferred
Definition: parsenodes.h:3377
List * excludeOpNames
Definition: parsenodes.h:3365
bool nulls_not_distinct
Definition: parsenodes.h:3373
char * idxname
Definition: parsenodes.h:3356
Node * whereClause
Definition: parsenodes.h:3364
char * accessMethod
Definition: parsenodes.h:3358
List * indexIncludingParams
Definition: parsenodes.h:3361

References IndexStmt::accessMethod, CreateStmtContext::alist, Assert, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, IndexStmt::deferrable, equal(), IndexStmt::excludeOpNames, IndexStmt::idxname, IndexStmt::indexIncludingParams, IndexStmt::indexParams, IndexStmt::initdeferred, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), list_make1, NIL, IndexStmt::nulls_not_distinct, CreateStmtContext::pkey, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformIndexStmt()

IndexStmt* transformIndexStmt ( Oid  relid,
IndexStmt stmt,
const char *  queryString 
)

Definition at line 2772 of file parse_utilcmd.c.

2773 {
2774  ParseState *pstate;
2775  ParseNamespaceItem *nsitem;
2776  ListCell *l;
2777  Relation rel;
2778 
2779  /* Nothing to do if statement already transformed. */
2780  if (stmt->transformed)
2781  return stmt;
2782 
2783  /* Set up pstate */
2784  pstate = make_parsestate(NULL);
2785  pstate->p_sourcetext = queryString;
2786 
2787  /*
2788  * Put the parent table into the rtable so that the expressions can refer
2789  * to its fields without qualification. Caller is responsible for locking
2790  * relation, but we still need to open it.
2791  */
2792  rel = relation_open(relid, NoLock);
2793  nsitem = addRangeTableEntryForRelation(pstate, rel,
2795  NULL, false, true);
2796 
2797  /* no to join list, yes to namespaces */
2798  addNSItemToQuery(pstate, nsitem, false, true, true);
2799 
2800  /* take care of the where clause */
2801  if (stmt->whereClause)
2802  {
2803  stmt->whereClause = transformWhereClause(pstate,
2804  stmt->whereClause,
2806  "WHERE");
2807  /* we have to fix its collations too */
2808  assign_expr_collations(pstate, stmt->whereClause);
2809  }
2810 
2811  /* take care of any index expressions */
2812  foreach(l, stmt->indexParams)
2813  {
2814  IndexElem *ielem = (IndexElem *) lfirst(l);
2815 
2816  if (ielem->expr)
2817  {
2818  /* Extract preliminary index col name before transforming expr */
2819  if (ielem->indexcolname == NULL)
2820  ielem->indexcolname = FigureIndexColname(ielem->expr);
2821 
2822  /* Now do parse transformation of the expression */
2823  ielem->expr = transformExpr(pstate, ielem->expr,
2825 
2826  /* We have to fix its collations too */
2827  assign_expr_collations(pstate, ielem->expr);
2828 
2829  /*
2830  * transformExpr() should have already rejected subqueries,
2831  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2832  * for an index expression.
2833  *
2834  * DefineIndex() will make more checks.
2835  */
2836  }
2837  }
2838 
2839  /*
2840  * Check that only the base rel is mentioned. (This should be dead code
2841  * now that add_missing_from is history.)
2842  */
2843  if (list_length(pstate->p_rtable) != 1)
2844  ereport(ERROR,
2845  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2846  errmsg("index expressions and predicates can refer only to the table being indexed")));
2847 
2848  free_parsestate(pstate);
2849 
2850  /* Close relation */
2851  table_close(rel, NoLock);
2852 
2853  /* Mark statement as successfully transformed */
2854  stmt->transformed = true;
2855 
2856  return stmt;
2857 }
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:72
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:72
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:73
char * FigureIndexColname(Node *node)
List * p_rtable
Definition: parse_node.h:194

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg(), ERROR, IndexElem::expr, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, FigureIndexColname(), free_parsestate(), IndexElem::indexcolname, lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), stmt, table_close(), transformExpr(), and transformWhereClause().

Referenced by ATPostAlterTypeParse(), ProcessUtilitySlow(), and transformAlterTableStmt().

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1436 of file parse_utilcmd.c.

1437 {
1438  HeapTuple tuple;
1439  TupleDesc tupdesc;
1440  int i;
1441  Oid ofTypeId;
1442 
1443  Assert(ofTypename);
1444 
1445  tuple = typenameType(NULL, ofTypename, NULL);
1446  check_of_type(tuple);
1447  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1448  ofTypename->typeOid = ofTypeId; /* cached for later */
1449 
1450  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1451  for (i = 0; i < tupdesc->natts; i++)
1452  {
1453  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1454  ColumnDef *n;
1455 
1456  if (attr->attisdropped)
1457  continue;
1458 
1459  n = makeColumnDef(NameStr(attr->attname), attr->atttypid,
1460  attr->atttypmod, attr->attcollation);
1461  n->is_from_type = true;
1462 
1463  cxt->columns = lappend(cxt->columns, n);
1464  }
1465  ReleaseTupleDesc(tupdesc);
1466 
1467  ReleaseSysCache(tuple);
1468 }
ColumnDef * makeColumnDef(const char *colname, Oid typeOid, int32 typmod, Oid collOid)
Definition: makefuncs.c:492
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:6946
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1833

References Assert, check_of_type(), CreateStmtContext::columns, GETSTRUCT, i, ColumnDef::is_from_type, lappend(), lookup_rowtype_tupdesc(), makeColumnDef(), NameStr, TupleDescData::natts, ReleaseSysCache(), ReleaseTupleDesc, TupleDescAttr, typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

◆ transformPartitionBound()

PartitionBoundSpec* transformPartitionBound ( ParseState pstate,
Relation  parent,
PartitionBoundSpec spec 
)

Definition at line 4132 of file parse_utilcmd.c.

4134 {
4135  PartitionBoundSpec *result_spec;
4137  char strategy = get_partition_strategy(key);
4138  int partnatts = get_partition_natts(key);
4139  List *partexprs = get_partition_exprs(key);
4140 
4141  /* Avoid scribbling on input */
4142  result_spec = copyObject(spec);
4143 
4144  if (spec->is_default)
4145  {
4146  /*
4147  * Hash partitioning does not support a default partition; there's no
4148  * use case for it (since the set of partitions to create is perfectly
4149  * defined), and if users do get into it accidentally, it's hard to
4150  * back out from it afterwards.
4151  */
4152  if (strategy == PARTITION_STRATEGY_HASH)
4153  ereport(ERROR,
4154  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4155  errmsg("a hash-partitioned table may not have a default partition")));
4156 
4157  /*
4158  * In case of the default partition, parser had no way to identify the
4159  * partition strategy. Assign the parent's strategy to the default
4160  * partition bound spec.
4161  */
4162  result_spec->strategy = strategy;
4163 
4164  return result_spec;
4165  }
4166 
4167  if (strategy == PARTITION_STRATEGY_HASH)
4168  {
4169  if (spec->strategy != PARTITION_STRATEGY_HASH)
4170  ereport(ERROR,
4171  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4172  errmsg("invalid bound specification for a hash partition"),
4173  parser_errposition(pstate, exprLocation((Node *) spec))));
4174 
4175  if (spec->modulus <= 0)
4176  ereport(ERROR,
4177  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4178  errmsg("modulus for hash partition must be an integer value greater than zero")));
4179 
4180  Assert(spec->remainder >= 0);
4181 
4182  if (spec->remainder >= spec->modulus)
4183  ereport(ERROR,
4184  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4185  errmsg("remainder for hash partition must be less than modulus")));
4186  }
4187  else if (strategy == PARTITION_STRATEGY_LIST)
4188  {
4189  ListCell *cell;
4190  char *colname;
4191  Oid coltype;
4192  int32 coltypmod;
4193  Oid partcollation;
4194 
4195  if (spec->strategy != PARTITION_STRATEGY_LIST)
4196  ereport(ERROR,
4197  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4198  errmsg("invalid bound specification for a list partition"),
4199  parser_errposition(pstate, exprLocation((Node *) spec))));
4200 
4201  /* Get the only column's name in case we need to output an error */
4202  if (key->partattrs[0] != 0)
4203  colname = get_attname(RelationGetRelid(parent),
4204  key->partattrs[0], false);
4205  else
4206  colname = deparse_expression((Node *) linitial(partexprs),
4208  RelationGetRelid(parent)),
4209  false, false);
4210  /* Need its type data too */
4211  coltype = get_partition_col_typid(key, 0);
4212  coltypmod = get_partition_col_typmod(key, 0);
4213  partcollation = get_partition_col_collation(key, 0);
4214 
4215  result_spec->listdatums = NIL;
4216  foreach(cell, spec->listdatums)
4217  {
4218  Node *expr = lfirst(cell);
4219  Const *value;
4220  ListCell *cell2;
4221  bool duplicate;
4222 
4223  value = transformPartitionBoundValue(pstate, expr,
4224  colname, coltype, coltypmod,
4225  partcollation);
4226 
4227  /* Don't add to the result if the value is a duplicate */
4228  duplicate = false;
4229  foreach(cell2, result_spec->listdatums)
4230  {
4231  Const *value2 = lfirst_node(Const, cell2);
4232 
4233  if (equal(value, value2))
4234  {
4235  duplicate = true;
4236  break;
4237  }
4238  }
4239  if (duplicate)
4240  continue;
4241 
4242  result_spec->listdatums = lappend(result_spec->listdatums,
4243  value);
4244  }
4245  }
4246  else if (strategy == PARTITION_STRATEGY_RANGE)
4247  {
4248  if (spec->strategy != PARTITION_STRATEGY_RANGE)
4249  ereport(ERROR,
4250  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4251  errmsg("invalid bound specification for a range partition"),
4252  parser_errposition(pstate, exprLocation((Node *) spec))));
4253 
4254  if (list_length(spec->lowerdatums) != partnatts)
4255  ereport(ERROR,
4256  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4257  errmsg("FROM must specify exactly one value per partitioning column")));
4258  if (list_length(spec->upperdatums) != partnatts)
4259  ereport(ERROR,
4260  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
4261  errmsg("TO must specify exactly one value per partitioning column")));
4262 
4263  /*
4264  * Convert raw parse nodes into PartitionRangeDatum nodes and perform
4265  * any necessary validation.
4266  */
4267  result_spec->lowerdatums =
4269  parent);
4270  result_spec->upperdatums =
4272  parent);
4273  }
4274  else
4275  elog(ERROR, "unexpected partition strategy: %d", (int) strategy);
4276 
4277  return result_spec;
4278 }
signed int int32
Definition: c.h:494
static struct @155 value
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1380
static List * transformPartitionRangeBounds(ParseState *pstate, List *blist, Relation parent)
static Const * transformPartitionBoundValue(ParseState *pstate, Node *val, const char *colName, Oid colType, int32 colTypmod, Oid partCollation)
@ PARTITION_STRATEGY_HASH
Definition: parsenodes.h:874
@ PARTITION_STRATEGY_LIST
Definition: parsenodes.h:872
@ PARTITION_STRATEGY_RANGE
Definition: parsenodes.h:873
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:51
static int get_partition_strategy(PartitionKey key)
Definition: partcache.h:59
static int32 get_partition_col_typmod(PartitionKey key, int col)
Definition: partcache.h:92
static int get_partition_natts(PartitionKey key)
Definition: partcache.h:65
static Oid get_partition_col_typid(PartitionKey key, int col)
Definition: partcache.h:86
static Oid get_partition_col_collation(PartitionKey key, int col)
Definition: partcache.h:98
static List * get_partition_exprs(PartitionKey key)
Definition: partcache.h:71
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3598
List * deparse_context_for(const char *aliasname, Oid relid)
Definition: ruleutils.c:3658

References Assert, copyObject, deparse_context_for(), deparse_expression(), elog, equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), get_partition_natts(), get_partition_strategy(), PartitionBoundSpec::is_default, sort-test::key, lappend(), lfirst, lfirst_node, linitial, list_length(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, PartitionBoundSpec::strategy, transformPartitionBoundValue(), transformPartitionRangeBounds(), PartitionBoundSpec::upperdatums, and value.

Referenced by DefineRelation(), and transformPartitionCmd().

◆ transformPartitionBoundValue()

static Const * transformPartitionBoundValue ( ParseState pstate,
Node val,
const char *  colName,
Oid  colType,
int32  colTypmod,
Oid  partCollation 
)
static

Definition at line 4442 of file parse_utilcmd.c.

4445 {
4446  Node *value;
4447 
4448  /* Transform raw parsetree */
4450 
4451  /*
4452  * transformExpr() should have already rejected column references,
4453  * subqueries, aggregates, window functions, and SRFs, based on the
4454  * EXPR_KIND_ of a partition bound expression.
4455  */
4457 
4458  /*
4459  * Coerce to the correct type. This might cause an explicit coercion step
4460  * to be added on top of the expression, which must be evaluated before
4461  * returning the result to the caller.
4462  */
4463  value = coerce_to_target_type(pstate,
4464  value, exprType(value),
4465  colType,
4466  colTypmod,
4469  -1);
4470 
4471  if (value == NULL)
4472  ereport(ERROR,
4473  (errcode(ERRCODE_DATATYPE_MISMATCH),
4474  errmsg("specified value cannot be cast to type %s for column \"%s\"",
4475  format_type_be(colType), colName),
4476  parser_errposition(pstate, exprLocation(val))));
4477 
4478  /*
4479  * Evaluate the expression, if needed, assigning the partition key's data
4480  * type and collation to the resulting Const node.
4481  */
4482  if (!IsA(value, Const))
4483  {
4484  assign_expr_collations(pstate, value);
4485  value = (Node *) expression_planner((Expr *) value);
4486  value = (Node *) evaluate_expr((Expr *) value, colType, colTypmod,
4487  partCollation);
4488  if (!IsA(value, Const))
4489  elog(ERROR, "could not evaluate partition bound expression");
4490  }
4491  else
4492  {
4493  /*
4494  * If the expression is already a Const, as is often the case, we can
4495  * skip the rather expensive steps above. But we still have to insert
4496  * the right collation, since coerce_to_target_type doesn't handle
4497  * that.
4498  */
4499  ((Const *) value)->constcollid = partCollation;
4500  }
4501 
4502  /*
4503  * Attach original expression's parse location to the Const, so that
4504  * that's what will be reported for any later errors related to this
4505  * partition bound.
4506  */
4507  ((Const *) value)->location = exprLocation(val);
4508 
4509  return (Const *) value;
4510 }
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition: clauses.c:4961
long val
Definition: informix.c:670
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:79
Expr * expression_planner(Expr *expr)
Definition: planner.c:6580
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:736
@ COERCION_ASSIGNMENT
Definition: primnodes.h:715
bool contain_var_clause(Node *node)
Definition: var.c:403

References Assert, assign_expr_collations(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, contain_var_clause(), elog, ereport, errcode(), errmsg(), ERROR, evaluate_expr(), EXPR_KIND_PARTITION_BOUND, expression_planner(), exprLocation(), exprType(), format_type_be(), IsA, parser_errposition(), transformExpr(), val, and value.

Referenced by transformPartitionBound(), and transformPartitionRangeBounds().

◆ transformPartitionCmd()

static void transformPartitionCmd ( CreateStmtContext cxt,
PartitionBoundSpec bound 
)
static

Definition at line 4079 of file parse_utilcmd.c.

4080 {
4081  Relation parentRel = cxt->rel;
4082 
4083  switch (parentRel->rd_rel->relkind)
4084  {
4085  case RELKIND_PARTITIONED_TABLE:
4086  /* transform the partition bound, if any */
4087  Assert(RelationGetPartitionKey(parentRel) != NULL);
4088  if (bound != NULL)
4089  cxt->partbound = transformPartitionBound(cxt->pstate, parentRel,
4090  bound);
4091  break;
4092  case RELKIND_PARTITIONED_INDEX:
4093 
4094  /*
4095  * A partitioned index cannot have a partition bound set. ALTER
4096  * INDEX prevents that with its grammar, but not ALTER TABLE.
4097  */
4098  if (bound != NULL)
4099  ereport(ERROR,
4100  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4101  errmsg("\"%s\" is not a partitioned table",
4102  RelationGetRelationName(parentRel))));
4103  break;
4104  case RELKIND_RELATION:
4105  /* the table must be partitioned */
4106  ereport(ERROR,
4107  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4108  errmsg("table \"%s\" is not partitioned",
4109  RelationGetRelationName(parentRel))));
4110  break;
4111  case RELKIND_INDEX:
4112  /* the index must be partitioned */
4113  ereport(ERROR,
4114  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4115  errmsg("index \"%s\" is not partitioned",
4116  RelationGetRelationName(parentRel))));
4117  break;
4118  default:
4119  /* parser shouldn't let this case through */
4120  elog(ERROR, "\"%s\" is not a partitioned table or index",
4121  RelationGetRelationName(parentRel));
4122  break;
4123  }
4124 }
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)

References Assert, elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::partbound, CreateStmtContext::pstate, RelationData::rd_rel, CreateStmtContext::rel, RelationGetPartitionKey(), RelationGetRelationName, and transformPartitionBound().

Referenced by transformAlterTableStmt(), and transformPartitionCmdForSplit().

◆ transformPartitionCmdForMerge()

static void transformPartitionCmdForMerge ( CreateStmtContext cxt,
PartitionCmd partcmd 
)
static

Definition at line 3320 of file parse_utilcmd.c.

3321 {
3322  Oid defaultPartOid;
3323  Oid partOid;
3324  Relation parent = cxt->rel;
3325  PartitionKey key;
3326  char strategy;
3327  ListCell *listptr,
3328  *listptr2;
3329  bool isDefaultPart = false;
3330  List *partOids = NIL;
3331 
3332  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3333  ereport(ERROR,
3334  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3335  errmsg("\"%s\" is not a partitioned table", RelationGetRelationName(parent))));
3336 
3337  key = RelationGetPartitionKey(parent);
3338  strategy = get_partition_strategy(key);
3339 
3340  if (strategy == PARTITION_STRATEGY_HASH)
3341  ereport(ERROR,
3342  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3343  errmsg("partition of hash-partitioned table cannot be merged")));
3344 
3345  /* Is current partition a DEFAULT partition? */
3346  defaultPartOid = get_default_oid_from_partdesc(
3347  RelationGetPartitionDesc(parent, true));
3348 
3349  foreach(listptr, partcmd->partlist)
3350  {
3351  RangeVar *name = (RangeVar *) lfirst(listptr);
3352 
3353  /* Partitions in the list should have different names. */
3354  for_each_cell(listptr2, partcmd->partlist, lnext(partcmd->partlist, listptr))
3355  {
3356  RangeVar *name2 = (RangeVar *) lfirst(listptr2);
3357 
3358  if (equal(name, name2))
3359  ereport(ERROR,
3360  (errcode(ERRCODE_DUPLICATE_TABLE),
3361  errmsg("partition with name \"%s\" is already used", name->relname)),
3362  parser_errposition(cxt->pstate, name2->location));
3363  }
3364 
3365  /* Search DEFAULT partition in the list. */
3366  partOid = RangeVarGetRelid(name, NoLock, false);
3367  if (partOid == defaultPartOid)
3368  isDefaultPart = true;
3369 
3370  checkPartition(parent, partOid);
3371 
3372  partOids = lappend_oid(partOids, partOid);
3373  }
3374 
3375  /* Allocate bound of resulting partition. */
3376  Assert(partcmd->bound == NULL);
3377  partcmd->bound = makeNode(PartitionBoundSpec);
3378 
3379  /* Fill partition bound. */
3380  partcmd->bound->strategy = strategy;
3381  partcmd->bound->location = -1;
3382  partcmd->bound->is_default = isDefaultPart;
3383  if (!isDefaultPart)
3385  partOids, partcmd->bound,
3386  cxt->pstate);
3387 }
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:80
static void checkPartition(Relation rel, Oid partRelOid)
void calculate_partition_bound_for_merge(Relation parent, List *partNames, List *partOids, PartitionBoundSpec *spec, ParseState *pstate)
Definition: partbounds.c:5782
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:71
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition: partdesc.c:487
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:438
ParseLoc location
Definition: primnodes.h:94
const char * name

References Assert, PartitionCmd::bound, calculate_partition_bound_for_merge(), checkPartition(), equal(), ereport, errcode(), errmsg(), ERROR, for_each_cell, get_default_oid_from_partdesc(), get_partition_strategy(), PartitionBoundSpec::is_default, sort-test::key, lappend_oid(), lfirst, lnext(), PartitionBoundSpec::location, RangeVar::location, makeNode, name, NIL, NoLock, parser_errposition(), PARTITION_STRATEGY_HASH, PartitionCmd::partlist, CreateStmtContext::pstate, RangeVarGetRelid, RelationData::rd_rel, CreateStmtContext::rel, RelationGetPartitionDesc(), RelationGetPartitionKey(), RelationGetRelationName, and PartitionBoundSpec::strategy.

Referenced by transformAlterTableStmt().

◆ transformPartitionCmdForSplit()

static void transformPartitionCmdForSplit ( CreateStmtContext cxt,
PartitionCmd partcmd 
)
static

Definition at line 3281 of file parse_utilcmd.c.

3282 {
3283  Relation parent = cxt->rel;
3284  Oid splitPartOid;
3285  ListCell *listptr;
3286 
3287  if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
3288  ereport(ERROR,
3289  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3290  errmsg("\"%s\" is not a partitioned table", RelationGetRelationName(parent))));
3291 
3292  /* Transform partition bounds for all partitions in the list: */
3293  foreach(listptr, partcmd->partlist)
3294  {
3295  SinglePartitionSpec *sps = (SinglePartitionSpec *) lfirst(listptr);
3296 
3297  cxt->partbound = NULL;
3298  transformPartitionCmd(cxt, sps->bound);
3299  /* Assign transformed value of the partition bound. */
3300  sps->bound = cxt->partbound;
3301  }
3302 
3303  splitPartOid = RangeVarGetRelid(partcmd->name, NoLock, false);
3304 
3305  checkPartition(parent, splitPartOid);
3306 
3307  /* Then we should check partitions with transformed bounds. */
3308  check_partitions_for_split(parent, splitPartOid, partcmd->name, partcmd->partlist, cxt->pstate);
3309 }
void check_partitions_for_split(Relation parent, Oid splitPartOid, RangeVar *splitPartName, List *partlist, ParseState *pstate)
Definition: partbounds.c:5563
RangeVar * name
Definition: parsenodes.h:957
PartitionBoundSpec * bound
Definition: parsenodes.h:948

References SinglePartitionSpec::bound, check_partitions_for_split(), checkPartition(), ereport, errcode(), errmsg(), ERROR, lfirst, PartitionCmd::name, NoLock, CreateStmtContext::partbound, PartitionCmd::partlist, CreateStmtContext::pstate, RangeVarGetRelid, RelationData::rd_rel, CreateStmtContext::rel, RelationGetRelationName, and transformPartitionCmd().

Referenced by transformAlterTableStmt().

◆ transformPartitionRangeBounds()

static List * transformPartitionRangeBounds ( ParseState pstate,
List blist,
Relation  parent 
)
static

Definition at line 4286 of file parse_utilcmd.c.

4288 {
4289  List *result = NIL;
4291  List *partexprs = get_partition_exprs(key);
4292  ListCell *lc;
4293  int i,
4294  j;
4295 
4296  i = j = 0;
4297  foreach(lc, blist)
4298  {
4299  Node *expr = lfirst(lc);
4300  PartitionRangeDatum *prd = NULL;
4301 
4302  /*
4303  * Infinite range bounds -- "minvalue" and "maxvalue" -- get passed in
4304  * as ColumnRefs.
4305  */
4306  if (IsA(expr, ColumnRef))
4307  {
4308  ColumnRef *cref = (ColumnRef *) expr;
4309  char *cname = NULL;
4310 
4311  /*
4312  * There should be a single field named either "minvalue" or
4313  * "maxvalue".
4314  */
4315  if (list_length(cref->fields) == 1 &&
4316  IsA(linitial(cref->fields), String))
4317  cname = strVal(linitial(cref->fields));
4318 
4319  if (cname == NULL)
4320  {
4321  /*
4322  * ColumnRef is not in the desired single-field-name form. For
4323  * consistency between all partition strategies, let the
4324  * expression transformation report any errors rather than
4325  * doing it ourselves.
4326  */
4327  }
4328  else if (strcmp("minvalue", cname) == 0)
4329  {
4332  prd->value = NULL;
4333  }
4334  else if (strcmp("maxvalue", cname) == 0)
4335  {
4338  prd->value = NULL;
4339  }
4340  }
4341 
4342  if (prd == NULL)
4343  {
4344  char *colname;
4345  Oid coltype;
4346  int32 coltypmod;
4347  Oid partcollation;
4348  Const *value;
4349 
4350  /* Get the column's name in case we need to output an error */
4351  if (key->partattrs[i] != 0)
4352  colname = get_attname(RelationGetRelid(parent),
4353  key->partattrs[i], false);
4354  else
4355  {
4356  colname = deparse_expression((Node *) list_nth(partexprs, j),
4358  RelationGetRelid(parent)),
4359  false, false);
4360  ++j;
4361  }
4362 
4363  /* Need its type data too */
4364  coltype = get_partition_col_typid(key, i);
4365  coltypmod = get_partition_col_typmod(key, i);
4366  partcollation = get_partition_col_collation(key, i);
4367 
4368  value = transformPartitionBoundValue(pstate, expr,
4369  colname,
4370  coltype, coltypmod,
4371  partcollation);
4372  if (value->constisnull)
4373  ereport(ERROR,
4374  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4375  errmsg("cannot specify NULL in range bound")));
4378  prd->value = (Node *) value;
4379  ++i;
4380  }
4381 
4382  prd->location = exprLocation(expr);
4383 
4384  result = lappend(result, prd);
4385  }
4386 
4387  /*
4388  * Once we see MINVALUE or MAXVALUE for one column, the remaining columns
4389  * must be the same.
4390  */
4391  validateInfiniteBounds(pstate, result);
4392 
4393  return result;
4394 }
int j
Definition: isn.c:74
static void validateInfiniteBounds(ParseState *pstate, List *blist)
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition: parsenodes.h:926
@ PARTITION_RANGE_DATUM_VALUE
Definition: parsenodes.h:925
@ PARTITION_RANGE_DATUM_MINVALUE
Definition: parsenodes.h:924
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
List * fields
Definition: parsenodes.h:294
PartitionRangeDatumKind kind
Definition: parsenodes.h:933
Definition: value.h:64

References deparse_context_for(), deparse_expression(), ereport, errcode(), errmsg(), ERROR, exprLocation(), ColumnRef::fields, get_attname(), get_partition_col_collation(), get_partition_col_typid(), get_partition_col_typmod(), get_partition_exprs(), i, IsA, j, sort-test::key, PartitionRangeDatum::kind, lappend(), lfirst, linitial, list_length(), list_nth(), PartitionRangeDatum::location, makeNode, NIL, PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, PARTITION_RANGE_DATUM_VALUE, RelationGetPartitionKey(), RelationGetRelationName, RelationGetRelid, strVal, transformPartitionBoundValue(), validateInfiniteBounds(), PartitionRangeDatum::value, and value.

Referenced by transformPartitionBound().

◆ transformRuleStmt()

void transformRuleStmt ( RuleStmt stmt,
const char *  queryString,
List **  actions,
Node **  whereClause 
)

Definition at line 2942 of file parse_utilcmd.c.

2944 {
2945  Relation rel;
2946  ParseState *pstate;
2947  ParseNamespaceItem *oldnsitem;
2948  ParseNamespaceItem *newnsitem;
2949 
2950  /*
2951  * To avoid deadlock, make sure the first thing we do is grab
2952  * AccessExclusiveLock on the target relation. This will be needed by
2953  * DefineQueryRewrite(), and we don't want to grab a lesser lock
2954  * beforehand.
2955  */
2956  rel = table_openrv(stmt->relation, AccessExclusiveLock);
2957 
2958  if (rel->rd_rel->relkind == RELKIND_MATVIEW)
2959  ereport(ERROR,
2960  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2961  errmsg("rules on materialized views are not supported")));
2962 
2963  /* Set up pstate */
2964  pstate = make_parsestate(NULL);
2965  pstate->p_sourcetext = queryString;
2966 
2967  /*
2968  * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
2969  * Set up their ParseNamespaceItems in the main pstate for use in parsing
2970  * the rule qualification.
2971  */
2972  oldnsitem = addRangeTableEntryForRelation(pstate, rel,
2974  makeAlias("old", NIL),
2975  false, false);
2976  newnsitem = addRangeTableEntryForRelation(pstate, rel,
2978  makeAlias("new", NIL),
2979  false, false);
2980 
2981  /*
2982  * They must be in the namespace too for lookup purposes, but only add the
2983  * one(s) that are relevant for the current kind of rule. In an UPDATE
2984  * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
2985  * there's no need to be so picky for INSERT & DELETE. We do not add them
2986  * to the joinlist.
2987  */
2988  switch (stmt->event)
2989  {
2990  case CMD_SELECT:
2991  addNSItemToQuery(pstate, oldnsitem, false, true, true);
2992  break;
2993  case CMD_UPDATE:
2994  addNSItemToQuery(pstate, oldnsitem, false, true, true);
2995  addNSItemToQuery(pstate, newnsitem, false, true, true);
2996  break;
2997  case CMD_INSERT:
2998  addNSItemToQuery(pstate, newnsitem, false, true, true);
2999  break;
3000  case CMD_DELETE:
3001  addNSItemToQuery(pstate, oldnsitem, false, true, true);
3002  break;
3003  default:
3004  elog(ERROR, "unrecognized event type: %d",
3005  (int) stmt->event);
3006  break;
3007  }
3008 
3009  /* take care of the where clause */
3010  *whereClause = transformWhereClause(pstate,
3011  stmt->whereClause,
3013  "WHERE");
3014  /* we have to fix its collations too */
3015  assign_expr_collations(pstate, *whereClause);
3016 
3017  /* this is probably dead code without add_missing_from: */
3018  if (list_length(pstate->p_rtable) != 2) /* naughty, naughty... */
3019  ereport(ERROR,
3020  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3021  errmsg("rule WHERE condition cannot contain references to other relations")));
3022 
3023  /*
3024  * 'instead nothing' rules with a qualification need a query rangetable so
3025  * the rewrite handler can add the negated rule qualification to the
3026  * original query. We create a query with the new command type CMD_NOTHING
3027  * here that is treated specially by the rewrite system.
3028  */
3029  if (stmt->actions == NIL)
3030  {
3031  Query *nothing_qry = makeNode(Query);
3032 
3033  nothing_qry->commandType = CMD_NOTHING;
3034  nothing_qry->rtable = pstate->p_rtable;
3035  nothing_qry->rteperminfos = pstate->p_rteperminfos;
3036  nothing_qry->jointree = makeFromExpr(NIL, NULL); /* no join wanted */
3037 
3038  *actions = list_make1(nothing_qry);
3039  }
3040  else
3041  {
3042  ListCell *l;
3043  List *newactions = NIL;
3044 
3045  /*
3046  * transform each statement, like parse_sub_analyze()
3047  */
3048  foreach(l, stmt->actions)
3049  {
3050  Node *action = (Node *) lfirst(l);
3051  ParseState *sub_pstate = make_parsestate(NULL);
3052  Query *sub_qry,
3053  *top_subqry;
3054  bool has_old,
3055  has_new;
3056 
3057  /*
3058  * Since outer ParseState isn't parent of inner, have to pass down
3059  * the query text by hand.
3060  */
3061  sub_pstate->p_sourcetext = queryString;
3062 
3063  /*
3064  * Set up OLD/NEW in the rtable for this statement. The entries
3065  * are added only to relnamespace, not varnamespace, because we
3066  * don't want them to be referred to by unqualified field names
3067  * nor "*" in the rule actions. We decide later whether to put
3068  * them in the joinlist.
3069  */
3070  oldnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3072  makeAlias("old", NIL),
3073  false, false);
3074  newnsitem = addRangeTableEntryForRelation(sub_pstate, rel,
3076  makeAlias("new", NIL),
3077  false, false);
3078  addNSItemToQuery(sub_pstate, oldnsitem, false, true, false);
3079  addNSItemToQuery(sub_pstate, newnsitem, false, true, false);
3080 
3081  /* Transform the rule action statement */
3082  top_subqry = transformStmt(sub_pstate, action);
3083 
3084  /*
3085  * We cannot support utility-statement actions (eg NOTIFY) with
3086  * nonempty rule WHERE conditions, because there's no way to make
3087  * the utility action execute conditionally.
3088  */
3089  if (top_subqry->commandType == CMD_UTILITY &&
3090  *whereClause != NULL)
3091  ereport(ERROR,
3092  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3093  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
3094 
3095  /*
3096  * If the action is INSERT...SELECT, OLD/NEW have been pushed down
3097  * into the SELECT, and that's what we need to look at. (Ugly
3098  * kluge ... try to fix this when we redesign querytrees.)
3099  */
3100  sub_qry = getInsertSelectQuery(top_subqry, NULL);
3101 
3102  /*
3103  * If the sub_qry is a setop, we cannot attach any qualifications
3104  * to it, because the planner won't notice them. This could
3105  * perhaps be relaxed someday, but for now, we may as well reject
3106  * such a rule immediately.
3107  */
3108  if (sub_qry->setOperations != NULL && *whereClause != NULL)
3109  ereport(ERROR,
3110  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3111  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3112 
3113  /*
3114  * Validate action's use of OLD/NEW, qual too
3115  */
3116  has_old =
3117  rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
3118  rangeTableEntry_used(*whereClause, PRS2_OLD_VARNO, 0);
3119  has_new =
3120  rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
3121  rangeTableEntry_used(*whereClause, PRS2_NEW_VARNO, 0);
3122 
3123  switch (stmt->event)
3124  {
3125  case CMD_SELECT:
3126  if (has_old)
3127  ereport(ERROR,
3128  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3129  errmsg("ON SELECT rule cannot use OLD")));
3130  if (has_new)
3131  ereport(ERROR,
3132  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3133  errmsg("ON SELECT rule cannot use NEW")));
3134  break;
3135  case CMD_UPDATE:
3136  /* both are OK */
3137  break;
3138  case CMD_INSERT:
3139  if (has_old)
3140  ereport(ERROR,
3141  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3142  errmsg("ON INSERT rule cannot use OLD")));
3143  break;
3144  case CMD_DELETE:
3145  if (has_new)
3146  ereport(ERROR,
3147  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3148  errmsg("ON DELETE rule cannot use NEW")));
3149  break;
3150  default:
3151  elog(ERROR, "unrecognized event type: %d",
3152  (int) stmt->event);
3153  break;
3154  }
3155 
3156  /*
3157  * OLD/NEW are not allowed in WITH queries, because they would
3158  * amount to outer references for the WITH, which we disallow.
3159  * However, they were already in the outer rangetable when we
3160  * analyzed the query, so we have to check.
3161  *
3162  * Note that in the INSERT...SELECT case, we need to examine the
3163  * CTE lists of both top_subqry and sub_qry.
3164  *
3165  * Note that we aren't digging into the body of the query looking
3166  * for WITHs in nested sub-SELECTs. A WITH down there can
3167  * legitimately refer to OLD/NEW, because it'd be an
3168  * indirect-correlated outer reference.
3169  */
3170  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3171  PRS2_OLD_VARNO, 0) ||
3172  rangeTableEntry_used((Node *) sub_qry->cteList,
3173  PRS2_OLD_VARNO, 0))
3174  ereport(ERROR,
3175  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3176  errmsg("cannot refer to OLD within WITH query")));
3177  if (rangeTableEntry_used((Node *) top_subqry->cteList,
3178  PRS2_NEW_VARNO, 0) ||
3179  rangeTableEntry_used((Node *) sub_qry->cteList,
3180  PRS2_NEW_VARNO, 0))
3181  ereport(ERROR,
3182  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3183  errmsg("cannot refer to NEW within WITH query")));
3184 
3185  /*
3186  * For efficiency's sake, add OLD to the rule action's jointree
3187  * only if it was actually referenced in the statement or qual.
3188  *
3189  * For INSERT, NEW is not really a relation (only a reference to
3190  * the to-be-inserted tuple) and should never be added to the
3191  * jointree.
3192  *
3193  * For UPDATE, we treat NEW as being another kind of reference to
3194  * OLD, because it represents references to *transformed* tuples
3195  * of the existing relation. It would be wrong to enter NEW
3196  * separately in the jointree, since that would cause a double
3197  * join of the updated relation. It's also wrong to fail to make
3198  * a jointree entry if only NEW and not OLD is mentioned.
3199  */
3200  if (has_old || (has_new && stmt->event == CMD_UPDATE))
3201  {
3202  RangeTblRef *rtr;
3203 
3204  /*
3205  * If sub_qry is a setop, manipulating its jointree will do no
3206  * good at all, because the jointree is dummy. (This should be
3207  * a can't-happen case because of prior tests.)
3208  */
3209  if (sub_qry->setOperations != NULL)
3210  ereport(ERROR,
3211  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3212  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
3213  /* hackishly add OLD to the already-built FROM clause */
3214  rtr = makeNode(RangeTblRef);
3215  rtr->rtindex = oldnsitem->p_rtindex;
3216  sub_qry->jointree->fromlist =
3217  lappend(sub_qry->jointree->fromlist, rtr);
3218  }
3219 
3220  newactions = lappend(newactions, top_subqry);
3221 
3222  free_parsestate(sub_pstate);
3223  }
3224 
3225  *actions = newactions;
3226  }
3227 
3228  free_parsestate(pstate);
3229 
3230  /* Close relation, but keep the exclusive lock */
3231  table_close(rel, NoLock);
3232 }
#define AccessExclusiveLock
Definition: lockdefs.h:43
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:389
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:287
@ CMD_UTILITY
Definition: nodes.h:270
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
@ CMD_NOTHING
Definition: nodes.h:272
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:311
#define PRS2_OLD_VARNO
Definition: primnodes.h:244
#define PRS2_NEW_VARNO
Definition: primnodes.h:245
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:998
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:966
List * fromlist
Definition: primnodes.h:2304
List * p_rteperminfos
Definition: parse_node.h:195
FromExpr * jointree
Definition: parsenodes.h:175
Node * setOperations
Definition: parsenodes.h:219
List * cteList
Definition: parsenodes.h:166
List * rtable
Definition: parsenodes.h:168
CmdType commandType
Definition: parsenodes.h:121

References AccessExclusiveLock, AccessShareLock, generate_unaccent_rules::action, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), CMD_DELETE, CMD_INSERT, CMD_NOTHING, CMD_SELECT, CMD_UPDATE, CMD_UTILITY, Query::commandType, Query::cteList, elog, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_WHERE, free_parsestate(), FromExpr::fromlist, getInsertSelectQuery(), Query::jointree, lappend(), lfirst, list_length(), list_make1, make_parsestate(), makeAlias(), makeFromExpr(), makeNode, NIL, NoLock, ParseState::p_rtable, ParseState::p_rteperminfos, ParseNamespaceItem::p_rtindex, ParseState::p_sourcetext, PRS2_NEW_VARNO, PRS2_OLD_VARNO, rangeTableEntry_used(), RelationData::rd_rel, Query::rtable, RangeTblRef::rtindex, Query::setOperations, stmt, table_close(), table_openrv(), transformStmt(), and transformWhereClause().

Referenced by DefineRule().

◆ transformStatsStmt()

CreateStatsStmt* transformStatsStmt ( Oid  relid,
CreateStatsStmt stmt,
const char *  queryString 
)

Definition at line 2867 of file parse_utilcmd.c.

2868 {
2869  ParseState *pstate;
2870  ParseNamespaceItem *nsitem;
2871  ListCell *l;
2872  Relation rel;
2873 
2874  /* Nothing to do if statement already transformed. */
2875  if (stmt->transformed)
2876  return stmt;
2877 
2878  /* Set up pstate */
2879  pstate = make_parsestate(NULL);
2880  pstate->p_sourcetext = queryString;
2881 
2882  /*
2883  * Put the parent table into the rtable so that the expressions can refer
2884  * to its fields without qualification. Caller is responsible for locking
2885  * relation, but we still need to open it.
2886  */
2887  rel = relation_open(relid, NoLock);
2888  nsitem = addRangeTableEntryForRelation(pstate, rel,
2890  NULL, false, true);
2891 
2892  /* no to join list, yes to namespaces */
2893  addNSItemToQuery(pstate, nsitem, false, true, true);
2894 
2895  /* take care of any expressions */
2896  foreach(l, stmt->exprs)
2897  {
2898  StatsElem *selem = (StatsElem *) lfirst(l);
2899 
2900  if (selem->expr)
2901  {
2902  /* Now do parse transformation of the expression */
2903  selem->expr = transformExpr(pstate, selem->expr,
2905 
2906  /* We have to fix its collations too */
2907  assign_expr_collations(pstate, selem->expr);
2908  }
2909  }
2910 
2911  /*
2912  * Check that only the base rel is mentioned. (This should be dead code
2913  * now that add_missing_from is history.)
2914  */
2915  if (list_length(pstate->p_rtable) != 1)
2916  ereport(ERROR,
2917  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2918  errmsg("statistics expressions can refer only to the table being referenced")));
2919 
2920  free_parsestate(pstate);
2921 
2922  /* Close relation */
2923  table_close(rel, NoLock);
2924 
2925  /* Mark statement as successfully transformed */
2926  stmt->transformed = true;
2927 
2928  return stmt;
2929 }
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:74

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), assign_expr_collations(), ereport, errcode(), errmsg(), ERROR, StatsElem::expr, EXPR_KIND_STATS_EXPRESSION, free_parsestate(), lfirst, list_length(), make_parsestate(), NoLock, ParseState::p_rtable, ParseState::p_sourcetext, relation_open(), stmt, table_close(), and transformExpr().

Referenced by ATPostAlterTypeParse(), and ProcessUtilitySlow().

◆ transformTableConstraint()

static void transformTableConstraint ( CreateStmtContext cxt,
Constraint constraint 
)
static

Definition at line 878 of file parse_utilcmd.c.

879 {
880  switch (constraint->contype)
881  {
882  case CONSTR_PRIMARY:
883  if (cxt->isforeign)
884  ereport(ERROR,
885  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
886  errmsg("primary key constraints are not supported on foreign tables"),
888  constraint->location)));
889  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
890  break;
891 
892  case CONSTR_UNIQUE:
893  if (cxt->isforeign)
894  ereport(ERROR,
895  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
896  errmsg("unique constraints are not supported on foreign tables"),
898  constraint->location)));
899  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
900  break;
901 
902  case CONSTR_EXCLUSION:
903  if (cxt->isforeign)
904  ereport(ERROR,
905  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
906  errmsg("exclusion constraints are not supported on foreign tables"),
908  constraint->location)));
909  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
910  break;
911 
912  case CONSTR_CHECK:
913  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
914  break;
915 
916  case CONSTR_FOREIGN:
917  if (cxt->isforeign)
918  ereport(ERROR,
919  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
920  errmsg("foreign key constraints are not supported on foreign tables"),
922  constraint->location)));
923  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
924  break;
925 
926  case CONSTR_NULL:
927  case CONSTR_NOTNULL:
928  case CONSTR_DEFAULT:
933  elog(ERROR, "invalid context for constraint type %d",
934  constraint->contype);
935  break;
936 
937  default:
938  elog(ERROR, "unrecognized constraint type: %d",
939  constraint->contype);
940  break;
941  }
942 }

References CreateStmtContext::ckconstraints, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::fkconstraints, CreateStmtContext::isforeign, CreateStmtContext::ixconstraints, lappend(), Constraint::location, parser_errposition(), and CreateStmtContext::pstate.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

◆ transformTableLikeClause()

static void transformTableLikeClause ( CreateStmtContext cxt,
TableLikeClause table_like_clause 
)
static

Definition at line 955 of file parse_utilcmd.c.

956 {
957  AttrNumber parent_attno;
958  Relation relation;
959  TupleDesc tupleDesc;
960  AclResult aclresult;
961  char *comment;
962  ParseCallbackState pcbstate;
963 
965  table_like_clause->relation->location);
966 
967  /* we could support LIKE in many cases, but worry about it another day */
968  if (cxt->isforeign)
969  ereport(ERROR,
970  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
971  errmsg("LIKE is not supported for creating foreign tables")));
972 
973  /* Open the relation referenced by the LIKE clause */
974  relation = relation_openrv(table_like_clause->relation, AccessShareLock);
975 
976  if (relation->rd_rel->relkind != RELKIND_RELATION &&
977  relation->rd_rel->relkind != RELKIND_VIEW &&
978  relation->rd_rel->relkind != RELKIND_MATVIEW &&
979  relation->rd_rel->relkind != RELKIND_COMPOSITE_TYPE &&
980  relation->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
981  relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
982  ereport(ERROR,
983  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
984  errmsg("relation \"%s\" is invalid in LIKE clause",
985  RelationGetRelationName(relation)),
986  errdetail_relkind_not_supported(relation->rd_rel->relkind)));
987 
989 
990  /*
991  * Check for privileges
992  */
993  if (relation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
994  {
995  aclresult = object_aclcheck(TypeRelationId, relation->rd_rel->reltype, GetUserId(),
996  ACL_USAGE);
997  if (aclresult != ACLCHECK_OK)
998  aclcheck_error(aclresult, OBJECT_TYPE,
999  RelationGetRelationName(relation));
1000  }
1001  else
1002  {
1003  aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1004  ACL_SELECT);
1005  if (aclresult != ACLCHECK_OK)
1006  aclcheck_error(aclresult, get_relkind_objtype(relation->rd_rel->relkind),
1007  RelationGetRelationName(relation));
1008  }
1009 
1010  tupleDesc = RelationGetDescr(relation);
1011 
1012  /*
1013  * Insert the copied attributes into the cxt for the new table definition.
1014  * We must do this now so that they appear in the table in the relative
1015  * position where the LIKE clause is, as required by SQL99.
1016  */
1017  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1018  parent_attno++)
1019  {
1020  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1021  parent_attno - 1);
1022  ColumnDef *def;
1023 
1024  /*
1025  * Ignore dropped columns in the parent.
1026  */
1027  if (attribute->attisdropped)
1028  continue;
1029 
1030  /*
1031  * Create a new column, which is marked as NOT inherited.
1032  *
1033  * For constraints, ONLY the not-null constraint is inherited by the
1034  * new column definition per SQL99.
1035  */
1036  def = makeColumnDef(NameStr(attribute->attname), attribute->atttypid,
1037  attribute->atttypmod, attribute->attcollation);
1038  def->is_not_null = attribute->attnotnull;
1039 
1040  /*
1041  * Add to column list
1042  */
1043  cxt->columns = lappend(cxt->columns, def);
1044 
1045  /*
1046  * Although we don't transfer the column's default/generation
1047  * expression now, we need to mark it GENERATED if appropriate.
1048  */
1049  if (attribute->atthasdef && attribute->attgenerated &&
1050  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED))
1051  def->generated = attribute->attgenerated;
1052 
1053  /*
1054  * Copy identity if requested
1055  */
1056  if (attribute->attidentity &&
1057  (table_like_clause->options & CREATE_TABLE_LIKE_IDENTITY))
1058  {
1059  Oid seq_relid;
1060  List *seq_options;
1061 
1062  /*
1063  * find sequence owned by old column; extract sequence parameters;
1064  * build new create sequence command
1065  */
1066  seq_relid = getIdentitySequence(relation, attribute->attnum, false);
1067  seq_options = sequence_options(seq_relid);
1068  generateSerialExtraStmts(cxt, def,
1069  InvalidOid, seq_options,
1070  true, false,
1071  NULL, NULL);
1072  def->identity = attribute->attidentity;
1073  }
1074 
1075  /* Likewise, copy storage if requested */
1076  if (table_like_clause->options & CREATE_TABLE_LIKE_STORAGE)
1077  def->storage = attribute->attstorage;
1078  else
1079  def->storage = 0;
1080 
1081  /* Likewise, copy compression if requested */
1082  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMPRESSION) != 0
1083  && CompressionMethodIsValid(attribute->attcompression))
1084  def->compression =
1085  pstrdup(GetCompressionMethodName(attribute->attcompression));
1086  else
1087  def->compression = NULL;
1088 
1089  /* Likewise, copy comment if requested */
1090  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1091  (comment = GetComment(attribute->attrelid,
1092  RelationRelationId,
1093  attribute->attnum)) != NULL)
1094  {
1096 
1097  stmt->objtype = OBJECT_COLUMN;
1098  stmt->object = (Node *) list_make3(makeString(cxt->relation->schemaname),
1099  makeString(cxt->relation->relname),
1100  makeString(def->colname));
1101  stmt->comment = comment;
1102 
1103  cxt->alist = lappend(cxt->alist, stmt);
1104  }
1105  }
1106 
1107  /*
1108  * We cannot yet deal with defaults, CHECK constraints, indexes, or
1109  * statistics, since we don't yet know what column numbers the copied
1110  * columns will have in the finished table. If any of those options are
1111  * specified, add the LIKE clause to cxt->likeclauses so that
1112  * expandTableLikeClause will be called after we do know that. Also,
1113  * remember the relation OID so that expandTableLikeClause is certain to
1114  * open the same table.
1115  */
1116  if (table_like_clause->options &
1122  {
1123  table_like_clause->relationOid = RelationGetRelid(relation);
1124  cxt->likeclauses = lappend(cxt->likeclauses, table_like_clause);
1125  }
1126 
1127  /*
1128  * Close the parent rel, but keep our AccessShareLock on it until xact
1129  * commit. That will prevent someone else from deleting or ALTERing the
1130  * parent before we can run expandTableLikeClause.
1131  */
1132  table_close(relation, NoLock);
1133 }
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3888
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4091
List * sequence_options(Oid relid)
Definition: sequence.c:1704
#define ACL_USAGE
Definition: parsenodes.h:84
@ OBJECT_COLUMN
Definition: parsenodes.h:2267
@ OBJECT_TYPE
Definition: parsenodes.h:2310
#define ACL_SELECT
Definition: parsenodes.h:77
@ CREATE_TABLE_LIKE_IDENTITY
Definition: parsenodes.h:766
@ CREATE_TABLE_LIKE_COMPRESSION
Definition: parsenodes.h:762
@ CREATE_TABLE_LIKE_STORAGE
Definition: parsenodes.h:769
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
char storage
Definition: parsenodes.h:733
char * compression
Definition: parsenodes.h:728
RangeVar * relation
Definition: parsenodes.h:754
const char * GetCompressionMethodName(char method)
#define CompressionMethodIsValid(cm)

References AccessShareLock, ACL_SELECT, ACL_USAGE, aclcheck_error(), ACLCHECK_OK, CreateStmtContext::alist, cancel_parser_errposition_callback(), ColumnDef::colname, CreateStmtContext::columns, comment, ColumnDef::compression, CompressionMethodIsValid, CREATE_TABLE_LIKE_COMMENTS, CREATE_TABLE_LIKE_COMPRESSION, CREATE_TABLE_LIKE_CONSTRAINTS, CREATE_TABLE_LIKE_DEFAULTS, CREATE_TABLE_LIKE_GENERATED, CREATE_TABLE_LIKE_IDENTITY, CREATE_TABLE_LIKE_INDEXES, CREATE_TABLE_LIKE_STATISTICS, CREATE_TABLE_LIKE_STORAGE, ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, ColumnDef::generated, generateSerialExtraStmts(), get_relkind_objtype(), GetComment(), GetCompressionMethodName(), getIdentitySequence(), GetUserId(), ColumnDef::identity, InvalidOid, ColumnDef::is_not_null, CreateStmtContext::isforeign, lappend(), CreateStmtContext::likeclauses, list_make3, RangeVar::location, makeColumnDef(), makeNode, makeString(), NameStr, TupleDescData::natts, NoLock, object_aclcheck(), OBJECT_COLUMN, OBJECT_TYPE, TableLikeClause::options, pg_class_aclcheck(), CreateStmtContext::pstate, pstrdup(), RelationData::rd_rel, CreateStmtContext::relation, TableLikeClause::relation, relation_openrv(), RelationGetDescr, RelationGetRelationName, RelationGetRelid, TableLikeClause::relationOid, RangeVar::relname, RangeVar::schemaname, sequence_options(), setup_parser_errposition_callback(), stmt, ColumnDef::storage, table_close(), and TupleDescAttr.

Referenced by transformCreateStmt().

◆ validateInfiniteBounds()

static void validateInfiniteBounds ( ParseState pstate,
List blist 
)
static

Definition at line 4403 of file parse_utilcmd.c.

4404 {
4405  ListCell *lc;
4407 
4408  foreach(lc, blist)
4409  {
4411 
4412  if (kind == prd->kind)
4413  continue;
4414 
4415  switch (kind)
4416  {
4418  kind = prd->kind;
4419  break;
4420 
4422  ereport(ERROR,
4423  (errcode(ERRCODE_DATATYPE_MISMATCH),
4424  errmsg("every bound following MAXVALUE must also be MAXVALUE"),
4425  parser_errposition(pstate, exprLocation((Node *) prd))));
4426  break;
4427 
4429  ereport(ERROR,
4430  (errcode(ERRCODE_DATATYPE_MISMATCH),
4431  errmsg("every bound following MINVALUE must also be MINVALUE"),
4432  parser_errposition(pstate, exprLocation((Node *) prd))));
4433  break;
4434  }
4435  }
4436 }
PartitionRangeDatumKind
Definition: parsenodes.h:923

References ereport, errcode(), errmsg(), ERROR, exprLocation(), PartitionRangeDatum::kind, lfirst_node, parser_errposition(), PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, and PARTITION_RANGE_DATUM_VALUE.

Referenced by transformPartitionRangeBounds().