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 1176 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, elog, 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, OidIsValid, TableLikeClause::options, pstrdup(), Constraint::raw_expr, RelationData::rd_rel, AlterTableStmt::relation, relation_open(), relation_openrv(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, RelationGetRelid, TableLikeClause::relationOid, RangeVar::relname, RangeVar::schemaname, Constraint::skip_validation, stringToNode(), AlterTableCmd::subtype, table_close(), and TupleDescAttr.

Referenced by ProcessUtilitySlow().

1177 {
1178  List *result = NIL;
1179  List *atsubcmds = NIL;
1180  AttrNumber parent_attno;
1181  Relation relation;
1182  Relation childrel;
1183  TupleDesc tupleDesc;
1184  TupleConstr *constr;
1185  AttrMap *attmap;
1186  char *comment;
1187 
1188  /*
1189  * Open the relation referenced by the LIKE clause. We should still have
1190  * the table lock obtained by transformTableLikeClause (and this'll throw
1191  * an assertion failure if not). Hence, no need to recheck privileges
1192  * etc. We must open the rel by OID not name, to be sure we get the same
1193  * table.
1194  */
1195  if (!OidIsValid(table_like_clause->relationOid))
1196  elog(ERROR, "expandTableLikeClause called on untransformed LIKE clause");
1197 
1198  relation = relation_open(table_like_clause->relationOid, NoLock);
1199 
1200  tupleDesc = RelationGetDescr(relation);
1201  constr = tupleDesc->constr;
1202 
1203  /*
1204  * Open the newly-created child relation; we have lock on that too.
1205  */
1206  childrel = relation_openrv(heapRel, NoLock);
1207 
1208  /*
1209  * Construct a map from the LIKE relation's attnos to the child rel's.
1210  * This re-checks type match etc, although it shouldn't be possible to
1211  * have a failure since both tables are locked.
1212  */
1213  attmap = build_attrmap_by_name(RelationGetDescr(childrel),
1214  tupleDesc);
1215 
1216  /*
1217  * Process defaults, if required.
1218  */
1219  if ((table_like_clause->options &
1221  constr != NULL)
1222  {
1223  AttrDefault *attrdef = constr->defval;
1224 
1225  for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1226  parent_attno++)
1227  {
1228  Form_pg_attribute attribute = TupleDescAttr(tupleDesc,
1229  parent_attno - 1);
1230 
1231  /*
1232  * Ignore dropped columns in the parent.
1233  */
1234  if (attribute->attisdropped)
1235  continue;
1236 
1237  /*
1238  * Copy default, if present and it should be copied. We have
1239  * separate options for plain default expressions and GENERATED
1240  * defaults.
1241  */
1242  if (attribute->atthasdef &&
1243  (attribute->attgenerated ?
1244  (table_like_clause->options & CREATE_TABLE_LIKE_GENERATED) :
1245  (table_like_clause->options & CREATE_TABLE_LIKE_DEFAULTS)))
1246  {
1247  Node *this_default = NULL;
1248  AlterTableCmd *atsubcmd;
1249  bool found_whole_row;
1250 
1251  /* Find default in constraint structure */
1252  for (int i = 0; i < constr->num_defval; i++)
1253  {
1254  if (attrdef[i].adnum == parent_attno)
1255  {
1256  this_default = stringToNode(attrdef[i].adbin);
1257  break;
1258  }
1259  }
1260  Assert(this_default != NULL);
1261 
1262  atsubcmd = makeNode(AlterTableCmd);
1263  atsubcmd->subtype = AT_CookedColumnDefault;
1264  atsubcmd->num = attmap->attnums[parent_attno - 1];
1265  atsubcmd->def = map_variable_attnos(this_default,
1266  1, 0,
1267  attmap,
1268  InvalidOid,
1269  &found_whole_row);
1270 
1271  /*
1272  * Prevent this for the same reason as for constraints below.
1273  * Note that defaults cannot contain any vars, so it's OK that
1274  * the error message refers to generated columns.
1275  */
1276  if (found_whole_row)
1277  ereport(ERROR,
1278  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1279  errmsg("cannot convert whole-row table reference"),
1280  errdetail("Generation expression for column \"%s\" contains a whole-row reference to table \"%s\".",
1281  NameStr(attribute->attname),
1282  RelationGetRelationName(relation))));
1283 
1284  atsubcmds = lappend(atsubcmds, atsubcmd);
1285  }
1286  }
1287  }
1288 
1289  /*
1290  * Copy CHECK constraints if requested, being careful to adjust attribute
1291  * numbers so they match the child.
1292  */
1293  if ((table_like_clause->options & CREATE_TABLE_LIKE_CONSTRAINTS) &&
1294  constr != NULL)
1295  {
1296  int ccnum;
1297 
1298  for (ccnum = 0; ccnum < constr->num_check; ccnum++)
1299  {
1300  char *ccname = constr->check[ccnum].ccname;
1301  char *ccbin = constr->check[ccnum].ccbin;
1302  bool ccnoinherit = constr->check[ccnum].ccnoinherit;
1303  Node *ccbin_node;
1304  bool found_whole_row;
1305  Constraint *n;
1306  AlterTableCmd *atsubcmd;
1307 
1308  ccbin_node = map_variable_attnos(stringToNode(ccbin),
1309  1, 0,
1310  attmap,
1311  InvalidOid, &found_whole_row);
1312 
1313  /*
1314  * We reject whole-row variables because the whole point of LIKE
1315  * is that the new table's rowtype might later diverge from the
1316  * parent's. So, while translation might be possible right now,
1317  * it wouldn't be possible to guarantee it would work in future.
1318  */
1319  if (found_whole_row)
1320  ereport(ERROR,
1321  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1322  errmsg("cannot convert whole-row table reference"),
1323  errdetail("Constraint \"%s\" contains a whole-row reference to table \"%s\".",
1324  ccname,
1325  RelationGetRelationName(relation))));
1326 
1327  n = makeNode(Constraint);
1328  n->contype = CONSTR_CHECK;
1329  n->conname = pstrdup(ccname);
1330  n->location = -1;
1331  n->is_no_inherit = ccnoinherit;
1332  n->raw_expr = NULL;
1333  n->cooked_expr = nodeToString(ccbin_node);
1334 
1335  /* We can skip validation, since the new table should be empty. */
1336  n->skip_validation = true;
1337  n->initially_valid = true;
1338 
1339  atsubcmd = makeNode(AlterTableCmd);
1340  atsubcmd->subtype = AT_AddConstraint;
1341  atsubcmd->def = (Node *) n;
1342  atsubcmds = lappend(atsubcmds, atsubcmd);
1343 
1344  /* Copy comment on constraint */
1345  if ((table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS) &&
1347  n->conname, false),
1348  ConstraintRelationId,
1349  0)) != NULL)
1350  {
1351  CommentStmt *stmt = makeNode(CommentStmt);
1352 
1353  stmt->objtype = OBJECT_TABCONSTRAINT;
1354  stmt->object = (Node *) list_make3(makeString(heapRel->schemaname),
1355  makeString(heapRel->relname),
1356  makeString(n->conname));
1357  stmt->comment = comment;
1358 
1359  result = lappend(result, stmt);
1360  }
1361  }
1362  }
1363 
1364  /*
1365  * If we generated any ALTER TABLE actions above, wrap them into a single
1366  * ALTER TABLE command. Stick it at the front of the result, so it runs
1367  * before any CommentStmts we made above.
1368  */
1369  if (atsubcmds)
1370  {
1372 
1373  atcmd->relation = copyObject(heapRel);
1374  atcmd->cmds = atsubcmds;
1375  atcmd->objtype = OBJECT_TABLE;
1376  atcmd->missing_ok = false;
1377  result = lcons(atcmd, result);
1378  }
1379 
1380  /*
1381  * Process indexes if required.
1382  */
1383  if ((table_like_clause->options & CREATE_TABLE_LIKE_INDEXES) &&
1384  relation->rd_rel->relhasindex)
1385  {
1386  List *parent_indexes;
1387  ListCell *l;
1388 
1389  parent_indexes = RelationGetIndexList(relation);
1390 
1391  foreach(l, parent_indexes)
1392  {
1393  Oid parent_index_oid = lfirst_oid(l);
1394  Relation parent_index;
1395  IndexStmt *index_stmt;
1396 
1397  parent_index = index_open(parent_index_oid, AccessShareLock);
1398 
1399  /* Build CREATE INDEX statement to recreate the parent_index */
1400  index_stmt = generateClonedIndexStmt(heapRel,
1401  parent_index,
1402  attmap,
1403  NULL);
1404 
1405  /* Copy comment on index, if requested */
1406  if (table_like_clause->options & CREATE_TABLE_LIKE_COMMENTS)
1407  {
1408  comment = GetComment(parent_index_oid, RelationRelationId, 0);
1409 
1410  /*
1411  * We make use of IndexStmt's idxcomment option, so as not to
1412  * need to know now what name the index will have.
1413  */
1414  index_stmt->idxcomment = comment;
1415  }
1416 
1417  result = lappend(result, index_stmt);
1418 
1419  index_close(parent_index, AccessShareLock);
1420  }
1421  }
1422 
1423  /* Done with child rel */
1424  table_close(childrel, NoLock);
1425 
1426  /*
1427  * Close the parent rel, but keep our AccessShareLock on it until xact
1428  * commit. That will prevent someone else from deleting or ALTERing the
1429  * parent before the child is committed.
1430  */
1431  table_close(relation, NoLock);
1432 
1433  return result;
1434 }
ObjectType objtype
Definition: parsenodes.h:2697
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:483
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:2178
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:704
void * stringToNode(const char *str)
Definition: read.c:89
AlterTableType subtype
Definition: parsenodes.h:1889
char * comment
Definition: parsenodes.h:2699
char * conname
Definition: parsenodes.h:2171
Node * object
Definition: parsenodes.h:2698
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:110
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:698
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:45
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
TupleConstr * constr
Definition: tupdesc.h:85
int errdetail(const char *fmt,...)
Definition: elog.c:1048
char * ccname
Definition: tupdesc.h:30
#define RelationGetRelationName(relation)
Definition: rel.h:491
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:1803
List * lappend(List *list, void *datum)
Definition: list.c:336
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:2177
bool initially_valid
Definition: parsenodes.h:2214
#define ereport(elevel,...)
Definition: elog.h:155
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: attmap.c:174
List * lcons(void *datum, List *list)
Definition: list.c:468
#define makeNode(_type_)
Definition: nodes.h:576
#define Assert(condition)
Definition: c.h:792
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
AttrNumber * attnums
Definition: attmap.h:36
char * idxcomment
Definition: parsenodes.h:2802
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4526
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
uint16 num_defval
Definition: tupdesc.h:42
int errmsg(const char *fmt,...)
Definition: elog.c:915
RangeVar * relation
Definition: parsenodes.h:1801
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:669
char * nodeToString(const void *obj)
Definition: outfuncs.c:4390
ConstrType contype
Definition: parsenodes.h:2168
ConstrCheck * check
Definition: tupdesc.h:40
char * cooked_expr
Definition: parsenodes.h:2179
#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:2213
#define RelationGetRelid(relation)
Definition: rel.h:457
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 1858 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().

1860 {
1861  HeapTuple ht_stats;
1862  Form_pg_statistic_ext statsrec;
1863  CreateStatsStmt *stats;
1864  List *stat_types = NIL;
1865  List *def_names = NIL;
1866  bool isnull;
1867  Datum datum;
1868  ArrayType *arr;
1869  char *enabled;
1870  int i;
1871 
1872  Assert(OidIsValid(heapRelid));
1873  Assert(heapRel != NULL);
1874 
1875  /*
1876  * Fetch pg_statistic_ext tuple of source statistics object.
1877  */
1878  ht_stats = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(source_statsid));
1879  if (!HeapTupleIsValid(ht_stats))
1880  elog(ERROR, "cache lookup failed for statistics object %u", source_statsid);
1881  statsrec = (Form_pg_statistic_ext) GETSTRUCT(ht_stats);
1882 
1883  /* Determine which statistics types exist */
1884  datum = SysCacheGetAttr(STATEXTOID, ht_stats,
1885  Anum_pg_statistic_ext_stxkind, &isnull);
1886  Assert(!isnull);
1887  arr = DatumGetArrayTypeP(datum);
1888  if (ARR_NDIM(arr) != 1 ||
1889  ARR_HASNULL(arr) ||
1890  ARR_ELEMTYPE(arr) != CHAROID)
1891  elog(ERROR, "stxkind is not a 1-D char array");
1892  enabled = (char *) ARR_DATA_PTR(arr);
1893  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
1894  {
1895  if (enabled[i] == STATS_EXT_NDISTINCT)
1896  stat_types = lappend(stat_types, makeString("ndistinct"));
1897  else if (enabled[i] == STATS_EXT_DEPENDENCIES)
1898  stat_types = lappend(stat_types, makeString("dependencies"));
1899  else if (enabled[i] == STATS_EXT_MCV)
1900  stat_types = lappend(stat_types, makeString("mcv"));
1901  else
1902  elog(ERROR, "unrecognized statistics kind %c", enabled[i]);
1903  }
1904 
1905  /* Determine which columns the statistics are on */
1906  for (i = 0; i < statsrec->stxkeys.dim1; i++)
1907  {
1908  ColumnRef *cref = makeNode(ColumnRef);
1909  AttrNumber attnum = statsrec->stxkeys.values[i];
1910 
1911  cref->fields = list_make1(makeString(get_attname(heapRelid,
1912  attnum, false)));
1913  cref->location = -1;
1914 
1915  def_names = lappend(def_names, cref);
1916  }
1917 
1918  /* finally, build the output node */
1919  stats = makeNode(CreateStatsStmt);
1920  stats->defnames = NULL;
1921  stats->stat_types = stat_types;
1922  stats->exprs = def_names;
1923  stats->relations = list_make1(heapRel);
1924  stats->stxcomment = NULL;
1925  stats->if_not_exists = false;
1926 
1927  /* Clean up */
1928  ReleaseSysCache(ht_stats);
1929 
1930  return stats;
1931 }
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:698
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:45
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define ARR_HASNULL(a)
Definition: array.h:284
List * lappend(List *list, void *datum)
Definition: list.c:336
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
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:792
#define ARR_NDIM(a)
Definition: array.h:283
#define elog(elevel,...)
Definition: elog.h:228
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:285
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:254

◆ generateClonedIndexStmt()

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

Definition at line 1500 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().

1503 {
1504  Oid source_relid = RelationGetRelid(source_idx);
1505  HeapTuple ht_idxrel;
1506  HeapTuple ht_idx;
1507  HeapTuple ht_am;
1508  Form_pg_class idxrelrec;
1509  Form_pg_index idxrec;
1510  Form_pg_am amrec;
1511  oidvector *indcollation;
1512  oidvector *indclass;
1513  IndexStmt *index;
1514  List *indexprs;
1515  ListCell *indexpr_item;
1516  Oid indrelid;
1517  int keyno;
1518  Oid keycoltype;
1519  Datum datum;
1520  bool isnull;
1521 
1522  if (constraintOid)
1523  *constraintOid = InvalidOid;
1524 
1525  /*
1526  * Fetch pg_class tuple of source index. We can't use the copy in the
1527  * relcache entry because it doesn't include optional fields.
1528  */
1529  ht_idxrel = SearchSysCache1(RELOID, ObjectIdGetDatum(source_relid));
1530  if (!HeapTupleIsValid(ht_idxrel))
1531  elog(ERROR, "cache lookup failed for relation %u", source_relid);
1532  idxrelrec = (Form_pg_class) GETSTRUCT(ht_idxrel);
1533 
1534  /* Fetch pg_index tuple for source index from relcache entry */
1535  ht_idx = source_idx->rd_indextuple;
1536  idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
1537  indrelid = idxrec->indrelid;
1538 
1539  /* Fetch the pg_am tuple of the index' access method */
1540  ht_am = SearchSysCache1(AMOID, ObjectIdGetDatum(idxrelrec->relam));
1541  if (!HeapTupleIsValid(ht_am))
1542  elog(ERROR, "cache lookup failed for access method %u",
1543  idxrelrec->relam);
1544  amrec = (Form_pg_am) GETSTRUCT(ht_am);
1545 
1546  /* Extract indcollation from the pg_index tuple */
1547  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1548  Anum_pg_index_indcollation, &isnull);
1549  Assert(!isnull);
1550  indcollation = (oidvector *) DatumGetPointer(datum);
1551 
1552  /* Extract indclass from the pg_index tuple */
1553  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1554  Anum_pg_index_indclass, &isnull);
1555  Assert(!isnull);
1556  indclass = (oidvector *) DatumGetPointer(datum);
1557 
1558  /* Begin building the IndexStmt */
1559  index = makeNode(IndexStmt);
1560  index->relation = heapRel;
1561  index->accessMethod = pstrdup(NameStr(amrec->amname));
1562  if (OidIsValid(idxrelrec->reltablespace))
1563  index->tableSpace = get_tablespace_name(idxrelrec->reltablespace);
1564  else
1565  index->tableSpace = NULL;
1566  index->excludeOpNames = NIL;
1567  index->idxcomment = NULL;
1568  index->indexOid = InvalidOid;
1569  index->oldNode = InvalidOid;
1572  index->unique = idxrec->indisunique;
1573  index->primary = idxrec->indisprimary;
1574  index->transformed = true; /* don't need transformIndexStmt */
1575  index->concurrent = false;
1576  index->if_not_exists = false;
1577  index->reset_default_tblspc = false;
1578 
1579  /*
1580  * We don't try to preserve the name of the source index; instead, just
1581  * let DefineIndex() choose a reasonable name. (If we tried to preserve
1582  * the name, we'd get duplicate-relation-name failures unless the source
1583  * table was in a different schema.)
1584  */
1585  index->idxname = NULL;
1586 
1587  /*
1588  * If the index is marked PRIMARY or has an exclusion condition, it's
1589  * certainly from a constraint; else, if it's not marked UNIQUE, it
1590  * certainly isn't. If it is or might be from a constraint, we have to
1591  * fetch the pg_constraint record.
1592  */
1593  if (index->primary || index->unique || idxrec->indisexclusion)
1594  {
1595  Oid constraintId = get_index_constraint(source_relid);
1596 
1597  if (OidIsValid(constraintId))
1598  {
1599  HeapTuple ht_constr;
1600  Form_pg_constraint conrec;
1601 
1602  if (constraintOid)
1603  *constraintOid = constraintId;
1604 
1605  ht_constr = SearchSysCache1(CONSTROID,
1606  ObjectIdGetDatum(constraintId));
1607  if (!HeapTupleIsValid(ht_constr))
1608  elog(ERROR, "cache lookup failed for constraint %u",
1609  constraintId);
1610  conrec = (Form_pg_constraint) GETSTRUCT(ht_constr);
1611 
1612  index->isconstraint = true;
1613  index->deferrable = conrec->condeferrable;
1614  index->initdeferred = conrec->condeferred;
1615 
1616  /* If it's an exclusion constraint, we need the operator names */
1617  if (idxrec->indisexclusion)
1618  {
1619  Datum *elems;
1620  int nElems;
1621  int i;
1622 
1623  Assert(conrec->contype == CONSTRAINT_EXCLUSION);
1624  /* Extract operator OIDs from the pg_constraint tuple */
1625  datum = SysCacheGetAttr(CONSTROID, ht_constr,
1626  Anum_pg_constraint_conexclop,
1627  &isnull);
1628  if (isnull)
1629  elog(ERROR, "null conexclop for constraint %u",
1630  constraintId);
1631 
1633  OIDOID, sizeof(Oid), true, TYPALIGN_INT,
1634  &elems, NULL, &nElems);
1635 
1636  for (i = 0; i < nElems; i++)
1637  {
1638  Oid operid = DatumGetObjectId(elems[i]);
1639  HeapTuple opertup;
1640  Form_pg_operator operform;
1641  char *oprname;
1642  char *nspname;
1643  List *namelist;
1644 
1645  opertup = SearchSysCache1(OPEROID,
1646  ObjectIdGetDatum(operid));
1647  if (!HeapTupleIsValid(opertup))
1648  elog(ERROR, "cache lookup failed for operator %u",
1649  operid);
1650  operform = (Form_pg_operator) GETSTRUCT(opertup);
1651  oprname = pstrdup(NameStr(operform->oprname));
1652  /* For simplicity we always schema-qualify the op name */
1653  nspname = get_namespace_name(operform->oprnamespace);
1654  namelist = list_make2(makeString(nspname),
1655  makeString(oprname));
1656  index->excludeOpNames = lappend(index->excludeOpNames,
1657  namelist);
1658  ReleaseSysCache(opertup);
1659  }
1660  }
1661 
1662  ReleaseSysCache(ht_constr);
1663  }
1664  else
1665  index->isconstraint = false;
1666  }
1667  else
1668  index->isconstraint = false;
1669 
1670  /* Get the index expressions, if any */
1671  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1672  Anum_pg_index_indexprs, &isnull);
1673  if (!isnull)
1674  {
1675  char *exprsString;
1676 
1677  exprsString = TextDatumGetCString(datum);
1678  indexprs = (List *) stringToNode(exprsString);
1679  }
1680  else
1681  indexprs = NIL;
1682 
1683  /* Build the list of IndexElem */
1684  index->indexParams = NIL;
1685  index->indexIncludingParams = NIL;
1686 
1687  indexpr_item = list_head(indexprs);
1688  for (keyno = 0; keyno < idxrec->indnkeyatts; keyno++)
1689  {
1690  IndexElem *iparam;
1691  AttrNumber attnum = idxrec->indkey.values[keyno];
1693  keyno);
1694  int16 opt = source_idx->rd_indoption[keyno];
1695 
1696  iparam = makeNode(IndexElem);
1697 
1698  if (AttributeNumberIsValid(attnum))
1699  {
1700  /* Simple index column */
1701  char *attname;
1702 
1703  attname = get_attname(indrelid, attnum, false);
1704  keycoltype = get_atttype(indrelid, attnum);
1705 
1706  iparam->name = attname;
1707  iparam->expr = NULL;
1708  }
1709  else
1710  {
1711  /* Expressional index */
1712  Node *indexkey;
1713  bool found_whole_row;
1714 
1715  if (indexpr_item == NULL)
1716  elog(ERROR, "too few entries in indexprs list");
1717  indexkey = (Node *) lfirst(indexpr_item);
1718  indexpr_item = lnext(indexprs, indexpr_item);
1719 
1720  /* Adjust Vars to match new table's column numbering */
1721  indexkey = map_variable_attnos(indexkey,
1722  1, 0,
1723  attmap,
1724  InvalidOid, &found_whole_row);
1725 
1726  /* As in expandTableLikeClause, reject whole-row variables */
1727  if (found_whole_row)
1728  ereport(ERROR,
1729  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1730  errmsg("cannot convert whole-row table reference"),
1731  errdetail("Index \"%s\" contains a whole-row table reference.",
1732  RelationGetRelationName(source_idx))));
1733 
1734  iparam->name = NULL;
1735  iparam->expr = indexkey;
1736 
1737  keycoltype = exprType(indexkey);
1738  }
1739 
1740  /* Copy the original index column name */
1741  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1742 
1743  /* Add the collation name, if non-default */
1744  iparam->collation = get_collation(indcollation->values[keyno], keycoltype);
1745 
1746  /* Add the operator class name, if non-default */
1747  iparam->opclass = get_opclass(indclass->values[keyno], keycoltype);
1748  iparam->opclassopts =
1749  untransformRelOptions(get_attoptions(source_relid, keyno + 1));
1750 
1751  iparam->ordering = SORTBY_DEFAULT;
1753 
1754  /* Adjust options if necessary */
1755  if (source_idx->rd_indam->amcanorder)
1756  {
1757  /*
1758  * If it supports sort ordering, copy DESC and NULLS opts. Don't
1759  * set non-default settings unnecessarily, though, so as to
1760  * improve the chance of recognizing equivalence to constraint
1761  * indexes.
1762  */
1763  if (opt & INDOPTION_DESC)
1764  {
1765  iparam->ordering = SORTBY_DESC;
1766  if ((opt & INDOPTION_NULLS_FIRST) == 0)
1768  }
1769  else
1770  {
1771  if (opt & INDOPTION_NULLS_FIRST)
1773  }
1774  }
1775 
1776  index->indexParams = lappend(index->indexParams, iparam);
1777  }
1778 
1779  /* Handle included columns separately */
1780  for (keyno = idxrec->indnkeyatts; keyno < idxrec->indnatts; keyno++)
1781  {
1782  IndexElem *iparam;
1783  AttrNumber attnum = idxrec->indkey.values[keyno];
1785  keyno);
1786 
1787  iparam = makeNode(IndexElem);
1788 
1789  if (AttributeNumberIsValid(attnum))
1790  {
1791  /* Simple index column */
1792  char *attname;
1793 
1794  attname = get_attname(indrelid, attnum, false);
1795 
1796  iparam->name = attname;
1797  iparam->expr = NULL;
1798  }
1799  else
1800  ereport(ERROR,
1801  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1802  errmsg("expressions are not supported in included columns")));
1803 
1804  /* Copy the original index column name */
1805  iparam->indexcolname = pstrdup(NameStr(attr->attname));
1806 
1807  index->indexIncludingParams = lappend(index->indexIncludingParams, iparam);
1808  }
1809  /* Copy reloptions if any */
1810  datum = SysCacheGetAttr(RELOID, ht_idxrel,
1811  Anum_pg_class_reloptions, &isnull);
1812  if (!isnull)
1813  index->options = untransformRelOptions(datum);
1814 
1815  /* If it's a partial index, decompile and append the predicate */
1816  datum = SysCacheGetAttr(INDEXRELID, ht_idx,
1817  Anum_pg_index_indpred, &isnull);
1818  if (!isnull)
1819  {
1820  char *pred_str;
1821  Node *pred_tree;
1822  bool found_whole_row;
1823 
1824  /* Convert text string to node tree */
1825  pred_str = TextDatumGetCString(datum);
1826  pred_tree = (Node *) stringToNode(pred_str);
1827 
1828  /* Adjust Vars to match new table's column numbering */
1829  pred_tree = map_variable_attnos(pred_tree,
1830  1, 0,
1831  attmap,
1832  InvalidOid, &found_whole_row);
1833 
1834  /* As in expandTableLikeClause, reject whole-row variables */
1835  if (found_whole_row)
1836  ereport(ERROR,
1837  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1838  errmsg("cannot convert whole-row table reference"),
1839  errdetail("Index \"%s\" contains a whole-row table reference.",
1840  RelationGetRelationName(source_idx))));
1841 
1842  index->whereClause = pred_tree;
1843  }
1844 
1845  /* Clean up */
1846  ReleaseSysCache(ht_idxrel);
1847  ReleaseSysCache(ht_am);
1848 
1849  return index;
1850 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
bool deferrable
Definition: parsenodes.h:2811
Value * makeString(char *str)
Definition: value.c:53
signed short int16
Definition: c.h:416
#define NIL
Definition: pg_list.h:65
static List * get_opclass(Oid opclass, Oid actual_datatype)
Definition: c.h:648
bool primary
Definition: parsenodes.h:2809
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
int16 * rd_indoption
Definition: rel.h:194
SortByDir ordering
Definition: parsenodes.h:707
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Definition: syscache.h:36
List * options
Definition: parsenodes.h:2799
SubTransactionId oldCreateSubid
Definition: parsenodes.h:2805
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define RelationGetDescr(relation)
Definition: rel.h:483
char * tableSpace
Definition: parsenodes.h:2795
#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:2800
Definition: nodes.h:528
int errcode(int sqlerrcode)
Definition: elog.c:704
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:698
List * opclassopts
Definition: parsenodes.h:706
struct HeapTupleData * rd_indextuple
Definition: rel.h:177
List * indexIncludingParams
Definition: parsenodes.h:2797
Definition: type.h:89
Oid indexOid
Definition: parsenodes.h:2803
Node * expr
Definition: parsenodes.h:702
RangeVar * relation
Definition: parsenodes.h:2793
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:45
NameData attname
Definition: pg_attribute.h:40
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
Oid values[FLEXIBLE_ARRAY_MEMBER]
Definition: c.h:656
bool transformed
Definition: parsenodes.h:2813
int errdetail(const char *fmt,...)
Definition: elog.c:1048
char * indexcolname
Definition: parsenodes.h:703
#define RelationGetRelationName(relation)
Definition: rel.h:491
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:978
SubTransactionId oldFirstRelfilenodeSubid
Definition: parsenodes.h:2806
Oid get_atttype(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:911
List * lappend(List *list, void *datum)
Definition: list.c:336
char * idxname
Definition: parsenodes.h:2792
FormData_pg_index * Form_pg_index
Definition: pg_index.h:68
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define TextDatumGetCString(d)
Definition: builtins.h:83
bool reset_default_tblspc
Definition: parsenodes.h:2816
bool if_not_exists
Definition: parsenodes.h:2815
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
bool unique
Definition: parsenodes.h:2808
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1308
char * accessMethod
Definition: parsenodes.h:2794
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:155
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:792
#define lfirst(lc)
Definition: pg_list.h:169
List * indexParams
Definition: parsenodes.h:2796
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
List * excludeOpNames
Definition: parsenodes.h:2801
bool initdeferred
Definition: parsenodes.h:2812
bool amcanorder
Definition: amapi.h:220
char * name
Definition: parsenodes.h:701
char * idxcomment
Definition: parsenodes.h:2802
#define InvalidSubTransactionId
Definition: c.h:581
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:3488
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
bool concurrent
Definition: parsenodes.h:2814
bool isconstraint
Definition: parsenodes.h:2810
FormData_pg_am * Form_pg_am
Definition: pg_am.h:48
int errmsg(const char *fmt,...)
Definition: elog.c:915
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1479
#define elog(elevel,...)
Definition: elog.h:228
int i
#define NameStr(name)
Definition: c.h:669
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:457
#define DatumGetArrayTypeP(X)
Definition: array.h:254

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

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

◆ get_collation()

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

Definition at line 1940 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().

1941 {
1942  List *result;
1943  HeapTuple ht_coll;
1944  Form_pg_collation coll_rec;
1945  char *nsp_name;
1946  char *coll_name;
1947 
1948  if (!OidIsValid(collation))
1949  return NIL; /* easy case */
1950  if (collation == get_typcollation(actual_datatype))
1951  return NIL; /* just let it default */
1952 
1953  ht_coll = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1954  if (!HeapTupleIsValid(ht_coll))
1955  elog(ERROR, "cache lookup failed for collation %u", collation);
1956  coll_rec = (Form_pg_collation) GETSTRUCT(ht_coll);
1957 
1958  /* For simplicity, we always schema-qualify the name */
1959  nsp_name = get_namespace_name(coll_rec->collnamespace);
1960  coll_name = pstrdup(NameStr(coll_rec->collname));
1961  result = list_make2(makeString(nsp_name), makeString(coll_name));
1962 
1963  ReleaseSysCache(ht_coll);
1964  return result;
1965 }
#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:698
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2976
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:47
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:669
Definition: pg_list.h:50

◆ get_opclass()

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

Definition at line 1974 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().

1975 {
1976  List *result = NIL;
1977  HeapTuple ht_opc;
1978  Form_pg_opclass opc_rec;
1979 
1980  ht_opc = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1981  if (!HeapTupleIsValid(ht_opc))
1982  elog(ERROR, "cache lookup failed for opclass %u", opclass);
1983  opc_rec = (Form_pg_opclass) GETSTRUCT(ht_opc);
1984 
1985  if (GetDefaultOpClass(actual_datatype, opc_rec->opcmethod) != opclass)
1986  {
1987  /* For simplicity, we always schema-qualify the name */
1988  char *nsp_name = get_namespace_name(opc_rec->opcnamespace);
1989  char *opc_name = pstrdup(NameStr(opc_rec->opcname));
1990 
1991  result = list_make2(makeString(nsp_name), makeString(opc_name));
1992  }
1993 
1994  ReleaseSysCache(ht_opc);
1995  return result;
1996 }
#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:2090
#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:45
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:669
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 3815 of file parse_utilcmd.c.

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

Referenced by transformCreateSchemaStmt().

3816 {
3817  if (*stmt_schema_name == NULL)
3818  *stmt_schema_name = context_schema;
3819  else if (strcmp(context_schema, *stmt_schema_name) != 0)
3820  ereport(ERROR,
3821  (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3822  errmsg("CREATE specifies a schema (%s) "
3823  "different from the one being created (%s)",
3824  *stmt_schema_name, context_schema)));
3825 }
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ transformAlterTableStmt()

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

Definition at line 3175 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, CreateStmtContext::likeclauses, 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().

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

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2658 {
2659  ListCell *ckclist;
2660 
2661  if (cxt->ckconstraints == NIL)
2662  return;
2663 
2664  /*
2665  * If creating a new table (but not a foreign table), we can safely skip
2666  * validation of check constraints, and nonetheless mark them valid. (This
2667  * will override any user-supplied NOT VALID flag.)
2668  */
2669  if (skipValidation)
2670  {
2671  foreach(ckclist, cxt->ckconstraints)
2672  {
2673  Constraint *constraint = (Constraint *) lfirst(ckclist);
2674 
2675  constraint->skip_validation = true;
2676  constraint->initially_valid = true;
2677  }
2678  }
2679 }
#define NIL
Definition: pg_list.h:65
bool initially_valid
Definition: parsenodes.h:2214
#define lfirst(lc)
Definition: pg_list.h:169
bool skip_validation
Definition: parsenodes.h:2213

◆ transformColumnDefinition()

static void transformColumnDefinition ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 528 of file parse_utilcmd.c.

References CreateStmtContext::alist, TypeCast::arg, TypeName::arrayBounds, Assert, AT_AlterColumnGenericOptions, AlterTableCmd::behavior, CreateStmtContext::ckconstraints, AlterTableStmt::cmds, COERCE_EXPLICIT_CALL, ColumnDef::colname, CreateStmtContext::columns, CONSTR_ATTR_DEFERRABLE, CONSTR_ATTR_DEFERRED, CONSTR_ATTR_IMMEDIATE, CONSTR_ATTR_NOT_DEFERRABLE, CONSTR_CHECK, CONSTR_DEFAULT, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_GENERATED, CONSTR_IDENTITY, CONSTR_NOTNULL, CONSTR_NULL, CONSTR_PRIMARY, CONSTR_UNIQUE, ColumnDef::constraints, Constraint::contype, Constraint::cooked_expr, AlterTableCmd::def, DROP_RESTRICT, elog, ereport, errcode(), errmsg(), ERROR, ColumnDef::fdwoptions, Constraint::fk_attrs, CreateStmtContext::fkconstraints, ColumnDef::generated, Constraint::generated_when, generateSerialExtraStmts(), GETSTRUCT, ColumnDef::identity, ColumnDef::is_not_null, CreateStmtContext::isforeign, CreateStmtContext::ixconstraints, Constraint::keys, lappend(), lfirst_node, linitial, list_length(), list_make1, TypeName::location, A_Const::location, TypeCast::location, Constraint::location, makeFuncCall(), makeNode, makeString(), AlterTableCmd::missing_ok, AlterTableCmd::name, TypeName::names, NIL, 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().

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

◆ transformColumnType()

static void transformColumnType ( CreateStmtContext cxt,
ColumnDef column 
)
static

Definition at line 3657 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().

3658 {
3659  /*
3660  * All we really need to do here is verify that the type is valid,
3661  * including any collation spec that might be present.
3662  */
3663  Type ctype = typenameType(cxt->pstate, column->typeName, NULL);
3664 
3665  if (column->collClause)
3666  {
3667  Form_pg_type typtup = (Form_pg_type) GETSTRUCT(ctype);
3668 
3669  LookupCollation(cxt->pstate,
3670  column->collClause->collname,
3671  column->collClause->location);
3672  /* Complain if COLLATE is applied to an uncollatable type */
3673  if (!OidIsValid(typtup->typcollation))
3674  ereport(ERROR,
3675  (errcode(ERRCODE_DATATYPE_MISMATCH),
3676  errmsg("collations are not supported by type %s",
3677  format_type_be(typtup->oid)),
3679  column->collClause->location)));
3680  }
3681 
3682  ReleaseSysCache(ctype);
3683 }
#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:704
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define OidIsValid(objectId)
Definition: c.h:698
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:45
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid LookupCollation(ParseState *pstate, List *collnames, int location)
Definition: parse_type.c:513
#define ereport(elevel,...)
Definition: elog.h:155
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
TypeName * typeName
Definition: parsenodes.h:648
CollateClause * collClause
Definition: parsenodes.h:660
List * collname
Definition: parsenodes.h:309
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ transformConstraintAttrs()

static void transformConstraintAttrs ( CreateStmtContext cxt,
List constraintList 
)
static

Definition at line 3542 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().

3543 {
3544  Constraint *lastprimarycon = NULL;
3545  bool saw_deferrability = false;
3546  bool saw_initially = false;
3547  ListCell *clist;
3548 
3549 #define SUPPORTS_ATTRS(node) \
3550  ((node) != NULL && \
3551  ((node)->contype == CONSTR_PRIMARY || \
3552  (node)->contype == CONSTR_UNIQUE || \
3553  (node)->contype == CONSTR_EXCLUSION || \
3554  (node)->contype == CONSTR_FOREIGN))
3555 
3556  foreach(clist, constraintList)
3557  {
3558  Constraint *con = (Constraint *) lfirst(clist);
3559 
3560  if (!IsA(con, Constraint))
3561  elog(ERROR, "unrecognized node type: %d",
3562  (int) nodeTag(con));
3563  switch (con->contype)
3564  {
3566  if (!SUPPORTS_ATTRS(lastprimarycon))
3567  ereport(ERROR,
3568  (errcode(ERRCODE_SYNTAX_ERROR),
3569  errmsg("misplaced DEFERRABLE clause"),
3570  parser_errposition(cxt->pstate, con->location)));
3571  if (saw_deferrability)
3572  ereport(ERROR,
3573  (errcode(ERRCODE_SYNTAX_ERROR),
3574  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3575  parser_errposition(cxt->pstate, con->location)));
3576  saw_deferrability = true;
3577  lastprimarycon->deferrable = true;
3578  break;
3579 
3581  if (!SUPPORTS_ATTRS(lastprimarycon))
3582  ereport(ERROR,
3583  (errcode(ERRCODE_SYNTAX_ERROR),
3584  errmsg("misplaced NOT DEFERRABLE clause"),
3585  parser_errposition(cxt->pstate, con->location)));
3586  if (saw_deferrability)
3587  ereport(ERROR,
3588  (errcode(ERRCODE_SYNTAX_ERROR),
3589  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed"),
3590  parser_errposition(cxt->pstate, con->location)));
3591  saw_deferrability = true;
3592  lastprimarycon->deferrable = false;
3593  if (saw_initially &&
3594  lastprimarycon->initdeferred)
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_DEFERRED:
3602  if (!SUPPORTS_ATTRS(lastprimarycon))
3603  ereport(ERROR,
3604  (errcode(ERRCODE_SYNTAX_ERROR),
3605  errmsg("misplaced INITIALLY DEFERRED 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 = true;
3614 
3615  /*
3616  * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3617  */
3618  if (!saw_deferrability)
3619  lastprimarycon->deferrable = true;
3620  else if (!lastprimarycon->deferrable)
3621  ereport(ERROR,
3622  (errcode(ERRCODE_SYNTAX_ERROR),
3623  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3624  parser_errposition(cxt->pstate, con->location)));
3625  break;
3626 
3627  case CONSTR_ATTR_IMMEDIATE:
3628  if (!SUPPORTS_ATTRS(lastprimarycon))
3629  ereport(ERROR,
3630  (errcode(ERRCODE_SYNTAX_ERROR),
3631  errmsg("misplaced INITIALLY IMMEDIATE clause"),
3632  parser_errposition(cxt->pstate, con->location)));
3633  if (saw_initially)
3634  ereport(ERROR,
3635  (errcode(ERRCODE_SYNTAX_ERROR),
3636  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed"),
3637  parser_errposition(cxt->pstate, con->location)));
3638  saw_initially = true;
3639  lastprimarycon->initdeferred = false;
3640  break;
3641 
3642  default:
3643  /* Otherwise it's not an attribute */
3644  lastprimarycon = con;
3645  /* reset flags for new primary node */
3646  saw_deferrability = false;
3647  saw_initially = false;
3648  break;
3649  }
3650  }
3651 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
int errcode(int sqlerrcode)
Definition: elog.c:704
bool initdeferred
Definition: parsenodes.h:2173
ParseState * pstate
Definition: parse_utilcmd.c:78
#define ERROR
Definition: elog.h:45
bool deferrable
Definition: parsenodes.h:2172
#define ereport(elevel,...)
Definition: elog.h:155
#define lfirst(lc)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define nodeTag(nodeptr)
Definition: nodes.h:533
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define SUPPORTS_ATTRS(node)
#define elog(elevel,...)
Definition: elog.h:228
ConstrType contype
Definition: parsenodes.h:2168

◆ transformCreateSchemaStmt()

List* transformCreateSchemaStmt ( CreateSchemaStmt stmt)

Definition at line 3710 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().

3711 {
3713  List *result;
3714  ListCell *elements;
3715 
3716  cxt.stmtType = "CREATE SCHEMA";
3717  cxt.schemaname = stmt->schemaname;
3718  cxt.authrole = (RoleSpec *) stmt->authrole;
3719  cxt.sequences = NIL;
3720  cxt.tables = NIL;
3721  cxt.views = NIL;
3722  cxt.indexes = NIL;
3723  cxt.triggers = NIL;
3724  cxt.grants = NIL;
3725 
3726  /*
3727  * Run through each schema element in the schema element list. Separate
3728  * statements by type, and do preliminary analysis.
3729  */
3730  foreach(elements, stmt->schemaElts)
3731  {
3732  Node *element = lfirst(elements);
3733 
3734  switch (nodeTag(element))
3735  {
3736  case T_CreateSeqStmt:
3737  {
3738  CreateSeqStmt *elp = (CreateSeqStmt *) element;
3739 
3741  cxt.sequences = lappend(cxt.sequences, element);
3742  }
3743  break;
3744 
3745  case T_CreateStmt:
3746  {
3747  CreateStmt *elp = (CreateStmt *) element;
3748 
3750 
3751  /*
3752  * XXX todo: deal with constraints
3753  */
3754  cxt.tables = lappend(cxt.tables, element);
3755  }
3756  break;
3757 
3758  case T_ViewStmt:
3759  {
3760  ViewStmt *elp = (ViewStmt *) element;
3761 
3762  setSchemaName(cxt.schemaname, &elp->view->schemaname);
3763 
3764  /*
3765  * XXX todo: deal with references between views
3766  */
3767  cxt.views = lappend(cxt.views, element);
3768  }
3769  break;
3770 
3771  case T_IndexStmt:
3772  {
3773  IndexStmt *elp = (IndexStmt *) element;
3774 
3776  cxt.indexes = lappend(cxt.indexes, element);
3777  }
3778  break;
3779 
3780  case T_CreateTrigStmt:
3781  {
3782  CreateTrigStmt *elp = (CreateTrigStmt *) element;
3783 
3785  cxt.triggers = lappend(cxt.triggers, element);
3786  }
3787  break;
3788 
3789  case T_GrantStmt:
3790  cxt.grants = lappend(cxt.grants, element);
3791  break;
3792 
3793  default:
3794  elog(ERROR, "unrecognized node type: %d",
3795  (int) nodeTag(element));
3796  }
3797  }
3798 
3799  result = NIL;
3800  result = list_concat(result, cxt.sequences);
3801  result = list_concat(result, cxt.tables);
3802  result = list_concat(result, cxt.views);
3803  result = list_concat(result, cxt.indexes);
3804  result = list_concat(result, cxt.triggers);
3805  result = list_concat(result, cxt.grants);
3806 
3807  return result;
3808 }
RangeVar * relation
Definition: parsenodes.h:2088
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:528
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
RangeVar * view
Definition: parsenodes.h:3145
char * schemaname
Definition: primnodes.h:67
RangeVar * relation
Definition: parsenodes.h:2793
RoleSpec * authrole
Definition: parsenodes.h:1783
#define ERROR
Definition: elog.h:45
List * lappend(List *list, void *datum)
Definition: list.c:336
static chr element(struct vars *v, const chr *startp, const chr *endp)
Definition: regc_locale.c:380
RangeVar * sequence
Definition: parsenodes.h:2562
#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:228
RangeVar * relation
Definition: parsenodes.h:2449
Definition: pg_list.h:50

◆ transformCreateStmt()

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

Definition at line 168 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, CreateStmtContext::likeclauses, 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().

169 {
170  ParseState *pstate;
171  CreateStmtContext cxt;
172  List *result;
173  List *save_alist;
174  ListCell *elements;
175  Oid namespaceid;
176  Oid existing_relid;
177  ParseCallbackState pcbstate;
178  bool is_foreign_table = IsA(stmt, CreateForeignTableStmt);
179 
180  /*
181  * We must not scribble on the passed-in CreateStmt, so copy it. (This is
182  * overkill, but easy.)
183  */
184  stmt = copyObject(stmt);
185 
186  /* Set up pstate */
187  pstate = make_parsestate(NULL);
188  pstate->p_sourcetext = queryString;
189 
190  /*
191  * Look up the creation namespace. This also checks permissions on the
192  * target namespace, locks it against concurrent drops, checks for a
193  * preexisting relation in that namespace with the same name, and updates
194  * stmt->relation->relpersistence if the selected namespace is temporary.
195  */
196  setup_parser_errposition_callback(&pcbstate, pstate,
197  stmt->relation->location);
198  namespaceid =
200  &existing_relid);
202 
203  /*
204  * If the relation already exists and the user specified "IF NOT EXISTS",
205  * bail out with a NOTICE.
206  */
207  if (stmt->if_not_exists && OidIsValid(existing_relid))
208  {
209  ereport(NOTICE,
210  (errcode(ERRCODE_DUPLICATE_TABLE),
211  errmsg("relation \"%s\" already exists, skipping",
212  stmt->relation->relname)));
213  return NIL;
214  }
215 
216  /*
217  * If the target relation name isn't schema-qualified, make it so. This
218  * prevents some corner cases in which added-on rewritten commands might
219  * think they should apply to other relations that have the same name and
220  * are earlier in the search path. But a local temp table is effectively
221  * specified to be in pg_temp, so no need for anything extra in that case.
222  */
223  if (stmt->relation->schemaname == NULL
224  && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
225  stmt->relation->schemaname = get_namespace_name(namespaceid);
226 
227  /* Set up CreateStmtContext */
228  cxt.pstate = pstate;
229  if (IsA(stmt, CreateForeignTableStmt))
230  {
231  cxt.stmtType = "CREATE FOREIGN TABLE";
232  cxt.isforeign = true;
233  }
234  else
235  {
236  cxt.stmtType = "CREATE TABLE";
237  cxt.isforeign = false;
238  }
239  cxt.relation = stmt->relation;
240  cxt.rel = NULL;
241  cxt.inhRelations = stmt->inhRelations;
242  cxt.isalter = false;
243  cxt.columns = NIL;
244  cxt.ckconstraints = NIL;
245  cxt.fkconstraints = NIL;
246  cxt.ixconstraints = NIL;
247  cxt.likeclauses = NIL;
248  cxt.extstats = NIL;
249  cxt.blist = NIL;
250  cxt.alist = NIL;
251  cxt.pkey = NULL;
252  cxt.ispartitioned = stmt->partspec != NULL;
253  cxt.partbound = stmt->partbound;
254  cxt.ofType = (stmt->ofTypename != NULL);
255 
256  Assert(!stmt->ofTypename || !stmt->inhRelations); /* grammar enforces */
257 
258  if (stmt->ofTypename)
259  transformOfType(&cxt, stmt->ofTypename);
260 
261  if (stmt->partspec)
262  {
263  if (stmt->inhRelations && !stmt->partbound)
264  ereport(ERROR,
265  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
266  errmsg("cannot create partitioned table as inheritance child")));
267  }
268 
269  /*
270  * Run through each primary element in the table creation clause. Separate
271  * column defs from constraints, and do preliminary analysis.
272  */
273  foreach(elements, stmt->tableElts)
274  {
275  Node *element = lfirst(elements);
276 
277  switch (nodeTag(element))
278  {
279  case T_ColumnDef:
280  transformColumnDefinition(&cxt, (ColumnDef *) element);
281  break;
282 
283  case T_Constraint:
284  transformTableConstraint(&cxt, (Constraint *) element);
285  break;
286 
287  case T_TableLikeClause:
288  transformTableLikeClause(&cxt, (TableLikeClause *) element);
289  break;
290 
291  default:
292  elog(ERROR, "unrecognized node type: %d",
293  (int) nodeTag(element));
294  break;
295  }
296  }
297 
298  /*
299  * Transfer anything we already have in cxt.alist into save_alist, to keep
300  * it separate from the output of transformIndexConstraints. (This may
301  * not be necessary anymore, but we'll keep doing it to preserve the
302  * historical order of execution of the alist commands.)
303  */
304  save_alist = cxt.alist;
305  cxt.alist = NIL;
306 
307  Assert(stmt->constraints == NIL);
308 
309  /*
310  * Postprocess constraints that give rise to index definitions.
311  */
313 
314  /*
315  * Re-consideration of LIKE clauses should happen after creation of
316  * indexes, but before creation of foreign keys. This order is critical
317  * because a LIKE clause may attempt to create a primary key. If there's
318  * also a pkey in the main CREATE TABLE list, creation of that will not
319  * check for a duplicate at runtime (since index_check_primary_key()
320  * expects that we rejected dups here). Creation of the LIKE-generated
321  * pkey behaves like ALTER TABLE ADD, so it will check, but obviously that
322  * only works if it happens second. On the other hand, we want to make
323  * pkeys before foreign key constraints, in case the user tries to make a
324  * self-referential FK.
325  */
326  cxt.alist = list_concat(cxt.alist, cxt.likeclauses);
327 
328  /*
329  * Postprocess foreign-key constraints.
330  */
331  transformFKConstraints(&cxt, true, false);
332 
333  /*
334  * Postprocess check constraints.
335  */
336  transformCheckConstraints(&cxt, !is_foreign_table ? true : false);
337 
338  /*
339  * Postprocess extended statistics.
340  */
342 
343  /*
344  * Output results.
345  */
346  stmt->tableElts = cxt.columns;
347  stmt->constraints = cxt.ckconstraints;
348 
349  result = lappend(cxt.blist, stmt);
350  result = list_concat(result, cxt.alist);
351  result = list_concat(result, save_alist);
352 
353  return result;
354 }
RangeVar * relation
Definition: parsenodes.h:2088
#define NIL
Definition: pg_list.h:65
List * inhRelations
Definition: parsenodes.h:2090
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Definition: nodes.h:528
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:704
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:698
char * schemaname
Definition: primnodes.h:67
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
List * constraints
Definition: parsenodes.h:2095
bool if_not_exists
Definition: parsenodes.h:2100
int location
Definition: primnodes.h:73
ParseState * pstate
Definition: parse_utilcmd.c:78
PartitionBoundSpec * partbound
Definition: parsenodes.h:2092
char * relname
Definition: primnodes.h:68
RangeVar * relation
Definition: parse_utilcmd.c:80
IndexStmt * pkey
Definition: parse_utilcmd.c:95
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:161
#define ERROR
Definition: elog.h:45
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
#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:145
PartitionBoundSpec * partbound
Definition: parse_utilcmd.c:97
List * lappend(List *list, void *datum)
Definition: list.c:336
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:155
#define NOTICE
Definition: elog.h:37
List * tableElts
Definition: parsenodes.h:2089
static void transformOfType(CreateStmtContext *cxt, TypeName *ofTypename)
#define Assert(condition)
Definition: c.h:792
#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:915
#define elog(elevel,...)
Definition: elog.h:228
#define copyObject(obj)
Definition: nodes.h:644
static void transformTableConstraint(CreateStmtContext *cxt, Constraint *constraint)
static void transformIndexConstraints(CreateStmtContext *cxt)
PartitionSpec * partspec
Definition: parsenodes.h:2093
Definition: pg_list.h:50
static void transformTableLikeClause(CreateStmtContext *cxt, TableLikeClause *table_like_clause)
TypeName * ofTypename
Definition: parsenodes.h:2094
static void transformCheckConstraints(CreateStmtContext *cxt, bool skipValidation)

◆ transformExtendedStatistics()

static void transformExtendedStatistics ( CreateStmtContext cxt)
static

Definition at line 2642 of file parse_utilcmd.c.

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

Referenced by transformAlterTableStmt(), and transformCreateStmt().

2643 {
2644  cxt->alist = list_concat(cxt->alist, cxt->extstats);
2645 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:530

◆ transformFKConstraints()

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

Definition at line 2686 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().

2688 {
2689  ListCell *fkclist;
2690 
2691  if (cxt->fkconstraints == NIL)
2692  return;
2693 
2694  /*
2695  * If CREATE TABLE or adding a column with NULL default, we can safely
2696  * skip validation of FK constraints, and nonetheless mark them valid.
2697  * (This will override any user-supplied NOT VALID flag.)
2698  */
2699  if (skipValidation)
2700  {
2701  foreach(fkclist, cxt->fkconstraints)
2702  {
2703  Constraint *constraint = (Constraint *) lfirst(fkclist);
2704 
2705  constraint->skip_validation = true;
2706  constraint->initially_valid = true;
2707  }
2708  }
2709 
2710  /*
2711  * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
2712  * CONSTRAINT command to execute after the basic command is complete. (If
2713  * called from ADD CONSTRAINT, that routine will add the FK constraints to
2714  * its own subcommand list.)
2715  *
2716  * Note: the ADD CONSTRAINT command must also execute after any index
2717  * creation commands. Thus, this should run after
2718  * transformIndexConstraints, so that the CREATE INDEX commands are
2719  * already in cxt->alist. See also the handling of cxt->likeclauses.
2720  */
2721  if (!isAddConstraint)
2722  {
2723  AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
2724 
2725  alterstmt->relation = cxt->relation;
2726  alterstmt->cmds = NIL;
2727  alterstmt->objtype = OBJECT_TABLE;
2728 
2729  foreach(fkclist, cxt->fkconstraints)
2730  {
2731  Constraint *constraint = (Constraint *) lfirst(fkclist);
2732  AlterTableCmd *altercmd = makeNode(AlterTableCmd);
2733 
2734  altercmd->subtype = AT_AddConstraint;
2735  altercmd->name = NULL;
2736  altercmd->def = (Node *) constraint;
2737  alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
2738  }
2739 
2740  cxt->alist = lappend(cxt->alist, alterstmt);
2741  }
2742 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:528
AlterTableType subtype
Definition: parsenodes.h:1889
RangeVar * relation
Definition: parse_utilcmd.c:80
ObjectType objtype
Definition: parsenodes.h:1803
List * lappend(List *list, void *datum)
Definition: list.c:336
bool initially_valid
Definition: parsenodes.h:2214
#define makeNode(_type_)
Definition: nodes.h:576
#define lfirst(lc)
Definition: pg_list.h:169
RangeVar * relation
Definition: parsenodes.h:1801
bool skip_validation
Definition: parsenodes.h:2213

◆ transformIndexConstraint()

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

Definition at line 2108 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().

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

◆ transformIndexConstraints()

static void transformIndexConstraints ( CreateStmtContext cxt)
static

Definition at line 2006 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().

2007 {
2008  IndexStmt *index;
2009  List *indexlist = NIL;
2010  List *finalindexlist = NIL;
2011  ListCell *lc;
2012 
2013  /*
2014  * Run through the constraints that need to generate an index. For PRIMARY
2015  * KEY, mark each column as NOT NULL and create an index. For UNIQUE or
2016  * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT
2017  * NULL.
2018  */
2019  foreach(lc, cxt->ixconstraints)
2020  {
2021  Constraint *constraint = lfirst_node(Constraint, lc);
2022 
2023  Assert(constraint->contype == CONSTR_PRIMARY ||
2024  constraint->contype == CONSTR_UNIQUE ||
2025  constraint->contype == CONSTR_EXCLUSION);
2026 
2027  index = transformIndexConstraint(constraint, cxt);
2028 
2029  indexlist = lappend(indexlist, index);
2030  }
2031 
2032  /*
2033  * Scan the index list and remove any redundant index specifications. This
2034  * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
2035  * strict reading of SQL would suggest raising an error instead, but that
2036  * strikes me as too anal-retentive. - tgl 2001-02-14
2037  *
2038  * XXX in ALTER TABLE case, it'd be nice to look for duplicate
2039  * pre-existing indexes, too.
2040  */
2041  if (cxt->pkey != NULL)
2042  {
2043  /* Make sure we keep the PKEY index in preference to others... */
2044  finalindexlist = list_make1(cxt->pkey);
2045  }
2046 
2047  foreach(lc, indexlist)
2048  {
2049  bool keep = true;
2050  ListCell *k;
2051 
2052  index = lfirst(lc);
2053 
2054  /* if it's pkey, it's already in finalindexlist */
2055  if (index == cxt->pkey)
2056  continue;
2057 
2058  foreach(k, finalindexlist)
2059  {
2060  IndexStmt *priorindex = lfirst(k);
2061 
2062  if (equal(index->indexParams, priorindex->indexParams) &&
2063  equal(index->indexIncludingParams, priorindex->indexIncludingParams) &&
2064  equal(index->whereClause, priorindex->whereClause) &&
2065  equal(index->excludeOpNames, priorindex->excludeOpNames) &&
2066  strcmp(index->accessMethod, priorindex->accessMethod) == 0 &&
2067  index->deferrable == priorindex->deferrable &&
2068  index->initdeferred == priorindex->initdeferred)
2069  {
2070  priorindex->unique |= index->unique;
2071 
2072  /*
2073  * If the prior index is as yet unnamed, and this one is
2074  * named, then transfer the name to the prior index. This
2075  * ensures that if we have named and unnamed constraints,
2076  * we'll use (at least one of) the names for the index.
2077  */
2078  if (priorindex->idxname == NULL)
2079  priorindex->idxname = index->idxname;
2080  keep = false;
2081  break;
2082  }
2083  }
2084 
2085  if (keep)
2086  finalindexlist = lappend(finalindexlist, index);
2087  }
2088 
2089  /*
2090  * Now append all the IndexStmts to cxt->alist. If we generated an ALTER
2091  * TABLE SET NOT NULL statement to support a primary key, it's already in
2092  * cxt->alist.
2093  */
2094  cxt->alist = list_concat(cxt->alist, finalindexlist);
2095 }
bool deferrable
Definition: parsenodes.h:2811
#define NIL
Definition: pg_list.h:65
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3042
Node * whereClause
Definition: parsenodes.h:2800
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
List * indexIncludingParams
Definition: parsenodes.h:2797
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:206
IndexStmt * pkey
Definition: parse_utilcmd.c:95
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * lappend(List *list, void *datum)
Definition: list.c:336
char * idxname
Definition: parsenodes.h:2792
static IndexStmt * transformIndexConstraint(Constraint *constraint, CreateStmtContext *cxt)
bool unique
Definition: parsenodes.h:2808
char * accessMethod
Definition: parsenodes.h:2794
#define Assert(condition)
Definition: c.h:792
#define lfirst(lc)
Definition: pg_list.h:169
List * indexParams
Definition: parsenodes.h:2796
List * excludeOpNames
Definition: parsenodes.h:2801
bool initdeferred
Definition: parsenodes.h:2812
ConstrType contype
Definition: parsenodes.h:2168
Definition: pg_list.h:50

◆ transformIndexStmt()

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

Definition at line 2757 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().

2758 {
2759  ParseState *pstate;
2760  ParseNamespaceItem *nsitem;
2761  ListCell *l;
2762  Relation rel;
2763 
2764  /* Nothing to do if statement already transformed. */
2765  if (stmt->transformed)
2766  return stmt;
2767 
2768  /*
2769  * We must not scribble on the passed-in IndexStmt, so copy it. (This is
2770  * overkill, but easy.)
2771  */
2772  stmt = copyObject(stmt);
2773 
2774  /* Set up pstate */
2775  pstate = make_parsestate(NULL);
2776  pstate->p_sourcetext = queryString;
2777 
2778  /*
2779  * Put the parent table into the rtable so that the expressions can refer
2780  * to its fields without qualification. Caller is responsible for locking
2781  * relation, but we still need to open it.
2782  */
2783  rel = relation_open(relid, NoLock);
2784  nsitem = addRangeTableEntryForRelation(pstate, rel,
2786  NULL, false, true);
2787 
2788  /* no to join list, yes to namespaces */
2789  addNSItemToQuery(pstate, nsitem, false, true, true);
2790 
2791  /* take care of the where clause */
2792  if (stmt->whereClause)
2793  {
2794  stmt->whereClause = transformWhereClause(pstate,
2795  stmt->whereClause,
2797  "WHERE");
2798  /* we have to fix its collations too */
2799  assign_expr_collations(pstate, stmt->whereClause);
2800  }
2801 
2802  /* take care of any index expressions */
2803  foreach(l, stmt->indexParams)
2804  {
2805  IndexElem *ielem = (IndexElem *) lfirst(l);
2806 
2807  if (ielem->expr)
2808  {
2809  /* Extract preliminary index col name before transforming expr */
2810  if (ielem->indexcolname == NULL)
2811  ielem->indexcolname = FigureIndexColname(ielem->expr);
2812 
2813  /* Now do parse transformation of the expression */
2814  ielem->expr = transformExpr(pstate, ielem->expr,
2816 
2817  /* We have to fix its collations too */
2818  assign_expr_collations(pstate, ielem->expr);
2819 
2820  /*
2821  * transformExpr() should have already rejected subqueries,
2822  * aggregates, window functions, and SRFs, based on the EXPR_KIND_
2823  * for an index expression.
2824  *
2825  * DefineIndex() will make more checks.
2826  */
2827  }
2828  }
2829 
2830  /*
2831  * Check that only the base rel is mentioned. (This should be dead code
2832  * now that add_missing_from is history.)
2833  */
2834  if (list_length(pstate->p_rtable) != 1)
2835  ereport(ERROR,
2836  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2837  errmsg("index expressions and predicates can refer only to the table being indexed")));
2838 
2839  free_parsestate(pstate);
2840 
2841  /* Close relation */
2842  table_close(rel, NoLock);
2843 
2844  /* Mark statement as successfully transformed */
2845  stmt->transformed = true;
2846 
2847  return stmt;
2848 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Node * whereClause
Definition: parsenodes.h:2800
#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:704
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:44
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * expr
Definition: parsenodes.h:702
#define ERROR
Definition: elog.h:45
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
#define NoLock
Definition: lockdefs.h:34
bool transformed
Definition: parsenodes.h:2813
char * indexcolname
Definition: parsenodes.h:703
const char * p_sourcetext
Definition: parse_node.h:179
#define ereport(elevel,...)
Definition: elog.h:155
#define lfirst(lc)
Definition: pg_list.h:169
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * indexParams
Definition: parsenodes.h:2796
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define copyObject(obj)
Definition: nodes.h:644
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
List * p_rtable
Definition: parse_node.h:180

◆ transformOfType()

static void transformOfType ( CreateStmtContext cxt,
TypeName ofTypename 
)
static

Definition at line 1437 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().

1438 {
1439  HeapTuple tuple;
1440  TupleDesc tupdesc;
1441  int i;
1442  Oid ofTypeId;
1443 
1444  AssertArg(ofTypename);
1445 
1446  tuple = typenameType(NULL, ofTypename, NULL);
1447  check_of_type(tuple);
1448  ofTypeId = ((Form_pg_type) GETSTRUCT(tuple))->oid;
1449  ofTypename->typeOid = ofTypeId; /* cached for later */
1450 
1451  tupdesc = lookup_rowtype_tupdesc(ofTypeId, -1);
1452  for (i = 0; i < tupdesc->natts; i++)
1453  {
1454  Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1455  ColumnDef *n;
1456 
1457  if (attr->attisdropped)
1458  continue;
1459 
1460  n = makeNode(ColumnDef);
1461  n->colname = pstrdup(NameStr(attr->attname));
1462  n->typeName = makeTypeNameFromOid(attr->atttypid, attr->atttypmod);
1463  n->inhcount = 0;
1464  n->is_local = true;
1465  n->is_not_null = false;
1466  n->is_from_type = true;
1467  n->storage = 0;
1468  n->raw_default = NULL;
1469  n->cooked_default = NULL;
1470  n->collClause = NULL;
1471  n->collOid = attr->attcollation;
1472  n->constraints = NIL;
1473  n->location = -1;
1474  cxt->columns = lappend(cxt->columns, n);
1475  }
1476  DecrTupleDescRefCount(tupdesc);
1477 
1478  ReleaseSysCache(tuple);
1479 }
#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:653
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1826
bool is_local
Definition: parsenodes.h:650
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * constraints
Definition: parsenodes.h:662
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool is_not_null
Definition: parsenodes.h:651
unsigned int Oid
Definition: postgres_ext.h:31
Node * cooked_default
Definition: parsenodes.h:655
void check_of_type(HeapTuple typetuple)
Definition: tablecmds.c:5990
Oid collOid
Definition: parsenodes.h:661
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
int location
Definition: parsenodes.h:664
#define AssertArg(condition)
Definition: c.h:794
Node * raw_default
Definition: parsenodes.h:654
List * lappend(List *list, void *datum)
Definition: list.c:336
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod)
Definition: makefuncs.c:472
bool is_from_type
Definition: parsenodes.h:652
#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:261
TypeName * typeName
Definition: parsenodes.h:648
CollateClause * collClause
Definition: parsenodes.h:660
int i
int inhcount
Definition: parsenodes.h:649
#define NameStr(name)
Definition: c.h:669
char * colname
Definition: parsenodes.h:647

◆ transformPartitionBound()

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

Definition at line 3888 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().

3890 {
3891  PartitionBoundSpec *result_spec;
3893  char strategy = get_partition_strategy(key);
3894  int partnatts = get_partition_natts(key);
3895  List *partexprs = get_partition_exprs(key);
3896 
3897  /* Avoid scribbling on input */
3898  result_spec = copyObject(spec);
3899 
3900  if (spec->is_default)
3901  {
3902  /*
3903  * Hash partitioning does not support a default partition; there's no
3904  * use case for it (since the set of partitions to create is perfectly
3905  * defined), and if users do get into it accidentally, it's hard to
3906  * back out from it afterwards.
3907  */
3908  if (strategy == PARTITION_STRATEGY_HASH)
3909  ereport(ERROR,
3910  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3911  errmsg("a hash-partitioned table may not have a default partition")));
3912 
3913  /*
3914  * In case of the default partition, parser had no way to identify the
3915  * partition strategy. Assign the parent's strategy to the default
3916  * partition bound spec.
3917  */
3918  result_spec->strategy = strategy;
3919 
3920  return result_spec;
3921  }
3922 
3923  if (strategy == PARTITION_STRATEGY_HASH)
3924  {
3925  if (spec->strategy != PARTITION_STRATEGY_HASH)
3926  ereport(ERROR,
3927  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3928  errmsg("invalid bound specification for a hash partition"),
3929  parser_errposition(pstate, exprLocation((Node *) spec))));
3930 
3931  if (spec->modulus <= 0)
3932  ereport(ERROR,
3933  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3934  errmsg("modulus for hash partition must be a positive integer")));
3935 
3936  Assert(spec->remainder >= 0);
3937 
3938  if (spec->remainder >= spec->modulus)
3939  ereport(ERROR,
3940  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
3941  errmsg("remainder for hash partition must be less than modulus")));
3942  }
3943