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-2018, 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/tuptoaster.h"
18 #include "access/xact.h"
19 #include "catalog/binary_upgrade.h"
20 #include "catalog/dependency.h"
21 #include "catalog/heap.h"
22 #include "catalog/index.h"
23 #include "catalog/namespace.h"
24 #include "catalog/pg_am.h"
25 #include "catalog/pg_namespace.h"
26 #include "catalog/pg_opclass.h"
27 #include "catalog/pg_type.h"
28 #include "catalog/toasting.h"
29 #include "miscadmin.h"
30 #include "nodes/makefuncs.h"
31 #include "storage/lock.h"
32 #include "utils/builtins.h"
33 #include "utils/rel.h"
34 #include "utils/syscache.h"
35 
36 /* Potentially set by pg_upgrade_support functions */
38 
39 static void CheckAndCreateToastTable(Oid relOid, Datum reloptions,
40  LOCKMODE lockmode, bool check);
41 static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
42  Datum reloptions, LOCKMODE lockmode, bool check);
43 static bool needs_toast_table(Relation rel);
44 
45 
46 /*
47  * CreateToastTable variants
48  * If the table needs a toast table, and doesn't already have one,
49  * then create a toast table for it.
50  *
51  * reloptions for the toast table can be passed, too. Pass (Datum) 0
52  * for default reloptions.
53  *
54  * We expect the caller to have verified that the relation is a table and have
55  * already done any necessary permission checks. Callers expect this function
56  * to end with CommandCounterIncrement if it makes any changes.
57  */
58 void
59 AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
60 {
61  CheckAndCreateToastTable(relOid, reloptions, lockmode, true);
62 }
63 
64 void
65 NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
66 {
67  CheckAndCreateToastTable(relOid, reloptions, lockmode, false);
68 }
69 
70 void
72 {
73  CheckAndCreateToastTable(relOid, reloptions, AccessExclusiveLock, false);
74 }
75 
76 static void
77 CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, bool check)
78 {
79  Relation rel;
80 
81  rel = heap_open(relOid, lockmode);
82 
83  /* create_toast_table does all the work */
84  (void) create_toast_table(rel, InvalidOid, InvalidOid, reloptions, lockmode, check);
85 
86  heap_close(rel, NoLock);
87 }
88 
89 /*
90  * Create a toast table during bootstrap
91  *
92  * Here we need to prespecify the OIDs of the toast table and its index
93  */
94 void
95 BootstrapToastTable(char *relName, Oid toastOid, Oid toastIndexOid)
96 {
97  Relation rel;
98 
99  rel = heap_openrv(makeRangeVar(NULL, relName, -1), AccessExclusiveLock);
100 
101  if (rel->rd_rel->relkind != RELKIND_RELATION &&
102  rel->rd_rel->relkind != RELKIND_MATVIEW)
103  ereport(ERROR,
104  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
105  errmsg("\"%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,
110  AccessExclusiveLock, false))
111  elog(ERROR, "\"%s\" does not require a toast table",
112  relName);
113 
114  heap_close(rel, NoLock);
115 }
116 
117 
118 /*
119  * create_toast_table --- internal workhorse
120  *
121  * rel is already opened and locked
122  * toastOid and toastIndexOid are normally InvalidOid, but during
123  * bootstrap they can be nonzero to specify hand-assigned OIDs
124  */
125 static bool
126 create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
127  Datum reloptions, LOCKMODE lockmode, bool check)
128 {
129  Oid relOid = RelationGetRelid(rel);
130  HeapTuple reltup;
131  TupleDesc tupdesc;
132  bool shared_relation;
133  bool mapped_relation;
134  Relation toast_rel;
135  Relation class_rel;
136  Oid toast_relid;
137  Oid toast_typid = InvalidOid;
138  Oid namespaceid;
139  char toast_relname[NAMEDATALEN];
140  char toast_idxname[NAMEDATALEN];
141  IndexInfo *indexInfo;
142  Oid collationObjectId[2];
143  Oid classObjectId[2];
144  int16 coloptions[2];
145  ObjectAddress baseobject,
146  toastobject;
147 
148  /*
149  * Toast table is shared if and only if its parent is.
150  *
151  * We cannot allow toasting a shared relation after initdb (because
152  * there's no way to mark it toasted in other databases' pg_class).
153  */
154  shared_relation = rel->rd_rel->relisshared;
155  if (shared_relation && !IsBootstrapProcessingMode())
156  ereport(ERROR,
157  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
158  errmsg("shared tables cannot be toasted after initdb")));
159 
160  /* It's mapped if and only if its parent is, too */
161  mapped_relation = RelationIsMapped(rel);
162 
163  /*
164  * Is it already toasted?
165  */
166  if (rel->rd_rel->reltoastrelid != InvalidOid)
167  return false;
168 
169  /*
170  * Check to see whether the table actually needs a TOAST table.
171  */
172  if (!IsBinaryUpgrade)
173  {
174  /* Normal mode, normal check */
175  if (!needs_toast_table(rel))
176  return false;
177  }
178  else
179  {
180  /*
181  * In binary-upgrade mode, create a TOAST table if and only if
182  * pg_upgrade told us to (ie, a TOAST table OID has been provided).
183  *
184  * This indicates that the old cluster had a TOAST table for the
185  * current table. We must create a TOAST table to receive the old
186  * TOAST file, even if the table seems not to need one.
187  *
188  * Contrariwise, if the old cluster did not have a TOAST table, we
189  * should be able to get along without one even if the new version's
190  * needs_toast_table rules suggest we should have one. There is a lot
191  * of daylight between where we will create a TOAST table and where
192  * one is really necessary to avoid failures, so small cross-version
193  * differences in the when-to-create heuristic shouldn't be a problem.
194  * If we tried to create a TOAST table anyway, we would have the
195  * problem that it might take up an OID that will conflict with some
196  * old-cluster table we haven't seen yet.
197  */
200  return false;
201  }
202 
203  /*
204  * If requested check lockmode is sufficient. This is a cross check in
205  * case of errors or conflicting decisions in earlier code.
206  */
207  if (check && lockmode != AccessExclusiveLock)
208  elog(ERROR, "AccessExclusiveLock required to add toast table.");
209 
210  /*
211  * Create the toast table and its index
212  */
213  snprintf(toast_relname, sizeof(toast_relname),
214  "pg_toast_%u", relOid);
215  snprintf(toast_idxname, sizeof(toast_idxname),
216  "pg_toast_%u_index", relOid);
217 
218  /* this is pretty painful... need a tuple descriptor */
219  tupdesc = CreateTemplateTupleDesc(3, false);
220  TupleDescInitEntry(tupdesc, (AttrNumber) 1,
221  "chunk_id",
222  OIDOID,
223  -1, 0);
224  TupleDescInitEntry(tupdesc, (AttrNumber) 2,
225  "chunk_seq",
226  INT4OID,
227  -1, 0);
228  TupleDescInitEntry(tupdesc, (AttrNumber) 3,
229  "chunk_data",
230  BYTEAOID,
231  -1, 0);
232 
233  /*
234  * Ensure that the toast table doesn't itself get toasted, or we'll be
235  * toast :-(. This is essential for chunk_data because type bytea is
236  * toastable; hit the other two just to be sure.
237  */
238  TupleDescAttr(tupdesc, 0)->attstorage = 'p';
239  TupleDescAttr(tupdesc, 1)->attstorage = 'p';
240  TupleDescAttr(tupdesc, 2)->attstorage = 'p';
241 
242  /*
243  * Toast tables for regular relations go in pg_toast; those for temp
244  * relations go into the per-backend temp-toast-table namespace.
245  */
246  if (isTempOrTempToastNamespace(rel->rd_rel->relnamespace))
247  namespaceid = GetTempToastNamespace();
248  else
249  namespaceid = PG_TOAST_NAMESPACE;
250 
251  /*
252  * Use binary-upgrade override for pg_type.oid, if supplied. We might be
253  * in the post-schema-restore phase where we are doing ALTER TABLE to
254  * create TOAST tables that didn't exist in the old cluster.
255  */
257  {
260  }
261 
262  toast_relid = heap_create_with_catalog(toast_relname,
263  namespaceid,
264  rel->rd_rel->reltablespace,
265  toastOid,
266  toast_typid,
267  InvalidOid,
268  rel->rd_rel->relowner,
269  tupdesc,
270  NIL,
271  RELKIND_TOASTVALUE,
272  rel->rd_rel->relpersistence,
273  shared_relation,
274  mapped_relation,
275  true,
276  0,
278  reloptions,
279  false,
280  true,
281  true,
282  InvalidOid,
283  NULL);
284  Assert(toast_relid != InvalidOid);
285 
286  /* make the toast relation visible, else heap_open will fail */
288 
289  /* ShareLock is not really needed here, but take it anyway */
290  toast_rel = heap_open(toast_relid, ShareLock);
291 
292  /*
293  * Create unique index on chunk_id, chunk_seq.
294  *
295  * NOTE: the normal TOAST access routines could actually function with a
296  * single-column index on chunk_id only. However, the slice access
297  * routines use both columns for faster access to an individual chunk. In
298  * addition, we want it to be unique as a check against the possibility of
299  * duplicate TOAST chunk OIDs. The index might also be a little more
300  * efficient this way, since btree isn't all that happy with large numbers
301  * of equal keys.
302  */
303 
304  indexInfo = makeNode(IndexInfo);
305  indexInfo->ii_NumIndexAttrs = 2;
306  indexInfo->ii_NumIndexKeyAttrs = 2;
307  indexInfo->ii_IndexAttrNumbers[0] = 1;
308  indexInfo->ii_IndexAttrNumbers[1] = 2;
309  indexInfo->ii_Expressions = NIL;
310  indexInfo->ii_ExpressionsState = NIL;
311  indexInfo->ii_Predicate = NIL;
312  indexInfo->ii_PredicateState = NULL;
313  indexInfo->ii_ExclusionOps = NULL;
314  indexInfo->ii_ExclusionProcs = NULL;
315  indexInfo->ii_ExclusionStrats = NULL;
316  indexInfo->ii_Unique = true;
317  indexInfo->ii_ReadyForInserts = true;
318  indexInfo->ii_Concurrent = false;
319  indexInfo->ii_BrokenHotChain = false;
320  indexInfo->ii_ParallelWorkers = 0;
321  indexInfo->ii_Am = BTREE_AM_OID;
322  indexInfo->ii_AmCache = NULL;
323  indexInfo->ii_Context = CurrentMemoryContext;
324 
325  collationObjectId[0] = InvalidOid;
326  collationObjectId[1] = InvalidOid;
327 
328  classObjectId[0] = OID_BTREE_OPS_OID;
329  classObjectId[1] = INT4_BTREE_OPS_OID;
330 
331  coloptions[0] = 0;
332  coloptions[1] = 0;
333 
334  index_create(toast_rel, toast_idxname, toastIndexOid, InvalidOid,
336  indexInfo,
337  list_make2("chunk_id", "chunk_seq"),
338  BTREE_AM_OID,
339  rel->rd_rel->reltablespace,
340  collationObjectId, classObjectId, coloptions, (Datum) 0,
341  INDEX_CREATE_IS_PRIMARY, 0, true, true, NULL);
342 
343  heap_close(toast_rel, NoLock);
344 
345  /*
346  * Store the toast table's OID in the parent relation's pg_class row
347  */
348  class_rel = heap_open(RelationRelationId, RowExclusiveLock);
349 
350  reltup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relOid));
351  if (!HeapTupleIsValid(reltup))
352  elog(ERROR, "cache lookup failed for relation %u", relOid);
353 
354  ((Form_pg_class) GETSTRUCT(reltup))->reltoastrelid = toast_relid;
355 
357  {
358  /* normal case, use a transactional update */
359  CatalogTupleUpdate(class_rel, &reltup->t_self, reltup);
360  }
361  else
362  {
363  /* While bootstrapping, we cannot UPDATE, so overwrite in-place */
364  heap_inplace_update(class_rel, reltup);
365  }
366 
367  heap_freetuple(reltup);
368 
369  heap_close(class_rel, RowExclusiveLock);
370 
371  /*
372  * Register dependency from the toast table to the master, so that the
373  * toast table will be deleted if the master is. Skip this in bootstrap
374  * mode.
375  */
377  {
378  baseobject.classId = RelationRelationId;
379  baseobject.objectId = relOid;
380  baseobject.objectSubId = 0;
381  toastobject.classId = RelationRelationId;
382  toastobject.objectId = toast_relid;
383  toastobject.objectSubId = 0;
384 
385  recordDependencyOn(&toastobject, &baseobject, DEPENDENCY_INTERNAL);
386  }
387 
388  /*
389  * Make changes visible
390  */
392 
393  return true;
394 }
395 
396 /*
397  * Check to see whether the table needs a TOAST table. It does only if
398  * (1) there are any toastable attributes, and (2) the maximum length
399  * of a tuple could exceed TOAST_TUPLE_THRESHOLD. (We don't want to
400  * create a toast table for something like "f1 varchar(20)".)
401  * No need to create a TOAST table for partitioned tables.
402  */
403 static bool
405 {
406  int32 data_length = 0;
407  bool maxlength_unknown = false;
408  bool has_toastable_attrs = false;
409  TupleDesc tupdesc;
410  int32 tuple_length;
411  int i;
412 
413  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
414  return false;
415 
416  tupdesc = rel->rd_att;
417 
418  for (i = 0; i < tupdesc->natts; i++)
419  {
420  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
421 
422  if (att->attisdropped)
423  continue;
424  data_length = att_align_nominal(data_length, att->attalign);
425  if (att->attlen > 0)
426  {
427  /* Fixed-length types are never toastable */
428  data_length += att->attlen;
429  }
430  else
431  {
432  int32 maxlen = type_maximum_size(att->atttypid,
433  att->atttypmod);
434 
435  if (maxlen < 0)
436  maxlength_unknown = true;
437  else
438  data_length += maxlen;
439  if (att->attstorage != 'p')
440  has_toastable_attrs = true;
441  }
442  }
443  if (!has_toastable_attrs)
444  return false; /* nothing to toast? */
445  if (maxlength_unknown)
446  return true; /* any unlimited-length attrs? */
447  tuple_length = MAXALIGN(SizeofHeapTupleHeader +
448  BITMAPLEN(tupdesc->natts)) +
449  MAXALIGN(data_length);
450  return (tuple_length > TOAST_TUPLE_THRESHOLD);
451 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
signed short int16
Definition: c.h:312
#define TOAST_TUPLE_THRESHOLD
Definition: tuptoaster.h:55
#define NIL
Definition: pg_list.h:69
MemoryContext ii_Context
Definition: execnodes.h:171
#define SizeofHeapTupleHeader
Definition: htup_details.h:183
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
List * ii_Predicate
Definition: execnodes.h:156
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:144
void AlterTableCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
Definition: toasting.c:59
int LOCKMODE
Definition: lockdefs.h:26
Oid binary_upgrade_next_toast_pg_class_oid
Definition: heap.c:90
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition: namespace.c:3161
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
ExprState * ii_PredicateState
Definition: execnodes.h:157
Oid * ii_ExclusionProcs
Definition: execnodes.h:159
int errcode(int sqlerrcode)
Definition: elog.c:575
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define BITMAPLEN(NATTS)
Definition: htup_details.h:560
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:84
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
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:745
void NewRelationCreateToastTable(Oid relOid, Datum reloptions)
Definition: toasting.c:71
#define OidIsValid(objectId)
Definition: c.h:605
int natts
Definition: tupdesc.h:82
bool IsBinaryUpgrade
Definition: globals.c:109
static bool create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid, Datum reloptions, LOCKMODE lockmode, bool check)
Definition: toasting.c:126
void BootstrapToastTable(char *relName, Oid toastOid, Oid toastIndexOid)
Definition: toasting.c:95
signed int int32
Definition: c.h:313
#define NAMEDATALEN
List * ii_ExpressionsState
Definition: execnodes.h:155
static void CheckAndCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode, bool check)
Definition: toasting.c:77
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, bool oidislocal, int oidinhcount, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, Oid relrewrite, ObjectAddress *typaddress)
Definition: heap.c:1027
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
int ii_NumIndexKeyAttrs
Definition: execnodes.h:152
int32 type_maximum_size(Oid type_oid, int32 typemod)
Definition: format_type.c:397
ItemPointerData t_self
Definition: htup.h:65
Oid GetTempToastNamespace(void)
Definition: namespace.c:3239
#define NoLock
Definition: lockdefs.h:34
static bool needs_toast_table(Relation rel)
Definition: toasting.c:404
#define RowExclusiveLock
Definition: lockdefs.h:38
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
bool ii_BrokenHotChain
Definition: execnodes.h:167
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Oid reltoastrelid
Definition: pg_class.h:47
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:600
bool ii_ReadyForInserts
Definition: execnodes.h:165
#define ereport(elevel, rest)
Definition: elog.h:122
void * ii_AmCache
Definition: execnodes.h:170
#define RelationIsMapped(relation)
Definition: rel.h:458
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:914
int ii_NumIndexAttrs
Definition: execnodes.h:151
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
TupleDesc rd_att
Definition: rel.h:85
#define INDEX_CREATE_IS_PRIMARY
Definition: index.h:45
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1323
#define InvalidOid
Definition: postgres_ext.h:36
bool ii_Unique
Definition: execnodes.h:164
#define makeNode(_type_)
Definition: nodes.h:565
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
List * ii_Expressions
Definition: execnodes.h:154
#define Assert(condition)
Definition: c.h:699
int ii_ParallelWorkers
Definition: execnodes.h:168
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:211
#define MAXALIGN(LEN)
Definition: c.h:652
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:45
bool ii_Concurrent
Definition: execnodes.h:166
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:372
FormData_pg_class * Form_pg_class
Definition: pg_class.h:93
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
#define AccessExclusiveLock
Definition: lockdefs.h:45
Oid * ii_ExclusionOps
Definition: execnodes.h:158
int errmsg(const char *fmt,...)
Definition: elog.c:797
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6390
#define ShareLock
Definition: lockdefs.h:41
int i
Oid binary_upgrade_next_toast_pg_type_oid
Definition: toasting.c:37
#define elog
Definition: elog.h:219
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:153
uint16 * ii_ExclusionStrats
Definition: execnodes.h:160
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:407
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:421
Oid ii_Am
Definition: execnodes.h:169
void NewHeapCreateToastTable(Oid relOid, Datum reloptions, LOCKMODE lockmode)
Definition: toasting.c:65