PostgreSQL Source Code  git master
toasting.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * toasting.c
4  * This file contains routines to support creation of toast tables
5  *
6  *
7  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * IDENTIFICATION
11  * src/backend/catalog/toasting.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "access/heapam.h"
19 #include "access/xact.h"
20 #include "catalog/binary_upgrade.h"
21 #include "catalog/catalog.h"
22 #include "catalog/dependency.h"
23 #include "catalog/heap.h"
24 #include "catalog/index.h"
25 #include "catalog/namespace.h"
26 #include "catalog/pg_am.h"
27 #include "catalog/pg_namespace.h"
28 #include "catalog/pg_opclass.h"
29 #include "catalog/pg_type.h"
30 #include "catalog/toasting.h"
31 #include "miscadmin.h"
32 #include "nodes/makefuncs.h"
33 #include "storage/lock.h"
34 #include "utils/builtins.h"
35 #include "utils/rel.h"
36 #include "utils/syscache.h"
37 
38 static void CheckAndCreateToastTable(Oid relOid, Datum reloptions,
39  LOCKMODE lockmode, bool check);
40 static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
41  Datum reloptions, LOCKMODE lockmode, bool check);
42 static bool needs_toast_table(Relation rel);
43 
44 
45 /*
46  * CreateToastTable variants
47  * If the table needs a toast table, and doesn't already have one,
48  * then create a toast table for it.
49  *
50  * reloptions for the toast table can be passed, too. Pass (Datum) 0
51  * for default reloptions.
52  *
53  * We expect the caller to have verified that the relation is a table and have
54  * already done any necessary permission checks. Callers expect this function
55  * to end with CommandCounterIncrement if it makes any changes.
56  */
57 void
58 AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
59 {
60  CheckAndCreateToastTable(relOid, reloptions, lockmode, true);
61 }
62 
63 void
64 NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
65 {
66  CheckAndCreateToastTable(relOid, reloptions, lockmode, false);
67 }
68 
69 void
71 {
72  CheckAndCreateToastTable(relOid, reloptions, AccessExclusiveLock, false);
73 }
74 
75 static void
76 CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, bool check)
77 {
78  Relation rel;
79 
80  rel = table_open(relOid, lockmode);
81 
82  /* create_toast_table does all the work */
83  (void) create_toast_table(rel, InvalidOid, InvalidOid, reloptions, lockmode, check);
84 
85  table_close(rel, NoLock);
86 }
87 
88 /*
89  * Create a toast table during bootstrap
90  *
91  * Here we need to prespecify the OIDs of the toast table and its index
92  */
93 void
94 BootstrapToastTable(char *relName, Oid toastOid, Oid toastIndexOid)
95 {
96  Relation rel;
97 
98  rel = table_openrv(makeRangeVar(NULL, relName, -1), AccessExclusiveLock);
99 
100  if (rel->rd_rel->relkind != RELKIND_RELATION &&
101  rel->rd_rel->relkind != RELKIND_MATVIEW)
102  ereport(ERROR,
103  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
104  errmsg("\"%s\" is not a table or materialized view",
105  relName)));
106 
107  /* create_toast_table does all the work */
108  if (!create_toast_table(rel, toastOid, toastIndexOid, (Datum) 0,
109  AccessExclusiveLock, false))
110  elog(ERROR, "\"%s\" does not require a toast table",
111  relName);
112 
113  table_close(rel, NoLock);
114 }
115 
116 
117 /*
118  * create_toast_table --- internal workhorse
119  *
120  * rel is already opened and locked
121  * toastOid and toastIndexOid are normally InvalidOid, but during
122  * bootstrap they can be nonzero to specify hand-assigned OIDs
123  */
124 static bool
125 create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
126  Datum reloptions, LOCKMODE lockmode, bool check)
127 {
128  Oid relOid = RelationGetRelid(rel);
129  HeapTuple reltup;
130  TupleDesc tupdesc;
131  bool shared_relation;
132  bool mapped_relation;
133  Relation toast_rel;
134  Relation class_rel;
135  Oid toast_relid;
136  Oid namespaceid;
137  char toast_relname[NAMEDATALEN];
138  char toast_idxname[NAMEDATALEN];
139  IndexInfo *indexInfo;
140  Oid collationObjectId[2];
141  Oid classObjectId[2];
142  int16 coloptions[2];
143  ObjectAddress baseobject,
144  toastobject;
145 
146  /*
147  * Is it already toasted?
148  */
149  if (rel->rd_rel->reltoastrelid != InvalidOid)
150  return false;
151 
152  /*
153  * Check to see whether the table actually needs a TOAST table.
154  */
155  if (!IsBinaryUpgrade)
156  {
157  /* Normal mode, normal check */
158  if (!needs_toast_table(rel))
159  return false;
160  }
161  else
162  {
163  /*
164  * In binary-upgrade mode, create a TOAST table if and only if
165  * pg_upgrade told us to (ie, a TOAST table OID has been provided).
166  *
167  * This indicates that the old cluster had a TOAST table for the
168  * current table. We must create a TOAST table to receive the old
169  * TOAST file, even if the table seems not to need one.
170  *
171  * Contrariwise, if the old cluster did not have a TOAST table, we
172  * should be able to get along without one even if the new version's
173  * needs_toast_table rules suggest we should have one. There is a lot
174  * of daylight between where we will create a TOAST table and where
175  * one is really necessary to avoid failures, so small cross-version
176  * differences in the when-to-create heuristic shouldn't be a problem.
177  * If we tried to create a TOAST table anyway, we would have the
178  * problem that it might take up an OID that will conflict with some
179  * old-cluster table we haven't seen yet.
180  */
182  return false;
183  }
184 
185  /*
186  * If requested check lockmode is sufficient. This is a cross check in
187  * case of errors or conflicting decisions in earlier code.
188  */
189  if (check && lockmode != AccessExclusiveLock)
190  elog(ERROR, "AccessExclusiveLock required to add toast table.");
191 
192  /*
193  * Create the toast table and its index
194  */
195  snprintf(toast_relname, sizeof(toast_relname),
196  "pg_toast_%u", relOid);
197  snprintf(toast_idxname, sizeof(toast_idxname),
198  "pg_toast_%u_index", relOid);
199 
200  /* this is pretty painful... need a tuple descriptor */
201  tupdesc = CreateTemplateTupleDesc(3);
202  TupleDescInitEntry(tupdesc, (AttrNumber) 1,
203  "chunk_id",
204  OIDOID,
205  -1, 0);
206  TupleDescInitEntry(tupdesc, (AttrNumber) 2,
207  "chunk_seq",
208  INT4OID,
209  -1, 0);
210  TupleDescInitEntry(tupdesc, (AttrNumber) 3,
211  "chunk_data",
212  BYTEAOID,
213  -1, 0);
214 
215  /*
216  * Ensure that the toast table doesn't itself get toasted, or we'll be
217  * toast :-(. This is essential for chunk_data because type bytea is
218  * toastable; hit the other two just to be sure.
219  */
220  TupleDescAttr(tupdesc, 0)->attstorage = TYPSTORAGE_PLAIN;
221  TupleDescAttr(tupdesc, 1)->attstorage = TYPSTORAGE_PLAIN;
222  TupleDescAttr(tupdesc, 2)->attstorage = TYPSTORAGE_PLAIN;
223 
224  /* Toast field should not be compressed */
225  TupleDescAttr(tupdesc, 0)->attcompression = InvalidCompressionMethod;
226  TupleDescAttr(tupdesc, 1)->attcompression = InvalidCompressionMethod;
227  TupleDescAttr(tupdesc, 2)->attcompression = InvalidCompressionMethod;
228 
229  /*
230  * Toast tables for regular relations go in pg_toast; those for temp
231  * relations go into the per-backend temp-toast-table namespace.
232  */
233  if (isTempOrTempToastNamespace(rel->rd_rel->relnamespace))
234  namespaceid = GetTempToastNamespace();
235  else
236  namespaceid = PG_TOAST_NAMESPACE;
237 
238  /* Toast table is shared if and only if its parent is. */
239  shared_relation = rel->rd_rel->relisshared;
240 
241  /* It's mapped if and only if its parent is, too */
242  mapped_relation = RelationIsMapped(rel);
243 
244  toast_relid = heap_create_with_catalog(toast_relname,
245  namespaceid,
246  rel->rd_rel->reltablespace,
247  toastOid,
248  InvalidOid,
249  InvalidOid,
250  rel->rd_rel->relowner,
252  tupdesc,
253  NIL,
254  RELKIND_TOASTVALUE,
255  rel->rd_rel->relpersistence,
256  shared_relation,
257  mapped_relation,
259  reloptions,
260  false,
261  true,
262  true,
263  InvalidOid,
264  NULL);
265  Assert(toast_relid != InvalidOid);
266 
267  /* make the toast relation visible, else table_open will fail */
269 
270  /* ShareLock is not really needed here, but take it anyway */
271  toast_rel = table_open(toast_relid, ShareLock);
272 
273  /*
274  * Create unique index on chunk_id, chunk_seq.
275  *
276  * NOTE: the normal TOAST access routines could actually function with a
277  * single-column index on chunk_id only. However, the slice access
278  * routines use both columns for faster access to an individual chunk. In
279  * addition, we want it to be unique as a check against the possibility of
280  * duplicate TOAST chunk OIDs. The index might also be a little more
281  * efficient this way, since btree isn't all that happy with large numbers
282  * of equal keys.
283  */
284 
285  indexInfo = makeNode(IndexInfo);
286  indexInfo->ii_NumIndexAttrs = 2;
287  indexInfo->ii_NumIndexKeyAttrs = 2;
288  indexInfo->ii_IndexAttrNumbers[0] = 1;
289  indexInfo->ii_IndexAttrNumbers[1] = 2;
290  indexInfo->ii_Expressions = NIL;
291  indexInfo->ii_ExpressionsState = NIL;
292  indexInfo->ii_Predicate = NIL;
293  indexInfo->ii_PredicateState = NULL;
294  indexInfo->ii_ExclusionOps = NULL;
295  indexInfo->ii_ExclusionProcs = NULL;
296  indexInfo->ii_ExclusionStrats = NULL;
297  indexInfo->ii_OpclassOptions = NULL;
298  indexInfo->ii_Unique = true;
299  indexInfo->ii_ReadyForInserts = true;
300  indexInfo->ii_Concurrent = false;
301  indexInfo->ii_BrokenHotChain = false;
302  indexInfo->ii_ParallelWorkers = 0;
303  indexInfo->ii_Am = BTREE_AM_OID;
304  indexInfo->ii_AmCache = NULL;
305  indexInfo->ii_Context = CurrentMemoryContext;
306 
307  collationObjectId[0] = InvalidOid;
308  collationObjectId[1] = InvalidOid;
309 
310  classObjectId[0] = OID_BTREE_OPS_OID;
311  classObjectId[1] = INT4_BTREE_OPS_OID;
312 
313  coloptions[0] = 0;
314  coloptions[1] = 0;
315 
316  index_create(toast_rel, toast_idxname, toastIndexOid, InvalidOid,
318  indexInfo,
319  list_make2("chunk_id", "chunk_seq"),
320  BTREE_AM_OID,
321  rel->rd_rel->reltablespace,
322  collationObjectId, classObjectId, coloptions, (Datum) 0,
323  INDEX_CREATE_IS_PRIMARY, 0, true, true, NULL);
324 
325  table_close(toast_rel, NoLock);
326 
327  /*
328  * Store the toast table's OID in the parent relation's pg_class row
329  */
330  class_rel = table_open(RelationRelationId, RowExclusiveLock);
331 
332  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
333  if (!HeapTupleIsValid(reltup))
334  elog(ERROR, "cache lookup failed for relation %u", relOid);
335 
336  ((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
337 
339  {
340  /* normal case, use a transactional update */
341  CatalogTupleUpdate(class_rel, &reltup->t_self, reltup);
342  }
343  else
344  {
345  /* While bootstrapping, we cannot UPDATE, so overwrite in-place */
346  heap_inplace_update(class_rel, reltup);
347  }
348 
349  heap_freetuple(reltup);
350 
351  table_close(class_rel, RowExclusiveLock);
352 
353  /*
354  * Register dependency from the toast table to the main, so that the
355  * toast table will be deleted if the main is. Skip this in bootstrap
356  * mode.
357  */
359  {
360  baseobject.classId = RelationRelationId;
361  baseobject.objectId = relOid;
362  baseobject.objectSubId = 0;
363  toastobject.classId = RelationRelationId;
364  toastobject.objectId = toast_relid;
365  toastobject.objectSubId = 0;
366 
367  recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
368  }
369 
370  /*
371  * Make changes visible
372  */
374 
375  return true;
376 }
377 
378 /*
379  * Check to see whether the table needs a TOAST table.
380  */
381 static bool
383 {
384  /*
385  * No need to create a TOAST table for partitioned tables.
386  */
387  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
388  return false;
389 
390  /*
391  * We cannot allow toasting a shared relation after initdb (because
392  * there's no way to mark it toasted in other databases' pg_class).
393  */
394  if (rel->rd_rel->relisshared && !IsBootstrapProcessingMode())
395  return false;
396 
397  /*
398  * Ignore attempts to create toast tables on catalog tables after initdb.
399  * Which catalogs get toast tables is explicitly chosen in
400  * catalog/pg_*.h. (We could get here via some ALTER TABLE command if
401  * the catalog doesn't have a toast table.)
402  */
404  return false;
405 
406  /* Otherwise, let the AM decide. */
408 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
signed short int16
Definition: c.h:428
#define NIL
Definition: pg_list.h:65
MemoryContext ii_Context
Definition: execnodes.h:179
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
List * ii_Predicate
Definition: execnodes.h:163
void AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
Definition: toasting.c:58
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
int LOCKMODE
Definition: lockdefs.h:26
Oid binary_upgrade_next_toast_pg_class_oid
Definition: heap.c:94
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition: namespace.c:3180
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
ExprState * ii_PredicateState
Definition: execnodes.h:164
Oid * ii_ExclusionProcs
Definition: execnodes.h:166
int errcode(int sqlerrcode)
Definition: elog.c:698
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:46
Form_pg_class rd_rel
Definition: rel.h:110
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
Oid index_create(Relation heapRelation, const char *indexRelationName, Oid indexRelationId, Oid parentIndexRelid, Oid parentConstraintId, Oid relFileNode, IndexInfo *indexInfo, List *indexColNames, Oid accessMethodObjectId, Oid tableSpaceId, Oid *collationObjectId, Oid *classObjectId, int16 *coloptions, Datum reloptions, bits16 flags, bits16 constr_flags, bool allow_system_table_mods, bool is_internal, Oid *constraintId)
Definition: index.c:698
void NewRelationCreateToastTable(Oid relOid, Datum reloptions)
Definition: toasting.c:70
#define OidIsValid(objectId)
Definition: c.h:710
bool IsBinaryUpgrade
Definition: globals.c:113
static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid, Datum reloptions, LOCKMODE lockmode, bool check)
Definition: toasting.c:125
void BootstrapToastTable(char *relName, Oid toastOid, Oid toastIndexOid)
Definition: toasting.c:94
#define NAMEDATALEN
List * ii_ExpressionsState
Definition: execnodes.h:162
static void CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, bool check)
Definition: toasting.c:76
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int ii_NumIndexKeyAttrs
Definition: execnodes.h:159
ItemPointerData t_self
Definition: htup.h:65
Oid GetTempToastNamespace(void)
Definition: namespace.c:3298
#define NoLock
Definition: lockdefs.h:34
static bool needs_toast_table(Relation rel)
Definition: toasting.c:382
#define RowExclusiveLock
Definition: lockdefs.h:38
bool ii_BrokenHotChain
Definition: execnodes.h:175
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:580
bool ii_ReadyForInserts
Definition: execnodes.h:173
void * ii_AmCache
Definition: execnodes.h:178
#define RelationIsMapped(relation)
Definition: rel.h:506
uintptr_t Datum
Definition: postgres.h:411
void CommandCounterIncrement(void)
Definition: xact.c:1021
int ii_NumIndexAttrs
Definition: execnodes.h:158
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:61
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
bool ii_Unique
Definition: execnodes.h:172
#define makeNode(_type_)
Definition: nodes.h:587
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:161
#define Assert(condition)
Definition: c.h:804
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:1144
int ii_ParallelWorkers
Definition: execnodes.h:176
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
bool ii_Concurrent
Definition: execnodes.h:174
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:394
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define InvalidCompressionMethod
Oid * ii_ExclusionOps
Definition: execnodes.h:165
int errmsg(const char *fmt,...)
Definition: elog.c:909
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6048
#define elog(elevel,...)
Definition: elog.h:232
#define ShareLock
Definition: lockdefs.h:41
static bool table_relation_needs_toast_table(Relation rel)
Definition: tableam.h:1847
static Oid table_relation_toast_am(Relation rel)
Definition: tableam.h:1857
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
uint16 * ii_ExclusionStrats
Definition: execnodes.h:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define snprintf
Definition: port.h:216
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:457
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
Datum * ii_OpclassOptions
Definition: execnodes.h:171
Oid ii_Am
Definition: execnodes.h:177
void NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
Definition: toasting.c:64