PostgreSQL Source Code  git master
parse_utilcmd.c File Reference
#include "postgres.h"
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/relation.h"
#include "access/reloptions.h"
#include "access/table.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_type.h"
#include "commands/comment.h"
#include "commands/defrem.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/analyze.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#include "rewrite/rewriteManip.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
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)
 
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 transformExtendedStatistics (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 (char *context_schema, char **stmt_schema_name)
 
static void transformPartitionCmd (CreateStmtContext *cxt, PartitionCmd *cmd)
 
static ListtransformPartitionRangeBounds (ParseState *pstate, List *blist, Relation parent)
 
static void validateInfiniteBounds (ParseState *pstate, List *blist)
 
static ConsttransformPartitionBoundValue (ParseState *pstate, Node *con, 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)
 
void transformRuleStmt (RuleStmt *stmt, const char *queryString, List **actions, Node **whereClause)
 
AlterTableStmttransformAlterTableStmt (Oid relid, AlterTableStmt *stmt, const char *queryString, List **beforeStmts, List **afterStmts)
 
ListtransformCreateSchemaStmt (CreateSchemaStmt *stmt)
 
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))

Referenced by transformConstraintAttrs().

Function Documentation

◆ expandTableLikeClause()

List* expandTableLikeClause ( RangeVar heapRel,
TableLikeClause table_like_clause 
)

Definition at line 1155 of file parse_utilcmd.c.

References AccessShareLock, Assert, AT_AddConstraint, AT_CookedColumnDefault, AttrMap::attnums, build_attrmap_by_name(), ConstrCheck::ccbin, ConstrCheck::ccname, ConstrCheck::ccnoinherit, TupleConstr::check, AlterTableStmt::cmds, CommentStmt::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, AlterTableCmd::def, TupleConstr::defval, ereport, errcode(), errdetail(), errmsg(), ERROR, generateClonedIndexStmt(), get_relation_constraint_oid(), GetComment(), i, IndexStmt::idxcomment, index_close(), index_open(), Constraint::initially_valid, InvalidOid, Constraint::is_no_inherit, lappend(), lcons(), lfirst_oid, list_make3, Constraint::location, makeNode, makeString(), map_variable_attnos(), AlterTableStmt::missing_ok, NameStr, TupleDescData::natts, NIL, nodeToString(), NoLock, AlterTableCmd::num, TupleConstr::num_check, TupleConstr::num_defval, CommentStmt::object, OBJECT_TABCONSTRAINT, OBJECT_TABLE, AlterTableStmt::objtype, CommentStmt::objtype, TableLikeClause::options, pstrdup(), Constraint::raw_expr, RelationData::rd_rel, TableLikeClause::relation, AlterTableStmt::relation, relation_openrv(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, RelationGetRelid, RangeVar::relname, RangeVar::schemaname, Constraint::skip_validation, stringToNode(), AlterTableCmd::subtype, table_close(), and TupleDescAttr.

Referenced by ProcessUtilitySlow().

1156 {
1157  List *result = NIL;
1158  List *atsubcmds = NIL;
1159  AttrNumber parent_attno;
1160  Relation relation;
1161  Relation childrel;
1162  TupleDesc tupleDesc;
1163  TupleConstr *constr;
1164  AttrMap *attmap;
1165  char *comment;
1166 
1167  /*
1168  * Open the relation referenced by the LIKE clause. We should still have
1169  * the table lock obtained by transformTableLikeClause (and this'll throw
1170  * an assertion failure if not). Hence, no need to recheck privileges
1171  * etc.
1172  */
1173  relation = relation_openrv(table_like_clause->relation, NoLock);
1174 
1175  tupleDesc = RelationGetDescr(relation);
1176  constr = tupleDesc->constr;
1177 
1178  /*
1179  * Open the newly-created child relation; we have lock on that too.
1180  */
1181  childrel = relation_openrv(heapRel, NoLock);
1182 
1183  /*
1184  * Construct a map from the LIKE relation's attnos to the child rel's.
1185  * This re-checks type match etc, although it shouldn't be possible to
1186  * have a failure since both tables are locked.
1187  */
1188  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1189  tupleDesc);
1190 
1191  /*
1192  * Process defaults, if required.
1193  */
1194  if ((table_like_clause->options &
1196  constr != NULL)
1197  {
1198  AttrDefault *attrdef = constr->defval;
1199 
1200  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1201  parent_attno++)
1202  {
1203  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1204  parent_attno - 1);
1205 
1206  /*
1207  * Ignore dropped columns in the parent.
1208  */
1209  if (attribute->attisdropped)
1210  continue;
1211 
1212  /*
1213  * Copy default, if present and it should be copied. We have
1214  * separate options for plain default expressions and GENERATED
1215  * defaults.
1216  */
1217  if (attribute->atthasdef &&
1218  (attribute->attgenerated ?
1219  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1220  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1221  {
1222  Node *this_default = NULL;
1223  AlterTableCmd *atsubcmd;
1224  bool found_whole_row;
1225 
1226  /* Find default in constraint structure */
1227  for (int i = 0; i < constr->num_defval; i++)
1228  {
1229  if (attrdef[i].adnum == parent_attno)
1230  {
1231  this_default = stringToNode(attrdef[i].adbin);
1232  break;
1233  }
1234  }
1235  Assert(this_default != NULL);
1236 
1237  atsubcmd = makeNode(AlterTableCmd);
1238  atsubcmd->subtype = AT_CookedColumnDefault;
1239  atsubcmd->num = attmap->attnums[parent_attno - 1];
1240  atsubcmd->def = map_variable_attnos(this_default,
1241  1, 0,
1242  attmap,
1243  InvalidOid,
1244  &found_whole_row);
1245 
1246  /*
1247  * Prevent this for the same reason as for constraints below.
1248  * Note that defaults cannot contain any vars, so it's OK that
1249  * the error message refers to generated columns.
1250  */
1251  if (found_whole_row)
1252  ereport(ERROR,
1253  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1254  errmsg("cannot convert whole-row table reference"),
1255  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1256  NameStr(attribute->attname),
1257  RelationGetRelationName(relation))));
1258 
1259  atsubcmds = lappend(atsubcmds, atsubcmd);
1260  }
1261  }
1262  }
1263 
1264  /*
1265  * Copy CHECK constraints if requested, being careful to adjust attribute
1266  * numbers so they match the child.
1267  */
1268  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1269  constr != NULL)
1270  {
1271  int ccnum;
1272 
1273  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1274  {
1275  char *ccname = constr->check[ccnum].ccname;
1276  char *ccbin = constr->check[ccnum].ccbin;
1277  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1278  Node *ccbin_node;
1279  bool found_whole_row;
1280  Constraint *n;
1281  AlterTableCmd *atsubcmd;
1282 
1283  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1284  1, 0,
1285  attmap,
1286  InvalidOid, &found_whole_row);
1287 
1288  /*
1289  * We reject whole-row variables because the whole point of LIKE
1290  * is that the new table's rowtype might later diverge from the
1291  * parent's. So, while translation might be possible right now,
1292  * it wouldn't be possible to guarantee it would work in future.
1293  */
1294  if (found_whole_row)
1295  ereport(ERROR,
1296  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1297  errmsg("cannot convert whole-row table reference"),
1298  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1299  ccname,
1300  RelationGetRelationName(relation))));
1301 
1302  n = makeNode(Constraint);
1303  n->contype = CONSTR_CHECK;
1304  n->conname = pstrdup(ccname);
1305  n->location = -1;
1306  n->is_no_inherit = ccnoinherit;
1307  n->raw_expr = NULL;
1308  n->cooked_expr = nodeToString(ccbin_node);
1309 
1310  /* We can skip validation, since the new table should be empty. */
1311  n->skip_validation = true;
1312  n->initially_valid = true;
1313 
1314  atsubcmd = makeNode(AlterTableCmd);
1315  atsubcmd->subtype = AT_AddConstraint;
1316  atsubcmd->def = (Node *) n;
1317  atsubcmds = lappend(atsubcmds, atsubcmd);
1318 
1319  /* Copy comment on constraint */
1320  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1322  n->conname, false),
1323  ConstraintRelationId,
1324  0)) != NULL)
1325  {
1326  CommentStmt *stmt = makeNode(CommentStmt);
1327 
1328  stmt->objtype = OBJECT_TABCONSTRAINT;
1329  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1330  makeString(heapRel->relname),
1331  makeString(n->conname));
1332  stmt->comment = comment;
1333 
1334  result = lappend(result, stmt);
1335  }
1336  }
1337  }
1338 
1339  /*
1340  * If we generated any ALTER TABLE actions above, wrap them into a single
1341  * ALTER TABLE command. Stick it at the front of the result, so it runs
1342  * before any CommentStmts we made above.
1343  */
1344  if (atsubcmds)
1345  {
1347 
1348  atcmd->relation = copyObject(heapRel);
1349  atcmd->cmds = atsubcmds;
1350  atcmd->objtype = OBJECT_TABLE;
1351  atcmd->missing_ok = false;
1352  result = lcons(atcmd, result);
1353  }
1354 
1355  /*
1356  * Process indexes if required.
1357  */
1358  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1359  relation->rd_rel->relhasindex)
1360  {
1361  List *parent_indexes;
1362  ListCell *l;
1363 
1364  parent_indexes = RelationGetIndexList(relation);
1365 
1366  foreach(l, parent_indexes)
1367  {
1368  Oid parent_index_oid = lfirst_oid(l);
1369  Relation parent_index;
1370  IndexStmt *index_stmt;
1371 
1372  parent_index = index_open(parent_index_oid, AccessShareLock);
1373 
1374  /* Build CREATE INDEX statement to recreate the parent_index */
1375  index_stmt = generateClonedIndexStmt(heapRel,
1376  parent_index,
1377  attmap,
1378  NULL);
1379 
1380  /* Copy comment on index, if requested */
1381  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1382  {
1383  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1384 
1385  /*
1386  * We make use of IndexStmt's idxcomment option, so as not to
1387  * need to know now what name the index will have.
1388  */
1389  index_stmt->idxcomment = comment;
1390  }
1391 
1392  result = lappend(result, index_stmt);
1393 
1394  index_close(parent_index, AccessShareLock);
1395  }
1396  }
1397 
1398  /* Done with child rel */
1399  table_close(childrel, NoLock);
1400 
1401  /*
1402  * Close the parent rel, but keep our AccessShareLock on it until xact
1403  * commit. That will prevent someone else from deleting or ALTERing the
1404  * parent before the child is committed.
1405  */
1406  table_close(relation, NoLock);
1407 
1408  return result;
1409 }
ObjectType objtype
Definition: parsenodes.h:2682
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:210
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:482
Oid get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1187
Node * raw_expr
Definition: parsenodes.h:2164
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:610
void * stringToNode(const char *str)
Definition: read.c:89
AlterTableType subtype
Definition: parsenodes.h:1865
char * comment
Definition: parsenodes.h:2684
char * conname
Definition: parsenodes.h:2157
Node * object
Definition: parsenodes.h:2683
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Definition: attmap.h:34
char * schemaname
Definition: primnodes.h:67
AttrDefault * defval
Definition: tupdesc.h:39
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
TupleConstr * constr
Definition: tupdesc.h:85
int errdetail(const char *fmt,...)
Definition: elog.c:954
char * ccname
Definition: tupdesc.h:30
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
char * GetComment(Oid oid, Oid classoid, int32 subid)
Definition: comment.c:409
ObjectType objtype
Definition: parsenodes.h:1780
List * lappend(List *list, void *datum)
Definition: list.c:321
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:138
uint16 num_check
Definition: tupdesc.h:43
#define InvalidOid
Definition: postgres_ext.h:36
bool is_no_inherit
Definition: parsenodes.h:2163
bool initially_valid
Definition: parsenodes.h:2200
#define ereport(elevel,...)
Definition: elog.h:144
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
List * lcons(void *datum, List *list)
Definition: list.c:453
#define makeNode(_type_)
Definition: nodes.h:576
#define Assert(condition)
Definition: c.h:746
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
AttrNumber * attnums
Definition: attmap.h:36
char * idxcomment
Definition: parsenodes.h:2787
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4514
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
RangeVar * relation
Definition: parsenodes.h:674
uint16 num_defval
Definition: tupdesc.h:42
int errmsg(const char *fmt,...)
Definition: elog.c:821
RangeVar * relation
Definition: parsenodes.h:1778
int i
#define NameStr(name)
Definition: c.h:623
char * nodeToString(const void *obj)
Definition: outfuncs.c:4358
ConstrType contype
Definition: parsenodes.h:2154
ConstrCheck * check
Definition: tupdesc.h:40
char * cooked_expr
Definition: parsenodes.h:2165
#define copyObject(obj)
Definition: nodes.h:644
Definition: pg_list.h:50
char * ccbin
Definition: tupdesc.h:31
int16 AttrNumber
Definition: attnum.h:21
bool skip_validation
Definition: parsenodes.h:2199
#define RelationGetRelid(relation)
Definition: rel.h:456
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define lfirst_oid(lc)
Definition: pg_list.h:171
bool ccnoinherit
Definition: tupdesc.h:33

◆ generateClonedExtStatsStmt()

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

Definition at line 1833 of file parse_utilcmd.c.

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, attnum, DatumGetArrayTypeP, CreateStatsStmt::defnames, elog, ERROR, CreateStatsStmt::exprs, ColumnRef::fields, get_attname(), GETSTRUCT, HeapTupleIsValid, i, CreateStatsStmt::if_not_exists, lappend(), list_make1, ColumnRef::location, makeNode, makeString(), NIL, ObjectIdGetDatum, OidIsValid, CreateStatsStmt::relations, ReleaseSysCache(), SearchSysCache1(), CreateStatsStmt::stat_types, STATEXTOID, CreateStatsStmt::stxcomment, and SysCacheGetAttr().

Referenced by transformTableLikeClause().

1835 {
1836  HeapTuple ht_stats;
1837  Form_pg_statistic_ext statsrec;
1838  CreateStatsStmt *stats;
1839  List *stat_types = NIL;
1840  List *def_names = NIL;
1841  bool isnull;
1842  Datum datum;
1843  ArrayType *arr;
1844  char *enabled;
1845  int i;
1846 
1847  Assert(OidIsValid(heapRelid));
1848  Assert(heapRel != NULL);
1849 
1850  /*
1851  * Fetch pg_statistic_ext tuple of source statistics object.
1852  */
1853  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1854  if (!HeapTupleIsValid(ht_stats))
1855  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1856  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1857 
1858  /* Determine which statistics types exist */
1859  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1860  Anum_pg_statistic_ext_stxkind, &isnull);
1861  Assert(!isnull);
1862  arr = DatumGetArrayTypeP(datum);
1863  if (ARR_NDIM(arr) != 1 ||
1864  ARR_HASNULL(arr) ||
1865  ARR_ELEMTYPE(arr) != CHAROID)
1866  elog(ERROR, "stxkind is not a 1-D char array");
1867  enabled = (char *) ARR_DATA_PTR(arr);
1868  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1869  {
1870  if (enabled[i] == STATS_EXT_NDISTINCT)
1871  stat_types = lappend(stat_types, makeString("ndistinct"));
1872  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1873  stat_types = lappend(stat_types, makeString("dependencies"));
1874  else if (enabled[i] == STATS_EXT_MCV)
1875  stat_types = lappend(stat_types, makeString("mcv"));
1876  else
1877  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1878  }
1879 
1880  /* Determine which columns the statistics are on */
1881  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1882  {
1883  ColumnRef *cref = makeNode(ColumnRef);
1884  AttrNumber attnum = statsrec->stxkeys.values[i];
1885 
1886  cref->fields = list_make1(makeString(get_attname(heapRelid,
1887  attnum, false)));
1888  cref->location = -1;
1889 
1890  def_names = lappend(def_names, cref);
1891  }
1892 
1893  /* finally, build the output node */
1894  stats = makeNode(CreateStatsStmt);
1895  stats->defnames = NULL;
1896  stats->stat_types = stat_types;
1897  stats->exprs = def_names;
1898  stats->relations = list_make1(heapRel);
1899  stats->stxcomment = NULL;
1900  stats->if_not_exists = false;
1901 
1902  /* Clean up */
1903  ReleaseSysCache(ht_stats);
1904 
1905  return stats;
1906 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define OidIsValid(objectId)
Definition: c.h:652
int location
Definition: parsenodes.h:237
#define list_make1(x1)
Definition: pg_list.h:206
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ARR_DIMS(a)
Definition: array.h:282
#define ARR_DATA_PTR(a)
Definition: array.h:310
#define ARR_HASNULL(a)
Definition: array.h:279
List * lappend(List *list, void *datum)
Definition: list.c:321
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
int16 attnum
Definition: pg_attribute.h:79
#define makeNode(_type_)
Definition: nodes.h:576
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:746
#define ARR_NDIM(a)
Definition: array.h:278
#define elog(elevel,...)
Definition: elog.h:214
int i
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
Definition: pg_list.h:50
#define ARR_ELEMTYPE(a)
Definition: array.h:280
int16 AttrNumber
Definition: attnum.h:21
List * fields
Definition: parsenodes.h:236
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ generateClonedIndexStmt()

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

Definition at line 1475 of file parse_utilcmd.c.

References IndexStmt::accessMethod, IndexAmRoutine::amcanorder, AMOID, Assert, attname, attnum, AttributeNumberIsValid, IndexElem::collation, IndexStmt::concurrent, CONSTROID, DatumGetArrayTypeP, DatumGetObjectId, DatumGetPointer, deconstruct_array(), IndexStmt::deferrable, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, 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, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, IndexElem::indexcolname, IndexStmt::indexIncludingParams, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, IndexStmt::initdeferred, InvalidOid, InvalidSubTransactionId, IndexStmt::isconstraint, lappend(), lfirst, list_head(), list_make2, lnext(), makeNode, makeString(), map_variable_attnos(), IndexElem::name, NameStr, NIL, IndexElem::nulls_ordering, ObjectIdGetDatum, OidIsValid, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilenodeSubid, IndexStmt::oldNode, IndexElem::opclass, IndexElem::opclassopts, OPEROID, IndexStmt::options, IndexElem::ordering, IndexStmt::primary, pstrdup(), RelationData::rd_indam, RelationData::rd_indextuple, RelationData::rd_indoption, IndexStmt::relation, RelationGetDescr, RelationGetRelationName, RelationGetRelid, ReleaseSysCache(), RELOID, IndexStmt::reset_default_tblspc, SearchSysCache1(), SORTBY_DEFAULT, SORTBY_DESC, SORTBY_NULLS_DEFAULT, SORTBY_NULLS_FIRST, SORTBY_NULLS_LAST, stringToNode(), SysCacheGetAttr(), IndexStmt::tableSpace, TextDatumGetCString, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, untransformRelOptions(), oidvector::values, and IndexStmt::whereClause.

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

1478 {
1479  Oid source_relid = RelationGetRelid(source_idx);
1480  HeapTuple ht_idxrel;
1481  HeapTuple ht_idx;
1482  HeapTuple ht_am;
1483  Form_pg_class idxrelrec;
1484  Form_pg_index idxrec;
1485  Form_pg_am amrec;
1486  oidvector *indcollation;
1487  oidvector *indclass;
1488  IndexStmt *index;
1489  List *indexprs;
1490  ListCell *indexpr_item;
1491  Oid indrelid;
1492  int keyno;
1493  Oid keycoltype;
1494  Datum datum;
1495  bool isnull;
1496 
1497  if (constraintOid)
1498  *constraintOid = InvalidOid;
1499 
1500  /*
1501  * Fetch pg_class tuple of source index. We can't use the copy in the
1502  * relcache entry because it doesn't include optional fields.
1503  */
1504  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1505  if (!HeapTupleIsValid(ht_idxrel))
1506  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1507  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1508 
1509  /* Fetch pg_index tuple for source index from relcache entry */
1510  ht_idx = source_idx->rd_indextuple;
1511  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1512  indrelid = idxrec->indrelid;
1513 
1514  /* Fetch the pg_am tuple of the index' access method */
1515  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1516  if (!HeapTupleIsValid(ht_am))
1517  elog(ERROR, "cache lookup failed for access method %u",
1518  idxrelrec->relam);
1519  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1520 
1521  /* Extract indcollation from the pg_index tuple */
1522  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1523  Anum_pg_index_indcollation, &isnull);
1524  Assert(!isnull);
1525  indcollation = (oidvector *) DatumGetPointer(datum);
1526 
1527  /* Extract indclass from the pg_index tuple */
1528  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1529  Anum_pg_index_indclass, &isnull);
1530  Assert(!isnull);
1531  indclass = (oidvector *) DatumGetPointer(datum);
1532 
1533  /* Begin building the IndexStmt */
1534  index = makeNode(IndexStmt);
1535  index->relation = heapRel;
1536  index->accessMethod = pstrdup(NameStr(amrec->amname));
1537  if (OidIsValid(idxrelrec->reltablespace))
1538  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1539  else
1540  index->tableSpace = NULL;
1541  index->excludeOpNames = NIL;
1542  index->idxcomment = NULL;
1543  index->indexOid = InvalidOid;
1544  index->oldNode = InvalidOid;
1547  index->unique = idxrec->indisunique;
1548  index->primary = idxrec->indisprimary;
1549  index->transformed = true; /* don't need transformIndexStmt */
1550  index->concurrent = false;
1551  index->if_not_exists = false;
1552  index->reset_default_tblspc = false;
1553 
1554  /*
1555  * We don't try to preserve the name of the source index; instead, just
1556  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1557  * the name, we'd get duplicate-relation-name failures unless the source
1558  * table was in a different schema.)
1559  */
1560  index->idxname = NULL;
1561 
1562  /*
1563  * If the index is marked PRIMARY or has an exclusion condition, it's
1564  * certainly from a constraint; else, if it's not marked UNIQUE, it
1565  * certainly isn't. If it is or might be from a constraint, we have to
1566  * fetch the pg_constraint record.
1567  */
1568  if (index->primary || index->unique || idxrec->indisexclusion)
1569  {
1570  Oid constraintId = get_index_constraint(source_relid);
1571 
1572  if (OidIsValid(constraintId))
1573  {
1574  HeapTuple ht_constr;
1575  Form_pg_constraint conrec;
1576 
1577  if (constraintOid)
1578  *constraintOid = constraintId;
1579 
1580  ht_constr = SearchSysCache1(CONSTROID,
1581  ObjectIdGetDatum(constraintId));
1582  if (!HeapTupleIsValid(ht_constr))
1583  elog(ERROR, "cache lookup failed for constraint %u",
1584  constraintId);
1585  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1586 
1587  index->isconstraint = true;
1588  index->deferrable = conrec->condeferrable;
1589  index->initdeferred = conrec->condeferred;
1590 
1591  /* If it's an exclusion constraint, we need the operator names */
1592  if (idxrec->indisexclusion)
1593  {
1594  Datum *elems;
1595  int nElems;
1596  int i;
1597 
1598  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1599  /* Extract operator OIDs from the pg_constraint tuple */
1600  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1601  Anum_pg_constraint_conexclop,
1602  &isnull);
1603  if (isnull)
1604  elog(ERROR, "null conexclop for constraint %u",
1605  constraintId);
1606 
1608  OIDOID, sizeof(Oid), true, TYPALIGN_INT,
1609  &elems, NULL, &nElems);
1610 
1611  for (i = 0; i < nElems; i++)
1612  {
1613  Oid operid = DatumGetObjectId(elems[i]);
1614  HeapTuple opertup;
1615  Form_pg_operator operform;
1616  char *oprname;
1617  char *nspname;
1618  List *namelist;
1619 
1620  opertup = SearchSysCache1(OPEROID,
1621  ObjectIdGetDatum(operid));
1622  if (!HeapTupleIsValid(opertup))
1623  elog(ERROR, "cache lookup failed for operator %u",
1624  operid);
1625  operform = (Form_pg_operator) GETSTRUCT(opertup);
1626  oprname = pstrdup(NameStr(operform->oprname));
1627  /* For simplicity we always schema-qualify the op name */
1628  nspname = get_namespace_name(operform->oprnamespace);
1629  namelist = list_make2(makeString(nspname),
1630  makeString(oprname));
1631  index->excludeOpNames = lappend(index->excludeOpNames,
1632  namelist);
1633  ReleaseSysCache(opertup);
1634  }
1635  }
1636 
1637  ReleaseSysCache(ht_constr);
1638  }
1639  else
1640  index->isconstraint = false;
1641  }
1642  else
1643  index->isconstraint = false;
1644 
1645  /* Get the index expressions, if any */
1646  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1647  Anum_pg_index_indexprs, &isnull);
1648  if (!isnull)
1649  {
1650  char *exprsString;
1651 
1652  exprsString = TextDatumGetCString(datum);
1653  indexprs = (List *) stringToNode(exprsString);
1654  }
1655  else
1656  indexprs = NIL;
1657 
1658  /* Build the list of IndexElem */
1659  index->indexParams = NIL;
1660  index->indexIncludingParams = NIL;
1661 
1662  indexpr_item = list_head(indexprs);
1663  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1664  {
1665  IndexElem *iparam;
1666  AttrNumber attnum = idxrec->indkey.values[keyno];
1668  keyno);
1669  int16 opt = source_idx->rd_indoption[keyno];
1670 
1671  iparam = makeNode(IndexElem);
1672 
1673  if (AttributeNumberIsValid(attnum))
1674  {
1675  /* Simple index column */
1676  char *attname;
1677 
1678  attname = get_attname(indrelid, attnum, false);
1679  keycoltype = get_atttype(indrelid, attnum);
1680 
1681  iparam->name = attname;
1682  iparam->expr = NULL;
1683  }
1684  else
1685  {
1686  /* Expressional index */
1687  Node *indexkey;
1688  bool found_whole_row;
1689 
1690  if (indexpr_item == NULL)
1691  elog(ERROR, "too few entries in indexprs list");
1692  indexkey = (Node *) lfirst(indexpr_item);
1693  indexpr_item = lnext(indexprs, indexpr_item);
1694 
1695  /* Adjust Vars to match new table's column numbering */
1696  indexkey = map_variable_attnos(indexkey,
1697  1, 0,
1698  attmap,
1699  InvalidOid, &found_whole_row);
1700 
1701  /* As in expandTableLikeClause, reject whole-row variables */
1702  if (found_whole_row)
1703  ereport(ERROR,
1704  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1705  errmsg("cannot convert whole-row table reference"),
1706  errdetail("Index \"%s\" contains a whole-row table reference.",
1707  RelationGetRelationName(source_idx))));
1708 
1709  iparam->name = NULL;
1710  iparam->expr = indexkey;
1711 
1712  keycoltype = exprType(indexkey);
1713  }
1714 
1715  /* Copy the original index column name */
1716  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1717 
1718  /* Add the collation name, if non-default */
1719  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1720 
1721  /* Add the operator class name, if non-default */
1722  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1723  iparam->opclassopts =
1724  untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1725 
1726  iparam->ordering = SORTBY_DEFAULT;
1728 
1729  /* Adjust options if necessary */
1730  if (source_idx->rd_indam->amcanorder)
1731  {
1732  /*
1733  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1734  * set non-default settings unnecessarily, though, so as to
1735  * improve the chance of recognizing equivalence to constraint
1736  * indexes.
1737  */
1738  if (opt & INDOPTION_DESC)
1739  {
1740  iparam->ordering = SORTBY_DESC;
1741  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1743  }
1744  else
1745  {
1746  if (opt & INDOPTION_NULLS_FIRST)
1748  }
1749  }
1750 
1751  index->indexParams = lappend(index->indexParams, iparam);
1752  }
1753 
1754  /* Handle included columns separately */
1755  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1756  {
1757  IndexElem *iparam;
1758  AttrNumber attnum = idxrec->indkey.values[keyno];
1760  keyno);
1761 
1762  iparam = makeNode(IndexElem);
1763 
1764  if (AttributeNumberIsValid(attnum))
1765  {
1766  /* Simple index column */
1767  char *attname;
1768 
1769  attname = get_attname(indrelid, attnum, false);
1770 
1771  iparam->name = attname;
1772  iparam->expr = NULL;
1773  }
1774  else
1775  ereport(ERROR,
1776  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1777  errmsg("expressions are not supported in included columns")));
1778 
1779  /* Copy the original index column name */
1780  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1781 
1782  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1783  }
1784  /* Copy reloptions if any */
1785  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1786  Anum_pg_class_reloptions, &isnull);
1787  if (!isnull)
1788  index->options = untransformRelOptions(datum);
1789 
1790  /* If it's a partial index, decompile and append the predicate */
1791  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1792  Anum_pg_index_indpred, &isnull);
1793  if (!isnull)
1794  {
1795  char *pred_str;
1796  Node *pred_tree;
1797  bool found_whole_row;
1798 
1799  /* Convert text string to node tree */
1800  pred_str = TextDatumGetCString(datum);
1801  pred_tree = (Node *) stringToNode(pred_str);
1802 
1803  /* Adjust Vars to match new table's column numbering */
1804  pred_tree = map_variable_attnos(pred_tree,
1805  1, 0,
1806  attmap,
1807  InvalidOid, &found_whole_row);
1808 
1809  /* As in expandTableLikeClause, reject whole-row variables */
1810  if (found_whole_row)
1811  ereport(ERROR,
1812  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1813  errmsg("cannot convert whole-row table reference"),
1814  errdetail("Index \"%s\" contains a whole-row table reference.",
1815  RelationGetRelationName(source_idx))));
1816 
1817  index->whereClause = pred_tree;
1818  }
1819 
1820  /* Clean up */
1821  ReleaseSysCache(ht_idxrel);
1822  ReleaseSysCache(ht_am);
1823 
1824  return index;
1825 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
bool deferrable
Definition: parsenodes.h:2796
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:362
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:602
bool primary
Definition: parsenodes.h:2794
struct IndexAmRoutine * rd_indam
Definition: rel.h:188
int16 * rd_indoption
Definition: rel.h:193
SortByDir ordering
Definition: parsenodes.h:707
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2784
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2790
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
#define RelationGetDescr(relation)
Definition: rel.h:482
char * tableSpace
Definition: parsenodes.h:2780
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define DatumGetObjectId(X)
Definition: postgres.h:500
char * pstrdup(const char *in)
Definition: mcxt.c:1187
Node * whereClause
Definition: parsenodes.h:2785
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:610
void * stringToNode(const char *str)
Definition: read.c:89
Node * map_variable_attnos(Node *node, int target_varno, int sublevels_up, const AttrMap *attno_map, Oid to_rowtype, bool *found_whole_row)
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
List * opclassopts
Definition: parsenodes.h:706
struct HeapTupleData * rd_indextuple
Definition: rel.h:176
List * indexIncludingParams
Definition: parsenodes.h:2782
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2788
Node * expr
Definition: parsenodes.h:702
RangeVar * relation
Definition: parsenodes.h:2778
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:968
SortByNulls nulls_ordering
Definition: parsenodes.h:708
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:610
bool transformed
Definition: parsenodes.h:2798
int errdetail(const char *fmt,...)
Definition: elog.c:954
char * indexcolname
Definition: parsenodes.h:703
#define RelationGetRelationName(relation)
Definition: rel.h:490
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:1007
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2791
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:911
List * lappend(List *list, void *datum)
Definition: list.c:321
char * idxname
Definition: parsenodes.h:2777
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:87
bool reset_default_tblspc
Definition: parsenodes.h:2801
bool if_not_exists
Definition: parsenodes.h:2800
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
bool unique
Definition: parsenodes.h:2793
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1308
char * accessMethod
Definition: parsenodes.h:2779
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
List * opclass
Definition: parsenodes.h:705
#define makeNode(_type_)
Definition: nodes.h:576
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
List * indexParams
Definition: parsenodes.h:2781
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
List * excludeOpNames
Definition: parsenodes.h:2786
bool initdeferred
Definition: parsenodes.h:2797
bool amcanorder
Definition: amapi.h:219
char * name
Definition: parsenodes.h:701
char * idxcomment
Definition: parsenodes.h:2787
#define InvalidSubTransactionId
Definition: c.h:527
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
#define DatumGetPointer(X)
Definition: postgres.h:549
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3483
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
bool concurrent
Definition: parsenodes.h:2799
bool isconstraint
Definition: parsenodes.h:2795
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
int errmsg(const char *fmt,...)
Definition: elog.c:821
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1467
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:623
List * collation
Definition: parsenodes.h:704
char * get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: lsyscache.c:825
static List * get_collation(Oid collation, Oid actual_datatype)
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ 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 350 of file parse_utilcmd.c.

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

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

354 {
355  ListCell *option;
356  DefElem *nameEl = NULL;
357  Oid snamespaceid;
358  char *snamespace;
359  char *sname;
360  CreateSeqStmt *seqstmt;
361  AlterSeqStmt *altseqstmt;
362  List *attnamelist;
363  int nameEl_idx = -1;
364 
365  /*
366  * Determine namespace and name to use for the sequence.
367  *
368  * First, check if a sequence name was passed in as an option. This is
369  * used by pg_dump. Else, generate a name.
370  *
371  * Although we use ChooseRelationName, it's not guaranteed that the
372  * selected sequence name won't conflict; given sufficiently long field
373  * names, two different serial columns in the same table could be assigned
374  * the same sequence name, and we'd not notice since we aren't creating
375  * the sequence quite yet. In practice this seems quite unlikely to be a
376  * problem, especially since few people would need two serial columns in
377  * one table.
378  */
379  foreach(option, seqoptions)
380  {
381  DefElem *defel = lfirst_node(DefElem, option);
382 
383  if (strcmp(defel->defname, "sequence_name") == 0)
384  {
385  if (nameEl)
386  ereport(ERROR,
387  (errcode(ERRCODE_SYNTAX_ERROR),
388  errmsg("conflicting or redundant options")));
389  nameEl = defel;
390  nameEl_idx = foreach_current_index(option);
391  }
392  }
393 
394  if (nameEl)
395  {
397 
398  snamespace = rv->schemaname;
399  if (!snamespace)
400  {
401  /* Given unqualified SEQUENCE NAME, select namespace */
402  if (cxt->rel)
403  snamespaceid = RelationGetNamespace(cxt->rel);
404  else
405  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
406  snamespace = get_namespace_name(snamespaceid);
407  }
408  sname = rv->relname;
409  /* Remove the SEQUENCE NAME item from seqoptions */
410  seqoptions = list_delete_nth_cell(seqoptions, nameEl_idx);
411  }
412  else
413  {
414  if (cxt->rel)
415  snamespaceid = RelationGetNamespace(cxt->rel);
416  else
417  {
418  snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
419  RangeVarAdjustRelationPersistence(cxt->relation, snamespaceid);
420  }
421  snamespace = get_namespace_name(snamespaceid);
422  sname = ChooseRelationName(cxt->relation->relname,
423  column->colname,
424  "seq",
425  snamespaceid,
426  false);
427  }
428 
429  ereport(DEBUG1,
430  (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
431  cxt->stmtType, sname,
432  cxt->relation->relname, column->colname)));
433 
434  /*
435  * Build a CREATE SEQUENCE command to create the sequence object, and add
436  * it to the list of things to be done before this CREATE/ALTER TABLE.
437  */
438  seqstmt = makeNode(CreateSeqStmt);
439  seqstmt->for_identity = for_identity;
440  seqstmt->sequence = makeRangeVar(snamespace, sname, -1);
441  seqstmt->options = seqoptions;
442 
443  /*
444  * If a sequence data type was specified, add it to the options. Prepend
445  * to the list rather than append; in case a user supplied their own AS
446  * clause, the "redundant options" error will point to their occurrence,
447  * not our synthetic one.
448  */
449  if (seqtypid)
450  seqstmt->options = lcons(makeDefElem("as",
451  (Node *) makeTypeNameFromOid(seqtypid, -1),
452  -1),
453  seqstmt->options);
454 
455  /*
456  * If this is ALTER ADD COLUMN, make sure the sequence will be owned by
457  * the table's owner. The current user might be someone else (perhaps a
458  * superuser, or someone who's only a member of the owning role), but the
459  * SEQUENCE OWNED BY mechanisms will bleat unless table and sequence have
460  * exactly the same owning role.
461  */
462  if (cxt->rel)
463  seqstmt->ownerId = cxt->rel->rd_rel->relowner;
464  else
465  seqstmt->ownerId = InvalidOid;
466 
467  cxt->blist = lappend(cxt->blist, seqstmt);
468 
469  /*
470  * Store the identity sequence name that we decided on. ALTER TABLE ...
471  * ADD COLUMN ... IDENTITY needs this so that it can fill the new column
472  * with values from the sequence, while the association of the sequence
473  * with the table is not set until after the ALTER TABLE.
474  */
475  column->identitySequence = seqstmt->sequence;
476 
477  /*
478  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence as
479  * owned by this column, and add it to the appropriate list of things to
480  * be done along with this CREATE/ALTER TABLE. In a CREATE or ALTER ADD
481  * COLUMN, it must be done after the statement because we don't know the
482  * column's attnum yet. But if we do have the attnum (in AT_AddIdentity),
483  * we can do the marking immediately, which improves some ALTER TABLE
484  * behaviors.
485  */
486  altseqstmt = makeNode(AlterSeqStmt);
487  altseqstmt->sequence = makeRangeVar(snamespace, sname, -1);
488  attnamelist = list_make3(makeString(snamespace),
489  makeString(cxt->relation->relname),
490  makeString(column->colname));
491  altseqstmt->options = list_make1(makeDefElem("owned_by",
492  (Node *) attnamelist, -1));
493  altseqstmt->for_identity = for_identity;
494 
495  if (col_exists)
496  cxt->blist = lappend(cxt->blist, altseqstmt);
497  else
498  cxt->alist = lappend(cxt->alist, altseqstmt);
499 
500  if (snamespace_p)
501  *snamespace_p = snamespace;
502  if (sname_p)
503  *sname_p = sname;
504 }
Value * makeString(char *str)
Definition: value.c:53
#define list_make3(x1, x2, x3)
Definition: pg_list.h:210
#define DEBUG1
Definition: elog.h:25
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:610
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:3061
char * ChooseRelationName(const char *name1, const char *name2, const char *label, Oid namespaceid, bool isconstraint)
Definition: indexcmds.c:2252
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:641
List * options
Definition: parsenodes.h:2558
char * schemaname
Definition: primnodes.h:67
#define list_make1(x1)
Definition: pg_list.h:206
RangeVar * identitySequence
Definition: parsenodes.h:658
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:172
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
Node * arg
Definition: parsenodes.h:734
List * lappend(List *list, void *datum)
Definition: list.c:321
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
#define InvalidOid
Definition: postgres_ext.h:36
RangeVar * sequence
Definition: parsenodes.h:2557
#define ereport(elevel,...)
Definition: elog.h:144
RangeVar * sequence
Definition: parsenodes.h:2547
List * lcons(void *datum, List *list)
Definition: list.c:453
#define makeNode(_type_)
Definition: nodes.h:576
const char * stmtType
Definition: parse_utilcmd.c:79
int errmsg(const char *fmt,...)
Definition: elog.c:821
bool for_identity
Definition: parsenodes.h:2559
char * defname
Definition: parsenodes.h:733
char * colname
Definition: parsenodes.h:648
List * list_delete_nth_cell(List *list, int n)
Definition: list.c:696
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:449
List * options
Definition: parsenodes.h:2548
#define foreach_current_index(cell)
Definition: pg_list.h:370
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ get_collation()

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

Definition at line 1915 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1916 {
1917  List *result;
1918  HeapTuple ht_coll;
1919  Form_pg_collation coll_rec;
1920  char *nsp_name;
1921  char *coll_name;
1922 
1923  if (!OidIsValid(collation))
1924  return NIL; /* easy case */
1925  if (collation == get_typcollation(actual_datatype))
1926  return NIL; /* just let it default */
1927 
1928  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1929  if (!HeapTupleIsValid(ht_coll))
1930  elog(ERROR, "cache lookup failed for collation %u", collation);
1931  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1932 
1933  /* For simplicity, we always schema-qualify the name */
1934  nsp_name = get_namespace_name(coll_rec->collnamespace);
1935  coll_name = pstrdup(NameStr(coll_rec->collname));
1936  result = list_make2(makeString(nsp_name), makeString(coll_name));
1937 
1938  ReleaseSysCache(ht_coll);
1939  return result;
1940 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#define OidIsValid(objectId)
Definition: c.h:652
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2933
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:623
Definition: pg_list.h:50

◆ get_opclass()

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

Definition at line 1949 of file parse_utilcmd.c.

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

Referenced by generateClonedIndexStmt().

1950 {
1951  List *result = NIL;
1952  HeapTuple ht_opc;
1953  Form_pg_opclass opc_rec;
1954 
1955  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1956  if (!HeapTupleIsValid(ht_opc))
1957  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1958  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1959 
1960  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1961  {
1962  /* For simplicity, we always schema-qualify the name */
1963  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1964  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1965 
1966  result = list_make2(makeString(nsp_name), makeString(opc_name));
1967  }
1968 
1969  ReleaseSysCache(ht_opc);
1970  return result;
1971 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2057
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:623
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
Definition: pg_list.h:50

◆ setSchemaName()

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

Definition at line 3789 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3790 {
3791  if (*stmt_schema_name == NULL)
3792  *stmt_schema_name = context_schema;
3793  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3794  ereport(ERROR,
3795  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3796  errmsg("CREATE specifies a schema (%s) "
3797  "different from the one being created (%s)",
3798  *stmt_schema_name, context_schema)));
3799 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ transformAlterTableStmt()

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

Definition at line 3150 of file parse_utilcmd.c.

References AccessShareLock, addNSItemToQuery(), addRangeTableEntryForRelation(), CreateStmtContext::alist, AT_AddColumn, AT_AddColumnRecurse, AT_AddConstraint, AT_AddConstraintRecurse, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AlterColumnType, AT_AttachPartition, AT_DetachPartition, AT_SetIdentity, attnum, CreateStmtContext::blist, PartitionCmd::bound, castNode, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, ColumnDef::colname, CreateStmtContext::columns, CONSTR_FOREIGN, ColumnDef::constraints, ColumnDef::cooked_default, copyObject, AlterTableCmd::def, DefElem::defname, elog, ereport, errcode(), errmsg(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, CreateStmtContext::extstats, 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, IndexStmt::indexOid, CreateStmtContext::inhRelations, InvalidAttrNumber, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, lfirst_node, list_concat(), 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, CreateStmtContext::pkey, CreateStmtContext::pstate, ColumnDef::raw_default, RelationData::rd_rel, CreateStmtContext::rel, CreateStmtContext::relation, AlterTableStmt::relation, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, AlterSeqStmt::sequence, CreateStmtContext::stmtType, AlterTableCmd::subtype, transformCheckConstraints(), transformColumnDefinition(), transformExpr(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformIndexStmt(), transformPartitionCmd(), transformTableConstraint(), TupleDescAttr, ColumnDef::typeName, and typenameTypeId().

Referenced by ATParseTransformCmd(), and ATPostAlterTypeParse().

3153 {
3154  Relation rel;
3155  TupleDesc tupdesc;
3156  ParseState *pstate;
3157  CreateStmtContext cxt;
3158  List *save_alist;
3159  ListCell *lcmd,
3160  *l;
3161  List *newcmds = NIL;
3162  bool skipValidation = true;
3163  AlterTableCmd *newcmd;
3164  ParseNamespaceItem *nsitem;
3165 
3166  /*
3167  * We must not scribble on the passed-in AlterTableStmt, so copy it. (This
3168  * is overkill, but easy.)
3169  */
3170  stmt = copyObject(stmt);
3171 
3172  /* Caller is responsible for locking the relation */
3173  rel = relation_open(relid, NoLock);
3174  tupdesc = RelationGetDescr(rel);
3175 
3176  /* Set up pstate */
3177  pstate = make_parsestate(NULL);
3178  pstate->p_sourcetext = queryString;
3179  nsitem = addRangeTableEntryForRelation(pstate,
3180  rel,
3182  NULL,
3183  false,
3184  true);
3185  addNSItemToQuery(pstate, nsitem, false, true, true);
3186 
3187  /* Set up CreateStmtContext */
3188  cxt.pstate = pstate;
3189  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3190  {
3191  cxt.stmtType = "ALTER FOREIGN TABLE";
3192  cxt.isforeign = true;
3193  }
3194  else
3195  {
3196  cxt.stmtType = "ALTER TABLE";
3197  cxt.isforeign = false;
3198  }
3199  cxt.relation = stmt->relation;
3200  cxt.rel = rel;
3201  cxt.inhRelations = NIL;
3202  cxt.isalter = true;
3203  cxt.columns = NIL;
3204  cxt.ckconstraints = NIL;
3205  cxt.fkconstraints = NIL;
3206  cxt.ixconstraints = NIL;
3207  cxt.extstats = NIL;
3208  cxt.blist = NIL;
3209  cxt.alist = NIL;
3210  cxt.pkey = NULL;
3211  cxt.ispartitioned = (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
3212  cxt.partbound = NULL;
3213  cxt.ofType = false;
3214 
3215  /*
3216  * Transform ALTER subcommands that need it (most don't). These largely
3217  * re-use code from CREATE TABLE.
3218  */
3219  foreach(lcmd, stmt->cmds)
3220  {
3221  AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3222 
3223  switch (cmd->subtype)
3224  {
3225  case AT_AddColumn:
3226  case AT_AddColumnRecurse:
3227  {
3228  ColumnDef *def = castNode(ColumnDef, cmd->def);
3229 
3230  transformColumnDefinition(&cxt, def);
3231 
3232  /*
3233  * If the column has a non-null default, we can't skip
3234  * validation of foreign keys.
3235  */
3236  if (def->raw_default != NULL)
3237  skipValidation = false;
3238 
3239  /*
3240  * All constraints are processed in other ways. Remove the
3241  * original list
3242  */
3243  def->constraints = NIL;
3244 
3245  newcmds = lappend(newcmds, cmd);
3246  break;
3247  }
3248 
3249  case AT_AddConstraint:
3251 
3252  /*
3253  * The original AddConstraint cmd node doesn't go to newcmds
3254  */
3255  if (IsA(cmd->def, Constraint))
3256  {
3257  transformTableConstraint(&cxt, (Constraint *) cmd->def);
3258  if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN)
3259  skipValidation = false;
3260  }
3261  else
3262  elog(ERROR, "unrecognized node type: %d",
3263  (int) nodeTag(cmd->def));
3264  break;
3265 
3266  case AT_AlterColumnType:
3267  {
3268  ColumnDef *def = castNode(ColumnDef, cmd->def);
3270 
3271  /*
3272  * For ALTER COLUMN TYPE, transform the USING clause if
3273  * one was specified.
3274  */
3275  if (def->raw_default)
3276  {
3277  def->cooked_default =
3278  transformExpr(pstate, def->raw_default,
3280  }
3281 
3282  /*
3283  * For identity column, create ALTER SEQUENCE command to
3284  * change the data type of the sequence.
3285  */
3286  attnum = get_attnum(relid, cmd->name);
3287  if (attnum == InvalidAttrNumber)
3288  ereport(ERROR,
3289  (errcode(ERRCODE_UNDEFINED_COLUMN),
3290  errmsg("column \"%s\" of relation \"%s\" does not exist",
3291  cmd->name, RelationGetRelationName(rel))));
3292 
3293  if (TupleDescAttr(tupdesc, attnum - 1)->attidentity)
3294  {
3295  Oid seq_relid = getIdentitySequence(relid, attnum, false);
3296  Oid typeOid = typenameTypeId(pstate, def->typeName);
3297  AlterSeqStmt *altseqstmt = makeNode(AlterSeqStmt);
3298 
3299  altseqstmt->sequence = makeRangeVar(get_namespace_name(get_rel_namespace(seq_relid)),
3300  get_rel_name(seq_relid),
3301  -1);
3302  altseqstmt->options = list_make1(makeDefElem("as", (Node *) makeTypeNameFromOid(typeOid, -1), -1));
3303  altseqstmt->for_identity = true;
3304  cxt.blist = lappend(cxt.blist, altseqstmt);
3305  }
3306 
3307  newcmds = lappend(newcmds, cmd);
3308  break;
3309  }
3310 
3311  case AT_AddIdentity:
3312  {
3313  Constraint *def = castNode(Constraint, cmd->def);
3314  ColumnDef *newdef = makeNode(ColumnDef);
3316 
3317  newdef->colname = cmd->name;
3318  newdef->identity = def->generated_when;
3319  cmd->def = (Node *) newdef;
3320 
3321  attnum = get_attnum(relid, cmd->name);
3322  if (attnum == InvalidAttrNumber)
3323  ereport(ERROR,
3324  (errcode(ERRCODE_UNDEFINED_COLUMN),
3325  errmsg("column \"%s\" of relation \"%s\" does not exist",
3326  cmd->name, RelationGetRelationName(rel))));
3327 
3328  generateSerialExtraStmts(&cxt, newdef,
3329  get_atttype(relid, attnum),
3330  def->options, true, true,
3331  NULL, NULL);
3332 
3333  newcmds = lappend(newcmds, cmd);
3334  break;
3335  }
3336 
3337  case AT_SetIdentity:
3338  {
3339  /*
3340  * Create an ALTER SEQUENCE statement for the internal
3341  * sequence of the identity column.
3342  */
3343  ListCell *lc;
3344  List *newseqopts = NIL;
3345  List *newdef = NIL;
3347  Oid seq_relid;
3348 
3349  /*
3350  * Split options into those handled by ALTER SEQUENCE and
3351  * those for ALTER TABLE proper.
3352  */
3353  foreach(lc, castNode(List, cmd->def))
3354  {
3355  DefElem *def = lfirst_node(DefElem, lc);
3356 
3357  if (strcmp(def->defname, "generated") == 0)
3358  newdef = lappend(newdef, def);
3359  else
3360  newseqopts = lappend(newseqopts, def);
3361  }
3362 
3363  attnum = get_attnum(relid, cmd->name);
3364  if (attnum == InvalidAttrNumber)
3365  ereport(ERROR,
3366  (errcode(ERRCODE_UNDEFINED_COLUMN),
3367  errmsg("column \"%s\" of relation \"%s\" does not exist",
3368  cmd->name, RelationGetRelationName(rel))));
3369 
3370  seq_relid = getIdentitySequence(relid, attnum, true);
3371 
3372  if (seq_relid)
3373  {
3374  AlterSeqStmt *seqstmt;
3375 
3376  seqstmt = makeNode(AlterSeqStmt);
3378  get_rel_name(seq_relid), -1);
3379  seqstmt->options = newseqopts;
3380  seqstmt->for_identity = true;
3381  seqstmt->missing_ok = false;
3382 
3383  cxt.blist = lappend(cxt.blist, seqstmt);
3384  }
3385 
3386  /*
3387  * If column was not an identity column, we just let the
3388  * ALTER TABLE command error out later. (There are cases
3389  * this fails to cover, but we'll need to restructure
3390  * where creation of the sequence dependency linkage
3391  * happens before we can fix it.)
3392  */
3393 
3394  cmd->def = (Node *) newdef;
3395  newcmds = lappend(newcmds, cmd);
3396  break;
3397  }
3398 
3399  case AT_AttachPartition:
3400  case AT_DetachPartition:
3401  {
3402  PartitionCmd *partcmd = (PartitionCmd *) cmd->def;
3403 
3404  transformPartitionCmd(&cxt, partcmd);
3405  /* assign transformed value of the partition bound */
3406  partcmd->bound = cxt.partbound;
3407  }
3408 
3409  newcmds = lappend(newcmds, cmd);
3410  break;
3411 
3412  default:
3413 
3414  /*
3415  * Currently, we shouldn't actually get here for subcommand
3416  * types that don't require transformation; but if we do, just
3417  * emit them unchanged.
3418  */
3419  newcmds = lappend(newcmds, cmd);
3420  break;
3421  }
3422  }
3423 
3424  /*
3425  * Transfer anything we already have in cxt.alist into save_alist, to keep
3426  * it separate from the output of transformIndexConstraints.
3427  */
3428  save_alist = cxt.alist;
3429  cxt.alist = NIL;
3430 
3431  /* Postprocess constraints */
3433  transformFKConstraints(&cxt, skipValidation, true);
3434  transformCheckConstraints(&cxt, false);
3435 
3436  /*
3437  * Push any index-creation commands into the ALTER, so that they can be
3438  * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that
3439  * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint
3440  * subcommand has already been through transformIndexStmt.
3441  */
3442  foreach(l, cxt.alist)
3443  {
3444  Node *istmt = (Node *) lfirst(l);
3445 
3446  /*
3447  * We assume here that cxt.alist contains only IndexStmts and possibly
3448  * ALTER TABLE SET NOT NULL statements generated from primary key
3449  * constraints. We absorb the subcommands of the latter directly.
3450  */
3451  if (IsA(istmt, IndexStmt))
3452  {
3453  IndexStmt *idxstmt = (IndexStmt *) istmt;
3454 
3455  idxstmt = transformIndexStmt(relid, idxstmt, queryString);
3456  newcmd = makeNode(AlterTableCmd);
3458  newcmd->def = (Node *) idxstmt;
3459  newcmds = lappend(newcmds, newcmd);
3460  }
3461  else if (IsA(istmt, AlterTableStmt))
3462  {
3463  AlterTableStmt *alterstmt = (AlterTableStmt *) istmt;
3464 
3465  newcmds = list_concat(newcmds, alterstmt->cmds);
3466  }
3467  else
3468  elog(ERROR, "unexpected stmt type %d", (int) nodeTag(istmt));
3469  }
3470  cxt.alist = NIL;
3471 
3472  /* Append any CHECK or FK constraints to the commands list */
3473  foreach(l, cxt.ckconstraints)
3474  {
3475  newcmd = makeNode(AlterTableCmd);
3476  newcmd->subtype = AT_AddConstraint;
3477  newcmd->def = (Node *) lfirst(l);
3478  newcmds = lappend(newcmds, newcmd);
3479  }
3480  foreach(l, cxt.fkconstraints)
3481  {
3482  newcmd = makeNode(AlterTableCmd);
3483  newcmd->subtype = AT_AddConstraint;
3484  newcmd->def = (Node *) lfirst(l);
3485  newcmds = lappend(newcmds, newcmd);
3486  }
3487 
3488  /* Append extended statistic objects */
3490 
3491  /* Close rel */
3492  relation_close(rel, NoLock);
3493 
3494  /*
3495  * Output results.
3496  */
3497  stmt->cmds = newcmds;
3498 
3499  *beforeStmts = cxt.blist;
3500  *afterStmts = list_concat(cxt.alist, save_alist);
3501 
3502  return stmt;
3503 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
char generated_when
Definition: parsenodes.h:2166
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
#define RelationGetDescr(relation)
Definition: rel.h:482
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
char identity
Definition: parsenodes.h:657
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:663
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:528
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
AlterTableType subtype
Definition: parsenodes.h:1865
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:914
#define OidIsValid(objectId)
Definition: c.h:652
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:546
List * options
Definition: parsenodes.h:2558
List * options
Definition: parsenodes.h:2178
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
#define list_make1(x1)
Definition: pg_list.h:206
ParseState * pstate
Definition: parse_utilcmd.c:78
Node * cooked_default
Definition: parsenodes.h:656
Oid indexOid
Definition: parsenodes.h:2788
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:94
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define lfirst_node(type, lc)
Definition: pg_list.h:172
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
#define NoLock
Definition: lockdefs.h:34
AttrNumber get_attnum(Oid relid, const char *attname)
Definition: lsyscache.c:856
#define RelationGetRelationName(relation)
Definition: rel.h:490
const char * p_sourcetext
Definition: parse_node.h:179
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:911
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
Node * raw_default
Definition: parsenodes.h:655
List * lappend(List *list, void *datum)
Definition: list.c:321
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
RangeVar * sequence
Definition: parsenodes.h:2557
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:576
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define lfirst(lc)
Definition: pg_list.h:169
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
PartitionBoundSpec * bound
Definition: parsenodes.h:862
TypeName * typeName
Definition: parsenodes.h:649
static void transformPartitionCmd(CreateStmtContext *cxt, PartitionCmd *cmd)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:533
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
int errmsg(const char *fmt,...)
Definition: elog.c:821
RangeVar * relation
Definition: parsenodes.h:1778
#define elog(elevel,...)
Definition: elog.h:214
bool for_identity
Definition: parsenodes.h:2559
char * defname
Definition: parsenodes.h:733
char * colname
Definition: parsenodes.h:648
#define copyObject(obj)
Definition: nodes.h:644
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
IndexStmt * transformIndexStmt(Oid relid, IndexStmt *stmt, const char *queryString)
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
int16 AttrNumber
Definition: attnum.h:21
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291

◆ transformCheckConstraints()

static void transformCheckConstraints ( CreateStmtContext cxt,
bool  skipValidation 
)
static

Definition at line 2632 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2633 {
2634  ListCell *ckclist;
2635 
2636  if (cxt->ckconstraints == NIL)
2637  return;
2638 
2639  /*
2640  * If creating a new table (but not a foreign table), we can safely skip
2641  * validation of check constraints, and nonetheless mark them valid. (This
2642  * will override any user-supplied NOT VALID flag.)
2643  */
2644  if (skipValidation)
2645  {
2646  foreach(ckclist, cxt->ckconstraints)
2647  {
2648  Constraint *constraint = (Constraint *) lfirst(ckclist);
2649 
2650  constraint->skip_validation = true;
2651  constraint->initially_valid = true;
2652  }
2653  }
2654 }
#define NIL
Definition: pg_list.h:65
bool initially_valid
Definition: parsenodes.h:2200
#define lfirst(lc)
Definition: pg_list.h:169
bool skip_validation
Definition: parsenodes.h:2199

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 512 of file parse_utilcmd.c.

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, 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, OBJECT_FOREIGN_TABLE, AlterTableStmt::objtype, CreateStmtContext::ofType, Constraint::options, parser_errposition(), CreateStmtContext::partbound, TypeName::pct_type, CreateStmtContext::pstate, quote_qualified_identifier(), ColumnDef::raw_default, Constraint::raw_expr, CreateStmtContext::relation, AlterTableStmt::relation, ReleaseSysCache(), RangeVar::relname, Value::ValUnion::str, strVal, AlterTableCmd::subtype, SystemFuncName(), SystemTypeName(), T_String, transformColumnType(), transformConstraintAttrs(), Value::type, TypeCast::typeName, ColumnDef::typeName, typenameType(), TypeName::typeOid, typname, Value::val, and A_Const::val.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

513 {
514  bool is_serial;
515  bool saw_nullable;
516  bool saw_default;
517  bool saw_identity;
518  bool saw_generated;
519  ListCell *clist;
520 
521  cxt->columns = lappend(cxt->columns, column);
522 
523  /* Check for SERIAL pseudo-types */
524  is_serial = false;
525  if (column->typeName
526  && list_length(column->typeName->names) == 1
527  && !column->typeName->pct_type)
528  {
529  char *typname = strVal(linitial(column->typeName->names));
530 
531  if (strcmp(typname, "smallserial") == 0 ||
532  strcmp(typname, "serial2") == 0)
533  {
534  is_serial = true;
535  column->typeName->names = NIL;
536  column->typeName->typeOid = INT2OID;
537  }
538  else if (strcmp(typname, "serial") == 0 ||
539  strcmp(typname, "serial4") == 0)
540  {
541  is_serial = true;
542  column->typeName->names = NIL;
543  column->typeName->typeOid = INT4OID;
544  }
545  else if (strcmp(typname, "bigserial") == 0 ||
546  strcmp(typname, "serial8") == 0)
547  {
548  is_serial = true;
549  column->typeName->names = NIL;
550  column->typeName->typeOid = INT8OID;
551  }
552 
553  /*
554  * We have to reject "serial[]" explicitly, because once we've set
555  * typeid, LookupTypeName won't notice arrayBounds. We don't need any
556  * special coding for serial(typmod) though.
557  */
558  if (is_serial && column->typeName->arrayBounds != NIL)
559  ereport(ERROR,
560  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
561  errmsg("array of serial is not implemented"),
563  column->typeName->location)));
564  }
565 
566  /* Do necessary work on the column type declaration */
567  if (column->typeName)
568  transformColumnType(cxt, column);
569 
570  /* Special actions for SERIAL pseudo-types */
571  if (is_serial)
572  {
573  char *snamespace;
574  char *sname;
575  char *qstring;
576  A_Const *snamenode;
577  TypeCast *castnode;
578  FuncCall *funccallnode;
579  Constraint *constraint;
580 
581  generateSerialExtraStmts(cxt, column,
582  column->typeName->typeOid, NIL,
583  false, false,
584  &snamespace, &sname);
585 
586  /*
587  * Create appropriate constraints for SERIAL. We do this in full,
588  * rather than shortcutting, so that we will detect any conflicting
589  * constraints the user wrote (like a different DEFAULT).
590  *
591  * Create an expression tree representing the function call
592  * nextval('sequencename'). We cannot reduce the raw tree to cooked
593  * form until after the sequence is created, but there's no need to do
594  * so.
595  */
596  qstring = quote_qualified_identifier(snamespace, sname);
597  snamenode = makeNode(A_Const);
598  snamenode->val.type = T_String;
599  snamenode->val.val.str = qstring;
600  snamenode->location = -1;
601  castnode = makeNode(TypeCast);
602  castnode->typeName = SystemTypeName("regclass");
603  castnode->arg = (Node *) snamenode;
604  castnode->location = -1;
605  funccallnode = makeFuncCall(SystemFuncName("nextval"),
606  list_make1(castnode),
607  -1);
608  constraint = makeNode(Constraint);
609  constraint->contype = CONSTR_DEFAULT;
610  constraint->location = -1;
611  constraint->raw_expr = (Node *) funccallnode;
612  constraint->cooked_expr = NULL;
613  column->constraints = lappend(column->constraints, constraint);
614 
615  constraint = makeNode(Constraint);
616  constraint->contype = CONSTR_NOTNULL;
617  constraint->location = -1;
618  column->constraints = lappend(column->constraints, constraint);
619  }
620 
621  /* Process column constraints, if any... */
623 
624  saw_nullable = false;
625  saw_default = false;
626  saw_identity = false;
627  saw_generated = false;
628 
629  foreach(clist, column->constraints)
630  {
631  Constraint *constraint = lfirst_node(Constraint, clist);
632 
633  switch (constraint->contype)
634  {
635  case CONSTR_NULL:
636  if (saw_nullable && column->is_not_null)
637  ereport(ERROR,
638  (errcode(ERRCODE_SYNTAX_ERROR),
639  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
640  column->colname, cxt->relation->relname),
642  constraint->location)));
643  column->is_not_null = false;
644  saw_nullable = true;
645  break;
646 
647  case CONSTR_NOTNULL:
648  if (saw_nullable && !column->is_not_null)
649  ereport(ERROR,
650  (errcode(ERRCODE_SYNTAX_ERROR),
651  errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
652  column->colname, cxt->relation->relname),
654  constraint->location)));
655  column->is_not_null = true;
656  saw_nullable = true;
657  break;
658 
659  case CONSTR_DEFAULT:
660  if (saw_default)
661  ereport(ERROR,
662  (errcode(ERRCODE_SYNTAX_ERROR),
663  errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
664  column->colname, cxt->relation->relname),
666  constraint->location)));
667  column->raw_default = constraint->raw_expr;
668  Assert(constraint->cooked_expr == NULL);
669  saw_default = true;
670  break;
671 
672  case CONSTR_IDENTITY:
673  {
674  Type ctype;
675  Oid typeOid;
676 
677  if (cxt->ofType)
678  ereport(ERROR,
679  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
680  errmsg("identity columns are not supported on typed tables")));
681  if (cxt->partbound)
682  ereport(ERROR,
683  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
684  errmsg("identity columns are not supported on partitions")));
685 
686  ctype = typenameType(cxt->pstate, column->typeName, NULL);
687  typeOid = ((Form_pg_type) GETSTRUCT(ctype))->oid;
688  ReleaseSysCache(ctype);
689 
690  if (saw_identity)
691  ereport(ERROR,
692  (errcode(ERRCODE_SYNTAX_ERROR),
693  errmsg("multiple identity specifications for column \"%s\" of table \"%s\"",
694  column->colname, cxt->relation->relname),
696  constraint->location)));
697 
698  generateSerialExtraStmts(cxt, column,
699  typeOid, constraint->options,
700  true, false,
701  NULL, NULL);
702 
703  column->identity = constraint->generated_when;
704  saw_identity = true;
705  column->is_not_null = true;
706  break;
707  }
708 
709  case CONSTR_GENERATED:
710  if (cxt->ofType)
711  ereport(ERROR,
712  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
713  errmsg("generated columns are not supported on typed tables")));
714  if (cxt->partbound)
715  ereport(ERROR,
716  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
717  errmsg("generated columns are not supported on partitions")));
718 
719  if (saw_generated)
720  ereport(ERROR,
721  (errcode(ERRCODE_SYNTAX_ERROR),
722  errmsg("multiple generation clauses specified for column \"%s\" of table \"%s\"",
723  column->colname, cxt->relation->relname),
725  constraint->location)));
726  column->generated = ATTRIBUTE_GENERATED_STORED;
727  column->raw_default = constraint->raw_expr;
728  Assert(constraint->cooked_expr == NULL);
729  saw_generated = true;
730  break;
731 
732  case CONSTR_CHECK:
733  cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
734  break;
735 
736  case CONSTR_PRIMARY:
737  if (cxt->isforeign)
738  ereport(ERROR,
739  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
740  errmsg("primary key constraints are not supported on foreign tables"),
742  constraint->location)));
743  /* FALL THRU */
744 
745  case CONSTR_UNIQUE:
746  if (cxt->isforeign)
747  ereport(ERROR,
748  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
749  errmsg("unique constraints are not supported on foreign tables"),
751  constraint->location)));
752  if (constraint->keys == NIL)
753  constraint->keys = list_make1(makeString(column->colname));
754  cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
755  break;
756 
757  case CONSTR_EXCLUSION:
758  /* grammar does not allow EXCLUDE as a column constraint */
759  elog(ERROR, "column exclusion constraints are not supported");
760  break;
761 
762  case CONSTR_FOREIGN:
763  if (cxt->isforeign)
764  ereport(ERROR,
765  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
766  errmsg("foreign key constraints are not supported on foreign tables"),
768  constraint->location)));
769 
770  /*
771  * Fill in the current attribute's name and throw it into the
772  * list of FK constraints to be processed later.
773  */
774  constraint->fk_attrs = list_make1(makeString(column->colname));
775  cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
776  break;
777 
782  /* transformConstraintAttrs took care of these */
783  break;
784 
785  default:
786  elog(ERROR, "unrecognized constraint type: %d",
787  constraint->contype);
788  break;
789  }
790 
791  if (saw_default && saw_identity)
792  ereport(ERROR,
793  (errcode(ERRCODE_SYNTAX_ERROR),
794  errmsg("both default and identity specified for column \"%s\" of table \"%s\"",
795  column->colname, cxt->relation->relname),
797  constraint->location)));
798 
799  if (saw_default && saw_generated)
800  ereport(ERROR,
801  (errcode(ERRCODE_SYNTAX_ERROR),
802  errmsg("both default and generation expression specified for column \"%s\" of table \"%s\"",
803  column->colname, cxt->relation->relname),
805  constraint->location)));
806 
807  if (saw_identity && saw_generated)
808  ereport(ERROR,
809  (errcode(ERRCODE_SYNTAX_ERROR),
810  errmsg("both identity and generation expression specified for column \"%s\" of table \"%s\"",
811  column->colname, cxt->relation->relname),
813  constraint->location)));
814  }
815 
816  /*
817  * If needed, generate ALTER FOREIGN TABLE ALTER COLUMN statement to add
818  * per-column foreign data wrapper options to this column after creation.
819  */
820  if (column->fdwoptions != NIL)
821  {
822  AlterTableStmt *stmt;
823  AlterTableCmd *cmd;
824 
825  cmd = makeNode(AlterTableCmd);
827  cmd->name = column->colname;
828  cmd->def = (Node *) column->fdwoptions;
829  cmd->behavior = DROP_RESTRICT;
830  cmd->missing_ok = false;
831 
832  stmt = makeNode(AlterTableStmt);
833  stmt->relation = cxt->relation;
834  stmt->cmds = NIL;
836  stmt->cmds = lappend(stmt->cmds, cmd);
837 
838  cxt->alist = lappend(cxt->alist, stmt);
839  }
840 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
List * SystemFuncName(char *name)
Oid typeOid
Definition: parsenodes.h:211
List * keys
Definition: parsenodes.h:2169
char generated_when
Definition: parsenodes.h:2166
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
List * names
Definition: parsenodes.h:210
static void generateSerialExtraStmts(CreateStmtContext *cxt, ColumnDef *column, Oid seqtypid, List *seqoptions, bool for_identity, bool col_exists, char **snamespace_p, char **sname_p)
char identity
Definition: parsenodes.h:657
List * constraints
Definition: parsenodes.h:663
Node * raw_expr
Definition: parsenodes.h:2164
Definition: nodes.h:528
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
AlterTableType subtype
Definition: parsenodes.h:1865
char generated
Definition: parsenodes.h:660
bool is_not_null
Definition: parsenodes.h:652
unsigned int Oid
Definition: postgres_ext.h:31
List * options
Definition: parsenodes.h:2178
int location
Definition: parsenodes.h:301
#define list_make1(x1)
Definition: pg_list.h:206
ParseState * pstate
Definition: parse_utilcmd.c:78
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:43
static void transformConstraintAttrs(CreateStmtContext *cxt, List *constraintList)
#define lfirst_node(type, lc)
Definition: pg_list.h:172
union Value::ValUnion val
List * fdwoptions
Definition: parsenodes.h:664
static void transformColumnType(CreateStmtContext *cxt, ColumnDef *column)
ObjectType objtype
Definition: parsenodes.h:1780
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
Node * raw_default
Definition: parsenodes.h:655
List * lappend(List *list, void *datum)
Definition: list.c:321
NameData typname
Definition: pg_type.h:41
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10793
FuncCall * makeFuncCall(List *name, List *args, int location)
Definition: makefuncs.c:585
TypeName * SystemTypeName(char *name)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
TypeName * typeName
Definition: parsenodes.h:300
#define ereport(elevel,...)
Definition: elog.h:144
#define makeNode(_type_)
Definition: nodes.h:576
#define Assert(condition)
Definition: c.h:746
int location
Definition: parsenodes.h:290
int location
Definition: parsenodes.h:217
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
TypeName * typeName
Definition: parsenodes.h:649
List * arrayBounds
Definition: parsenodes.h:216
int errmsg(const char *fmt,...)
Definition: elog.c:821
RangeVar * relation
Definition: parsenodes.h:1778
char * str
Definition: value.h:48
#define elog(elevel,...)
Definition: elog.h:214
ConstrType contype
Definition: parsenodes.h:2154
DropBehavior behavior
Definition: parsenodes.h:1873
char * colname
Definition: parsenodes.h:648
char * cooked_expr
Definition: parsenodes.h:2165
Value val
Definition: parsenodes.h:289
List * fk_attrs
Definition: parsenodes.h:2189
NodeTag type
Definition: value.h:44
bool pct_type
Definition: parsenodes.h:213
Node * arg
Definition: parsenodes.h:299

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3631 of file parse_utilcmd.c.

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().

3632 {
3633  /*
3634  * All we really need to do here is verify that the type is valid,
3635  * including any collation spec that might be present.
3636  */
3637  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3638 
3639  if (column->collClause)
3640  {
3641  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3642 
3643  LookupCollation(cxt->pstate,
3644  column->collClause->collname,
3645  column->collClause->location);
3646  /* Complain if COLLATE is applied to an uncollatable type */
3647  if (!OidIsValid(typtup->typcollation))
3648  ereport(ERROR,
3649  (errcode(ERRCODE_DATATYPE_MISMATCH),
3650  errmsg("collations are not supported by type %s",
3651  format_type_be(typtup->oid)),
3653  column->collClause->location)));
3654  }
3655 
3656  ReleaseSysCache(ctype);
3657 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define OidIsValid(objectId)
Definition: c.h:652
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:513
#define ereport(elevel,...)
Definition: elog.h:144
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
TypeName * typeName
Definition: parsenodes.h:649
CollateClause * collClause
Definition: parsenodes.h:661
List * collname
Definition: parsenodes.h:311
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3516 of file parse_utilcmd.c.

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().

3517 {
3518  Constraint *lastprimarycon = NULL;
3519  bool saw_deferrability = false;
3520  bool saw_initially = false;
3521  ListCell *clist;
3522 
3523 #define SUPPORTS_ATTRS(node) \
3524  ((node) != NULL && \
3525  ((node)->contype == CONSTR_PRIMARY || \
3526  (node)->contype == CONSTR_UNIQUE || \
3527  (node)->contype == CONSTR_EXCLUSION || \
3528  (node)->contype == CONSTR_FOREIGN))
3529 
3530  foreach(clist, constraintList)
3531  {
3532  Constraint *con = (Constraint *) lfirst(clist);
3533 
3534  if (!IsA(con, Constraint))
3535  elog(ERROR, "unrecognized node type: %d",
3536  (int) nodeTag(con));
3537  switch (con->contype)
3538  {
3540  if (!SUPPORTS_ATTRS(lastprimarycon))
3541  ereport(ERROR,
3542  (errcode(ERRCODE_SYNTAX_ERROR),
3543  errmsg("misplaced DEFERRABLE clause"),
3544  parser_errposition(cxt->pstate, con->location)));
3545  if (saw_deferrability)
3546  ereport(ERROR,
3547  (errcode(ERRCODE_SYNTAX_ERROR),
3548  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3549  parser_errposition(cxt->pstate, con->location)));
3550  saw_deferrability = true;
3551  lastprimarycon->deferrable = true;
3552  break;
3553 
3555  if (!SUPPORTS_ATTRS(lastprimarycon))
3556  ereport(ERROR,
3557  (errcode(ERRCODE_SYNTAX_ERROR),
3558  errmsg("misplaced NOT DEFERRABLE clause"),
3559  parser_errposition(cxt->pstate, con->location)));
3560  if (saw_deferrability)
3561  ereport(ERROR,
3562  (errcode(ERRCODE_SYNTAX_ERROR),
3563  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3564  parser_errposition(cxt->pstate, con->location)));
3565  saw_deferrability = true;
3566  lastprimarycon->deferrable = false;
3567  if (saw_initially &&
3568  lastprimarycon->initdeferred)
3569  ereport(ERROR,
3570  (errcode(ERRCODE_SYNTAX_ERROR),
3571  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3572  parser_errposition(cxt->pstate, con->location)));
3573  break;
3574 
3575  case CONSTR_ATTR_DEFERRED:
3576  if (!SUPPORTS_ATTRS(lastprimarycon))
3577  ereport(ERROR,
3578  (errcode(ERRCODE_SYNTAX_ERROR),
3579  errmsg("misplaced INITIALLY DEFERRED clause"),
3580  parser_errposition(cxt->pstate, con->location)));
3581  if (saw_initially)
3582  ereport(ERROR,
3583  (errcode(ERRCODE_SYNTAX_ERROR),
3584  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3585  parser_errposition(cxt->pstate, con->location)));
3586  saw_initially = true;
3587  lastprimarycon->initdeferred = true;
3588 
3589  /*
3590  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3591  */
3592  if (!saw_deferrability)
3593  lastprimarycon->deferrable = true;
3594  else if (!lastprimarycon->deferrable)
3595  ereport(ERROR,
3596  (errcode(ERRCODE_SYNTAX_ERROR),
3597  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3598  parser_errposition(cxt->pstate, con->location)));
3599  break;
3600 
3601  case CONSTR_ATTR_IMMEDIATE:
3602  if (!SUPPORTS_ATTRS(lastprimarycon))
3603  ereport(ERROR,
3604  (errcode(ERRCODE_SYNTAX_ERROR),
3605  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3606  parser_errposition(cxt->pstate, con->location)));
3607  if (saw_initially)
3608  ereport(ERROR,
3609  (errcode(ERRCODE_SYNTAX_ERROR),
3610  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3611  parser_errposition(cxt->pstate, con->location)));
3612  saw_initially = true;
3613  lastprimarycon->initdeferred = false;
3614  break;
3615 
3616  default:
3617  /* Otherwise it's not an attribute */
3618  lastprimarycon = con;
3619  /* reset flags for new primary node */
3620  saw_deferrability = false;
3621  saw_initially = false;
3622  break;
3623  }
3624  }
3625 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2159
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:43
bool deferrable
Definition: parsenodes.h:2158
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define nodeTag(nodeptr)
Definition: nodes.h:533
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define SUPPORTS_ATTRS(node)
#define elog(elevel,...)
Definition: elog.h:214
ConstrType contype
Definition: parsenodes.h:2154

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3684 of file parse_utilcmd.c.

References CreateSchemaStmtContext::authrole, CreateSchemaStmt::authrole, element(), elog, ERROR, CreateSchemaStmtContext::grants, CreateSchemaStmtContext::indexes, lappend(), lfirst, list_concat(), NIL, nodeTag, CreateStmt::relation, CreateTrigStmt::relation, IndexStmt::relation, CreateSchemaStmt::schemaElts, RangeVar::schemaname, CreateSchemaStmtContext::schemaname, CreateSchemaStmt::schemaname, CreateSeqStmt::sequence, CreateSchemaStmtContext::sequences, setSchemaName(), CreateSchemaStmtContext::stmtType, T_CreateSeqStmt, T_CreateStmt, T_CreateTrigStmt, T_GrantStmt, T_IndexStmt, T_ViewStmt, CreateSchemaStmtContext::tables, CreateSchemaStmtContext::triggers, ViewStmt::view, and CreateSchemaStmtContext::views.

Referenced by CreateSchemaCommand().

3685 {
3687  List *result;
3688  ListCell *elements;
3689 
3690  cxt.stmtType = "CREATE SCHEMA";
3691  cxt.schemaname = stmt->schemaname;
3692  cxt.authrole = (RoleSpec *) stmt->authrole;
3693  cxt.sequences = NIL;
3694  cxt.tables = NIL;
3695  cxt.views = NIL;
3696  cxt.indexes = NIL;
3697  cxt.triggers = NIL;
3698  cxt.grants = NIL;
3699 
3700  /*
3701  * Run through each schema element in the schema element list. Separate
3702  * statements by type, and do preliminary analysis.
3703  */
3704  foreach(elements, stmt->schemaElts)
3705  {
3706  Node *element = lfirst(elements);
3707 
3708  switch (nodeTag(element))
3709  {
3710  case T_CreateSeqStmt:
3711  {
3712  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3713 
3715  cxt.sequences = lappend(cxt.sequences, element);
3716  }
3717  break;
3718 
3719  case T_CreateStmt:
3720  {
3721  CreateStmt *elp = (CreateStmt *) element;
3722 
3724 
3725  /*
3726  * XXX todo: deal with constraints
3727  */
3728  cxt.tables = lappend(cxt.tables, element);
3729  }
3730  break;
3731 
3732  case T_ViewStmt:
3733  {
3734  ViewStmt *elp = (ViewStmt *) element;
3735 
3736  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3737 
3738  /*
3739  * XXX todo: deal with references between views
3740  */
3741  cxt.views = lappend(cxt.views, element);
3742  }
3743  break;
3744 
3745  case T_IndexStmt:
3746  {
3747  IndexStmt *elp = (IndexStmt *) element;
3748 
3750  cxt.indexes = lappend(cxt.indexes, element);
3751  }
3752  break;
3753 
3754  case T_CreateTrigStmt:
3755  {
3756  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3757 
3759  cxt.triggers = lappend(cxt.triggers, element);
3760  }
3761  break;
3762 
3763  case T_GrantStmt:
3764  cxt.grants = lappend(cxt.grants, element);
3765  break;
3766 
3767  default:
3768  elog(ERROR, "unrecognized node type: %d",
3769  (int) nodeTag(element));
3770  }
3771  }
3772 
3773  result = NIL;
3774  result = list_concat(result, cxt.sequences);
3775  result = list_concat(result, cxt.tables);
3776  result = list_concat(result, cxt.views);
3777  result = list_concat(result, cxt.indexes);
3778  result = list_concat(result, cxt.triggers);
3779  result = list_concat(result, cxt.grants);
3780 
3781  return result;
3782 }
RangeVar * relation
Definition: parsenodes.h:2074
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:528
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
RangeVar * view
Definition: parsenodes.h:3130
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2778
RoleSpec * authrole
Definition: parsenodes.h:1760
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:321
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2547
#define lfirst(lc)
Definition: pg_list.h:169
static void setSchemaName(char *context_schema, char **stmt_schema_name)
#define nodeTag(nodeptr)
Definition: nodes.h:533
#define elog(elevel,...)
Definition: elog.h:214
RangeVar * relation
Definition: parsenodes.h:2433
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 167 of file parse_utilcmd.c.

References CreateStmtContext::alist, Assert, CreateStmtContext::blist, cancel_parser_errposition_callback(), CreateStmtContext::ckconstraints, CreateStmtContext::columns, CreateStmt::constraints, copyObject, element(), elog, ereport, errcode(), errmsg(), ERROR, CreateStmtContext::extstats, CreateStmtContext::fkconstraints, get_namespace_name(), CreateStmt::if_not_exists, CreateStmtContext::inhRelations, CreateStmt::inhRelations, IsA, CreateStmtContext::isalter, CreateStmtContext::isforeign, CreateStmtContext::ispartitioned, CreateStmtContext::ixconstraints, lappend(), lfirst, list_concat(), RangeVar::location, make_parsestate(), NIL, nodeTag, NoLock, NOTICE, CreateStmtContext::ofType, CreateStmt::ofTypename, OidIsValid, ParseState::p_sourcetext, CreateStmtContext::partbound, CreateStmt::partbound, CreateStmt::partspec, CreateStmtContext::pkey, CreateStmtContext::pstate, RangeVarGetAndCheckCreationNamespace(), CreateStmtContext::rel, CreateStmtContext::relation, CreateStmt::relation, RangeVar::relname, RangeVar::relpersistence, RangeVar::schemaname, setup_parser_errposition_callback(), CreateStmtContext::stmtType, T_ColumnDef, T_Constraint, T_TableLikeClause, CreateStmt::tableElts, transformCheckConstraints(), transformColumnDefinition(), transformExtendedStatistics(), transformFKConstraints(), transformIndexConstraints(), transformOfType(), transformTableConstraint(), and transformTableLikeClause().

Referenced by ProcessUtilitySlow().

168 {
169  ParseState *pstate;
170  CreateStmtContext cxt;
171  List *result;
172  List *save_alist;
173  ListCell *elements;
174  Oid namespaceid;
175  Oid existing_relid;
176  ParseCallbackState pcbstate;
177  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
178 
179  /*
180  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
181  * overkill, but easy.)
182  */
183  stmt = copyObject(stmt);
184 
185  /* Set up pstate */
186  pstate = make_parsestate(NULL);
187  pstate->p_sourcetext = queryString;
188 
189  /*
190  * Look up the creation namespace. This also checks permissions on the
191  * target namespace, locks it against concurrent drops, checks for a
192  * preexisting relation in that namespace with the same name, and updates
193  * stmt->relation->relpersistence if the selected namespace is temporary.
194  */
195  setup_parser_errposition_callback(&pcbstate, pstate,
196  stmt->relation->location);
197  namespaceid =
199  &existing_relid);
201 
202  /*
203  * If the relation already exists and the user specified "IF NOT EXISTS",
204  * bail out with a NOTICE.
205  */
206  if (stmt->if_not_exists && OidIsValid(existing_relid))
207  {
208  ereport(NOTICE,
209  (errcode(ERRCODE_DUPLICATE_TABLE),
210  errmsg("relation \"%s\" already exists, skipping",
211  stmt->relation->relname)));
212  return NIL;
213  }
214 
215  /*
216  * If the target relation name isn't schema-qualified, make it so. This
217  * prevents some corner cases in which added-on rewritten commands might
218  * think they should apply to other relations that have the same name and
219  * are earlier in the search path. But a local temp table is effectively
220  * specified to be in pg_temp, so no need for anything extra in that case.
221  */
222  if (stmt->relation->schemaname == NULL
223  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
224  stmt->relation->schemaname = get_namespace_name(namespaceid);
225 
226  /* Set up CreateStmtContext */
227  cxt.pstate = pstate;
228  if (IsA(stmt, CreateForeignTableStmt))
229  {
230  cxt.stmtType = "CREATE FOREIGN TABLE";
231  cxt.isforeign = true;
232  }
233  else
234  {
235  cxt.stmtType = "CREATE TABLE";
236  cxt.isforeign = false;
237  }
238  cxt.relation = stmt->relation;
239  cxt.rel = NULL;
240  cxt.inhRelations = stmt->inhRelations;
241  cxt.isalter = false;
242  cxt.columns = NIL;
243  cxt.ckconstraints = NIL;
244  cxt.fkconstraints = NIL;
245  cxt.ixconstraints = NIL;
246  cxt.extstats = NIL;
247  cxt.blist = NIL;
248  cxt.alist = NIL;
249  cxt.pkey = NULL;
250  cxt.ispartitioned = stmt->partspec != NULL;
251  cxt.partbound = stmt->partbound;
252  cxt.ofType = (stmt->ofTypename != NULL);
253 
254  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
255 
256  if (stmt->ofTypename)
257  transformOfType(&cxt, stmt->ofTypename);
258 
259  if (stmt->partspec)
260  {
261  if (stmt->inhRelations && !stmt->partbound)
262  ereport(ERROR,
263  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
264  errmsg("cannot create partitioned table as inheritance child")));
265  }
266 
267  /*
268  * Run through each primary element in the table creation clause. Separate
269  * column defs from constraints, and do preliminary analysis.
270  */
271  foreach(elements, stmt->tableElts)
272  {
273  Node *element = lfirst(elements);
274 
275  switch (nodeTag(element))
276  {
277  case T_ColumnDef:
278  transformColumnDefinition(&cxt, (ColumnDef *) element);
279  break;
280 
281  case T_Constraint:
282  transformTableConstraint(&cxt, (Constraint *) element);
283  break;
284 
285  case T_TableLikeClause:
286  transformTableLikeClause(&cxt, (TableLikeClause *) element);
287  break;
288 
289  default:
290  elog(ERROR, "unrecognized node type: %d",
291  (int) nodeTag(element));
292  break;
293  }
294  }
295 
296  /*
297  * Transfer anything we already have in cxt.alist into save_alist, to keep
298  * it separate from the output of transformIndexConstraints. (This may
299  * not be necessary anymore, but we'll keep doing it to preserve the
300  * historical order of execution of the alist commands.)
301  */
302  save_alist = cxt.alist;
303  cxt.alist = NIL;
304 
305  Assert(stmt->constraints == NIL);
306 
307  /*
308  * Postprocess constraints that give rise to index definitions.
309  */
311 
312  /*
313  * Postprocess foreign-key constraints.
314  */
315  transformFKConstraints(&cxt, true, false);
316 
317  /*
318  * Postprocess check constraints.
319  */
320  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
321 
322  /*
323  * Postprocess extended statistics.
324  */
326 
327  /*
328  * Output results.
329  */
330  stmt->tableElts = cxt.columns;
331  stmt->constraints = cxt.ckconstraints;
332 
333  result = lappend(cxt.blist, stmt);
334  result = list_concat(result, cxt.alist);
335  result = list_concat(result, save_alist);
336 
337  return result;
338 }
RangeVar * relation
Definition: parsenodes.h:2074
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2076
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Definition: nodes.h:528
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
List * constraints
Definition: parsenodes.h:2081
bool if_not_exists
Definition: parsenodes.h:2086
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parsenodes.h:2078
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:94
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:160
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
#define NoLock
Definition: lockdefs.h:34
const char * p_sourcetext
Definition: parse_node.h:179
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:144
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:96
List * lappend(List *list, void *datum)
Definition: list.c:321
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:534
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2075
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
static void transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
static void transformFKConstraints(CreateStmtContext *cxt, bool skipValidation, bool isAddConstraint)
#define nodeTag(nodeptr)
Definition: nodes.h:533
const char * stmtType
Definition: parse_utilcmd.c:79
static void transformExtendedStatistics(CreateStmtContext *cxt)
char relpersistence
Definition: primnodes.h:71
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
#define copyObject(obj)
Definition: nodes.h:644
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2079
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2080
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2617 of file parse_utilcmd.c.

References CreateStmtContext::alist, CreateStmtContext::extstats, and list_concat().

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2618 {
2619  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2620 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:515

◆ transformFKConstraints()

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

Definition at line 2661 of file parse_utilcmd.c.

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().

2663 {
2664  ListCell *fkclist;
2665 
2666  if (cxt->fkconstraints == NIL)
2667  return;
2668 
2669  /*
2670  * If CREATE TABLE or adding a column with NULL default, we can safely
2671  * skip validation of FK constraints, and nonetheless mark them valid.
2672  * (This will override any user-supplied NOT VALID flag.)
2673  */
2674  if (skipValidation)
2675  {
2676  foreach(fkclist, cxt->fkconstraints)
2677  {
2678  Constraint *constraint = (Constraint *) lfirst(fkclist);
2679 
2680  constraint->skip_validation = true;
2681  constraint->initially_valid = true;
2682  }
2683  }
2684 
2685  /*
2686  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2687  * CONSTRAINT command to execute after the basic command is complete. (If
2688  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2689  * its own subcommand list.)
2690  *
2691  * Note: the ADD CONSTRAINT command must also execute after any index
2692  * creation commands. Thus, this should run after
2693  * transformIndexConstraints, so that the CREATE INDEX commands are
2694  * already in cxt->alist.
2695  */
2696  if (!isAddConstraint)
2697  {
2698  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2699 
2700  alterstmt->relation = cxt->relation;
2701  alterstmt->cmds = NIL;
2702  alterstmt->objtype = OBJECT_TABLE;
2703 
2704  foreach(fkclist, cxt->fkconstraints)
2705  {
2706  Constraint *constraint = (Constraint *) lfirst(fkclist);
2707  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2708 
2709  altercmd->subtype = AT_AddConstraint;
2710  altercmd->name = NULL;
2711  altercmd->def = (Node *) constraint;
2712  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2713  }
2714 
2715  cxt->alist = lappend(cxt->alist, alterstmt);
2716  }
2717 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:528
AlterTableType subtype
Definition: parsenodes.h:1865
RangeVar * relation
Definition: parse_utilcmd.c:80
ObjectType objtype
Definition: parsenodes.h:1780
List * lappend(List *list, void *datum)
Definition: list.c:321
bool initially_valid
Definition: parsenodes.h:2200
#define makeNode(_type_)
Definition: nodes.h:576
#define lfirst(lc)
Definition: pg_list.h:169
RangeVar * relation
Definition: parsenodes.h:1778
bool skip_validation
Definition: parsenodes.h:2199

◆ transformIndexConstraint()

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

Definition at line 2083 of file parse_utilcmd.c.

References Constraint::access_method, IndexStmt::accessMethod, AccessShareLock, CreateStmtContext::alist, Assert, AT_SetNotNull, attname, attnum, castNode, AlterTableStmt::cmds, IndexElem::collation, ColumnDef::colname, CreateStmtContext::columns, IndexStmt::concurrent, Constraint::conname, CONSTR_EXCLUSION, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, copyObject, DatumGetPointer, DEFAULT_INDEX_TYPE, Constraint::deferrable, IndexStmt::deferrable, ereport, errcode(), errdetail(), errmsg(), ERROR, IndexStmt::excludeOpNames, Constraint::exclusions, IndexElem::expr, FormData_pg_attribute, get_attoptions(), get_index_am_oid(), get_index_constraint(), get_relname_relid(), GetDefaultOpClass(), i, IndexStmt::idxcomment, IndexStmt::idxname, IndexStmt::if_not_exists, Constraint::including, index_open(), IndexElem::indexcolname, IndexStmt::indexIncludingParams, Constraint::indexname, IndexStmt::indexOid, IndexStmt::indexParams, INDEXRELID, Constraint::indexspace, CreateStmtContext::inhRelations, Constraint::initdeferred, IndexStmt::initdeferred, InvalidOid, InvalidSubTransactionId, ColumnDef::is_from_type, ColumnDef::is_not_null, CreateStmtContext::isalter, IndexStmt::isconstraint, 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, IndexElem::nulls_ordering, OBJECT_TABLE, AlterTableStmt::objtype, OidIsValid, IndexStmt::oldCreateSubid, IndexStmt::oldFirstRelfilenodeSubid, IndexStmt::oldNode, IndexElem::opclass, IndexElem::opclassopts, Constraint::options, IndexStmt::options, IndexElem::ordering, parser_errposition(), CreateStmtContext::pkey, IndexStmt::primary, 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, IndexStmt::relation, relation_close(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeVar::relname, Constraint::reset_default_tblspc, IndexStmt::reset_default_tblspc, SORTBY_DEFAULT, SORTBY_NULLS_DEFAULT, strVal, AlterTableCmd::subtype, SysCacheGetAttr(), SystemAttributeByName(), SystemAttributeDefinition(), table_close(), table_openrv(), IndexStmt::tableSpace, IndexStmt::transformed, TupleDescAttr, IndexStmt::unique, oidvector::values, Constraint::where_clause, and IndexStmt::whereClause.

Referenced by transformIndexConstraints().

2084 {
2085  IndexStmt *index;
2086  List *notnullcmds = NIL;
2087  ListCell *lc;
2088 
2089  index = makeNode(IndexStmt);
2090 
2091  index->unique = (constraint->contype != CONSTR_EXCLUSION);
2092  index->primary = (constraint->contype == CONSTR_PRIMARY);
2093  if (index->primary)
2094  {
2095  if (cxt->pkey != NULL)
2096  ereport(ERROR,
2097  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2098  errmsg("multiple primary keys for table \"%s\" are not allowed",
2099  cxt->relation->relname),
2100  parser_errposition(cxt->pstate, constraint->location)));
2101  cxt->pkey = index;
2102 
2103  /*
2104  * In ALTER TABLE case, a primary index might already exist, but
2105  * DefineIndex will check for it.
2106  */
2107  }
2108  index->isconstraint = true;
2109  index->deferrable = constraint->deferrable;
2110  index->initdeferred = constraint->initdeferred;
2111 
2112  if (constraint->conname != NULL)
2113  index->idxname = pstrdup(constraint->conname);
2114  else
2115  index->idxname = NULL; /* DefineIndex will choose name */
2116 
2117  index->relation = cxt->relation;
2118  index->accessMethod = constraint->access_method ? constraint->access_method : DEFAULT_INDEX_TYPE;
2119  index->options = constraint->options;
2120  index->tableSpace = constraint->indexspace;
2121  index->whereClause = constraint->where_clause;
2122  index->indexParams = NIL;
2123  index->indexIncludingParams = NIL;
2124  index->excludeOpNames = NIL;
2125  index->idxcomment = NULL;
2126  index->indexOid = InvalidOid;
2127  index->oldNode = InvalidOid;
2130  index->transformed = false;
2131  index->concurrent = false;
2132  index->if_not_exists = false;
2133  index->reset_default_tblspc = constraint->reset_default_tblspc;
2134 
2135  /*
2136  * If it's ALTER TABLE ADD CONSTRAINT USING INDEX, look up the index and
2137  * verify it's usable, then extract the implied column name list. (We
2138  * will not actually need the column name list at runtime, but we need it
2139  * now to check for duplicate column entries below.)
2140  */
2141  if (constraint->indexname != NULL)
2142  {
2143  char *index_name = constraint->indexname;
2144  Relation heap_rel = cxt->rel;
2145  Oid index_oid;
2146  Relation index_rel;
2147  Form_pg_index index_form;
2148  oidvector *indclass;
2149  Datum indclassDatum;
2150  bool isnull;
2151  int i;
2152 
2153  /* Grammar should not allow this with explicit column list */
2154  Assert(constraint->keys == NIL);
2155 
2156  /* Grammar should only allow PRIMARY and UNIQUE constraints */
2157  Assert(constraint->contype == CONSTR_PRIMARY ||
2158  constraint->contype == CONSTR_UNIQUE);
2159 
2160  /* Must be ALTER, not CREATE, but grammar doesn't enforce that */
2161  if (!cxt->isalter)
2162  ereport(ERROR,
2163  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2164  errmsg("cannot use an existing index in CREATE TABLE"),
2165  parser_errposition(cxt->pstate, constraint->location)));
2166 
2167  /* Look for the index in the same schema as the table */
2168  index_oid = get_relname_relid(index_name, RelationGetNamespace(heap_rel));
2169 
2170  if (!OidIsValid(index_oid))
2171  ereport(ERROR,
2172  (errcode(ERRCODE_UNDEFINED_OBJECT),
2173  errmsg("index \"%s\" does not exist", index_name),
2174  parser_errposition(cxt->pstate, constraint->location)));
2175 
2176  /* Open the index (this will throw an error if it is not an index) */
2177  index_rel = index_open(index_oid, AccessShareLock);
2178  index_form = index_rel->rd_index;
2179 
2180  /* Check that it does not have an associated constraint already */
2181  if (OidIsValid(get_index_constraint(index_oid)))
2182  ereport(ERROR,
2183  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2184  errmsg("index \"%s\" is already associated with a constraint",
2185  index_name),
2186  parser_errposition(cxt->pstate, constraint->location)));
2187 
2188  /* Perform validity checks on the index */
2189  if (index_form->indrelid != RelationGetRelid(heap_rel))
2190  ereport(ERROR,
2191  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2192  errmsg("index \"%s\" does not belong to table \"%s\"",
2193  index_name, RelationGetRelationName(heap_rel)),
2194  parser_errposition(cxt->pstate, constraint->location)));
2195 
2196  if (!index_form->indisvalid)
2197  ereport(ERROR,
2198  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2199  errmsg("index \"%s\" is not valid", index_name),
2200  parser_errposition(cxt->pstate, constraint->location)));
2201 
2202  if (!index_form->indisunique)
2203  ereport(ERROR,
2204  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2205  errmsg("\"%s\" is not a unique index", index_name),
2206  errdetail("Cannot create a primary key or unique constraint using such an index."),
2207  parser_errposition(cxt->pstate, constraint->location)));
2208 
2209  if (RelationGetIndexExpressions(index_rel) != NIL)
2210  ereport(ERROR,
2211  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2212  errmsg("index \"%s\" contains expressions", index_name),
2213  errdetail("Cannot create a primary key or unique constraint using such an index."),
2214  parser_errposition(cxt->pstate, constraint->location)));
2215 
2216  if (RelationGetIndexPredicate(index_rel) != NIL)
2217  ereport(ERROR,
2218  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2219  errmsg("\"%s\" is a partial index", index_name),
2220  errdetail("Cannot create a primary key or unique constraint using such an index."),
2221  parser_errposition(cxt->pstate, constraint->location)));
2222 
2223  /*
2224  * It's probably unsafe to change a deferred index to non-deferred. (A
2225  * non-constraint index couldn't be deferred anyway, so this case
2226  * should never occur; no need to sweat, but let's check it.)
2227  */
2228  if (!index_form->indimmediate && !constraint->deferrable)
2229  ereport(ERROR,
2230  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2231  errmsg("\"%s\" is a deferrable index", index_name),
2232  errdetail("Cannot create a non-deferrable constraint using a deferrable index."),
2233  parser_errposition(cxt->pstate, constraint->location)));
2234 
2235  /*
2236  * Insist on it being a btree. That's the only kind that supports
2237  * uniqueness at the moment anyway; but we must have an index that
2238  * exactly matches what you'd get from plain ADD CONSTRAINT syntax,
2239  * else dump and reload will produce a different index (breaking
2240  * pg_upgrade in particular).
2241  */
2242  if (index_rel->rd_rel->relam != get_index_am_oid(DEFAULT_INDEX_TYPE, false))
2243  ereport(ERROR,
2244  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2245  errmsg("index \"%s\" is not a btree", index_name),
2246  parser_errposition(cxt->pstate, constraint->location)));
2247 
2248  /* Must get indclass the hard way */
2249  indclassDatum = SysCacheGetAttr(INDEXRELID, index_rel->rd_indextuple,
2250  Anum_pg_index_indclass, &isnull);
2251  Assert(!isnull);
2252  indclass = (oidvector *) DatumGetPointer(indclassDatum);
2253 
2254  for (i = 0; i < index_form->indnatts; i++)
2255  {
2256  int16 attnum = index_form->indkey.values[i];
2257  const FormData_pg_attribute *attform;
2258  char *attname;
2259  Oid defopclass;
2260 
2261  /*
2262  * We shouldn't see attnum == 0 here, since we already rejected
2263  * expression indexes. If we do, SystemAttributeDefinition will
2264  * throw an error.
2265  */
2266  if (attnum > 0)
2267  {
2268  Assert(attnum <= heap_rel->rd_att->natts);
2269  attform = TupleDescAttr(heap_rel->rd_att, attnum - 1);
2270  }
2271  else
2272  attform = SystemAttributeDefinition(attnum);
2273  attname = pstrdup(NameStr(attform->attname));
2274 
2275  if (i < index_form->indnkeyatts)
2276  {
2277  /*
2278  * Insist on default opclass, collation, and sort options.
2279  * While the index would still work as a constraint with
2280  * non-default settings, it might not provide exactly the same
2281  * uniqueness semantics as you'd get from a normally-created
2282  * constraint; and there's also the dump/reload problem
2283  * mentioned above.
2284  */
2285  Datum attoptions =
2286  get_attoptions(RelationGetRelid(index_rel), i + 1);
2287 
2288  defopclass = GetDefaultOpClass(attform->atttypid,
2289  index_rel->rd_rel->relam);
2290  if (indclass->values[i] != defopclass ||
2291  attform->attcollation != index_rel->rd_indcollation[i] ||
2292  attoptions != (Datum) 0 ||
2293  index_rel->rd_indoption[i] != 0)
2294  ereport(ERROR,
2295  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2296  errmsg("index \"%s\" column number %d does not have default sorting behavior", index_name, i + 1),
2297  errdetail("Cannot create a primary key or unique constraint using such an index."),
2298  parser_errposition(cxt->pstate, constraint->location)));
2299 
2300  constraint->keys = lappend(constraint->keys, makeString(attname));
2301  }
2302  else
2303  constraint->including = lappend(constraint->including, makeString(attname));
2304  }
2305 
2306  /* Close the index relation but keep the lock */
2307  relation_close(index_rel, NoLock);
2308 
2309  index->indexOid = index_oid;
2310  }
2311 
2312  /*
2313  * If it's an EXCLUDE constraint, the grammar returns a list of pairs of
2314  * IndexElems and operator names. We have to break that apart into
2315  * separate lists.
2316  */
2317  if (constraint->contype == CONSTR_EXCLUSION)
2318  {
2319  foreach(lc, constraint->exclusions)
2320  {
2321  List *pair = (List *) lfirst(lc);
2322  IndexElem *elem;
2323  List *opname;
2324 
2325  Assert(list_length(pair) == 2);
2326  elem = linitial_node(IndexElem, pair);
2327  opname = lsecond_node(List, pair);
2328 
2329  index->indexParams = lappend(index->indexParams, elem);
2330  index->excludeOpNames = lappend(index->excludeOpNames, opname);
2331  }
2332  }
2333 
2334  /*
2335  * For UNIQUE and PRIMARY KEY, we just have a list of column names.
2336  *
2337  * Make sure referenced keys exist. If we are making a PRIMARY KEY index,
2338  * also make sure they are NOT NULL.
2339  */
2340  else
2341  {
2342  foreach(lc, constraint->keys)
2343  {
2344  char *key = strVal(lfirst(lc));
2345  bool found = false;
2346  bool forced_not_null = false;
2347  ColumnDef *column = NULL;
2348  ListCell *columns;
2349  IndexElem *iparam;
2350 
2351  /* Make sure referenced column exists. */
2352  foreach(columns, cxt->columns)
2353  {
2354  column = castNode(ColumnDef, lfirst(columns));
2355  if (strcmp(column->colname, key) == 0)
2356  {
2357  found = true;
2358  break;
2359  }
2360  }
2361  if (found)
2362  {
2363  /*
2364  * column is defined in the new table. For PRIMARY KEY, we
2365  * can apply the NOT NULL constraint cheaply here ... unless
2366  * the column is marked is_from_type, in which case marking it
2367  * here would be ineffective (see MergeAttributes).
2368  */
2369  if (constraint->contype == CONSTR_PRIMARY &&
2370  !column->is_from_type)
2371  {
2372  column->is_not_null = true;
2373  forced_not_null = true;
2374  }
2375  }
2376  else if (SystemAttributeByName(key) != NULL)
2377  {
2378  /*
2379  * column will be a system column in the new table, so accept
2380  * it. System columns can't ever be null, so no need to worry
2381  * about PRIMARY/NOT NULL constraint.
2382  */
2383  found = true;
2384  }
2385  else if (cxt->inhRelations)
2386  {
2387  /* try inherited tables */
2388  ListCell *inher;
2389 
2390  foreach(inher, cxt->inhRelations)
2391  {
2392  RangeVar *inh = castNode(RangeVar, lfirst(inher));
2393  Relation rel;
2394  int count;
2395 
2396  rel = table_openrv(inh, AccessShareLock);
2397  /* check user requested inheritance from valid relkind */
2398  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2399  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2400  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2401  ereport(ERROR,
2402  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2403  errmsg("inherited relation \"%s\" is not a table or foreign table",
2404  inh->relname)));
2405  for (count = 0; count < rel->rd_att->natts; count++)
2406  {
2407  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2408  count);
2409  char *inhname = NameStr(inhattr->attname);
2410 
2411  if (inhattr->attisdropped)
2412  continue;
2413  if (strcmp(key, inhname) == 0)
2414  {
2415  found = true;
2416 
2417  /*
2418  * It's tempting to set forced_not_null if the
2419  * parent column is already NOT NULL, but that
2420  * seems unsafe because the column's NOT NULL
2421  * marking might disappear between now and
2422  * execution. Do the runtime check to be safe.
2423  */
2424  break;
2425  }
2426  }
2427  table_close(rel, NoLock);
2428  if (found)
2429  break;
2430  }
2431  }
2432 
2433  /*
2434  * In the ALTER TABLE case, don't complain about index keys not
2435  * created in the command; they may well exist already.
2436  * DefineIndex will complain about them if not.
2437  */
2438  if (!found && !cxt->isalter)
2439  ereport(ERROR,
2440  (errcode(ERRCODE_UNDEFINED_COLUMN),
2441  errmsg("column \"%s\" named in key does not exist", key),
2442  parser_errposition(cxt->pstate, constraint->location)));
2443 
2444  /* Check for PRIMARY KEY(foo, foo) */
2445  foreach(columns, index->indexParams)
2446  {
2447  iparam = (IndexElem *) lfirst(columns);
2448  if (iparam->name && strcmp(key, iparam->name) == 0)
2449  {
2450  if (index->primary)
2451  ereport(ERROR,
2452  (errcode(ERRCODE_DUPLICATE_COLUMN),
2453  errmsg("column \"%s\" appears twice in primary key constraint",
2454  key),
2455  parser_errposition(cxt->pstate, constraint->location)));
2456  else
2457  ereport(ERROR,
2458  (errcode(ERRCODE_DUPLICATE_COLUMN),
2459  errmsg("column \"%s\" appears twice in unique constraint",
2460  key),
2461  parser_errposition(cxt->pstate, constraint->location)));
2462  }
2463  }
2464 
2465  /* OK, add it to the index definition */
2466  iparam = makeNode(IndexElem);
2467  iparam->name = pstrdup(key);
2468  iparam->expr = NULL;
2469  iparam->indexcolname = NULL;
2470  iparam->collation = NIL;
2471  iparam->opclass = NIL;
2472  iparam->opclassopts = NIL;
2473  iparam->ordering = SORTBY_DEFAULT;
2475  index->indexParams = lappend(index->indexParams, iparam);
2476 
2477  /*
2478  * For a primary-key column, also create an item for ALTER TABLE
2479  * SET NOT NULL if we couldn't ensure it via is_not_null above.
2480  */
2481  if (constraint->contype == CONSTR_PRIMARY && !forced_not_null)
2482  {
2483  AlterTableCmd *notnullcmd = makeNode(AlterTableCmd);
2484 
2485  notnullcmd->subtype = AT_SetNotNull;
2486  notnullcmd->name = pstrdup(key);
2487  notnullcmds = lappend(notnullcmds, notnullcmd);
2488  }
2489  }
2490  }
2491 
2492  /*
2493  * Add included columns to index definition. This is much like the
2494  * simple-column-name-list code above, except that we don't worry about
2495  * NOT NULL marking; included columns in a primary key should not be
2496  * forced NOT NULL. We don't complain about duplicate columns, either,
2497  * though maybe we should?
2498  */
2499  foreach(lc, constraint->including)
2500  {
2501  char *key = strVal(lfirst(lc));
2502  bool found = false;
2503  ColumnDef *column = NULL;
2504  ListCell *columns;
2505  IndexElem *iparam;
2506 
2507  foreach(columns, cxt->columns)
2508  {
2509  column = lfirst_node(ColumnDef, columns);
2510  if (strcmp(column->colname, key) == 0)
2511  {
2512  found = true;
2513  break;
2514  }
2515  }
2516 
2517  if (!found)
2518  {
2519  if (SystemAttributeByName(key) != NULL)
2520  {
2521  /*
2522  * column will be a system column in the new table, so accept
2523  * it.
2524  */
2525  found = true;
2526  }
2527  else if (cxt->inhRelations)
2528  {
2529  /* try inherited tables */
2530  ListCell *inher;
2531 
2532  foreach(inher, cxt->inhRelations)
2533  {
2534  RangeVar *inh = lfirst_node(RangeVar, inher);
2535  Relation rel;
2536  int count;
2537 
2538  rel = table_openrv(inh, AccessShareLock);
2539  /* check user requested inheritance from valid relkind */
2540  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2541  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2542  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2543  ereport(ERROR,
2544  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2545  errmsg("inherited relation \"%s\" is not a table or foreign table",
2546  inh->relname)));
2547  for (count = 0; count < rel->rd_att->natts; count++)
2548  {
2549  Form_pg_attribute inhattr = TupleDescAttr(rel->rd_att,
2550  count);
2551  char *inhname = NameStr(inhattr->attname);
2552 
2553  if (inhattr->attisdropped)
2554  continue;
2555  if (strcmp(key, inhname) == 0)
2556  {
2557  found = true;
2558  break;
2559  }
2560  }
2561  table_close(rel, NoLock);
2562  if (found)
2563  break;
2564  }
2565  }
2566  }
2567 
2568  /*
2569  * In the ALTER TABLE case, don't complain about index keys not
2570  * created in the command; they may well exist already. DefineIndex
2571  * will complain about them if not.
2572  */
2573  if (!found && !cxt->isalter)
2574  ereport(ERROR,
2575  (errcode(ERRCODE_UNDEFINED_COLUMN),
2576  errmsg("column \"%s\" named in key does not exist", key),
2577  parser_errposition(cxt->pstate, constraint->location)));
2578 
2579  /* OK, add it to the index definition */
2580  iparam = makeNode(IndexElem);
2581  iparam->name = pstrdup(key);
2582  iparam->expr = NULL;
2583  iparam->indexcolname = NULL;
2584  iparam->collation = NIL;
2585  iparam->opclass = NIL;
2586  iparam->opclassopts = NIL;
2587  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
2588  }
2589 
2590  /*
2591  * If we found anything that requires run-time SET NOT NULL, build a full
2592  * ALTER TABLE command for that and add it to cxt->alist.
2593  */
2594  if (notnullcmds)
2595  {
2596  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2597 
2598  alterstmt->relation = copyObject(cxt->relation);
2599  alterstmt->cmds = notnullcmds;
2600  alterstmt->objtype = OBJECT_TABLE;
2601  alterstmt->missing_ok = false;
2602 
2603  cxt->alist = lappend(cxt->alist, alterstmt);
2604  }
2605 
2606  return index;
2607 }
bool deferrable
Definition: parsenodes.h:2796
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:362
#define NIL
Definition: pg_list.h:65
Definition: c.h:602
bool primary
Definition: parsenodes.h:2794
List * keys
Definition: parsenodes.h:2169
List * exclusions
Definition: parsenodes.h:2175
int16 * rd_indoption
Definition: rel.h:193
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Oid GetDefaultOpClass(Oid type_id, Oid am_id)
Definition: indexcmds.c:2057
SortByDir ordering
Definition: parsenodes.h:707
List * options
Definition: parsenodes.h:2784
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2790
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
char * tableSpace
Definition: parsenodes.h:2780
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1187
Node * whereClause
Definition: parsenodes.h:2785
#define AccessShareLock
Definition: lockdefs.h:36
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
bool initdeferred
Definition: parsenodes.h:2159
AlterTableType subtype
Definition: parsenodes.h:1865
char * conname
Definition: parsenodes.h:2157
bool is_not_null
Definition: parsenodes.h:652
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:177
#define OidIsValid(objectId)
Definition: c.h:652
List * opclassopts
Definition: parsenodes.h:706
List * options
Definition: parsenodes.h:2178
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4861
struct HeapTupleData * rd_indextuple
Definition: rel.h:176
List * indexIncludingParams
Definition: parsenodes.h:2782
Definition: type.h:89
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:249
ParseState * pstate
Definition: parse_utilcmd.c:78
char * relname
Definition: primnodes.h:68
Oid indexOid
Definition: parsenodes.h:2788
Node * expr
Definition: parsenodes.h:702
RangeVar * relation
Definition: parse_utilcmd.c:80
RangeVar * relation
Definition: parsenodes.h:2778
IndexStmt * pkey
Definition: parse_utilcmd.c:94
Datum get_attoptions(Oid relid, int16 attnum)
Definition: lsyscache.c:968
Form_pg_index rd_index
Definition: rel.h:174
Oid * rd_indcollation
Definition: rel.h:199
SortByNulls nulls_ordering
Definition: parsenodes.h:708
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
bool deferrable
Definition: parsenodes.h:2158
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1797
#define lfirst_node(type, lc)
Definition: pg_list.h:172
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:261
Oid get_index_am_oid(const char *amname, bool missing_ok)
Definition: amcmds.c:163
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4748
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:610
bool transformed
Definition: parsenodes.h:2798
int errdetail(const char *fmt,...)
Definition: elog.c:954
char * indexcolname
Definition: parsenodes.h:703
#define DEFAULT_INDEX_TYPE
Definition: index.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
Oid get_index_constraint(Oid indexId)
Definition: pg_depend.c:1007
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2791
bool reset_default_tblspc
Definition: parsenodes.h:2181
ObjectType objtype
Definition: parsenodes.h:1780
List * lappend(List *list, void *datum)
Definition: list.c:321
char * idxname
Definition: parsenodes.h:2777
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
bool reset_default_tblspc
Definition: parsenodes.h:2801
bool if_not_exists
Definition: parsenodes.h:2800
#define lsecond_node(type, l)
Definition: pg_list.h:182
uintptr_t Datum
Definition: postgres.h:367
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
bool unique
Definition: parsenodes.h:2793
TupleDesc rd_att
Definition: rel.h:110
char * accessMethod
Definition: parsenodes.h:2779
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_attribute
Definition: pg_attribute.h:177
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
List * opclass
Definition: parsenodes.h:705
bool is_from_type
Definition: parsenodes.h:653
Node * where_clause
Definition: parsenodes.h:2185
#define makeNode(_type_)
Definition: nodes.h:576
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
List * indexParams
Definition: parsenodes.h:2781
List * excludeOpNames
Definition: parsenodes.h:2786
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
bool initdeferred
Definition: parsenodes.h:2797
char * name
Definition: parsenodes.h:701
char * idxcomment
Definition: parsenodes.h:2787
#define InvalidSubTransactionId
Definition: c.h:527
#define DatumGetPointer(X)
Definition: postgres.h:549
bool concurrent
Definition: parsenodes.h:2799
bool isconstraint
Definition: parsenodes.h:2795
char * indexname
Definition: parsenodes.h:2179
int errmsg(const char *fmt,...)
Definition: elog.c:821
RangeVar * relation
Definition: parsenodes.h:1778
int i
#define NameStr(name)
Definition: c.h:623
ConstrType contype
Definition: parsenodes.h:2154
List * collation
Definition: parsenodes.h:704
char * colname
Definition: parsenodes.h:648
List * including
Definition: parsenodes.h:2171
#define copyObject(obj)
Definition: nodes.h:644
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
char * access_method
Definition: parsenodes.h:2184
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
char * indexspace
Definition: parsenodes.h:2180
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 1981 of file parse_utilcmd.c.

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, CreateStmtContext::pkey, transformIndexConstraint(), IndexStmt::unique, and IndexStmt::whereClause.

Referenced by transformAlterTableStmt(), and transformCreateStmt().

1982 {
1983  IndexStmt *index;
1984  List *indexlist = NIL;
1985  List *finalindexlist = NIL;
1986  ListCell *lc;
1987 
1988  /*
1989  * Run through the constraints that need to generate an index. For PRIMARY
1990  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
1991  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
1992  * NULL.
1993  */
1994  foreach(lc, cxt->ixconstraints)
1995  {
1996  Constraint *constraint = lfirst_node(Constraint, lc);
1997 
1998  Assert(constraint->contype == CONSTR_PRIMARY ||
1999  constraint->contype == CONSTR_UNIQUE ||
2000  constraint->contype == CONSTR_EXCLUSION);
2001 
2002  index = transformIndexConstraint(constraint, cxt);
2003 
2004  indexlist = lappend(indexlist, index);
2005  }
2006 
2007  /*
2008  * Scan the index list and remove any redundant index specifications. This
2009  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2010  * strict reading of SQL would suggest raising an error instead, but that
2011  * strikes me as too anal-retentive. - tgl 2001-02-14
2012  *
2013  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2014  * pre-existing indexes, too.
2015  */
2016  if (cxt->pkey != NULL)
2017  {
2018  /* Make sure we keep the PKEY index in preference to others... */
2019  finalindexlist = list_make1(cxt->pkey);
2020  }
2021 
2022  foreach(lc, indexlist)
2023  {
2024  bool keep = true;
2025  ListCell *k;
2026 
2027  index = lfirst(lc);
2028 
2029  /* if it's pkey, it's already in finalindexlist */
2030  if (index == cxt->pkey)
2031  continue;
2032 
2033  foreach(k, finalindexlist)
2034  {
2035  IndexStmt *priorindex = lfirst(k);
2036 
2037  if (equal(index->indexParams, priorindex->indexParams) &&
2038  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2039  equal(index->whereClause, priorindex->whereClause) &&
2040  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2041  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2042  index->deferrable == priorindex->deferrable &&
2043  index->initdeferred == priorindex->initdeferred)
2044  {
2045  priorindex->unique |= index->unique;
2046 
2047  /*
2048  * If the prior index is as yet unnamed, and this one is
2049  * named, then transfer the name to the prior index. This
2050  * ensures that if we have named and unnamed constraints,
2051  * we'll use (at least one of) the names for the index.
2052  */
2053  if (priorindex->idxname == NULL)
2054  priorindex->idxname = index->idxname;
2055  keep = false;
2056  break;
2057  }
2058  }
2059 
2060  if (keep)
2061  finalindexlist = lappend(finalindexlist, index);
2062  }
2063 
2064  /*
2065  * Now append all the IndexStmts to cxt->alist. If we generated an ALTER
2066  * TABLE SET NOT NULL statement to support a primary key, it's already in
2067  * cxt->alist.
2068  */
2069  cxt->alist = list_concat(cxt->alist, finalindexlist);
2070 }
bool deferrable
Definition: parsenodes.h:2796
#define NIL
Definition: pg_list.h:65
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3032
Node * whereClause
Definition: parsenodes.h:2785
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
List * indexIncludingParams
Definition: parsenodes.h:2782
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:206
IndexStmt * pkey
Definition: parse_utilcmd.c:94
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * lappend(List *list, void *datum)
Definition: list.c:321
char * idxname
Definition: parsenodes.h:2777
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2793
char * accessMethod
Definition: parsenodes.h:2779
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
List * indexParams
Definition: parsenodes.h:2781
List * excludeOpNames
Definition: parsenodes.h:2786
bool initdeferred
Definition: parsenodes.h:2797
ConstrType contype
Definition: parsenodes.h:2154
Definition: pg_list.h:50

◆ transformIndexStmt()

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

Definition at line 2732 of file parse_utilcmd.c.

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

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

2733 {
2734  ParseState *pstate;
2735  ParseNamespaceItem *nsitem;
2736  ListCell *l;
2737  Relation rel;
2738 
2739  /* Nothing to do if statement already transformed. */
2740  if (stmt->transformed)
2741  return stmt;
2742 
2743  /*
2744  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2745  * overkill, but easy.)
2746  */
2747  stmt = copyObject(stmt);
2748 
2749  /* Set up pstate */
2750  pstate = make_parsestate(NULL);
2751  pstate->p_sourcetext = queryString;
2752 
2753  /*
2754  * Put the parent table into the rtable so that the expressions can refer
2755  * to its fields without qualification. Caller is responsible for locking
2756  * relation, but we still need to open it.
2757  */
2758  rel = relation_open(relid, NoLock);
2759  nsitem = addRangeTableEntryForRelation(pstate, rel,
2761  NULL, false, true);
2762 
2763  /* no to join list, yes to namespaces */
2764  addNSItemToQuery(pstate, nsitem, false, true, true);
2765 
2766  /* take care of the where clause */
2767  if (stmt->whereClause)
2768  {
2769  stmt->whereClause = transformWhereClause(pstate,
2770  stmt->whereClause,
2772  "WHERE");
2773  /* we have to fix its collations too */
2774  assign_expr_collations(pstate, stmt->whereClause);
2775  }
2776 
2777  /* take care of any index expressions */
2778  foreach(l, stmt->indexParams)
2779  {
2780  IndexElem *ielem = (IndexElem *) lfirst(l);
2781 
2782  if (ielem->expr)
2783  {
2784  /* Extract preliminary index col name before transforming expr */
2785  if (ielem->indexcolname == NULL)
2786  ielem->indexcolname = FigureIndexColname(ielem->expr);
2787 
2788  /* Now do parse transformation of the expression */
2789  ielem->expr = transformExpr(pstate, ielem->expr,
2791 
2792  /* We have to fix its collations too */
2793  assign_expr_collations(pstate, ielem->expr);
2794 
2795  /*
2796  * transformExpr() should have already rejected subqueries,
2797  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2798  * for an index expression.
2799  *
2800  * DefineIndex() will make more checks.
2801  */
2802  }
2803  }
2804 
2805  /*
2806  * Check that only the base rel is mentioned. (This should be dead code
2807  * now that add_missing_from is history.)
2808  */
2809  if (list_length(pstate->p_rtable) != 1)
2810  ereport(ERROR,
2811  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2812  errmsg("index expressions and predicates can refer only to the table being indexed")));
2813 
2814  free_parsestate(pstate);
2815 
2816  /* Close relation */
2817  table_close(rel, NoLock);
2818 
2819  /* Mark statement as successfully transformed */
2820  stmt->transformed = true;
2821 
2822  return stmt;
2823 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:145
Node * whereClause
Definition: parsenodes.h:2785
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
int errcode(int sqlerrcode)
Definition: elog.c:610
char * FigureIndexColname(Node *node)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:43
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:702
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2798
char * indexcolname
Definition: parsenodes.h:703
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:169
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2781
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define copyObject(obj)
Definition: nodes.h:644
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:76
List * p_rtable
Definition: parse_node.h:180

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1412 of file parse_utilcmd.c.

References AssertArg, check_of_type(), ColumnDef::collClause, ColumnDef::collOid, ColumnDef::colname, CreateStmtContext::columns, ColumnDef::constraints, ColumnDef::cooked_default, DecrTupleDescRefCount(), GETSTRUCT, i, ColumnDef::inhcount, ColumnDef::is_from_type, ColumnDef::is_local, ColumnDef::is_not_null, lappend(), ColumnDef::location, lookup_rowtype_tupdesc(), makeNode, makeTypeNameFromOid(), NameStr, TupleDescData::natts, NIL, pstrdup(), ColumnDef::raw_default, ReleaseSysCache(), ColumnDef::storage, TupleDescAttr, ColumnDef::typeName, typenameType(), and TypeName::typeOid.

Referenced by transformCreateStmt().

1413 {
1414  HeapTuple tuple;
1415  TupleDesc tupdesc;
1416  int i;
1417  Oid ofTypeId;
1418 
1419  AssertArg(ofTypename);
1420 
1421  tuple = typenameType(NULL, ofTypename, NULL);
1422  check_of_type(tuple);
1423  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1424  ofTypename->typeOid = ofTypeId; /* cached for later */
1425 
1426  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1427  for (i = 0; i < tupdesc->natts; i++)
1428  {
1429  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1430  ColumnDef *n;
1431 
1432  if (attr->attisdropped)
1433  continue;
1434 
1435  n = makeNode(ColumnDef);
1436  n->colname = pstrdup(NameStr(attr->attname));
1437  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1438  n->inhcount = 0;
1439  n->is_local = true;
1440  n->is_not_null = false;
1441  n->is_from_type = true;
1442  n->storage = 0;
1443  n->raw_default = NULL;
1444  n->cooked_default = NULL;
1445  n->collClause = NULL;
1446  n->collOid = attr->attcollation;
1447  n->constraints = NIL;
1448  n->location = -1;
1449  cxt->columns = lappend(cxt->columns, n);
1450  }
1451  DecrTupleDescRefCount(tupdesc);
1452 
1453  ReleaseSysCache(tuple);
1454 }
#define NIL
Definition: pg_list.h:65
Oid typeOid
Definition: parsenodes.h:211
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Type typenameType(ParseState *pstate, const TypeName *typeName, int32 *typmod_p)
Definition: parse_type.c:264
char storage
Definition: parsenodes.h:654
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1710
bool is_local
Definition: parsenodes.h:651
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:663
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool is_not_null
Definition: parsenodes.h:652
unsigned int Oid
Definition: postgres_ext.h:31
Node * cooked_default
Definition: parsenodes.h:656
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5973
Oid collOid
Definition: parsenodes.h:662
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
int location
Definition: parsenodes.h:665
#define AssertArg(condition)
Definition: c.h:748
Node * raw_default
Definition: parsenodes.h:655
List * lappend(List *list, void *datum)
Definition: list.c:321
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
bool is_from_type
Definition: parsenodes.h:653
#define makeNode(_type_)
Definition: nodes.h:576
void DecrTupleDescRefCount(TupleDesc tupdesc)
Definition: tupdesc.c:393
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
TypeName * typeName
Definition: parsenodes.h:649
CollateClause * collClause
Definition: parsenodes.h:661
int i
int inhcount
Definition: parsenodes.h:650
#define NameStr(name)
Definition: c.h:623
char * colname
Definition: parsenodes.h:648

◆ transformPartitionBound()

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

Definition at line 3862 of file parse_utilcmd.c.

References Assert, castNode, 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, linitial, list_length(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, NIL, parser_errposition(), PartitionKeyData::partattrs, 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().

3864 {
3865  PartitionBoundSpec *result_spec;
3867  char strategy = get_partition_strategy(key);
3868  int partnatts = get_partition_natts(key);
3869  List *partexprs = get_partition_exprs(key);
3870 
3871  /* Avoid scribbling on input */
3872  result_spec = copyObject(spec);
3873 
3874  if (spec->is_default)
3875  {
3876  /*
3877  * Hash partitioning does not support a default partition; there's no
3878  * use case for it (since the set of partitions to create is perfectly
3879  * defined), and if users do get into it accidentally, it's hard to
3880  * back out from it afterwards.
3881  */
3882  if (strategy == PARTITION_STRATEGY_HASH)
3883  ereport(ERROR,
3884  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3885  errmsg("a hash-partitioned table may not have a default partition")));
3886 
3887  /*
3888  * In case of the default partition, parser had no way to identify the
3889  * partition strategy. Assign the parent's strategy to the default
3890  * partition bound spec.
3891  */
3892  result_spec->strategy = strategy;
3893 
3894  return result_spec;
3895  }
3896 
3897  if (strategy == PARTITION_STRATEGY_HASH)
3898  {
3899  if (spec->strategy != PARTITION_STRATEGY_HASH)
3900  ereport(ERROR,
3901  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3902  errmsg("invalid bound specification for a hash partition"),
3903  parser_errposition(pstate, exprLocation((Node *) spec))));
3904 
3905  if (spec->modulus <= 0)
3906  ereport(ERROR,
3907  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3908  errmsg("modulus for hash partition must be a positive integer")));
3909 
3910  Assert(spec->remainder >= 0);
3911 
3912  if (spec->remainder >= spec->modulus)
3913  ereport(ERROR,
3914  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3915  errmsg("remainder for hash partition must be less than modulus")));
3916  }
3917  else if (strategy == PARTITION_STRATEGY_LIST)
3918  {
3919  ListCell *cell;
3920  char *colname;
3921  Oid coltype;
3922  int32 coltypmod;
3923  Oid partcollation;
3924 
3925  if (spec->strategy != PARTITION_STRATEGY_LIST)
3926  ereport(ERROR,
3927  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3928  errmsg("invalid bound specification for a list partition"),
3929  parser_errposition(pstate, exprLocation((Node *) spec))));
3930 
3931  /* Get the only column's name in case we need to output an error */
3932  if (key->partattrs[0] != 0)
3933  colname = get_attname(RelationGetRelid(parent),
3934  key->partattrs[0], false);
3935  else
3936  colname = deparse_expression((Node *) linitial(partexprs),
3938  RelationGetRelid(parent)),
3939  false, false);
3940  /* Need its type data too */
3941  coltype = get_partition_col_typid(key, 0);
3942  coltypmod = get_partition_col_typmod(key, 0);
3943  partcollation = get_partition_col_collation(key, 0);
3944 
3945  result_spec->listdatums = NIL;
3946  foreach(cell, spec->listdatums)
3947  {
3948  Node *expr = lfirst(cell);
3949  Const *value;
3950  L