PostgreSQL Source Code  git master
toasting.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/toast_compression.h"
#include "access/xact.h"
#include "catalog/binary_upgrade.h"
#include "catalog/catalog.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_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/toasting.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "utils/rel.h"
#include "utils/syscache.h"
Include dependency graph for toasting.c:

Go to the source code of this file.

Functions

static void CheckAndCreateToastTable (Oid relOid, Datum reloptions, LOCKMODE lockmode, bool check, Oid OIDOldToast)
 
static bool create_toast_table (Relation rel, Oid toastOid, Oid toastIndexOid, Datum reloptions, LOCKMODE lockmode, bool check, Oid OIDOldToast)
 
static bool needs_toast_table (Relation rel)
 
void AlterTableCreateToastTable (Oid relOid, Datum reloptions, LOCKMODE lockmode)
 
void NewHeapCreateToastTable (Oid relOid, Datum reloptions, LOCKMODE lockmode, Oid OIDOldToast)
 
void NewRelationCreateToastTable (Oid relOid, Datum reloptions)
 
void BootstrapToastTable (char *relName, Oid toastOid, Oid toastIndexOid)
 

Function Documentation

◆ AlterTableCreateToastTable()

void AlterTableCreateToastTable ( Oid  relOid,
Datum  reloptions,
LOCKMODE  lockmode 
)

Definition at line 57 of file toasting.c.

58 {
59  CheckAndCreateToastTable(relOid, reloptions, lockmode, true, InvalidOid);
60 }
#define InvalidOid
Definition: postgres_ext.h:36
static void CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, bool check, Oid OIDOldToast)
Definition: toasting.c:77

References CheckAndCreateToastTable(), and InvalidOid.

Referenced by ATRewriteCatalogs().

◆ BootstrapToastTable()

void BootstrapToastTable ( char *  relName,
Oid  toastOid,
Oid  toastIndexOid 
)

Definition at line 97 of file toasting.c.

98 {
99  Relation rel;
100 
101  rel = table_openrv(makeRangeVar(NULL, relName, -1), AccessExclusiveLock);
102 
103  if (rel->rd_rel->relkind != RELKIND_RELATION &&
104  rel->rd_rel->relkind != RELKIND_MATVIEW)
105  elog(ERROR, "\"%s\" is not a table or materialized view",
106  relName);
107 
108  /* create_toast_table does all the work */
109  if (!create_toast_table(rel, toastOid, toastIndexOid, (Datum) 0,
111  elog(ERROR, "\"%s\" does not require a toast table",
112  relName);
113 
114  table_close(rel, NoLock);
115 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define NoLock
Definition: lockdefs.h:34
#define AccessExclusiveLock
Definition: lockdefs.h:43
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
uintptr_t Datum
Definition: postgres.h:64
Form_pg_class rd_rel
Definition: rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83
static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid, Datum reloptions, LOCKMODE lockmode, bool check, Oid OIDOldToast)
Definition: toasting.c:126

References AccessExclusiveLock, create_toast_table(), elog, ERROR, InvalidOid, makeRangeVar(), NoLock, RelationData::rd_rel, table_close(), and table_openrv().

◆ CheckAndCreateToastTable()

static void CheckAndCreateToastTable ( Oid  relOid,
Datum  reloptions,
LOCKMODE  lockmode,
bool  check,
Oid  OIDOldToast 
)
static

Definition at line 77 of file toasting.c.

79 {
80  Relation rel;
81 
82  rel = table_open(relOid, lockmode);
83 
84  /* create_toast_table does all the work */
85  (void) create_toast_table(rel, InvalidOid, InvalidOid, reloptions, lockmode,
86  check, OIDOldToast);
87 
88  table_close(rel, NoLock);
89 }
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References create_toast_table(), InvalidOid, NoLock, table_close(), and table_open().

Referenced by AlterTableCreateToastTable(), NewHeapCreateToastTable(), and NewRelationCreateToastTable().

◆ create_toast_table()

static bool create_toast_table ( Relation  rel,
Oid  toastOid,
Oid  toastIndexOid,
Datum  reloptions,
LOCKMODE  lockmode,
bool  check,
Oid  OIDOldToast 
)
static

Definition at line 126 of file toasting.c.

129 {
130  Oid relOid = RelationGetRelid(rel);
131  HeapTuple reltup;
132  TupleDesc tupdesc;
133  bool shared_relation;
134  bool mapped_relation;
135  Relation toast_rel;
136  Relation class_rel;
137  Oid toast_relid;
138  Oid namespaceid;
139  char toast_relname[NAMEDATALEN];
140  char toast_idxname[NAMEDATALEN];
141  IndexInfo *indexInfo;
142  Oid collationIds[2];
143  Oid opclassIds[2];
144  int16 coloptions[2];
145  ObjectAddress baseobject,
146  toastobject;
147 
148  /*
149  * Is it already toasted?
150  */
151  if (rel->rd_rel->reltoastrelid != InvalidOid)
152  return false;
153 
154  /*
155  * Check to see whether the table actually needs a TOAST table.
156  */
157  if (!IsBinaryUpgrade)
158  {
159  /* Normal mode, normal check */
160  if (!needs_toast_table(rel))
161  return false;
162  }
163  else
164  {
165  /*
166  * In binary-upgrade mode, create a TOAST table if and only if
167  * pg_upgrade told us to (ie, a TOAST table OID has been provided).
168  *
169  * This indicates that the old cluster had a TOAST table for the
170  * current table. We must create a TOAST table to receive the old
171  * TOAST file, even if the table seems not to need one.
172  *
173  * Contrariwise, if the old cluster did not have a TOAST table, we
174  * should be able to get along without one even if the new version's
175  * needs_toast_table rules suggest we should have one. There is a lot
176  * of daylight between where we will create a TOAST table and where
177  * one is really necessary to avoid failures, so small cross-version
178  * differences in the when-to-create heuristic shouldn't be a problem.
179  * If we tried to create a TOAST table anyway, we would have the
180  * problem that it might take up an OID that will conflict with some
181  * old-cluster table we haven't seen yet.
182  */
184  return false;
185  }
186 
187  /*
188  * If requested check lockmode is sufficient. This is a cross check in
189  * case of errors or conflicting decisions in earlier code.
190  */
191  if (check && lockmode != AccessExclusiveLock)
192  elog(ERROR, "AccessExclusiveLock required to add toast table.");
193 
194  /*
195  * Create the toast table and its index
196  */
197  snprintf(toast_relname, sizeof(toast_relname),
198  "pg_toast_%u", relOid);
199  snprintf(toast_idxname, sizeof(toast_idxname),
200  "pg_toast_%u_index", relOid);
201 
202  /* this is pretty painful... need a tuple descriptor */
203  tupdesc = CreateTemplateTupleDesc(3);
204  TupleDescInitEntry(tupdesc, (AttrNumber) 1,
205  "chunk_id",
206  OIDOID,
207  -1, 0);
208  TupleDescInitEntry(tupdesc, (AttrNumber) 2,
209  "chunk_seq",
210  INT4OID,
211  -1, 0);
212  TupleDescInitEntry(tupdesc, (AttrNumber) 3,
213  "chunk_data",
214  BYTEAOID,
215  -1, 0);
216 
217  /*
218  * Ensure that the toast table doesn't itself get toasted, or we'll be
219  * toast :-(. This is essential for chunk_data because type bytea is
220  * toastable; hit the other two just to be sure.
221  */
222  TupleDescAttr(tupdesc, 0)->attstorage = TYPSTORAGE_PLAIN;
223  TupleDescAttr(tupdesc, 1)->attstorage = TYPSTORAGE_PLAIN;
224  TupleDescAttr(tupdesc, 2)->attstorage = TYPSTORAGE_PLAIN;
225 
226  /* Toast field should not be compressed */
227  TupleDescAttr(tupdesc, 0)->attcompression = InvalidCompressionMethod;
228  TupleDescAttr(tupdesc, 1)->attcompression = InvalidCompressionMethod;
229  TupleDescAttr(tupdesc, 2)->attcompression = InvalidCompressionMethod;
230 
231  /*
232  * Toast tables for regular relations go in pg_toast; those for temp
233  * relations go into the per-backend temp-toast-table namespace.
234  */
235  if (isTempOrTempToastNamespace(rel->rd_rel->relnamespace))
236  namespaceid = GetTempToastNamespace();
237  else
238  namespaceid = PG_TOAST_NAMESPACE;
239 
240  /* Toast table is shared if and only if its parent is. */
241  shared_relation = rel->rd_rel->relisshared;
242 
243  /* It's mapped if and only if its parent is, too */
244  mapped_relation = RelationIsMapped(rel);
245 
246  toast_relid = heap_create_with_catalog(toast_relname,
247  namespaceid,
248  rel->rd_rel->reltablespace,
249  toastOid,
250  InvalidOid,
251  InvalidOid,
252  rel->rd_rel->relowner,
254  tupdesc,
255  NIL,
256  RELKIND_TOASTVALUE,
257  rel->rd_rel->relpersistence,
258  shared_relation,
259  mapped_relation,
261  reloptions,
262  false,
263  true,
264  true,
265  OIDOldToast,
266  NULL);
267  Assert(toast_relid != InvalidOid);
268 
269  /* make the toast relation visible, else table_open will fail */
271 
272  /* ShareLock is not really needed here, but take it anyway */
273  toast_rel = table_open(toast_relid, ShareLock);
274 
275  /*
276  * Create unique index on chunk_id, chunk_seq.
277  *
278  * NOTE: the normal TOAST access routines could actually function with a
279  * single-column index on chunk_id only. However, the slice access
280  * routines use both columns for faster access to an individual chunk. In
281  * addition, we want it to be unique as a check against the possibility of
282  * duplicate TOAST chunk OIDs. The index might also be a little more
283  * efficient this way, since btree isn't all that happy with large numbers
284  * of equal keys.
285  */
286 
287  indexInfo = makeNode(IndexInfo);
288  indexInfo->ii_NumIndexAttrs = 2;
289  indexInfo->ii_NumIndexKeyAttrs = 2;
290  indexInfo->ii_IndexAttrNumbers[0] = 1;
291  indexInfo->ii_IndexAttrNumbers[1] = 2;
292  indexInfo->ii_Expressions = NIL;
293  indexInfo->ii_ExpressionsState = NIL;
294  indexInfo->ii_Predicate = NIL;
295  indexInfo->ii_PredicateState = NULL;
296  indexInfo->ii_ExclusionOps = NULL;
297  indexInfo->ii_ExclusionProcs = NULL;
298  indexInfo->ii_ExclusionStrats = NULL;
299  indexInfo->ii_Unique = true;
300  indexInfo->ii_NullsNotDistinct = false;
301  indexInfo->ii_ReadyForInserts = true;
302  indexInfo->ii_CheckedUnchanged = false;
303  indexInfo->ii_IndexUnchanged = false;
304  indexInfo->ii_Concurrent = false;
305  indexInfo->ii_BrokenHotChain = false;
306  indexInfo->ii_ParallelWorkers = 0;
307  indexInfo->ii_Am = BTREE_AM_OID;
308  indexInfo->ii_AmCache = NULL;
309  indexInfo->ii_Context = CurrentMemoryContext;
310 
311  collationIds[0] = InvalidOid;
312  collationIds[1] = InvalidOid;
313 
314  opclassIds[0] = OID_BTREE_OPS_OID;
315  opclassIds[1] = INT4_BTREE_OPS_OID;
316 
317  coloptions[0] = 0;
318  coloptions[1] = 0;
319 
320  index_create(toast_rel, toast_idxname, toastIndexOid, InvalidOid,
322  indexInfo,
323  list_make2("chunk_id", "chunk_seq"),
324  BTREE_AM_OID,
325  rel->rd_rel->reltablespace,
326  collationIds, opclassIds, NULL, coloptions, (Datum) 0,
327  INDEX_CREATE_IS_PRIMARY, 0, true, true, NULL);
328 
329  table_close(toast_rel, NoLock);
330 
331  /*
332  * Store the toast table's OID in the parent relation's pg_class row
333  */
334  class_rel = table_open(RelationRelationId, RowExclusiveLock);
335 
336  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
337  if (!HeapTupleIsValid(reltup))
338  elog(ERROR, "cache lookup failed for relation %u", relOid);
339 
340  ((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
341 
343  {
344  /* normal case, use a transactional update */
345  CatalogTupleUpdate(class_rel, &reltup->t_self, reltup);
346  }
347  else
348  {
349  /* While bootstrapping, we cannot UPDATE, so overwrite in-place */
350  heap_inplace_update(class_rel, reltup);
351  }
352 
353  heap_freetuple(reltup);
354 
355  table_close(class_rel, RowExclusiveLock);
356 
357  /*
358  * Register dependency from the toast table to the main, so that the toast
359  * table will be deleted if the main is. Skip this in bootstrap mode.
360  */
362  {
363  baseobject.classId = RelationRelationId;
364  baseobject.objectId = relOid;
365  baseobject.objectSubId = 0;
366  toastobject.classId = RelationRelationId;
367  toastobject.objectId = toast_relid;
368  toastobject.objectSubId = 0;
369 
370  recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
371  }
372 
373  /*
374  * Make changes visible
375  */
377 
378  return true;
379 }
int16 AttrNumber
Definition: attnum.h:21
signed short int16
Definition: c.h:480
#define OidIsValid(objectId)
Definition: c.h:762
@ DEPENDENCY_INTERNAL
Definition: dependency.h:35
bool IsBinaryUpgrade
Definition: globals.c:117
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, Oid accessmtd, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, Oid relrewrite, ObjectAddress *typaddress)
Definition: heap.c:1094
Oid binary_upgrade_next_toast_pg_class_oid
Definition: heap.c:81
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5889
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, RelFileNumber relFileNumber, IndexInfo *indexInfo, const List *indexColNames, Oid accessMethodId, Oid tableSpaceId, const Oid *collationIds, const Oid *opclassIds, const Datum *opclassOptions, const int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition: index.c:705
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:61
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
Assert(fmt[strlen(fmt) - 1] !='\n')
#define ShareLock
Definition: lockdefs.h:40
#define RowExclusiveLock
Definition: lockdefs.h:38
MemoryContext CurrentMemoryContext
Definition: mcxt.c:131
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:451
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition: namespace.c:3658
Oid GetTempToastNamespace(void)
Definition: namespace.c:3776
#define makeNode(_type_)
Definition: nodes.h:155
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define NAMEDATALEN
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define NIL
Definition: pg_list.h:68
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define snprintf
Definition: port.h:238
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
@ ONCOMMIT_NOOP
Definition: primnodes.h:57
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationIsMapped(relation)
Definition: rel.h:553
ItemPointerData t_self
Definition: htup.h:65
bool ii_Unique
Definition: execnodes.h:197
uint16 * ii_ExclusionStrats
Definition: execnodes.h:193
bool ii_BrokenHotChain
Definition: execnodes.h:203
int ii_NumIndexAttrs
Definition: execnodes.h:184
void * ii_AmCache
Definition: execnodes.h:207
bool ii_CheckedUnchanged
Definition: execnodes.h:200
ExprState * ii_PredicateState
Definition: execnodes.h:190
Oid * ii_ExclusionOps
Definition: execnodes.h:191
bool ii_NullsNotDistinct
Definition: execnodes.h:198
int ii_ParallelWorkers
Definition: execnodes.h:205
bool ii_Concurrent
Definition: execnodes.h:202
int ii_NumIndexKeyAttrs
Definition: execnodes.h:185
List * ii_ExpressionsState
Definition: execnodes.h:188
List * ii_Expressions
Definition: execnodes.h:187
bool ii_IndexUnchanged
Definition: execnodes.h:201
Oid * ii_ExclusionProcs
Definition: execnodes.h:192
Oid ii_Am
Definition: execnodes.h:206
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:186
MemoryContext ii_Context
Definition: execnodes.h:208
bool ii_ReadyForInserts
Definition: execnodes.h:199
List * ii_Predicate
Definition: execnodes.h:189
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86
static Oid table_relation_toast_am(Relation rel)
Definition: tableam.h:1884
#define InvalidCompressionMethod
static bool needs_toast_table(Relation rel)
Definition: toasting.c:385
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:67
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:603
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void CommandCounterIncrement(void)
Definition: xact.c:1076

References AccessExclusiveLock, Assert(), binary_upgrade_next_toast_pg_class_oid, CatalogTupleUpdate(), ObjectAddress::classId, CommandCounterIncrement(), CreateTemplateTupleDesc(), CurrentMemoryContext, DEPENDENCY_INTERNAL, elog, ERROR, GETSTRUCT, GetTempToastNamespace(), heap_create_with_catalog(), heap_freetuple(), heap_inplace_update(), HeapTupleIsValid, IndexInfo::ii_Am, IndexInfo::ii_AmCache, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_CheckedUnchanged, IndexInfo::ii_Concurrent, IndexInfo::ii_Context, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Expressions, IndexInfo::ii_ExpressionsState, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_IndexUnchanged, IndexInfo::ii_NullsNotDistinct, IndexInfo::ii_NumIndexAttrs, IndexInfo::ii_NumIndexKeyAttrs, IndexInfo::ii_ParallelWorkers, IndexInfo::ii_Predicate, IndexInfo::ii_PredicateState, IndexInfo::ii_ReadyForInserts, IndexInfo::ii_Unique, index_create(), INDEX_CREATE_IS_PRIMARY, InvalidCompressionMethod, InvalidOid, IsBinaryUpgrade, IsBootstrapProcessingMode, isTempOrTempToastNamespace(), list_make2, makeNode, NAMEDATALEN, needs_toast_table(), NIL, NoLock, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, OidIsValid, ONCOMMIT_NOOP, RelationData::rd_rel, recordDependencyOn(), RelationGetRelid, RelationIsMapped, RowExclusiveLock, SearchSysCacheCopy1, ShareLock, snprintf, HeapTupleData::t_self, table_close(), table_open(), table_relation_toast_am(), TupleDescAttr, and TupleDescInitEntry().

Referenced by BootstrapToastTable(), and CheckAndCreateToastTable().

◆ needs_toast_table()

static bool needs_toast_table ( Relation  rel)
static

Definition at line 385 of file toasting.c.

386 {
387  /*
388  * No need to create a TOAST table for partitioned tables.
389  */
390  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
391  return false;
392 
393  /*
394  * We cannot allow toasting a shared relation after initdb (because
395  * there's no way to mark it toasted in other databases' pg_class).
396  */
397  if (rel->rd_rel->relisshared && !IsBootstrapProcessingMode())
398  return false;
399 
400  /*
401  * Ignore attempts to create toast tables on catalog tables after initdb.
402  * Which catalogs get toast tables is explicitly chosen in catalog/pg_*.h.
403  * (We could get here via some ALTER TABLE command if the catalog doesn't
404  * have a toast table.)
405  */
407  return false;
408 
409  /* Otherwise, let the AM decide. */
411 }
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
static bool table_relation_needs_toast_table(Relation rel)
Definition: tableam.h:1874

References IsBootstrapProcessingMode, IsCatalogRelation(), RelationData::rd_rel, and table_relation_needs_toast_table().

Referenced by create_toast_table().

◆ NewHeapCreateToastTable()

void NewHeapCreateToastTable ( Oid  relOid,
Datum  reloptions,
LOCKMODE  lockmode,
Oid  OIDOldToast 
)

Definition at line 63 of file toasting.c.

65 {
66  CheckAndCreateToastTable(relOid, reloptions, lockmode, false, OIDOldToast);
67 }

References CheckAndCreateToastTable().

Referenced by make_new_heap().

◆ NewRelationCreateToastTable()

void NewRelationCreateToastTable ( Oid  relOid,
Datum  reloptions 
)

Definition at line 70 of file toasting.c.

71 {
72  CheckAndCreateToastTable(relOid, reloptions, AccessExclusiveLock, false,
73  InvalidOid);
74 }

References AccessExclusiveLock, CheckAndCreateToastTable(), and InvalidOid.

Referenced by create_ctas_internal(), and ProcessUtilitySlow().